1#](https://github.com/bevyengine/bevy#license)\n[](https://crates.io/crates/bevy_time)\n[](https://crates.io/crates/bevy_time)\n[](https://docs.rs/bevy_time/latest/bevy_time/)\n[](https://discord.gg/bevy)\n\nThe built-in timekeeping plugin for the Bevy game engine.\n"include_str!("../README.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![forbid(unsafe_code)]
4#![doc(
5 html_logo_url = "https://bevy.org/assets/icon.png",
6 html_favicon_url = "https://bevy.org/assets/icon.png"
7)]
8#![no_std]
910#[cfg(feature = "std")]
11extern crate std;
1213extern crate alloc;
1415/// Common run conditions
16pub mod common_conditions;
17mod delayed_commands;
18mod fixed;
19mod real;
20mod stopwatch;
21mod time;
22mod timer;
23mod virt;
2425pub use delayed_commands::*;
26pub use fixed::*;
27pub use real::*;
28pub use stopwatch::*;
29pub use time::*;
30pub use timer::*;
31pub use virt::*;
3233/// The time prelude.
34///
35/// This includes the most common types in this crate, re-exported for your convenience.
36pub mod prelude {
37#[doc(hidden)]
38pub use crate::{DelayedCommandsExt, Fixed, Real, Time, Timer, TimerMode, Virtual};
39}
4041use bevy_app::{prelude::*, OnAppExitSystems, RunFixedMainLoop};
42use bevy_ecs::{
43 message::{
44message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
45 },
46prelude::*,
47};
48use bevy_platform::time::Instant;
49use core::time::Duration;
5051#[cfg(feature = "std")]
52pub use crossbeam_channel::TrySendError;
5354#[cfg(feature = "std")]
55use crossbeam_channel::{Receiver, Sender};
5657/// Adds time functionality to Apps.
58#[derive(#[automatically_derived]
impl ::core::default::Default for TimePlugin {
#[inline]
fn default() -> Self { Self }
}Default)]
59pub struct TimePlugin;
6061/// Updates the elapsed time. Any system that interacts with [`Time`] component should run after
62/// this.
63#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TimeSystems {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "TimeSystems")
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for TimeSystems { }
#[automatically_derived]
impl ::core::cmp::PartialEq for TimeSystems {
#[inline]
fn eq(&self, other: &Self) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TimeSystems { }Eq, #[automatically_derived]
impl ::core::clone::Clone for TimeSystems {
#[inline]
fn clone(&self) -> Self { Self }
}Clone, #[automatically_derived]
impl ::core::hash::Hash for TimeSystems {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {}
}Hash, const _: () =
{
extern crate alloc;
impl bevy_ecs::schedule::SystemSet for TimeSystems where
Self: 'static + ::core::marker::Send + ::core::marker::Sync +
::core::clone::Clone + ::core::cmp::Eq + ::core::fmt::Debug +
::core::hash::Hash {
fn dyn_clone(&self)
-> alloc::boxed::Box<dyn bevy_ecs::schedule::SystemSet> {
alloc::boxed::Box::new(::core::clone::Clone::clone(self))
}
}
};SystemSet)]
64pub struct TimeSystems;
6566impl Pluginfor TimePlugin {
67fn build(&self, app: &mut App) {
68app.init_resource::<Time>()
69 .init_resource::<Time<Real>>()
70 .init_resource::<Time<Virtual>>()
71 .init_resource::<Time<Fixed>>()
72 .init_resource::<TimeUpdateStrategy>();
7374#[cfg(feature = "bevy_reflect")]
75{
76app.register_type::<Time>()
77 .register_type::<Time<Real>>()
78 .register_type::<Time<Virtual>>()
79 .register_type::<Time<Fixed>>();
80 }
8182app.add_systems(
83First,
84time_system85 .in_set(TimeSystems)
86 .ambiguous_with(message_update_system),
87 )
88 .add_systems(PreUpdate, check_delayed_command_queues)
89 .add_systems(
90RunFixedMainLoop,
91run_fixed_main_schedule.in_set(RunFixedMainLoopSystems::FixedMainLoop),
92 )
93 .add_systems(
94Last,
95silence_delayed_command_queues_on_exit96 .in_set(OnAppExitSystems)
97 .run_if(|messages: Res<Messages<AppExit>>| !messages.is_empty()),
98 );
99100// Ensure the messages are not dropped until `FixedMain` systems can observe them
101app.add_systems(FixedPostUpdate, signal_message_update_system);
102let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
103// We need to start in a waiting state so that the messages are not updated until the first fixed update
104message_registry.should_update = ShouldUpdateMessages::Waiting;
105 }
106}
107108/// Configuration resource used to determine how the time system should run.
109///
110/// For most cases, [`TimeUpdateStrategy::Automatic`] is fine. When writing tests, dealing with
111/// networking or similar, you may prefer to set the next [`Time`] value manually.
112#[derive(impl bevy_ecs::component::Component for TimeUpdateStrategy where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {
const STORAGE_TYPE: bevy_ecs::component::StorageType =
bevy_ecs::component::StorageType::SparseSet;
type Mutability = bevy_ecs::component::Mutable;
fn register_required_components(_requiree:
bevy_ecs::component::ComponentId,
required_components:
&mut bevy_ecs::component::RequiredComponentsRegistrator) {
let resource_component_id =
if let ::core::option::Option::Some(id) =
required_components.components_registrator().component_id::<TimeUpdateStrategy>()
{
id
} else {
required_components.components_registrator().register_component::<TimeUpdateStrategy>()
};
required_components.register_required::<bevy_ecs::resource::IsResource>(move
||
bevy_ecs::resource::IsResource::new(resource_component_id));
}
fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
use bevy_ecs::component::{
DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
};
(&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
}
fn map_entities<M: bevy_ecs::entity::EntityMapper>(this: &mut Self,
mapper: &mut M) {
use bevy_ecs::entity::MapEntities;
match this {
Self::Automatic { .. } => {}
Self::ManualInstant { .. } => {}
Self::ManualDuration { .. } => {}
Self::FixedTimesteps { .. } => {}
_ => {}
}
}
fn relationship_accessor()
->
::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
::core::option::Option::None
}
}
impl bevy_ecs::resource::Resource for TimeUpdateStrategy where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {}Resource, #[automatically_derived]
impl ::core::default::Default for TimeUpdateStrategy {
#[inline]
fn default() -> Self { Self::Automatic }
}Default)]
113pub enum TimeUpdateStrategy {
114/// [`Time`] will be automatically updated each frame using an [`Instant`] sent from the render world.
115 /// If nothing is sent, the system clock will be used instead.
116#[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
117 #[default]
118Automatic,
119/// [`Time`] will be updated to the specified [`Instant`] value each frame.
120 /// In order for time to progress, this value must be manually updated each frame.
121 ///
122 /// Note that the `Time` resource will not be updated until [`TimeSystems`] runs.
123ManualInstant(Instant),
124/// [`Time`] will be incremented by the specified [`Duration`] each frame.
125ManualDuration(Duration),
126/// [`Time`] will be incremented by the fixed timestep each frame, multiplied by the specified factor `n`.
127 /// This means that a call to [`App::update`] will always run the fixed loop exactly n times.
128FixedTimesteps(u32),
129}
130131/// Channel resource used to receive time from the render world.
132#[cfg(feature = "std")]
133#[derive(impl bevy_ecs::component::Component for TimeReceiver where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {
const STORAGE_TYPE: bevy_ecs::component::StorageType =
bevy_ecs::component::StorageType::SparseSet;
type Mutability = bevy_ecs::component::Mutable;
fn register_required_components(_requiree:
bevy_ecs::component::ComponentId,
required_components:
&mut bevy_ecs::component::RequiredComponentsRegistrator) {
let resource_component_id =
if let ::core::option::Option::Some(id) =
required_components.components_registrator().component_id::<TimeReceiver>()
{
id
} else {
required_components.components_registrator().register_component::<TimeReceiver>()
};
required_components.register_required::<bevy_ecs::resource::IsResource>(move
||
bevy_ecs::resource::IsResource::new(resource_component_id));
}
fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
use bevy_ecs::component::{
DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
};
(&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
}
fn relationship_accessor()
->
::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
::core::option::Option::None
}
}
impl bevy_ecs::resource::Resource for TimeReceiver where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {}Resource)]
134pub struct TimeReceiver(pub Receiver<Instant>);
135136/// Channel resource used to send time from the render world.
137#[cfg(feature = "std")]
138#[derive(impl bevy_ecs::component::Component for TimeSender where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {
const STORAGE_TYPE: bevy_ecs::component::StorageType =
bevy_ecs::component::StorageType::SparseSet;
type Mutability = bevy_ecs::component::Mutable;
fn register_required_components(_requiree:
bevy_ecs::component::ComponentId,
required_components:
&mut bevy_ecs::component::RequiredComponentsRegistrator) {
let resource_component_id =
if let ::core::option::Option::Some(id) =
required_components.components_registrator().component_id::<TimeSender>()
{
id
} else {
required_components.components_registrator().register_component::<TimeSender>()
};
required_components.register_required::<bevy_ecs::resource::IsResource>(move
||
bevy_ecs::resource::IsResource::new(resource_component_id));
}
fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
use bevy_ecs::component::{
DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
};
(&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
}
fn relationship_accessor()
->
::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
::core::option::Option::None
}
}
impl bevy_ecs::resource::Resource for TimeSender where
Self: ::core::marker::Send + ::core::marker::Sync + 'static {}Resource)]
139pub struct TimeSender(pub Sender<Instant>);
140141/// Creates channels used for sending time between the render world and the main world.
142#[cfg(feature = "std")]
143pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
144// bound the channel to 2 since when pipelined the render phase can finish before
145 // the time system runs.
146let (s, r) = crossbeam_channel::bounded::<Instant>(2);
147 (TimeSender(s), TimeReceiver(r))
148}
149150/// The system used to update the [`Time`] used by app logic. If there is a render world the time is
151/// sent from there to this system through channels. Otherwise the time is updated in this system.
152pub fn time_system(
153mut real_time: ResMut<Time<Real>>,
154mut virtual_time: ResMut<Time<Virtual>>,
155 fixed_time: Res<Time<Fixed>>,
156mut time: ResMut<Time>,
157 update_strategy: Res<TimeUpdateStrategy>,
158#[cfg(feature = "std")] time_recv: Option<Res<TimeReceiver>>,
159#[cfg(feature = "std")] mut has_received_time: Local<bool>,
160) {
161#[cfg(feature = "std")]
162// TODO: Figure out how to handle this when using pipelined rendering.
163let sent_time = match time_recv.map(|res| res.0.try_recv()) {
164Some(Ok(new_time)) => {
165*has_received_time = true;
166Some(new_time)
167 }
168Some(Err(_)) => {
169if *has_received_time {
170{
{
let lvl = ::log::Level::Warn;
if lvl <= ::log::STATIC_MAX_LEVEL && lvl <= ::log::max_level() {
::log::__private_api::log({ ::log::__private_api::GlobalLogger },
format_args!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect."),
lvl, &("bevy_time", "bevy_time", ::log::__private_api::loc()),
());
}
}
};log::warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
171 }
172None173 }
174None => None,
175 };
176177match update_strategy.as_ref() {
178 TimeUpdateStrategy::Automatic => {
179#[cfg(feature = "std")]
180real_time.update_with_instant(sent_time.unwrap_or_else(Instant::now));
181182#[cfg(not(feature = "std"))]
183real_time.update_with_instant(Instant::now());
184 }
185 TimeUpdateStrategy::ManualInstant(instant) => real_time.update_with_instant(*instant),
186 TimeUpdateStrategy::ManualDuration(duration) => real_time.update_with_duration(*duration),
187 TimeUpdateStrategy::FixedTimesteps(factor) => {
188real_time.update_with_duration(fixed_time.timestep() * *factor);
189 }
190 }
191192update_virtual_time(&mut time, &mut virtual_time, &real_time);
193}
194195#[cfg(test)]
196#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
197mod tests {
198use crate::{Fixed, Time, TimePlugin, TimeUpdateStrategy, Virtual};
199use bevy_app::{App, FixedUpdate, Startup, Update};
200use bevy_ecs::{
201 message::{
202 Message, MessageReader, MessageRegistry, MessageWriter, Messages, ShouldUpdateMessages,
203 },
204 resource::Resource,
205 system::{Local, Res, ResMut},
206 };
207use core::error::Error;
208use core::time::Duration;
209use std::println;
210211#[derive(Message)]
212struct TestMessage<T: Default> {
213 sender: std::sync::mpsc::Sender<T>,
214 }
215216impl<T: Default> Drop for TestMessage<T> {
217fn drop(&mut self) {
218self.sender
219 .send(T::default())
220 .expect("Failed to send drop signal");
221 }
222 }
223224#[derive(Message)]
225struct DummyMessage;
226227#[derive(Resource, Default)]
228struct FixedUpdateCounter(u8);
229230fn count_fixed_updates(mut counter: ResMut<FixedUpdateCounter>) {
231 counter.0 += 1;
232 }
233234fn report_time(
235mut frame_count: Local<u64>,
236 virtual_time: Res<Time<Virtual>>,
237 fixed_time: Res<Time<Fixed>>,
238 ) {
239println!(
240"Virtual time on frame {}: {:?}",
241*frame_count,
242 virtual_time.elapsed()
243 );
244println!(
245"Fixed time on frame {}: {:?}",
246*frame_count,
247 fixed_time.elapsed()
248 );
249250*frame_count += 1;
251 }
252253#[test]
254fn fixed_main_schedule_should_run_with_time_plugin_enabled() {
255// Set the time step to just over half the fixed update timestep
256 // This way, it will have not accumulated enough time to run the fixed update after one update
257 // But will definitely have enough time after two updates
258let fixed_update_timestep = Time::<Fixed>::default().timestep();
259let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
260261let mut app = App::new();
262 app.add_plugins(TimePlugin)
263 .add_systems(FixedUpdate, count_fixed_updates)
264 .add_systems(Update, report_time)
265 .init_resource::<FixedUpdateCounter>()
266 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
267268// Frame 0
269 // Fixed update should not have run yet
270app.update();
271272assert!(Duration::ZERO < fixed_update_timestep);
273let counter = app.world().resource::<FixedUpdateCounter>();
274assert_eq!(counter.0, 0, "Fixed update should not have run yet");
275276// Frame 1
277 // Fixed update should not have run yet
278app.update();
279280assert!(time_step < fixed_update_timestep);
281let counter = app.world().resource::<FixedUpdateCounter>();
282assert_eq!(counter.0, 0, "Fixed update should not have run yet");
283284// Frame 2
285 // Fixed update should have run now
286app.update();
287288assert!(2 * time_step > fixed_update_timestep);
289let counter = app.world().resource::<FixedUpdateCounter>();
290assert_eq!(counter.0, 1, "Fixed update should have run once");
291292// Frame 3
293 // Fixed update should have run exactly once still
294app.update();
295296assert!(3 * time_step < 2 * fixed_update_timestep);
297let counter = app.world().resource::<FixedUpdateCounter>();
298assert_eq!(counter.0, 1, "Fixed update should have run once");
299300// Frame 4
301 // Fixed update should have run twice now
302app.update();
303304assert!(4 * time_step > 2 * fixed_update_timestep);
305let counter = app.world().resource::<FixedUpdateCounter>();
306assert_eq!(counter.0, 2, "Fixed update should have run twice");
307 }
308309#[test]
310fn events_get_dropped_regression_test_11528() -> Result<(), impl Error> {
311let (tx1, rx1) = std::sync::mpsc::channel();
312let (tx2, rx2) = std::sync::mpsc::channel();
313let mut app = App::new();
314 app.add_plugins(TimePlugin)
315 .add_message::<TestMessage<i32>>()
316 .add_message::<TestMessage<()>>()
317 .add_systems(Startup, move |mut ev2: MessageWriter<TestMessage<()>>| {
318 ev2.write(TestMessage {
319 sender: tx2.clone(),
320 });
321 })
322 .add_systems(Update, move |mut ev1: MessageWriter<TestMessage<i32>>| {
323// Keep adding events so this event type is processed every update
324ev1.write(TestMessage {
325 sender: tx1.clone(),
326 });
327 })
328 .add_systems(
329 Update,
330 |mut m1: MessageReader<TestMessage<i32>>,
331mut m2: MessageReader<TestMessage<()>>| {
332// Read events so they can be dropped
333for _ in m1.read() {}
334for _ in m2.read() {}
335 },
336 )
337 .insert_resource(TimeUpdateStrategy::ManualDuration(
338 Time::<Fixed>::default().timestep(),
339 ));
340341for _ in 0..10 {
342 app.update();
343 }
344345// Check event type 1 as been dropped at least once
346let _drop_signal = rx1.try_recv()?;
347// Check event type 2 has been dropped
348rx2.try_recv()
349 }
350351#[test]
352fn event_update_should_wait_for_fixed_main() {
353// Set the time step to just over half the fixed update timestep
354 // This way, it will have not accumulated enough time to run the fixed update after one update
355 // But will definitely have enough time after two updates
356let fixed_update_timestep = Time::<Fixed>::default().timestep();
357let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
358359fn write_message(mut messages: ResMut<Messages<DummyMessage>>) {
360 messages.write(DummyMessage);
361 }
362363let mut app = App::new();
364 app.add_plugins(TimePlugin)
365 .add_message::<DummyMessage>()
366 .init_resource::<FixedUpdateCounter>()
367 .add_systems(Startup, write_message)
368 .add_systems(FixedUpdate, count_fixed_updates)
369 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
370371for frame in 0..10 {
372 app.update();
373let fixed_updates_seen = app.world().resource::<FixedUpdateCounter>().0;
374let messages = app.world().resource::<Messages<DummyMessage>>();
375let n_total_messages = messages.len();
376let n_current_messages = messages.iter_current_update_messages().count();
377let message_registry = app.world().resource::<MessageRegistry>();
378let should_update = message_registry.should_update;
379380println!("Frame {frame}, {fixed_updates_seen} fixed updates seen. Should update: {should_update:?}");
381println!("Total messages: {n_total_messages} | Current messages: {n_current_messages}",);
382383match frame {
3840 | 1 => {
385assert_eq!(fixed_updates_seen, 0);
386assert_eq!(n_total_messages, 1);
387assert_eq!(n_current_messages, 1);
388assert_eq!(should_update, ShouldUpdateMessages::Waiting);
389 }
3902 => {
391assert_eq!(fixed_updates_seen, 1); // Time to trigger event updates
392assert_eq!(n_total_messages, 1);
393assert_eq!(n_current_messages, 1);
394assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping first update
395}
3963 => {
397assert_eq!(fixed_updates_seen, 1);
398assert_eq!(n_total_messages, 1);
399assert_eq!(n_current_messages, 0); // First update has occurred
400assert_eq!(should_update, ShouldUpdateMessages::Waiting);
401 }
4024 => {
403assert_eq!(fixed_updates_seen, 2); // Time to trigger the second update
404assert_eq!(n_total_messages, 1);
405assert_eq!(n_current_messages, 0);
406assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping second update
407}
4085 => {
409assert_eq!(fixed_updates_seen, 2);
410assert_eq!(n_total_messages, 0); // Second update has occurred
411assert_eq!(n_current_messages, 0);
412assert_eq!(should_update, ShouldUpdateMessages::Waiting);
413 }
414_ => {
415assert_eq!(n_total_messages, 0); // No more events are sent
416assert_eq!(n_current_messages, 0);
417 }
418 }
419 }
420 }
421}