bevy/crates/bevy_time/src/real.rs

221 lines
7.9 KiB
Rust
Raw Normal View History

Unify `FixedTime` and `Time` while fixing several problems (#8964) # Objective Current `FixedTime` and `Time` have several problems. This pull aims to fix many of them at once. - If there is a longer pause between app updates, time will jump forward a lot at once and fixed time will iterate on `FixedUpdate` for a large number of steps. If the pause is merely seconds, then this will just mean jerkiness and possible unexpected behaviour in gameplay. If the pause is hours/days as with OS suspend, the game will appear to freeze until it has caught up with real time. - If calculating a fixed step takes longer than specified fixed step period, the game will enter a death spiral where rendering each frame takes longer and longer due to more and more fixed step updates being run per frame and the game appears to freeze. - There is no way to see current fixed step elapsed time inside fixed steps. In order to track this, the game designer needs to add a custom system inside `FixedUpdate` that calculates elapsed or step count in a resource. - Access to delta time inside fixed step is `FixedStep::period` rather than `Time::delta`. This, coupled with the issue that `Time::elapsed` isn't available at all for fixed steps, makes it that time requiring systems are either implemented to be run in `FixedUpdate` or `Update`, but rarely work in both. - Fixes #8800 - Fixes #8543 - Fixes #7439 - Fixes #5692 ## Solution - Create a generic `Time<T>` clock that has no processing logic but which can be instantiated for multiple usages. This is also exposed for users to add custom clocks. - Create three standard clocks, `Time<Real>`, `Time<Virtual>` and `Time<Fixed>`, all of which contain their individual logic. - Create one "default" clock, which is just `Time` (or `Time<()>`), which will be overwritten from `Time<Virtual>` on each update, and `Time<Fixed>` inside `FixedUpdate` schedule. This way systems that do not care specifically which time they track can work both in `Update` and `FixedUpdate` without changes and the behaviour is intuitive. - Add `max_delta` to virtual time update, which limits how much can be added to virtual time by a single update. This fixes both the behaviour after a long freeze, and also the death spiral by limiting how many fixed timestep iterations there can be per update. Possible future work could be adding `max_accumulator` to add a sort of "leaky bucket" time processing to possibly smooth out jumps in time while keeping frame rate stable. - Many minor tweaks and clarifications to the time functions and their documentation. ## Changelog - `Time::raw_delta()`, `Time::raw_elapsed()` and related methods are moved to `Time<Real>::delta()` and `Time<Real>::elapsed()` and now match `Time` API - `FixedTime` is now `Time<Fixed>` and matches `Time` API. - `Time<Fixed>` default timestep is now 64 Hz, or 15625 microseconds. - `Time` inside `FixedUpdate` now reflects fixed timestep time, making systems portable between `Update ` and `FixedUpdate`. - `Time::pause()`, `Time::set_relative_speed()` and related methods must now be called as `Time<Virtual>::pause()` etc. - There is a new `max_delta` setting in `Time<Virtual>` that limits how much the clock can jump by a single update. The default value is 0.25 seconds. - Removed `on_fixed_timer()` condition as `on_timer()` does the right thing inside `FixedUpdate` now. ## Migration Guide - Change all `Res<Time>` instances that access `raw_delta()`, `raw_elapsed()` and related methods to `Res<Time<Real>>` and `delta()`, `elapsed()`, etc. - Change access to `period` from `Res<FixedTime>` to `Res<Time<Fixed>>` and use `delta()`. - The default timestep has been changed from 60 Hz to 64 Hz. If you wish to restore the old behaviour, use `app.insert_resource(Time::<Fixed>::from_hz(60.0))`. - Change `app.insert_resource(FixedTime::new(duration))` to `app.insert_resource(Time::<Fixed>::from_duration(duration))` - Change `app.insert_resource(FixedTime::new_from_secs(secs))` to `app.insert_resource(Time::<Fixed>::from_seconds(secs))` - Change `system.on_fixed_timer(duration)` to `system.on_timer(duration)`. Timers in systems placed in `FixedUpdate` schedule automatically use the fixed time clock. - Change `ResMut<Time>` calls to `pause()`, `is_paused()`, `set_relative_speed()` and related methods to `ResMut<Time<Virtual>>` calls. The API is the same, with the exception that `relative_speed()` will return the actual last ste relative speed, while `effective_relative_speed()` returns 0.0 if the time is paused and corresponds to the speed that was set when the update for the current frame started. ## Todo - [x] Update pull name and description - [x] Top level documentation on usage - [x] Fix examples - [x] Decide on default `max_delta` value - [x] Decide naming of the three clocks: is `Real`, `Virtual`, `Fixed` good? - [x] Decide if the three clock inner structures should be in prelude - [x] Decide on best way to configure values at startup: is manually inserting a new clock instance okay, or should there be config struct separately? - [x] Fix links in docs - [x] Decide what should be public and what not - [x] Decide how `wrap_period` should be handled when it is changed - [x] ~~Add toggles to disable setting the clock as default?~~ No, separate pull if needed. - [x] Add tests - [x] Reformat, ensure adheres to conventions etc. - [x] Build documentation and see that it looks correct ## Contributors Huge thanks to @alice-i-cecile and @maniwani while building this pull. It was a shared effort! --------- Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com> Co-authored-by: Cameron <51241057+maniwani@users.noreply.github.com> Co-authored-by: Jerome Humbert <djeedai@gmail.com>
2023-10-16 01:57:55 +00:00
use bevy_reflect::Reflect;
use bevy_utils::{Duration, Instant};
use crate::time::Time;
/// Real time clock representing elapsed wall clock time.
///
/// A specialization of the [`Time`] structure. **For method documentation, see
/// [`Time<Real>#impl-Time<Real>`].**
///
/// It is automatically inserted as a resource by
/// [`TimePlugin`](crate::TimePlugin) and updated with time instants according
/// to [`TimeUpdateStrategy`](crate::TimeUpdateStrategy).
///
/// The [`delta()`](Time::delta) and [`elapsed()`](Time::elapsed) values of this
/// clock should be used for anything which deals specifically with real time
/// (wall clock time). It will not be affected by relative game speed
/// adjustments, pausing or other adjustments.
///
/// The clock does not count time from [`startup()`](Time::startup) to
/// [`first_update()`](Time::first_update()) into elapsed, but instead will
/// start counting time from the first update call. [`delta()`](Time::delta) and
/// [`elapsed()`](Time::elapsed) will report zero on the first update as there
/// is no previous update instant. This means that a [`delta()`](Time::delta) of
/// zero must be handled without errors in application logic, as it may
/// theoretically also happen at other times.
///
/// [`Instant`](std::time::Instant)s for [`startup()`](Time::startup),
/// [`first_update()`](Time::first_update) and
/// [`last_update()`](Time::last_update) are recorded and accessible.
#[derive(Debug, Copy, Clone, Reflect)]
pub struct Real {
startup: Instant,
first_update: Option<Instant>,
last_update: Option<Instant>,
}
impl Default for Real {
fn default() -> Self {
Self {
startup: Instant::now(),
first_update: None,
last_update: None,
}
}
}
impl Time<Real> {
/// Constructs a new `Time<Real>` instance with a specific startup
/// [`Instant`](std::time::Instant).
pub fn new(startup: Instant) -> Self {
Self::new_with(Real {
startup,
..Default::default()
})
}
/// Updates the internal time measurements.
///
/// Calling this method as part of your app will most likely result in
/// inaccurate timekeeping, as the [`Time`] resource is ordinarily managed
/// by the [`TimePlugin`](crate::TimePlugin).
pub fn update(&mut self) {
let instant = Instant::now();
self.update_with_instant(instant);
}
/// Updates time with a specified [`Duration`].
///
/// This method is provided for use in tests.
///
/// Calling this method as part of your app will most likely result in
/// inaccurate timekeeping, as the [`Time`] resource is ordinarily managed
/// by the [`TimePlugin`](crate::TimePlugin).
pub fn update_with_duration(&mut self, duration: Duration) {
let last_update = self.context().last_update.unwrap_or(self.context().startup);
self.update_with_instant(last_update + duration);
}
/// Updates time with a specified [`Instant`](std::time::Instant).
///
/// This method is provided for use in tests.
///
/// Calling this method as part of your app will most likely result in inaccurate timekeeping,
/// as the [`Time`] resource is ordinarily managed by the [`TimePlugin`](crate::TimePlugin).
pub fn update_with_instant(&mut self, instant: Instant) {
let Some(last_update) = self.context().last_update else {
let context = self.context_mut();
context.first_update = Some(instant);
context.last_update = Some(instant);
return;
};
let delta = instant - last_update;
self.advance_by(delta);
self.context_mut().last_update = Some(instant);
}
/// Returns the [`Instant`](std::time::Instant) the clock was created.
///
/// This usually represents when the app was started.
#[inline]
pub fn startup(&self) -> Instant {
self.context().startup
}
/// Returns the [`Instant`](std::time::Instant) when [`Self::update`] was first called, if it
/// exists.
///
/// This usually represents when the first app update started.
#[inline]
pub fn first_update(&self) -> Option<Instant> {
self.context().first_update
}
/// Returns the [`Instant`](std::time::Instant) when [`Self::update`] was last called, if it
/// exists.
///
/// This usually represents when the current app update started.
#[inline]
pub fn last_update(&self) -> Option<Instant> {
self.context().last_update
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_update() {
let startup = Instant::now();
let mut time = Time::<Real>::new(startup);
assert_eq!(time.startup(), startup);
assert_eq!(time.first_update(), None);
assert_eq!(time.last_update(), None);
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
time.update();
assert_ne!(time.first_update(), None);
assert_ne!(time.last_update(), None);
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
time.update();
assert_ne!(time.first_update(), None);
assert_ne!(time.last_update(), None);
assert_ne!(time.last_update(), time.first_update());
assert_ne!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), time.delta());
let prev_elapsed = time.elapsed();
time.update();
assert_ne!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), prev_elapsed + time.delta());
}
#[test]
fn test_update_with_instant() {
let startup = Instant::now();
let mut time = Time::<Real>::new(startup);
let first_update = Instant::now();
time.update_with_instant(first_update);
assert_eq!(time.startup(), startup);
assert_eq!(time.first_update(), Some(first_update));
assert_eq!(time.last_update(), Some(first_update));
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
let second_update = Instant::now();
time.update_with_instant(second_update);
assert_eq!(time.first_update(), Some(first_update));
assert_eq!(time.last_update(), Some(second_update));
assert_eq!(time.delta(), second_update - first_update);
assert_eq!(time.elapsed(), second_update - first_update);
let third_update = Instant::now();
time.update_with_instant(third_update);
assert_eq!(time.first_update(), Some(first_update));
assert_eq!(time.last_update(), Some(third_update));
assert_eq!(time.delta(), third_update - second_update);
assert_eq!(time.elapsed(), third_update - first_update);
}
#[test]
fn test_update_with_duration() {
let startup = Instant::now();
let mut time = Time::<Real>::new(startup);
time.update_with_duration(Duration::from_secs(1));
assert_eq!(time.startup(), startup);
assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1)));
assert_eq!(time.last_update(), Some(startup + Duration::from_secs(1)));
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
time.update_with_duration(Duration::from_secs(1));
assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1)));
assert_eq!(time.last_update(), Some(startup + Duration::from_secs(2)));
assert_eq!(time.delta(), Duration::from_secs(1));
assert_eq!(time.elapsed(), Duration::from_secs(1));
time.update_with_duration(Duration::from_secs(1));
assert_eq!(time.first_update(), Some(startup + Duration::from_secs(1)));
assert_eq!(time.last_update(), Some(startup + Duration::from_secs(3)));
assert_eq!(time.delta(), Duration::from_secs(1));
assert_eq!(time.elapsed(), Duration::from_secs(2));
}
}