1#![doc = 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]
9
10#[cfg(feature = "std")]
11extern crate std;
12
13extern crate alloc;
14
15pub mod common_conditions;
17mod fixed;
18mod real;
19mod stopwatch;
20mod time;
21mod timer;
22mod virt;
23
24pub use fixed::*;
25pub use real::*;
26pub use stopwatch::*;
27pub use time::*;
28pub use timer::*;
29pub use virt::*;
30
31pub mod prelude {
35 #[doc(hidden)]
36 pub use crate::{Fixed, Real, Time, Timer, TimerMode, Virtual};
37}
38
39use bevy_app::{prelude::*, RunFixedMainLoop};
40use bevy_ecs::{
41 message::{
42 message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
43 },
44 prelude::*,
45};
46use bevy_platform::time::Instant;
47use core::time::Duration;
48
49#[cfg(feature = "std")]
50pub use crossbeam_channel::TrySendError;
51
52#[cfg(feature = "std")]
53use crossbeam_channel::{Receiver, Sender};
54
55#[derive(Default)]
57pub struct TimePlugin;
58
59#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
62pub struct TimeSystems;
63
64#[deprecated(since = "0.17.0", note = "Renamed to `TimeSystems`.")]
66pub type TimeSystem = TimeSystems;
67
68impl Plugin for TimePlugin {
69 fn build(&self, app: &mut App) {
70 app.init_resource::<Time>()
71 .init_resource::<Time<Real>>()
72 .init_resource::<Time<Virtual>>()
73 .init_resource::<Time<Fixed>>()
74 .init_resource::<TimeUpdateStrategy>();
75
76 #[cfg(feature = "bevy_reflect")]
77 {
78 app.register_type::<Time>()
79 .register_type::<Time<Real>>()
80 .register_type::<Time<Virtual>>()
81 .register_type::<Time<Fixed>>();
82 }
83
84 app.add_systems(
85 First,
86 time_system
87 .in_set(TimeSystems)
88 .ambiguous_with(message_update_system),
89 )
90 .add_systems(
91 RunFixedMainLoop,
92 run_fixed_main_schedule.in_set(RunFixedMainLoopSystems::FixedMainLoop),
93 );
94
95 app.add_systems(FixedPostUpdate, signal_message_update_system);
97 let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
98 message_registry.should_update = ShouldUpdateMessages::Waiting;
100 }
101}
102
103#[derive(Resource, Default)]
108pub enum TimeUpdateStrategy {
109 #[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
112 #[default]
113 Automatic,
114 ManualInstant(Instant),
119 ManualDuration(Duration),
121}
122
123#[cfg(feature = "std")]
125#[derive(Resource)]
126pub struct TimeReceiver(pub Receiver<Instant>);
127
128#[cfg(feature = "std")]
130#[derive(Resource)]
131pub struct TimeSender(pub Sender<Instant>);
132
133#[cfg(feature = "std")]
135pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
136 let (s, r) = crossbeam_channel::bounded::<Instant>(2);
139 (TimeSender(s), TimeReceiver(r))
140}
141
142pub fn time_system(
145 mut real_time: ResMut<Time<Real>>,
146 mut virtual_time: ResMut<Time<Virtual>>,
147 mut time: ResMut<Time>,
148 update_strategy: Res<TimeUpdateStrategy>,
149 #[cfg(feature = "std")] time_recv: Option<Res<TimeReceiver>>,
150 #[cfg(feature = "std")] mut has_received_time: Local<bool>,
151) {
152 #[cfg(feature = "std")]
153 let sent_time = match time_recv.map(|res| res.0.try_recv()) {
155 Some(Ok(new_time)) => {
156 *has_received_time = true;
157 Some(new_time)
158 }
159 Some(Err(_)) => {
160 if *has_received_time {
161 log::warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
162 }
163 None
164 }
165 None => None,
166 };
167
168 match update_strategy.as_ref() {
169 TimeUpdateStrategy::Automatic => {
170 #[cfg(feature = "std")]
171 real_time.update_with_instant(sent_time.unwrap_or_else(Instant::now));
172
173 #[cfg(not(feature = "std"))]
174 real_time.update_with_instant(Instant::now());
175 }
176 TimeUpdateStrategy::ManualInstant(instant) => real_time.update_with_instant(*instant),
177 TimeUpdateStrategy::ManualDuration(duration) => real_time.update_with_duration(*duration),
178 }
179
180 update_virtual_time(&mut time, &mut virtual_time, &real_time);
181}
182
183#[cfg(test)]
184#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
185mod tests {
186 use crate::{Fixed, Time, TimePlugin, TimeUpdateStrategy, Virtual};
187 use bevy_app::{App, FixedUpdate, Startup, Update};
188 use bevy_ecs::{
189 message::{
190 Message, MessageReader, MessageRegistry, MessageWriter, Messages, ShouldUpdateMessages,
191 },
192 resource::Resource,
193 system::{Local, Res, ResMut},
194 };
195 use core::error::Error;
196 use core::time::Duration;
197 use std::println;
198
199 #[derive(Message)]
200 struct TestMessage<T: Default> {
201 sender: std::sync::mpsc::Sender<T>,
202 }
203
204 impl<T: Default> Drop for TestMessage<T> {
205 fn drop(&mut self) {
206 self.sender
207 .send(T::default())
208 .expect("Failed to send drop signal");
209 }
210 }
211
212 #[derive(Message)]
213 struct DummyMessage;
214
215 #[derive(Resource, Default)]
216 struct FixedUpdateCounter(u8);
217
218 fn count_fixed_updates(mut counter: ResMut<FixedUpdateCounter>) {
219 counter.0 += 1;
220 }
221
222 fn report_time(
223 mut frame_count: Local<u64>,
224 virtual_time: Res<Time<Virtual>>,
225 fixed_time: Res<Time<Fixed>>,
226 ) {
227 println!(
228 "Virtual time on frame {}: {:?}",
229 *frame_count,
230 virtual_time.elapsed()
231 );
232 println!(
233 "Fixed time on frame {}: {:?}",
234 *frame_count,
235 fixed_time.elapsed()
236 );
237
238 *frame_count += 1;
239 }
240
241 #[test]
242 fn fixed_main_schedule_should_run_with_time_plugin_enabled() {
243 let fixed_update_timestep = Time::<Fixed>::default().timestep();
247 let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
248
249 let mut app = App::new();
250 app.add_plugins(TimePlugin)
251 .add_systems(FixedUpdate, count_fixed_updates)
252 .add_systems(Update, report_time)
253 .init_resource::<FixedUpdateCounter>()
254 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
255
256 app.update();
259
260 assert!(Duration::ZERO < fixed_update_timestep);
261 let counter = app.world().resource::<FixedUpdateCounter>();
262 assert_eq!(counter.0, 0, "Fixed update should not have run yet");
263
264 app.update();
267
268 assert!(time_step < fixed_update_timestep);
269 let counter = app.world().resource::<FixedUpdateCounter>();
270 assert_eq!(counter.0, 0, "Fixed update should not have run yet");
271
272 app.update();
275
276 assert!(2 * time_step > fixed_update_timestep);
277 let counter = app.world().resource::<FixedUpdateCounter>();
278 assert_eq!(counter.0, 1, "Fixed update should have run once");
279
280 app.update();
283
284 assert!(3 * time_step < 2 * fixed_update_timestep);
285 let counter = app.world().resource::<FixedUpdateCounter>();
286 assert_eq!(counter.0, 1, "Fixed update should have run once");
287
288 app.update();
291
292 assert!(4 * time_step > 2 * fixed_update_timestep);
293 let counter = app.world().resource::<FixedUpdateCounter>();
294 assert_eq!(counter.0, 2, "Fixed update should have run twice");
295 }
296
297 #[test]
298 fn events_get_dropped_regression_test_11528() -> Result<(), impl Error> {
299 let (tx1, rx1) = std::sync::mpsc::channel();
300 let (tx2, rx2) = std::sync::mpsc::channel();
301 let mut app = App::new();
302 app.add_plugins(TimePlugin)
303 .add_message::<TestMessage<i32>>()
304 .add_message::<TestMessage<()>>()
305 .add_systems(Startup, move |mut ev2: MessageWriter<TestMessage<()>>| {
306 ev2.write(TestMessage {
307 sender: tx2.clone(),
308 });
309 })
310 .add_systems(Update, move |mut ev1: MessageWriter<TestMessage<i32>>| {
311 ev1.write(TestMessage {
313 sender: tx1.clone(),
314 });
315 })
316 .add_systems(
317 Update,
318 |mut m1: MessageReader<TestMessage<i32>>,
319 mut m2: MessageReader<TestMessage<()>>| {
320 for _ in m1.read() {}
322 for _ in m2.read() {}
323 },
324 )
325 .insert_resource(TimeUpdateStrategy::ManualDuration(
326 Time::<Fixed>::default().timestep(),
327 ));
328
329 for _ in 0..10 {
330 app.update();
331 }
332
333 let _drop_signal = rx1.try_recv()?;
335 rx2.try_recv()
337 }
338
339 #[test]
340 fn event_update_should_wait_for_fixed_main() {
341 let fixed_update_timestep = Time::<Fixed>::default().timestep();
345 let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
346
347 fn write_message(mut messages: ResMut<Messages<DummyMessage>>) {
348 messages.write(DummyMessage);
349 }
350
351 let mut app = App::new();
352 app.add_plugins(TimePlugin)
353 .add_message::<DummyMessage>()
354 .init_resource::<FixedUpdateCounter>()
355 .add_systems(Startup, write_message)
356 .add_systems(FixedUpdate, count_fixed_updates)
357 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
358
359 for frame in 0..10 {
360 app.update();
361 let fixed_updates_seen = app.world().resource::<FixedUpdateCounter>().0;
362 let messages = app.world().resource::<Messages<DummyMessage>>();
363 let n_total_messages = messages.len();
364 let n_current_messages = messages.iter_current_update_messages().count();
365 let message_registry = app.world().resource::<MessageRegistry>();
366 let should_update = message_registry.should_update;
367
368 println!("Frame {frame}, {fixed_updates_seen} fixed updates seen. Should update: {should_update:?}");
369 println!("Total messages: {n_total_messages} | Current messages: {n_current_messages}",);
370
371 match frame {
372 0 | 1 => {
373 assert_eq!(fixed_updates_seen, 0);
374 assert_eq!(n_total_messages, 1);
375 assert_eq!(n_current_messages, 1);
376 assert_eq!(should_update, ShouldUpdateMessages::Waiting);
377 }
378 2 => {
379 assert_eq!(fixed_updates_seen, 1); assert_eq!(n_total_messages, 1);
381 assert_eq!(n_current_messages, 1);
382 assert_eq!(should_update, ShouldUpdateMessages::Ready); }
384 3 => {
385 assert_eq!(fixed_updates_seen, 1);
386 assert_eq!(n_total_messages, 1);
387 assert_eq!(n_current_messages, 0); assert_eq!(should_update, ShouldUpdateMessages::Waiting);
389 }
390 4 => {
391 assert_eq!(fixed_updates_seen, 2); assert_eq!(n_total_messages, 1);
393 assert_eq!(n_current_messages, 0);
394 assert_eq!(should_update, ShouldUpdateMessages::Ready); }
396 5 => {
397 assert_eq!(fixed_updates_seen, 2);
398 assert_eq!(n_total_messages, 0); assert_eq!(n_current_messages, 0);
400 assert_eq!(should_update, ShouldUpdateMessages::Waiting);
401 }
402 _ => {
403 assert_eq!(n_total_messages, 0); assert_eq!(n_current_messages, 0);
405 }
406 }
407 }
408 }
409}