Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add TimeUpdateStrategy resource for manual Time updating #6159

Closed
wants to merge 12 commits into from
9 changes: 9 additions & 0 deletions crates/bevy_time/src/lib.rs
Expand Up @@ -44,6 +44,12 @@ impl Plugin for TimePlugin {
}
}

/// Resource for updating time with a desired value.
///
/// See [`update_with_interval`](self::TimeUpdater::update_with_instant) for more details.
#[derive(Resource)]
pub struct DesiredTime(pub Instant);

/// Channel resource used to receive time from render world
#[derive(Resource)]
pub struct TimeReceiver(pub Receiver<Instant>);
Expand All @@ -64,6 +70,7 @@ pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
/// there to this system through channels. Otherwise the time is updated in this system.
fn time_system(
mut time: ResMut<Time>,
wanted_time: Option<Res<DesiredTime>>,
time_recv: Option<Res<TimeReceiver>>,
mut has_received_time: Local<bool>,
) {
Expand All @@ -75,6 +82,8 @@ fn time_system(
} else if *has_received_time {
warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
}
} else if let Some(wanted_time) = wanted_time {
time.update_with_instant(wanted_time.0);
} else {
time.update();
}
Expand Down
18 changes: 18 additions & 0 deletions crates/bevy_time/src/time.rs
Expand Up @@ -2,8 +2,14 @@ use bevy_ecs::{reflect::ReflectResource, system::Resource};
use bevy_reflect::{FromReflect, Reflect};
use bevy_utils::{Duration, Instant};

use crate::DesiredTime;

const SECONDS_PER_HOUR: u64 = 60 * 60;

pub trait TimeUpdater {
fn update_with_instant(&mut self, instant: Instant);
}

/// Tracks elapsed time since the last update and since the App has started
#[derive(Resource, Reflect, FromReflect, Debug, Clone)]
#[reflect(Resource)]
Expand Down Expand Up @@ -170,6 +176,18 @@ impl Time {
}
}

impl TimeUpdater for bevy_app::App {
/// Runs the app's schedule once, manually setting the [`Time`] resource to the provided value.
///
/// This is ordinarily done automatically, but setting this time value directly can be useful when writing tests,
/// dealing with networking code, or similar.
fn update_with_instant(&mut self, instant: Instant) {
self.world.insert_resource(DesiredTime(instant));
self.update();
self.world.remove_resource::<DesiredTime>();
}
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
Expand Down