Skip to main content

sim_logic/application/
time.rs

1//! Validated frame and fixed-step timekeeping.
2
3use std::{error::Error, fmt, time::Duration};
4
5use bevy_ecs::{
6    prelude::{Res, Resource},
7    system::SystemParam,
8};
9
10/// Nearest nanosecond `Duration` representation of one sixtieth of a second.
11pub const DEFAULT_FIXED_STEP: Duration = Duration::from_nanos(16_666_667);
12
13/// Default maximum number of fixed ticks attempted in one application frame.
14pub const DEFAULT_MAX_CATCH_UP_TICKS: u32 = 8;
15
16/// Failure to construct or change fixed-step time configuration.
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub enum TimeConfigurationError {
19    /// A zero fixed step cannot advance simulation time.
20    ZeroFixedStep,
21    /// A zero catch-up limit would silently disable fixed simulation.
22    ZeroCatchUpLimit,
23    /// Time scale must be finite and non-negative.
24    InvalidTimeScale {
25        /// The rejected scale value.
26        value: f64,
27    },
28}
29
30impl fmt::Display for TimeConfigurationError {
31    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            Self::ZeroFixedStep => formatter.write_str("the fixed step must be positive"),
34            Self::ZeroCatchUpLimit => {
35                formatter.write_str("the maximum catch-up tick count must be positive")
36            }
37            Self::InvalidTimeScale { value } => write!(
38                formatter,
39                "time scale must be finite and non-negative, but received {value}"
40            ),
41        }
42    }
43}
44
45impl Error for TimeConfigurationError {}
46
47/// Validated fixed-step timing configuration.
48///
49/// The configuration is frozen before the runner starts. Pause and time scale
50/// may later be changed by the runtime without altering the fixed step or
51/// catch-up limit.
52#[derive(Debug, Clone, Copy, PartialEq)]
53pub struct TimeConfig {
54    fixed_step: Duration,
55    max_catch_up_ticks: u32,
56    time_scale: f64,
57}
58
59impl Default for TimeConfig {
60    fn default() -> Self {
61        Self {
62            fixed_step: DEFAULT_FIXED_STEP,
63            max_catch_up_ticks: DEFAULT_MAX_CATCH_UP_TICKS,
64            time_scale: 1.0,
65        }
66    }
67}
68
69impl TimeConfig {
70    /// Creates a configuration with time scale `1.0`.
71    pub fn new(
72        fixed_step: Duration,
73        max_catch_up_ticks: u32,
74    ) -> Result<Self, TimeConfigurationError> {
75        if fixed_step.is_zero() {
76            return Err(TimeConfigurationError::ZeroFixedStep);
77        }
78        if max_catch_up_ticks == 0 {
79            return Err(TimeConfigurationError::ZeroCatchUpLimit);
80        }
81
82        Ok(Self {
83            fixed_step,
84            max_catch_up_ticks,
85            time_scale: 1.0,
86        })
87    }
88
89    /// Returns the exact `Duration` supplied to every FixedUpdate tick.
90    pub const fn fixed_step(self) -> Duration {
91        self.fixed_step
92    }
93
94    /// Returns the maximum fixed ticks attempted in one application frame.
95    pub const fn max_catch_up_ticks(self) -> u32 {
96        self.max_catch_up_ticks
97    }
98
99    /// Returns the multiplier applied before wall delta enters the accumulator.
100    pub const fn time_scale(self) -> f64 {
101        self.time_scale
102    }
103
104    /// Sets the initial finite, non-negative simulation time scale.
105    ///
106    /// The configuration remains unchanged when validation fails.
107    pub fn set_time_scale(&mut self, time_scale: f64) -> Result<(), TimeConfigurationError> {
108        validate_time_scale(time_scale)?;
109        self.time_scale = normalize_zero(time_scale);
110        Ok(())
111    }
112
113    /// Returns this configuration with a validated initial time scale.
114    pub fn with_time_scale(mut self, time_scale: f64) -> Result<Self, TimeConfigurationError> {
115        self.set_time_scale(time_scale)?;
116        Ok(self)
117    }
118}
119
120/// Unscaled elapsed wall time accepted for one application frame.
121///
122/// FrameUpdate receives this value even while fixed simulation is paused.
123/// Time scale affects the fixed accumulator, not this presentation delta.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Resource)]
125pub(crate) struct FrameTimeState {
126    delta: Duration,
127    paused: bool,
128}
129
130impl FrameTimeState {
131    pub const fn delta(self) -> Duration {
132        self.delta
133    }
134
135    pub fn seconds(self) -> f64 {
136        self.delta.as_secs_f64()
137    }
138
139    #[inline]
140    pub fn seconds_f32(self) -> f32 {
141        self.delta.as_secs_f32()
142    }
143
144    pub const fn is_paused(self) -> bool {
145        self.paused
146    }
147
148    pub(crate) const fn new(delta: Duration, paused: bool) -> Self {
149        Self { delta, paused }
150    }
151}
152
153/// Read-only unscaled wall time for the current FrameUpdate.
154///
155/// This custom System parameter prevents systems from replacing the
156/// runtime-owned clock value through `ResMut`. It is not available during an
157/// active FixedUpdate stage.
158#[derive(SystemParam)]
159pub struct FrameTime<'w> {
160    state: Res<'w, FrameTimeState>,
161}
162
163impl FrameTime<'_> {
164    /// Returns the unscaled elapsed duration supplied by the runner.
165    pub fn delta(&self) -> Duration {
166        self.state.delta()
167    }
168
169    /// Returns the unscaled elapsed duration in seconds.
170    pub fn seconds(&self) -> f64 {
171        self.state.seconds()
172    }
173
174    /// Returns the unscaled elapsed duration using [`Duration::as_secs_f32`].
175    ///
176    /// This uses [`Duration::as_secs_f32`] rather than narrowing the result of
177    /// [`Self::seconds`]. It is convenient for Sim;Engine's `f32` geometry.
178    /// Use [`Self::seconds`] for wider floating-point arithmetic or
179    /// [`Self::delta`] for exact `Duration` operations.
180    #[inline]
181    pub fn seconds_f32(&self) -> f32 {
182        self.state.seconds_f32()
183    }
184
185    /// Returns whether fixed simulation was paused when FrameUpdate began.
186    ///
187    /// Pause changes queued by Systems in this same stage are deferred until
188    /// its Commands barrier, so every System sees the same entry snapshot.
189    pub fn is_paused(&self) -> bool {
190        self.state.is_paused()
191    }
192}
193
194/// Exact fixed delta and application-wide index for one FixedUpdate attempt.
195///
196/// The runtime consumes the tick before invoking systems. Its index therefore
197/// advances even when a later system fails after earlier systems mutated the
198/// World.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Resource)]
200pub(crate) struct FixedTimeState {
201    delta: Duration,
202    tick_index: u64,
203}
204
205impl FixedTimeState {
206    pub const fn delta(self) -> Duration {
207        self.delta
208    }
209
210    pub fn seconds(self) -> f64 {
211        self.delta.as_secs_f64()
212    }
213
214    #[inline]
215    pub fn seconds_f32(self) -> f32 {
216        self.delta.as_secs_f32()
217    }
218
219    pub const fn tick_index(self) -> u64 {
220        self.tick_index
221    }
222
223    pub(crate) const fn initial(delta: Duration) -> Self {
224        Self {
225            delta,
226            tick_index: 0,
227        }
228    }
229}
230
231/// Read-only exact fixed delta and application-wide tick index.
232///
233/// The runtime consumes the tick before invoking systems. Its index therefore
234/// advances even when a later system fails. This parameter is not available
235/// during FrameUpdate.
236#[derive(SystemParam)]
237pub struct FixedTime<'w> {
238    state: Res<'w, FixedTimeState>,
239}
240
241impl FixedTime<'_> {
242    /// Returns the exact configured fixed simulation delta.
243    pub fn delta(&self) -> Duration {
244        self.state.delta()
245    }
246
247    /// Returns the exact fixed simulation delta in seconds.
248    pub fn seconds(&self) -> f64 {
249        self.state.seconds()
250    }
251
252    /// Returns the configured fixed-step delta using [`Duration::as_secs_f32`].
253    ///
254    /// This uses [`Duration::as_secs_f32`] rather than narrowing the result of
255    /// [`Self::seconds`]. It is convenient for Sim;Engine's `f32` geometry.
256    /// Use [`Self::seconds`] for wider floating-point arithmetic or
257    /// [`Self::delta`] for exact `Duration` operations.
258    #[inline]
259    pub fn seconds_f32(&self) -> f32 {
260        self.state.seconds_f32()
261    }
262
263    /// Returns the zero-based application-wide index of this fixed tick.
264    pub fn tick_index(&self) -> u64 {
265        self.state.tick_index()
266    }
267}
268
269/// Failure while scaling or accumulating a supplied frame delta.
270#[derive(Debug, Clone, Copy, PartialEq)]
271pub enum TimeAdvanceError {
272    /// Multiplying the wall delta by time scale cannot produce a `Duration`.
273    ScaledDeltaOutOfRange {
274        /// Unscaled wall delta supplied by the runner.
275        elapsed: Duration,
276        /// Configured multiplier used for fixed simulation.
277        time_scale: f64,
278    },
279    /// Adding the scaled delta would exceed `Duration` capacity.
280    AccumulatorOverflow,
281    /// Internal duration accounting exceeded the representable range.
282    DurationAccountingOverflow,
283}
284
285impl fmt::Display for TimeAdvanceError {
286    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
287        match self {
288            Self::ScaledDeltaOutOfRange {
289                elapsed,
290                time_scale,
291            } => write!(
292                formatter,
293                "scaling frame delta {elapsed:?} by {time_scale} cannot produce a Duration"
294            ),
295            Self::AccumulatorOverflow => {
296                formatter.write_str("the fixed-step accumulator would overflow")
297            }
298            Self::DurationAccountingOverflow => {
299                formatter.write_str("fixed-step duration accounting overflowed")
300            }
301        }
302    }
303}
304
305impl Error for TimeAdvanceError {}
306
307/// Planned and dropped fixed work for one application frame.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct FixedFramePlan {
310    ticks_to_attempt: u32,
311    dropped_ticks: u128,
312    dropped_time: Duration,
313    scaled_delta: Duration,
314}
315
316impl FixedFramePlan {
317    /// Returns the fixed ticks the runtime may attempt in this frame.
318    pub const fn ticks_to_attempt(self) -> u32 {
319        self.ticks_to_attempt
320    }
321
322    /// Returns the complete fixed ticks removed by bounded catch-up.
323    pub const fn dropped_ticks(self) -> u128 {
324        self.dropped_ticks
325    }
326
327    /// Returns the simulation duration removed by bounded catch-up.
328    pub const fn dropped_time(self) -> Duration {
329        self.dropped_time
330    }
331
332    /// Returns the wall delta after applying time scale.
333    pub const fn scaled_delta(self) -> Duration {
334        self.scaled_delta
335    }
336}
337
338/// Fixed simulation time explicitly discarded after update planning.
339///
340/// The first slice uses this report when a pending transition stops catch-up
341/// but arbitration rejects the transition as malformed or conflicting. Whole
342/// ticks are discarded so the retained accumulator is again a valid
343/// interpolation remainder.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct DroppedFixedTime {
346    ticks: u128,
347    duration: Duration,
348}
349
350impl DroppedFixedTime {
351    /// Returns the number of complete fixed ticks that were discarded.
352    pub const fn ticks(self) -> u128 {
353        self.ticks
354    }
355
356    /// Returns the total fixed simulation duration that was discarded.
357    pub const fn duration(self) -> Duration {
358        self.duration
359    }
360}
361
362/// Failure to begin one of the fixed ticks planned for the current frame.
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub enum FixedTickError {
365    /// Fixed execution is paused.
366    Paused,
367    /// No planned fixed tick remains in the current frame.
368    NoPlannedTick,
369    /// The application-wide fixed tick index cannot advance further.
370    TickIndexExhausted,
371}
372
373impl fmt::Display for FixedTickError {
374    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
375        match self {
376            Self::Paused => formatter.write_str("fixed simulation is paused"),
377            Self::NoPlannedTick => {
378                formatter.write_str("no planned fixed tick remains in this frame")
379            }
380            Self::TickIndexExhausted => formatter.write_str("the fixed tick index is exhausted"),
381        }
382    }
383}
384
385impl Error for FixedTickError {}
386
387#[derive(Debug, Clone)]
388pub(crate) struct TimeState {
389    config: TimeConfig,
390    paused: bool,
391    accumulator: Duration,
392    next_tick_index: u64,
393    remaining_planned_ticks: u32,
394}
395
396impl TimeState {
397    pub(crate) fn new(config: TimeConfig) -> Self {
398        Self {
399            config,
400            paused: false,
401            accumulator: Duration::ZERO,
402            next_tick_index: 0,
403            remaining_planned_ticks: 0,
404        }
405    }
406
407    pub(crate) fn frame_time(&self, elapsed: Duration) -> FrameTimeState {
408        FrameTimeState::new(elapsed, self.paused)
409    }
410
411    pub(crate) fn plan_frame(
412        &mut self,
413        elapsed: Duration,
414    ) -> Result<FixedFramePlan, TimeAdvanceError> {
415        if self.paused {
416            self.remaining_planned_ticks = 0;
417            return Ok(FixedFramePlan {
418                ticks_to_attempt: 0,
419                dropped_ticks: 0,
420                dropped_time: Duration::ZERO,
421                scaled_delta: Duration::ZERO,
422            });
423        }
424
425        let scaled_delta = scale_duration(elapsed, self.config.time_scale)?;
426        let accumulated = self
427            .accumulator
428            .checked_add(scaled_delta)
429            .ok_or(TimeAdvanceError::AccumulatorOverflow)?;
430
431        let step_nanoseconds = self.config.fixed_step.as_nanos();
432        let accumulated_nanoseconds = accumulated.as_nanos();
433        let available_ticks = accumulated_nanoseconds / step_nanoseconds;
434        let maximum_ticks = u128::from(self.config.max_catch_up_ticks);
435        let planned_u128 = available_ticks.min(maximum_ticks);
436        let planned_ticks = u32::try_from(planned_u128)
437            .map_err(|_| TimeAdvanceError::DurationAccountingOverflow)?;
438        let dropped_ticks = available_ticks - planned_u128;
439        let dropped_nanoseconds = dropped_ticks
440            .checked_mul(step_nanoseconds)
441            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
442        let retained_nanoseconds = accumulated_nanoseconds
443            .checked_sub(dropped_nanoseconds)
444            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
445        let retained = duration_from_nanoseconds(retained_nanoseconds)
446            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
447        let dropped_time = duration_from_nanoseconds(dropped_nanoseconds)
448            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
449
450        self.accumulator = retained;
451        self.remaining_planned_ticks = planned_ticks;
452
453        Ok(FixedFramePlan {
454            ticks_to_attempt: planned_ticks,
455            dropped_ticks,
456            dropped_time,
457            scaled_delta,
458        })
459    }
460
461    pub(crate) fn begin_fixed_tick(&mut self) -> Result<FixedTimeState, FixedTickError> {
462        if self.paused {
463            return Err(FixedTickError::Paused);
464        }
465        if self.remaining_planned_ticks == 0 || self.accumulator < self.config.fixed_step {
466            return Err(FixedTickError::NoPlannedTick);
467        }
468
469        let Some(next_tick_index) = self.next_tick_index.checked_add(1) else {
470            return Err(FixedTickError::TickIndexExhausted);
471        };
472
473        let fixed_time = FixedTimeState {
474            delta: self.config.fixed_step,
475            tick_index: self.next_tick_index,
476        };
477        self.accumulator -= self.config.fixed_step;
478        self.remaining_planned_ticks -= 1;
479        self.next_tick_index = next_tick_index;
480        Ok(fixed_time)
481    }
482
483    pub(crate) fn stop_remaining_ticks(&mut self) {
484        self.remaining_planned_ticks = 0;
485    }
486
487    pub(crate) fn drop_remaining_whole_ticks(
488        &mut self,
489    ) -> Result<DroppedFixedTime, TimeAdvanceError> {
490        let step_nanoseconds = self.config.fixed_step.as_nanos();
491        let accumulated_nanoseconds = self.accumulator.as_nanos();
492        let dropped_ticks = accumulated_nanoseconds / step_nanoseconds;
493        let dropped_nanoseconds = dropped_ticks
494            .checked_mul(step_nanoseconds)
495            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
496        let remainder_nanoseconds = accumulated_nanoseconds
497            .checked_sub(dropped_nanoseconds)
498            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
499        let remainder = duration_from_nanoseconds(remainder_nanoseconds)
500            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
501        let duration = duration_from_nanoseconds(dropped_nanoseconds)
502            .ok_or(TimeAdvanceError::DurationAccountingOverflow)?;
503
504        self.accumulator = remainder;
505        self.remaining_planned_ticks = 0;
506
507        Ok(DroppedFixedTime {
508            ticks: dropped_ticks,
509            duration,
510        })
511    }
512
513    pub(crate) fn clear_accumulator(&mut self) {
514        self.accumulator = Duration::ZERO;
515        self.remaining_planned_ticks = 0;
516    }
517
518    pub(crate) fn set_paused(&mut self, paused: bool) {
519        self.paused = paused;
520        if paused {
521            self.remaining_planned_ticks = 0;
522        }
523    }
524
525    pub(crate) const fn is_paused(&self) -> bool {
526        self.paused
527    }
528
529    pub(crate) fn set_time_scale(&mut self, time_scale: f64) -> Result<(), TimeConfigurationError> {
530        self.config.set_time_scale(time_scale)
531    }
532
533    #[cfg(test)]
534    pub(crate) fn accumulator(&self) -> Duration {
535        self.accumulator
536    }
537
538    #[cfg(test)]
539    pub(crate) fn remaining_planned_ticks(&self) -> u32 {
540        self.remaining_planned_ticks
541    }
542
543    pub(crate) fn interpolation_alpha(&self) -> Option<f64> {
544        if self.paused {
545            return Some(0.0);
546        }
547        if self.accumulator >= self.config.fixed_step {
548            return None;
549        }
550
551        Some(self.accumulator.as_secs_f64() / self.config.fixed_step.as_secs_f64())
552    }
553}
554
555fn validate_time_scale(time_scale: f64) -> Result<(), TimeConfigurationError> {
556    if !time_scale.is_finite() || time_scale < 0.0 {
557        return Err(TimeConfigurationError::InvalidTimeScale { value: time_scale });
558    }
559    Ok(())
560}
561
562fn normalize_zero(value: f64) -> f64 {
563    if value == 0.0 { 0.0 } else { value }
564}
565
566fn scale_duration(elapsed: Duration, time_scale: f64) -> Result<Duration, TimeAdvanceError> {
567    if time_scale == 0.0 {
568        return Ok(Duration::ZERO);
569    }
570    if time_scale == 1.0 {
571        return Ok(elapsed);
572    }
573
574    let scaled_seconds = elapsed.as_secs_f64() * time_scale;
575    Duration::try_from_secs_f64(scaled_seconds).map_err(|_| {
576        TimeAdvanceError::ScaledDeltaOutOfRange {
577            elapsed,
578            time_scale,
579        }
580    })
581}
582
583fn duration_from_nanoseconds(nanoseconds: u128) -> Option<Duration> {
584    const NANOS_PER_SECOND: u128 = 1_000_000_000;
585
586    let seconds = u64::try_from(nanoseconds / NANOS_PER_SECOND).ok()?;
587    let subsecond_nanoseconds = u32::try_from(nanoseconds % NANOS_PER_SECOND).ok()?;
588    Some(Duration::new(seconds, subsecond_nanoseconds))
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    fn config(step_milliseconds: u64, maximum_ticks: u32) -> TimeConfig {
596        let result = TimeConfig::new(Duration::from_millis(step_milliseconds), maximum_ticks);
597        let Ok(config) = result else {
598            panic!("test time configuration should be valid");
599        };
600        config
601    }
602
603    #[test]
604    fn defaults_are_one_sixtieth_and_eight_ticks() {
605        let config = TimeConfig::default();
606
607        assert_eq!(config.fixed_step(), Duration::from_nanos(16_666_667));
608        assert_eq!(config.max_catch_up_ticks(), 8);
609        assert_eq!(config.time_scale(), 1.0);
610    }
611
612    #[test]
613    fn time_states_follow_the_standard_duration_float_conversions_exactly() {
614        let durations = [
615            Duration::ZERO,
616            Duration::from_nanos(1),
617            DEFAULT_FIXED_STEP,
618            Duration::new(42, 987_654_321),
619            Duration::MAX,
620        ];
621
622        for duration in durations {
623            let frame = FrameTimeState::new(duration, false);
624            let fixed = FixedTimeState::initial(duration);
625            assert_eq!(frame.seconds().to_bits(), duration.as_secs_f64().to_bits());
626            assert_eq!(fixed.seconds().to_bits(), duration.as_secs_f64().to_bits());
627            assert_eq!(
628                frame.seconds_f32().to_bits(),
629                duration.as_secs_f32().to_bits()
630            );
631            assert_eq!(
632                fixed.seconds_f32().to_bits(),
633                duration.as_secs_f32().to_bits()
634            );
635            assert!(!frame.is_paused());
636        }
637
638        assert!(FrameTimeState::new(Duration::ZERO, true).is_paused());
639
640        let direct_rounding_witness = Duration::new(0, 16_874_317);
641        assert_ne!(
642            direct_rounding_witness.as_secs_f32().to_bits(),
643            (direct_rounding_witness.as_secs_f64() as f32).to_bits()
644        );
645    }
646
647    #[test]
648    fn invalid_configuration_is_rejected() {
649        assert_eq!(
650            TimeConfig::new(Duration::ZERO, 8),
651            Err(TimeConfigurationError::ZeroFixedStep)
652        );
653        assert_eq!(
654            TimeConfig::new(Duration::from_millis(1), 0),
655            Err(TimeConfigurationError::ZeroCatchUpLimit)
656        );
657
658        let mut config = TimeConfig::default();
659        assert!(matches!(
660            config.set_time_scale(f64::NAN),
661            Err(TimeConfigurationError::InvalidTimeScale { .. })
662        ));
663        assert!(matches!(
664            config.set_time_scale(-1.0),
665            Err(TimeConfigurationError::InvalidTimeScale { .. })
666        ));
667        assert_eq!(config.time_scale(), 1.0);
668    }
669
670    #[test]
671    fn accumulator_plans_zero_one_and_multiple_ticks() {
672        let mut time = TimeState::new(config(10, 8));
673
674        let first = time.plan_frame(Duration::from_millis(5));
675        let Ok(first) = first else {
676            panic!("small frame should be representable");
677        };
678        assert_eq!(first.ticks_to_attempt(), 0);
679        assert_eq!(time.interpolation_alpha(), Some(0.5));
680
681        let second = time.plan_frame(Duration::from_millis(5));
682        let Ok(second) = second else {
683            panic!("second frame should be representable");
684        };
685        assert_eq!(second.ticks_to_attempt(), 1);
686        let tick = time.begin_fixed_tick();
687        let Ok(tick) = tick else {
688            panic!("one fixed tick should be planned");
689        };
690        assert_eq!(tick.tick_index(), 0);
691        assert_eq!(time.accumulator(), Duration::ZERO);
692
693        let third = time.plan_frame(Duration::from_millis(25));
694        let Ok(third) = third else {
695            panic!("multi-tick frame should be representable");
696        };
697        assert_eq!(third.ticks_to_attempt(), 2);
698    }
699
700    #[test]
701    fn catch_up_is_bounded_and_reports_dropped_time() {
702        let mut time = TimeState::new(config(10, 3));
703        let plan = time.plan_frame(Duration::from_millis(105));
704        let Ok(plan) = plan else {
705            panic!("bounded frame should be representable");
706        };
707
708        assert_eq!(plan.ticks_to_attempt(), 3);
709        assert_eq!(plan.dropped_ticks(), 7);
710        assert_eq!(plan.dropped_time(), Duration::from_millis(70));
711        assert_eq!(time.accumulator(), Duration::from_millis(35));
712
713        for _ in 0..3 {
714            assert!(time.begin_fixed_tick().is_ok());
715        }
716        assert_eq!(time.accumulator(), Duration::from_millis(5));
717        assert_eq!(time.interpolation_alpha(), Some(0.5));
718    }
719
720    #[test]
721    fn beginning_a_tick_consumes_it_even_if_systems_later_fail() {
722        let mut time = TimeState::new(config(10, 8));
723        assert!(time.plan_frame(Duration::from_millis(25)).is_ok());
724
725        let attempted = time.begin_fixed_tick();
726        let Ok(attempted) = attempted else {
727            panic!("the first fixed tick should begin");
728        };
729        assert_eq!(attempted.tick_index(), 0);
730
731        // This is the runtime action after a failed system: no rollback of the
732        // consumed tick, while the remaining accumulated time is preserved.
733        time.stop_remaining_ticks();
734        assert_eq!(time.accumulator(), Duration::from_millis(15));
735        assert_eq!(time.remaining_planned_ticks(), 0);
736
737        let next_plan = time.plan_frame(Duration::ZERO);
738        let Ok(next_plan) = next_plan else {
739            panic!("preserved accumulated time should remain representable");
740        };
741        assert_eq!(next_plan.ticks_to_attempt(), 1);
742        let next_tick = time.begin_fixed_tick();
743        let Ok(next_tick) = next_tick else {
744            panic!("the preserved fixed tick should be attempted later");
745        };
746        assert_eq!(next_tick.tick_index(), 1);
747        assert_eq!(time.accumulator(), Duration::from_millis(5));
748    }
749
750    #[test]
751    fn pause_freezes_accumulated_time_and_accepts_no_fixed_work() {
752        let mut time = TimeState::new(config(10, 8));
753        assert!(time.plan_frame(Duration::from_millis(5)).is_ok());
754        time.set_paused(true);
755
756        let paused = time.plan_frame(Duration::from_secs(1));
757        let Ok(paused) = paused else {
758            panic!("paused frame should not scale wall time");
759        };
760        assert_eq!(paused.ticks_to_attempt(), 0);
761        assert_eq!(time.accumulator(), Duration::from_millis(5));
762        assert_eq!(time.begin_fixed_tick(), Err(FixedTickError::Paused));
763
764        time.set_paused(false);
765        assert!(time.plan_frame(Duration::from_millis(5)).is_ok());
766        assert!(time.begin_fixed_tick().is_ok());
767        assert_eq!(time.accumulator(), Duration::ZERO);
768    }
769
770    #[test]
771    fn paused_interpolation_is_defined_even_with_a_whole_tick_retained() {
772        let mut time = TimeState::new(config(10, 8));
773        assert!(time.plan_frame(Duration::from_millis(25)).is_ok());
774        assert!(time.begin_fixed_tick().is_ok());
775        time.stop_remaining_ticks();
776        assert_eq!(time.interpolation_alpha(), None);
777
778        time.set_paused(true);
779
780        assert_eq!(time.accumulator(), Duration::from_millis(15));
781        assert_eq!(time.interpolation_alpha(), Some(0.0));
782    }
783
784    #[test]
785    fn time_scale_changes_accumulator_input_not_frame_time() {
786        let mut time = TimeState::new(config(10, 8));
787        assert!(time.set_time_scale(2.0).is_ok());
788
789        let elapsed = Duration::from_millis(6);
790        let plan = time.plan_frame(elapsed);
791        let Ok(plan) = plan else {
792            panic!("scaled frame should be representable");
793        };
794        assert_eq!(plan.scaled_delta(), Duration::from_millis(12));
795        assert_eq!(plan.ticks_to_attempt(), 1);
796        assert_eq!(time.frame_time(elapsed).delta(), elapsed);
797    }
798
799    #[test]
800    fn reset_discards_accumulated_and_planned_work() {
801        let mut time = TimeState::new(config(10, 8));
802        assert!(time.plan_frame(Duration::from_millis(25)).is_ok());
803
804        time.clear_accumulator();
805
806        assert_eq!(time.accumulator(), Duration::ZERO);
807        assert_eq!(time.remaining_planned_ticks(), 0);
808        assert_eq!(time.interpolation_alpha(), Some(0.0));
809    }
810
811    #[test]
812    fn interpolation_is_unavailable_while_whole_ticks_remain() {
813        let mut time = TimeState::new(config(10, 8));
814        assert!(time.plan_frame(Duration::from_millis(25)).is_ok());
815        assert_eq!(time.interpolation_alpha(), None);
816
817        assert!(time.begin_fixed_tick().is_ok());
818        assert!(time.begin_fixed_tick().is_ok());
819        assert_eq!(time.interpolation_alpha(), Some(0.5));
820    }
821
822    #[test]
823    fn rejected_transition_drops_whole_ticks_and_preserves_remainder() {
824        let mut time = TimeState::new(config(10, 8));
825        assert!(time.plan_frame(Duration::from_millis(35)).is_ok());
826        assert!(time.begin_fixed_tick().is_ok());
827        time.stop_remaining_ticks();
828
829        let dropped = time.drop_remaining_whole_ticks();
830        let Ok(dropped) = dropped else {
831            panic!("remaining fixed time should be representable");
832        };
833
834        assert_eq!(dropped.ticks(), 2);
835        assert_eq!(dropped.duration(), Duration::from_millis(20));
836        assert_eq!(time.accumulator(), Duration::from_millis(5));
837        assert_eq!(time.remaining_planned_ticks(), 0);
838        assert_eq!(time.interpolation_alpha(), Some(0.5));
839    }
840}