1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use bevy_app::FixedMain;
use bevy_ecs::world::World;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use bevy_utils::Duration;

use crate::{time::Time, virt::Virtual};

/// The fixed timestep game clock following virtual time.
///
/// A specialization of the [`Time`] structure. **For method documentation, see
/// [`Time<Fixed>#impl-Time<Fixed>`].**
///     
/// It is automatically inserted as a resource by
/// [`TimePlugin`](crate::TimePlugin) and updated based on
/// [`Time<Virtual>`](Virtual). The fixed clock is automatically set as the
/// generic [`Time`] resource during [`FixedUpdate`](bevy_app::FixedUpdate)
/// schedule processing.
///
/// The fixed timestep clock advances in fixed-size increments, which is
/// extremely useful for writing logic (like physics) that should have
/// consistent behavior, regardless of framerate.
///
/// The default [`timestep()`](Time::timestep) is 64 hertz, or 15625
/// microseconds. This value was chosen because using 60 hertz has the potential
/// for a pathological interaction with the monitor refresh rate where the game
/// alternates between running two fixed timesteps and zero fixed timesteps per
/// frame (for example when running two fixed timesteps takes longer than a
/// frame). Additionally, the value is a power of two which losslessly converts
/// into [`f32`] and [`f64`].
///
/// To run a system on a fixed timestep, add it to one of the [`FixedMain`]
/// schedules, most commonly [`FixedUpdate`](bevy_app::FixedUpdate).
///
/// This schedule is run a number of times between
/// [`PreUpdate`](bevy_app::PreUpdate) and [`Update`](bevy_app::Update)
/// according to the accumulated [`overstep()`](Time::overstep) time divided by
/// the [`timestep()`](Time::timestep). This means the schedule may run 0, 1 or
/// more times during a single update (which typically corresponds to a rendered
/// frame).
///
/// `Time<Fixed>` and the generic [`Time`] resource will report a
/// [`delta()`](Time::delta) equal to [`timestep()`](Time::timestep) and always
/// grow [`elapsed()`](Time::elapsed) by one [`timestep()`](Time::timestep) per
/// iteration.
///
/// The fixed timestep clock follows the [`Time<Virtual>`](Virtual) clock, which
/// means it is affected by [`pause()`](Time::pause),
/// [`set_relative_speed()`](Time::set_relative_speed) and
/// [`set_max_delta()`](Time::set_max_delta) from virtual time. If the virtual
/// clock is paused, the [`FixedUpdate`](bevy_app::FixedUpdate) schedule will
/// not run. It is guaranteed that the [`elapsed()`](Time::elapsed) time in
/// `Time<Fixed>` is always between the previous `elapsed()` and the current
/// `elapsed()` value in `Time<Virtual>`, so the values are compatible.
///
/// Changing the timestep size while the game is running should not normally be
/// done, as having a regular interval is the point of this schedule, but it may
/// be necessary for effects like "bullet-time" if the normal granularity of the
/// fixed timestep is too big for the slowed down time. In this case,
/// [`set_timestep()`](Time::set_timestep) and be called to set a new value. The
/// new value will be used immediately for the next run of the
/// [`FixedUpdate`](bevy_app::FixedUpdate) schedule, meaning that it will affect
/// the [`delta()`](Time::delta) value for the very next
/// [`FixedUpdate`](bevy_app::FixedUpdate), even if it is still during the same
/// frame. Any [`overstep()`](Time::overstep) present in the accumulator will be
/// processed according to the new [`timestep()`](Time::timestep) value.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct Fixed {
    timestep: Duration,
    overstep: Duration,
}

impl Time<Fixed> {
    /// Corresponds to 64 Hz.
    const DEFAULT_TIMESTEP: Duration = Duration::from_micros(15625);

    /// Return new fixed time clock with given timestep as [`Duration`]
    ///
    /// # Panics
    ///
    /// Panics if `timestep` is zero.
    pub fn from_duration(timestep: Duration) -> Self {
        let mut ret = Self::default();
        ret.set_timestep(timestep);
        ret
    }

    /// Return new fixed time clock with given timestep seconds as `f64`
    ///
    /// # Panics
    ///
    /// Panics if `seconds` is zero, negative or not finite.
    pub fn from_seconds(seconds: f64) -> Self {
        let mut ret = Self::default();
        ret.set_timestep_seconds(seconds);
        ret
    }

    /// Return new fixed time clock with given timestep frequency in Hertz (1/seconds)
    ///
    /// # Panics
    ///
    /// Panics if `hz` is zero, negative or not finite.
    pub fn from_hz(hz: f64) -> Self {
        let mut ret = Self::default();
        ret.set_timestep_hz(hz);
        ret
    }

