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    /// Inside a fixed-schedule execution it is [`Self::fixed_delta`].
15    pub delta: Duration,
16    /// Total game time, without time spent paused.
17    pub elapsed: Duration,
18    /// Time simulated by one fixed-schedule execution.
19    pub fixed_delta: Duration,
20    /// Number of completed fixed-schedule executions.
21    pub fixed_tick: u64,
22}
23
24impl Default for FrameTime {
25    fn default() -> Self {
26        Self {
27            frame: 0,
28            real_delta: Duration::ZERO,
29            delta: Duration::ZERO,
30            elapsed: Duration::ZERO,
31            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
32            fixed_tick: 0,
33        }
34    }
35}
36
37impl FrameTime {
38    /// Returns [`Self::delta`] in seconds: the frame's game time, or the
39    /// fixed step inside a fixed-schedule execution such as a game's
40    /// `tick` function.
41    #[must_use]
42    pub fn delta_seconds(&self) -> f32 {
43        self.delta.as_secs_f32()
44    }
45
46    /// Returns total running game time as an easy-to-use `f32` value.
47    #[must_use]
48    pub fn elapsed_seconds(&self) -> f32 {
49        self.elapsed.as_secs_f32()
50    }
51}
52
53/// Pause, stepping, scale, and fixed-schedule catch-up controls.
54#[derive(Resource, Clone, Debug)]
55pub struct TimeControl {
56    /// Whether variable time and ordinary fixed-schedule executions are paused.
57    pub paused: bool,
58    /// Multiplier applied to real time while the simulation is running.
59    pub time_scale: f64,
60    /// Time simulated by one fixed-schedule execution.
61    pub fixed_delta: Duration,
62    /// Maximum number of accumulated fixed-schedule executions run per application update.
63    pub max_fixed_steps: u32,
64    accumulator: Duration,
65    pending_steps: u32,
66}
67
68impl Default for TimeControl {
69    fn default() -> Self {
70        Self {
71            paused: false,
72            time_scale: 1.0,
73            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
74            max_fixed_steps: 8,
75            accumulator: Duration::ZERO,
76            pending_steps: 0,
77        }
78    }
79}
80
81impl TimeControl {
82    /// Pauses variable time and ordinary fixed-schedule executions.
83    pub fn pause(&mut self) {
84        self.paused = true;
85    }
86
87    /// Resumes variable time and ordinary fixed-schedule executions.
88    pub fn resume(&mut self) {
89        self.paused = false;
90    }
91
92    /// Time accumulated toward the next fixed step: how far real time has
93    /// run past the last completed tick.
94    #[must_use]
95    pub fn accumulator(&self) -> Duration {
96        self.accumulator
97    }
98
99    /// Queues one fixed-schedule execution to be consumed while paused.
100    pub fn step(&mut self) {
101        self.pending_steps = self.pending_steps.saturating_add(1);
102    }
103}
104
105/// Errors produced while advancing simulation time.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum TimeAdvanceError {
108    /// The configured fixed timestep is zero.
109    InvalidFixedDelta,
110}
111
112impl fmt::Display for TimeAdvanceError {
113    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114        match self {
115            Self::InvalidFixedDelta => {
116                formatter.write_str("fixed delta must be greater than zero")
117            }
118        }
119    }
120}
121
122impl Error for TimeAdvanceError {}
123
124/// Advances frame and fixed-schedule bookkeeping by one application update.
125///
126/// Catch-up work is capped by [`TimeControl::max_fixed_steps`]. Remaining
127/// accumulated time is retained for later updates, up to one more capped
128/// update's worth; older backlog is dropped. A queued step is
129/// consumed only while paused and advances elapsed time by exactly one fixed
130/// timestep without consuming the accumulator.
131///
132/// # Errors
133///
134/// Returns [`TimeAdvanceError::InvalidFixedDelta`] when `control.fixed_delta`
135/// is zero, before mutating either the supplied [`TimeControl`] or
136/// [`FrameTime`].
137///
138/// # Panics
139///
140/// After fixed-delta validation, when the simulation is not paused, this may
141/// panic if `control.time_scale` is positive and non-finite, or if scaling
142/// `real_delta` by the non-negative time scale cannot be represented by
143/// [`Duration::mul_f64`]. Negative and `NaN` time scales are clamped to zero
144/// and do not panic.
145pub fn advance(
146    control: &mut TimeControl,
147    time: &mut FrameTime,
148    real_delta: Duration,
149) -> Result<u32, TimeAdvanceError> {
150    if control.fixed_delta.is_zero() {
151        return Err(TimeAdvanceError::InvalidFixedDelta);
152    }
153
154    let scaled_delta = if control.paused {
155        Duration::ZERO
156    } else {
157        real_delta.mul_f64(control.time_scale.max(0.0))
158    };
159    control.accumulator = control.accumulator.saturating_add(scaled_delta);
160
161    let mut fixed_steps = 0;
162    let fixed_delta = control.fixed_delta;
163    while control.accumulator >= fixed_delta
164        && fixed_steps < control.max_fixed_steps
165        && !control.paused
166    {
167        control.accumulator -= fixed_delta;
168        fixed_steps += 1;
169    }
170    if !control.paused && control.max_fixed_steps > 0 {
171        // Keep at most one more capped update of backlog, so one long stall
172        // does not make many later frames run the maximum number of steps.
173        control.accumulator = control
174            .accumulator
175            .min(fixed_delta.saturating_mul(control.max_fixed_steps));
176    }
177    let stepped_while_paused = control.paused && control.pending_steps > 0;
178    if stepped_while_paused {
179        control.pending_steps -= 1;
180        fixed_steps = 1;
181    }
182    let elapsed_delta = if stepped_while_paused {
183        fixed_delta
184    } else {
185        scaled_delta
186    };
187
188    time.frame = time.frame.saturating_add(1);
189    time.real_delta = real_delta;
190    time.delta = scaled_delta;
191    time.elapsed = time.elapsed.saturating_add(elapsed_delta);
192    time.fixed_delta = fixed_delta;
193    time.fixed_tick = time.fixed_tick.saturating_add(u64::from(fixed_steps));
194    Ok(fixed_steps)
195}
196
197/// Seed for gameplay randomness. Draw values with [`RandomSeed::value`],
198/// indexed by the fixed tick and a stream from [`RandomSeed::stream`], so a
199/// run repeats exactly for the same seed. Scenario tests set the seed they
200/// record. Simulation code takes all its randomness from here, never from a
201/// global or thread-local generator.
202#[derive(Resource, Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub struct RandomSeed(pub u64);
204
205impl RandomSeed {
206    /// Uniform 64-bit value for `stream` at fixed `tick`. The same seed,
207    /// tick and stream always give the same value.
208    #[must_use]
209    pub fn value(self, tick: u64, stream: u64) -> u64 {
210        splitmix64(self.0 ^ splitmix64(tick ^ splitmix64(stream)))
211    }
212
213    /// Stream `key` of the subsystem called `subsystem`, such as
214    /// `"bursts"`. The name is hashed in, so two subsystems that pick the
215    /// same keys still draw independent values.
216    #[must_use]
217    pub fn stream(subsystem: &str, key: u64) -> u64 {
218        // FNV-1a over the name.
219        let name =
220            subsystem
221                .bytes()
222                .fold(0xCBF2_9CE4_8422_2325_u64, |hash, byte| {
223                    (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01B3)
224                });
225        splitmix64(name ^ splitmix64(key))
226    }
227
228    /// Uniform value in `[0, 1)` for `stream` at fixed `tick`.
229    #[must_use]
230    pub fn unit(self, tick: u64, stream: u64) -> f32 {
231        (self.value(tick, stream) >> 40) as f32 / (1_u64 << 24) as f32
232    }
233}
234
235fn splitmix64(mut value: u64) -> u64 {
236    value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
237    value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
238    value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
239    value ^ (value >> 31)
240}
241
242#[cfg(test)]
243mod tests {
244    use std::time::Duration;
245
246    use bevy_ecs::prelude::Resource;
247
248    use super::{
249        advance, FrameTime, RandomSeed, TimeAdvanceError, TimeControl,
250    };
251
252    #[test]
253    fn default_starts_at_frame_zero_with_sixty_hz_fixed_delta() {
254        let time = FrameTime::default();
255
256        assert_eq!(time.frame, 0);
257        assert_eq!(time.real_delta, Duration::ZERO);
258        assert_eq!(time.delta, Duration::ZERO);
259        assert_eq!(time.elapsed, Duration::ZERO);
260        assert_eq!(time.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
261        assert_eq!(time.fixed_tick, 0);
262    }
263
264    #[test]
265    fn duration_accessors_return_seconds() {
266        let time = FrameTime {
267            delta: Duration::from_millis(125),
268            elapsed: Duration::from_millis(2_500),
269            ..FrameTime::default()
270        };
271
272        assert_eq!(time.delta_seconds(), 0.125);
273        assert_eq!(time.elapsed_seconds(), 2.5);
274    }
275
276    #[test]
277    fn frame_time_is_an_ecs_resource() {
278        fn assert_resource<T: Resource>() {}
279
280        assert_resource::<FrameTime>();
281    }
282
283    #[test]
284    fn frame_time_is_clone_and_copy() {
285        fn assert_clone_copy<T: Clone + Copy>() {}
286
287        assert_clone_copy::<FrameTime>();
288    }
289
290    #[test]
291    fn time_control_defaults_and_public_traits_are_stable() {
292        fn assert_resource_clone_debug<
293            T: Resource + Clone + std::fmt::Debug,
294        >() {
295        }
296        fn assert_error_traits<T: std::error::Error + Clone + Copy + Eq>() {}
297
298        assert_resource_clone_debug::<TimeControl>();
299        assert_error_traits::<TimeAdvanceError>();
300
301        let control = TimeControl::default();
302        assert!(!control.paused);
303        assert_eq!(control.time_scale, 1.0);
304        assert_eq!(control.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
305        assert_eq!(control.max_fixed_steps, 8);
306        assert_eq!(control.accumulator, Duration::ZERO);
307        assert_eq!(control.pending_steps, 0);
308        assert_eq!(
309            TimeAdvanceError::InvalidFixedDelta.to_string(),
310            "fixed delta must be greater than zero"
311        );
312    }
313
314    #[test]
315    fn normal_scaled_advance_updates_all_bookkeeping() {
316        let mut control = TimeControl {
317            time_scale: 0.5,
318            fixed_delta: Duration::from_millis(10),
319            ..TimeControl::default()
320        };
321        let mut time = FrameTime::default();
322
323        assert_eq!(
324            advance(&mut control, &mut time, Duration::from_millis(25)),
325            Ok(1)
326        );
327        assert_eq!(control.accumulator, Duration::from_micros(2_500));
328        assert_eq!(time.frame, 1);
329        assert_eq!(time.real_delta, Duration::from_millis(25));
330        assert_eq!(time.delta, Duration::from_micros(12_500));
331        assert_eq!(time.elapsed, Duration::from_micros(12_500));
332        assert_eq!(time.fixed_delta, Duration::from_millis(10));
333        assert_eq!(time.fixed_tick, 1);
334    }
335
336    #[test]
337    fn catch_up_cap_retains_backlog_for_later_frames() {
338        let mut control = TimeControl {
339            fixed_delta: Duration::from_millis(10),
340            max_fixed_steps: 2,
341            ..TimeControl::default()
342        };
343        let mut time = FrameTime::default();
344
345        assert_eq!(
346            advance(&mut control, &mut time, Duration::from_millis(35)),
347            Ok(2)
348        );
349        assert_eq!(control.accumulator, Duration::from_millis(15));
350        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
351        assert_eq!(control.accumulator, Duration::from_millis(5));
352        assert_eq!(time.fixed_tick, 3);
353        assert_eq!(time.elapsed, Duration::from_millis(35));
354    }
355
356    #[test]
357    fn pause_drains_one_queued_step_per_update_and_resume_restores_time() {
358        let mut control = TimeControl {
359            fixed_delta: Duration::from_millis(10),
360            ..TimeControl::default()
361        };
362        let mut time = FrameTime::default();
363        control.pause();
364        control.step();
365        control.step();
366
367        assert_eq!(
368            advance(&mut control, &mut time, Duration::from_secs(1)),
369            Ok(1)
370        );
371        assert_eq!(time.delta, Duration::ZERO);
372        assert_eq!(time.elapsed, Duration::from_millis(10));
373        assert_eq!(control.pending_steps, 1);
374        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
375        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
376
377        control.resume();
378        assert_eq!(
379            advance(&mut control, &mut time, Duration::from_millis(10)),
380            Ok(1)
381        );
382        assert_eq!(time.elapsed, Duration::from_millis(30));
383        assert_eq!(time.fixed_tick, 3);
384    }
385
386    #[test]
387    fn steps_queued_while_running_persist_until_paused() {
388        let mut control = TimeControl {
389            fixed_delta: Duration::from_millis(10),
390            ..TimeControl::default()
391        };
392        let mut time = FrameTime::default();
393        control.step();
394
395        assert_eq!(
396            advance(&mut control, &mut time, Duration::from_millis(10)),
397            Ok(1)
398        );
399        assert_eq!(control.pending_steps, 1);
400        control.pause();
401        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
402        assert_eq!(control.pending_steps, 0);
403    }
404
405    #[test]
406    fn negative_and_nan_time_scales_clamp_to_zero() {
407        for scale in [-1.0, f64::NAN] {
408            let mut control = TimeControl {
409                time_scale: scale,
410                fixed_delta: Duration::from_millis(10),
411                ..TimeControl::default()
412            };
413            let mut time = FrameTime::default();
414
415            assert_eq!(
416                advance(&mut control, &mut time, Duration::from_secs(1)),
417                Ok(0)
418            );
419            assert_eq!(control.accumulator, Duration::ZERO);
420            assert_eq!(time.delta, Duration::ZERO);
421            assert_eq!(time.elapsed, Duration::ZERO);
422        }
423    }
424
425    #[test]
426    #[should_panic]
427    fn positive_infinite_time_scale_panics_while_running() {
428        let mut control = TimeControl {
429            time_scale: f64::INFINITY,
430            ..TimeControl::default()
431        };
432        let mut time = FrameTime::default();
433
434        let _ = advance(&mut control, &mut time, Duration::from_secs(1));
435    }
436
437    #[test]
438    fn long_stall_backlog_is_bounded_to_one_capped_update() {
439        let mut control = TimeControl {
440            fixed_delta: Duration::from_millis(10),
441            max_fixed_steps: 2,
442            ..TimeControl::default()
443        };
444        let mut time = FrameTime::default();
445
446        assert_eq!(
447            advance(&mut control, &mut time, Duration::from_secs(5)),
448            Ok(2)
449        );
450        assert_eq!(control.accumulator, Duration::from_millis(20));
451        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(2));
452        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
453    }
454
455    #[test]
456    fn zero_max_fixed_steps_retains_the_entire_backlog() {
457        let mut control = TimeControl {
458            fixed_delta: Duration::from_millis(10),
459            max_fixed_steps: 0,
460            ..TimeControl::default()
461        };
462        let mut time = FrameTime::default();
463
464        assert_eq!(
465            advance(&mut control, &mut time, Duration::from_millis(25)),
466            Ok(0)
467        );
468        assert_eq!(control.accumulator, Duration::from_millis(25));
469        assert_eq!(time.elapsed, Duration::from_millis(25));
470        assert_eq!(time.fixed_tick, 0);
471    }
472
473    #[test]
474    fn zero_fixed_delta_errors_before_mutating_either_resource() {
475        let mut control = TimeControl {
476            paused: true,
477            time_scale: 2.0,
478            fixed_delta: Duration::ZERO,
479            max_fixed_steps: 3,
480            accumulator: Duration::from_millis(7),
481            pending_steps: 2,
482        };
483        let mut time = FrameTime {
484            frame: 4,
485            real_delta: Duration::from_millis(1),
486            delta: Duration::from_millis(2),
487            elapsed: Duration::from_millis(3),
488            fixed_delta: Duration::from_millis(4),
489            fixed_tick: 5,
490        };
491
492        assert_eq!(
493            advance(&mut control, &mut time, Duration::from_secs(1)),
494            Err(TimeAdvanceError::InvalidFixedDelta)
495        );
496        assert!(control.paused);
497        assert_eq!(control.time_scale, 2.0);
498        assert_eq!(control.fixed_delta, Duration::ZERO);
499        assert_eq!(control.max_fixed_steps, 3);
500        assert_eq!(control.accumulator, Duration::from_millis(7));
501        assert_eq!(control.pending_steps, 2);
502        assert_eq!(time.frame, 4);
503        assert_eq!(time.real_delta, Duration::from_millis(1));
504        assert_eq!(time.delta, Duration::from_millis(2));
505        assert_eq!(time.elapsed, Duration::from_millis(3));
506        assert_eq!(time.fixed_delta, Duration::from_millis(4));
507        assert_eq!(time.fixed_tick, 5);
508    }
509
510    #[test]
511    fn paused_updates_and_steps_preserve_accumulated_partial_time() {
512        let mut control = TimeControl {
513            fixed_delta: Duration::from_millis(10),
514            ..TimeControl::default()
515        };
516        let mut time = FrameTime::default();
517        advance(&mut control, &mut time, Duration::from_millis(6)).unwrap();
518        control.pause();
519        advance(&mut control, &mut time, Duration::from_secs(1)).unwrap();
520        control.step();
521        advance(&mut control, &mut time, Duration::ZERO).unwrap();
522        assert_eq!(control.accumulator, Duration::from_millis(6));
523
524        control.resume();
525        assert_eq!(
526            advance(&mut control, &mut time, Duration::from_millis(4)),
527            Ok(1)
528        );
529        assert_eq!(control.accumulator, Duration::ZERO);
530    }
531
532    #[test]
533    fn counters_durations_and_step_queue_saturate() {
534        let mut control = TimeControl {
535            paused: true,
536            fixed_delta: Duration::from_nanos(1),
537            accumulator: Duration::MAX,
538            pending_steps: u32::MAX,
539            ..TimeControl::default()
540        };
541        control.step();
542        assert_eq!(control.pending_steps, u32::MAX);
543
544        let mut time = FrameTime {
545            frame: u64::MAX,
546            elapsed: Duration::MAX,
547            fixed_tick: u64::MAX,
548            ..FrameTime::default()
549        };
550        assert_eq!(advance(&mut control, &mut time, Duration::MAX), Ok(1));
551        assert_eq!(control.accumulator, Duration::MAX);
552        assert_eq!(control.pending_steps, u32::MAX - 1);
553        assert_eq!(time.frame, u64::MAX);
554        assert_eq!(time.elapsed, Duration::MAX);
555        assert_eq!(time.fixed_tick, u64::MAX);
556    }
557
558    #[test]
559    fn random_seed_repeats_per_seed_tick_and_stream() {
560        let seed = RandomSeed(42);
561        assert_eq!(seed.value(3, 1), RandomSeed(42).value(3, 1));
562        assert_ne!(seed.value(3, 1), seed.value(4, 1));
563        assert_ne!(seed.value(3, 1), seed.value(3, 2));
564        assert_ne!(seed.value(3, 1), RandomSeed(43).value(3, 1));
565        let units: Vec<_> = (0..1000).map(|tick| seed.unit(tick, 0)).collect();
566        assert!(units.iter().all(|unit| (0.0..1.0).contains(unit)));
567        let mean = units.iter().sum::<f32>() / units.len() as f32;
568        assert!((0.45..0.55).contains(&mean), "{mean}");
569    }
570
571    #[test]
572    fn subsystem_streams_are_independent_and_fixed() {
573        let bursts = RandomSeed::stream("bursts", 7);
574        assert_eq!(bursts, RandomSeed::stream("bursts", 7));
575        assert_ne!(bursts, RandomSeed::stream("bursts", 8));
576        assert_ne!(bursts, RandomSeed::stream("spawner", 7));
577        // Pinned so a replay recorded today draws the same values later.
578        assert_eq!(RandomSeed(42).value(3, bursts), 5_142_468_438_960_481_807);
579    }
580}