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