    /// Returns the amount of virtual time that must pass before the fixed
    /// timestep schedule is run again.
    #[inline]
    pub fn timestep(&self) -> Duration {
        self.context().timestep
    }

    /// Sets the amount of virtual time that must pass before the fixed timestep
    /// schedule is run again, as [`Duration`].
    ///
    /// Takes effect immediately on the next run of the schedule, respecting
    /// what is currently in [`Self::overstep`].
    ///
    /// # Panics
    ///
    /// Panics if `timestep` is zero.
    #[inline]
    pub fn set_timestep(&mut self, timestep: Duration) {
        assert_ne!(
            timestep,
            Duration::ZERO,
            "attempted to set fixed timestep to zero"
        );
        self.context_mut().timestep = timestep;
    }

    /// Sets the amount of virtual time that must pass before the fixed timestep
    /// schedule is run again, as seconds.
    ///
    /// Timestep is stored as a [`Duration`], which has fixed nanosecond
    /// resolution and will be converted from the floating point number.
    ///
    /// Takes effect immediately on the next run of the schedule, respecting
    /// what is currently in [`Self::overstep`].
    ///
    /// # Panics
    ///
    /// Panics if `seconds` is zero, negative or not finite.
    #[inline]
    pub fn set_timestep_seconds(&mut self, seconds: f64) {
        assert!(
            seconds.is_sign_positive(),
            "seconds less than or equal to zero"
        );
        assert!(seconds.is_finite(), "seconds is infinite");
        self.set_timestep(Duration::from_secs_f64(seconds));
    }

    /// Sets the amount of virtual time that must pass before the fixed timestep
    /// schedule is run again, as frequency.
    ///
    /// The timestep value is set to `1 / hz`, converted to a [`Duration`] which
    /// has fixed nanosecond resolution.
    ///
    /// Takes effect immediately on the next run of the schedule, respecting
    /// what is currently in [`Self::overstep`].
    ///
    /// # Panics
    ///
    /// Panics if `hz` is zero, negative or not finite.
    #[inline]
    pub fn set_timestep_hz(&mut self, hz: f64) {
        assert!(hz.is_sign_positive(), "Hz less than or equal to zero");
        assert!(hz.is_finite(), "Hz is infinite");
        self.set_timestep_seconds(1.0 / hz);
    }

    /// Returns the amount of overstep time accumulated toward new steps, as
    /// [`Duration`].
    #[inline]
    pub fn overstep(&self) -> Duration {
        self.context().overstep
    }

    /// Discard a part of the overstep amount.
    ///
    /// If `discard` is higher than overstep, the overstep becomes zero.
    #[inline]
    pub fn discard_overstep(&mut self, discard: Duration) {
        let context = self.context_mut();
        context.overstep = context.overstep.saturating_sub(discard);
    }

    /// Returns the amount of overstep time accumulated toward new steps, as an
    /// [`f32`] fraction of the timestep.
    #[inline]
    pub fn overstep_fraction(&self) -> f32 {
        self.context().overstep.as_secs_f32() / self.context().timestep.as_secs_f32()
    }

    /// Returns the amount of overstep time accumulated toward new steps, as an
    /// [`f64`] fraction of the timestep.
    #[inline]
    pub fn overstep_fraction_f64(&self) -> f64 {
        self.context().overstep.as_secs_f64() / self.context().timestep.as_secs_f64()
    }

    fn accumulate(&mut self, delta: Duration) {
        self.context_mut().overstep += delta;
    }

    fn expend(&mut self) -> bool {
        let timestep = self.timestep();
        if let Some(new_value) = self.context_mut().overstep.checked_sub(timestep) {
            // reduce accumulated and increase elapsed by period
            self.context_mut().overstep = new_value;
            self.advance_by(timestep);
            true
        } else {
            // no more periods left in accumulated
            false
        }
    }
}

impl Default for Fixed {
    fn default() -> Self {
        Self {
            timestep: Time::<Fixed>::DEFAULT_TIMESTEP,
            overstep: Duration::ZERO,
        }
    }
}

/// Runs [`FixedMain`] zero or more times based on delta of
/// [`Time<Virtual>`](Virtual) and [`Time::overstep`]
pub fn run_fixed_main_schedule(world: &mut World) {
    let delta = world.resource::<Time<Virtual>>().delta();
    world.resource_mut::<Time<Fixed>>().accumulate(delta);

    // Run the schedule until we run out of accumulated time
    let _ = world.try_schedule_scope(FixedMain, |world, schedule| {
        while world.resource_mut::<Time<Fixed>>().expend() {
            *world.resource_mut::<Time>() = world.resource::<Time<Fixed>>().as_generic();
            schedule.run(world);
        }
    });

    *world.resource_mut::<Time>() = world.resource::<Time<Virtual>>().as_generic();
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_set_timestep() {
        let mut time = Time::<Fixed>::default();

        assert_eq!(time.timestep(), Time::<Fixed>::DEFAULT_TIMESTEP);

        time.set_timestep(Duration::from_millis(500));
        assert_eq!(time.timestep(), Duration::from_millis(500));

        time.set_timestep_seconds(0.25);
        assert_eq!(time.timestep(), Duration::from_millis(250));

        time.set_timestep_hz(8.0);
        assert_eq!(time.timestep(), Duration::from_millis(125));
    }

    #[test]
    fn test_expend() {
        let mut time = Time::<Fixed>::from_seconds(2.0);

        assert_eq!(time.delta(), Duration::ZERO);
        assert_eq!(time.elapsed(), Duration::ZERO);

        time.accumulate(Duration::from_secs(1));

        assert_eq!(time.delta(), Duration::ZERO);
        assert_eq!(time.elapsed(), Duration::ZERO);
        assert_eq!(time.overstep(), Duration::from_secs(1));
        assert_eq!(time.overstep_fraction(), 0.5);
        assert_eq!(time.overstep_fraction_f64(), 0.5);

        assert!(!time.expend()); // false

        assert_eq!(time.delta(), Duration::ZERO);
        assert_eq!(time.elapsed(), Duration::ZERO);
        assert_eq!(time.overstep(), Duration::from_secs(1));
        assert_eq!(time.overstep_fraction(), 0.5);
        assert_eq!(time.overstep_fraction_f64(), 0.5);

        time.accumulate(Duration::from_secs(1));

        assert_eq!(time.delta(), Duration::ZERO);
        assert_eq!(time.elapsed(), Duration::ZERO);
        assert_eq!(time.overstep(), Duration::from_secs(2));
        assert_eq!(time.overstep_fraction(), 1.0);
        assert_eq!(time.overstep_fraction_f64(), 1.0);

        assert!(time.expend()); // true

        assert_eq!(time.delta(), Duration::from_secs(2));
        assert_eq!(time.elapsed(), Duration::from_secs(2));
        assert_eq!(time.overstep(), Duration::ZERO);
        assert_eq!(time.overstep_fraction(), 0.0);
        assert_eq!(time.overstep_fraction_f64(), 0.0);

        assert!(!time.expend()); // false

        assert_eq!(time.delta(), Duration::from_secs(2));
        assert_eq!(time.elapsed(), Duration::from_secs(2));
        assert_eq!(time.overstep(), Duration::ZERO);
        assert_eq!(time.overstep_fraction(), 0.0);
        assert_eq!(time.overstep_fraction_f64(), 0.0);

        time.accumulate(Duration::from_secs(1));

        assert_eq!(time.delta(), Duration::from_secs(2));
        assert_eq!(time.elapsed(), Duration::from_secs(2));
        assert_eq!(time.overstep(), Duration::from_secs(1));
        assert_eq!(time.overstep_fraction(), 0.5);
        assert_eq!(time.overstep_fraction_f64(), 0.5);

        assert!(!time.expend()); // false

        assert_eq!(time.delta(), Duration::from_secs(2));
        assert_eq!(time.elapsed(), Duration::from_secs(2));
        assert_eq!(time.overstep(), Duration::from_secs(1));
        assert_eq!(time.overstep_fraction(), 0.5);
        assert_eq!(time.overstep_fraction_f64(), 0.5);
    }

    #[test]
    fn test_expend_multiple() {
        let mut time = Time::<Fixed>::from_seconds(2.0);

        time.accumulate(Duration::from_secs(7));
        assert_eq!(time.overstep(), Duration::from_secs(7));

        assert!(time.expend()); // true
        assert_eq!(time.elapsed(), Duration::from_secs(2));
        assert_eq!(time.overstep(), Duration::from_secs(5));

        assert!(time.expend()); // true
        assert_eq!(time.elapsed(), Duration::from_secs(4));
        assert_eq!(time.overstep(), Duration::from_secs(3));

        assert!(time.expend()); // true
        assert_eq!(time.elapsed(), Duration::from_secs(6));
        assert_eq!(time.overstep(), Duration::from_secs(1));

        assert!(!time.expend()); // false
        assert_eq!(time.elapsed(), Duration::from_secs(6));
        assert_eq!(time.overstep(), Duration::from_secs(1));
    }
}