bevy_ecs/system/system.rs
1#![expect(
2 clippy::module_inception,
3 reason = "This instance of module inception is being discussed; see #17353."
4)]
5use bevy_utils::prelude::DebugName;
6use bitflags::bitflags;
7use core::fmt::{Debug, Display};
8use log::warn;
9
10use crate::{
11 change_detection::{CheckChangeTicks, Tick},
12 error::BevyError,
13 query::FilteredAccessSet,
14 schedule::InternedSystemSet,
15 system::{input::SystemInput, SystemIn},
16 world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},
17};
18
19use alloc::{boxed::Box, vec::Vec};
20use core::any::{Any, TypeId};
21
22use super::{IntoSystem, SystemParamValidationError};
23
24bitflags! {
25 /// Bitflags representing system states and requirements.
26 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
27 pub struct SystemStateFlags: u8 {
28 /// Set if system cannot be sent across threads
29 const NON_SEND = 1 << 0;
30 /// Set if system requires exclusive World access
31 const EXCLUSIVE = 1 << 1;
32 /// Set if system has deferred buffers.
33 const DEFERRED = 1 << 2;
34 }
35}
36/// An ECS system that can be added to a [`Schedule`](crate::schedule::Schedule)
37///
38/// Systems are functions with all arguments implementing
39/// [`SystemParam`](crate::system::SystemParam).
40///
41/// Systems are added to an application using `App::add_systems(Update, my_system)`
42/// or similar methods, and will generally run once per pass of the main loop.
43///
44/// Systems are executed in parallel, in opportunistic order; data access is managed automatically.
45/// It's possible to specify explicit execution order between specific systems,
46/// see [`IntoScheduleConfigs`](crate::schedule::IntoScheduleConfigs).
47#[diagnostic::on_unimplemented(message = "`{Self}` is not a system", label = "invalid system")]
48pub trait System: Send + Sync + 'static {
49 /// The system's input.
50 type In: SystemInput;
51 /// The system's output.
52 type Out;
53
54 /// Returns the system's name.
55 fn name(&self) -> DebugName;
56 /// Returns the [`TypeId`] of the underlying system type.
57 #[inline]
58 fn type_id(&self) -> TypeId {
59 TypeId::of::<Self>()
60 }
61
62 /// Returns the [`SystemStateFlags`] of the system.
63 fn flags(&self) -> SystemStateFlags;
64
65 /// Returns true if the system is [`Send`].
66 #[inline]
67 fn is_send(&self) -> bool {
68 !self.flags().intersects(SystemStateFlags::NON_SEND)
69 }
70
71 /// Returns true if the system must be run exclusively.
72 #[inline]
73 fn is_exclusive(&self) -> bool {
74 self.flags().intersects(SystemStateFlags::EXCLUSIVE)
75 }
76
77 /// Returns true if system has deferred buffers.
78 #[inline]
79 fn has_deferred(&self) -> bool {
80 self.flags().intersects(SystemStateFlags::DEFERRED)
81 }
82
83 /// Runs the system with the given input in the world. Unlike [`System::run`], this function
84 /// can be called in parallel with other systems and may break Rust's aliasing rules
85 /// if used incorrectly, making it unsafe to call.
86 ///
87 /// Unlike [`System::run`], this will not apply deferred parameters, which must be independently
88 /// applied by calling [`System::apply_deferred`] at later point in time.
89 ///
90 /// # Safety
91 ///
92 /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data
93 /// registered in the access returned from [`System::initialize`]. There must be no conflicting
94 /// simultaneous accesses while the system is running.
95 /// - If [`System::is_exclusive`] returns `true`, then it must be valid to call
96 /// [`UnsafeWorldCell::world_mut`] on `world`.
97 unsafe fn run_unsafe(
98 &mut self,
99 input: SystemIn<'_, Self>,
100 world: UnsafeWorldCell,
101 ) -> Result<Self::Out, RunSystemError>;
102
103 /// Refresh the inner pointer based on the latest hot patch jump table
104 #[cfg(feature = "hotpatching")]
105 fn refresh_hotpatch(&mut self);
106
107 /// Runs the system with the given input in the world.
108 ///
109 /// For [read-only](ReadOnlySystem) systems, see [`run_readonly`], which can be called using `&World`.
110 ///
111 /// Unlike [`System::run_unsafe`], this will apply deferred parameters *immediately*.
112 ///
113 /// [`run_readonly`]: ReadOnlySystem::run_readonly
114 fn run(
115 &mut self,
116 input: SystemIn<'_, Self>,
117 world: &mut World,
118 ) -> Result<Self::Out, RunSystemError> {
119 let ret = self.run_without_applying_deferred(input, world)?;
120 self.apply_deferred(world);
121 Ok(ret)
122 }
123
124 /// Runs the system with the given input in the world.
125 ///
126 /// [`run_readonly`]: ReadOnlySystem::run_readonly
127 fn run_without_applying_deferred(
128 &mut self,
129 input: SystemIn<'_, Self>,
130 world: &mut World,
131 ) -> Result<Self::Out, RunSystemError> {
132 let world_cell = world.as_unsafe_world_cell();
133 // SAFETY:
134 // - We have exclusive access to the entire world.
135 unsafe { self.validate_param_unsafe(world_cell) }?;
136 // SAFETY:
137 // - We have exclusive access to the entire world.
138 unsafe { self.run_unsafe(input, world_cell) }
139 }
140
141 /// Applies any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers) of this system to the world.
142 ///
143 /// This is where [`Commands`](crate::system::Commands) get applied.
144 fn apply_deferred(&mut self, world: &mut World);
145
146 /// Enqueues any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers)
147 /// of this system into the world's command buffer.
148 fn queue_deferred(&mut self, world: DeferredWorld);
149
150 /// Validates that all parameters can be acquired and that system can run without panic.
151 /// Built-in executors use this to prevent invalid systems from running.
152 ///
153 /// However calling and respecting [`System::validate_param_unsafe`] or its safe variant
154 /// is not a strict requirement, both [`System::run`] and [`System::run_unsafe`]
155 /// should provide their own safety mechanism to prevent undefined behavior.
156 ///
157 /// This method has to be called directly before [`System::run_unsafe`] with no other (relevant)
158 /// world mutations in between. Otherwise, while it won't lead to any undefined behavior,
159 /// the validity of the param may change.
160 ///
161 /// # Safety
162 ///
163 /// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data
164 /// registered in the access returned from [`System::initialize`]. There must be no conflicting
165 /// simultaneous accesses while the system is running.
166 unsafe fn validate_param_unsafe(
167 &mut self,
168 world: UnsafeWorldCell,
169 ) -> Result<(), SystemParamValidationError>;
170
171 /// Safe version of [`System::validate_param_unsafe`].
172 /// that runs on exclusive, single-threaded `world` pointer.
173 fn validate_param(&mut self, world: &World) -> Result<(), SystemParamValidationError> {
174 let world_cell = world.as_unsafe_world_cell_readonly();
175 // SAFETY:
176 // - We have exclusive access to the entire world.
177 unsafe { self.validate_param_unsafe(world_cell) }
178 }
179
180 /// Initialize the system.
181 ///
182 /// Returns a [`FilteredAccessSet`] with the access required to run the system.
183 fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet;
184
185 /// Checks any [`Tick`]s stored on this system and wraps their value if they get too old.
186 ///
187 /// This method must be called periodically to ensure that change detection behaves correctly.
188 /// When using bevy's default configuration, this will be called for you as needed.
189 fn check_change_tick(&mut self, check: CheckChangeTicks);
190
191 /// Returns the system's default [system sets](crate::schedule::SystemSet).
192 ///
193 /// Each system will create a default system set that contains the system.
194 fn default_system_sets(&self) -> Vec<InternedSystemSet> {
195 Vec::new()
196 }
197
198 /// Gets the tick indicating the last time this system ran.
199 fn get_last_run(&self) -> Tick;
200
201 /// Overwrites the tick indicating the last time this system ran.
202 ///
203 /// # Warning
204 /// This is a complex and error-prone operation, that can have unexpected consequences on any system relying on this code.
205 /// However, it can be an essential escape hatch when, for example,
206 /// you are trying to synchronize representations using change detection and need to avoid infinite recursion.
207 fn set_last_run(&mut self, last_run: Tick);
208}
209
210/// [`System`] types that do not modify the [`World`] when run.
211/// This is implemented for any systems whose parameters all implement [`ReadOnlySystemParam`].
212///
213/// Note that systems which perform [deferred](System::apply_deferred) mutations (such as with [`Commands`])
214/// may implement this trait.
215///
216/// [`ReadOnlySystemParam`]: crate::system::ReadOnlySystemParam
217/// [`Commands`]: crate::system::Commands
218///
219/// # Safety
220///
221/// This must only be implemented for system types which do not mutate the `World`
222/// when [`System::run_unsafe`] is called.
223#[diagnostic::on_unimplemented(
224 message = "`{Self}` is not a read-only system",
225 label = "invalid read-only system"
226)]
227pub unsafe trait ReadOnlySystem: System {
228 /// Runs this system with the given input in the world.
229 ///
230 /// Unlike [`System::run`], this can be called with a shared reference to the world,
231 /// since this system is known not to modify the world.
232 fn run_readonly(
233 &mut self,
234 input: SystemIn<'_, Self>,
235 world: &World,
236 ) -> Result<Self::Out, RunSystemError> {
237 let world = world.as_unsafe_world_cell_readonly();
238 // SAFETY:
239 // - We have read-only access to the entire world.
240 unsafe { self.validate_param_unsafe(world) }?;
241 // SAFETY:
242 // - We have read-only access to the entire world.
243 unsafe { self.run_unsafe(input, world) }
244 }
245}
246
247/// A convenience type alias for a boxed [`System`] trait object.
248pub type BoxedSystem<In = (), Out = ()> = Box<dyn System<In = In, Out = Out>>;
249
250/// A convenience type alias for a boxed [`ReadOnlySystem`] trait object.
251pub type BoxedReadOnlySystem<In = (), Out = ()> = Box<dyn ReadOnlySystem<In = In, Out = Out>>;
252
253pub(crate) fn check_system_change_tick(
254 last_run: &mut Tick,
255 check: CheckChangeTicks,
256 system_name: DebugName,
257) {
258 if last_run.check_tick(check) {
259 let age = check.present_tick().relative_to(*last_run).get();
260 warn!(
261 "System '{system_name}' has not run for {age} ticks. \
262 Changes older than {} ticks will not be detected.",
263 Tick::MAX.get() - 1,
264 );
265 }
266}
267
268impl<In, Out> Debug for dyn System<In = In, Out = Out>
269where
270 In: SystemInput + 'static,
271 Out: 'static,
272{
273 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
274 f.debug_struct("System")
275 .field("name", &self.name())
276 .field("is_exclusive", &self.is_exclusive())
277 .field("is_send", &self.is_send())
278 .finish_non_exhaustive()
279 }
280}
281
282/// Trait used to run a system immediately on a [`World`].
283///
284/// # Warning
285/// This function is not an efficient method of running systems and it's meant to be used as a utility
286/// for testing and/or diagnostics.
287///
288/// Systems called through [`run_system_once`](RunSystemOnce::run_system_once) do not hold onto any state,
289/// as they are created and destroyed every time [`run_system_once`](RunSystemOnce::run_system_once) is called.
290/// Practically, this means that [`Local`](crate::system::Local) variables are
291/// reset on every run and change detection does not work.
292///
293/// ```
294/// # use bevy_ecs::prelude::*;
295/// # use bevy_ecs::system::RunSystemOnce;
296/// #[derive(Resource, Default)]
297/// struct Counter(u8);
298///
299/// fn increment(mut counter: Local<Counter>) {
300/// counter.0 += 1;
301/// println!("{}", counter.0);
302/// }
303///
304/// let mut world = World::default();
305/// world.run_system_once(increment); // prints 1
306/// world.run_system_once(increment); // still prints 1
307/// ```
308///
309/// If you do need systems to hold onto state between runs, use [`World::run_system_cached`](World::run_system_cached)
310/// or [`World::run_system`](World::run_system).
311///
312/// # Usage
313/// Typically, to test a system, or to extract specific diagnostics information from a world,
314/// you'd need a [`Schedule`](crate::schedule::Schedule) to run the system. This can create redundant boilerplate code
315/// when writing tests or trying to quickly iterate on debug specific systems.
316///
317/// For these situations, this function can be useful because it allows you to execute a system
318/// immediately with some custom input and retrieve its output without requiring the necessary boilerplate.
319///
320/// # Examples
321///
322/// ## Immediate Command Execution
323///
324/// This usage is helpful when trying to test systems or functions that operate on [`Commands`](crate::system::Commands):
325/// ```
326/// # use bevy_ecs::prelude::*;
327/// # use bevy_ecs::system::RunSystemOnce;
328/// let mut world = World::default();
329/// let entity = world.run_system_once(|mut commands: Commands| {
330/// commands.spawn_empty().id()
331/// }).unwrap();
332/// # assert!(world.get_entity(entity).is_ok());
333/// ```
334///
335/// ## Immediate Queries
336///
337/// This usage is helpful when trying to run an arbitrary query on a world for testing or debugging purposes:
338/// ```
339/// # use bevy_ecs::prelude::*;
340/// # use bevy_ecs::system::RunSystemOnce;
341///
342/// #[derive(Component)]
343/// struct T(usize);
344///
345/// let mut world = World::default();
346/// world.spawn(T(0));
347/// world.spawn(T(1));
348/// world.spawn(T(1));
349/// let count = world.run_system_once(|query: Query<&T>| {
350/// query.iter().filter(|t| t.0 == 1).count()
351/// }).unwrap();
352///
353/// # assert_eq!(count, 2);
354/// ```
355///
356/// Note that instead of closures you can also pass in regular functions as systems:
357///
358/// ```
359/// # use bevy_ecs::prelude::*;
360/// # use bevy_ecs::system::RunSystemOnce;
361///
362/// #[derive(Component)]
363/// struct T(usize);
364///
365/// fn count(query: Query<&T>) -> usize {
366/// query.iter().filter(|t| t.0 == 1).count()
367/// }
368///
369/// let mut world = World::default();
370/// world.spawn(T(0));
371/// world.spawn(T(1));
372/// world.spawn(T(1));
373/// let count = world.run_system_once(count).unwrap();
374///
375/// # assert_eq!(count, 2);
376/// ```
377pub trait RunSystemOnce: Sized {
378 /// Tries to run a system and apply its deferred parameters.
379 fn run_system_once<T, Out, Marker>(self, system: T) -> Result<Out, RunSystemError>
380 where
381 T: IntoSystem<(), Out, Marker>,
382 {
383 self.run_system_once_with(system, ())
384 }
385
386 /// Tries to run a system with given input and apply deferred parameters.
387 fn run_system_once_with<T, In, Out, Marker>(
388 self,
389 system: T,
390 input: SystemIn<'_, T::System>,
391 ) -> Result<Out, RunSystemError>
392 where
393 T: IntoSystem<In, Out, Marker>,
394 In: SystemInput;
395}
396
397impl RunSystemOnce for &mut World {
398 fn run_system_once_with<T, In, Out, Marker>(
399 self,
400 system: T,
401 input: SystemIn<'_, T::System>,
402 ) -> Result<Out, RunSystemError>
403 where
404 T: IntoSystem<In, Out, Marker>,
405 In: SystemInput,
406 {
407 let mut system: T::System = IntoSystem::into_system(system);
408 system.initialize(self);
409 system.run(input, self)
410 }
411}
412
413/// Running system failed.
414#[derive(Debug)]
415pub enum RunSystemError {
416 /// System could not be run due to parameters that failed validation.
417 /// This is not considered an error.
418 Skipped(SystemParamValidationError),
419 /// System returned an error or failed required parameter validation.
420 Failed(BevyError),
421}
422
423impl Display for RunSystemError {
424 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
425 match self {
426 Self::Skipped(err) => write!(
427 f,
428 "System did not run due to failed parameter validation: {err}"
429 ),
430 Self::Failed(err) => write!(f, "{err}"),
431 }
432 }
433}
434
435impl<E: Any> From<E> for RunSystemError
436where
437 BevyError: From<E>,
438{
439 fn from(mut value: E) -> Self {
440 // Specialize the impl so that a skipped `SystemParamValidationError`
441 // is converted to `Skipped` instead of `Failed`.
442 // Note that the `downcast_mut` check is based on the static type,
443 // and can be optimized out after monomorphization.
444 let any: &mut dyn Any = &mut value;
445 if let Some(err) = any.downcast_mut::<SystemParamValidationError>()
446 && err.skipped
447 {
448 return Self::Skipped(core::mem::replace(err, SystemParamValidationError::EMPTY));
449 }
450 Self::Failed(From::from(value))
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457 use crate::prelude::*;
458 use alloc::string::ToString;
459
460 #[test]
461 fn run_system_once() {
462 #[derive(Resource)]
463 struct T(usize);
464
465 fn system(In(n): In<usize>, mut commands: Commands) -> usize {
466 commands.insert_resource(T(n));
467 n + 1
468 }
469
470 let mut world = World::default();
471 let n = world.run_system_once_with(system, 1).unwrap();
472 assert_eq!(n, 2);
473 assert_eq!(world.resource::<T>().0, 1);
474 }
475
476 #[derive(Resource, Default, PartialEq, Debug)]
477 struct Counter(u8);
478
479 fn count_up(mut counter: ResMut<Counter>) {
480 counter.0 += 1;
481 }
482
483 #[test]
484 fn run_two_systems() {
485 let mut world = World::new();
486 world.init_resource::<Counter>();
487 assert_eq!(*world.resource::<Counter>(), Counter(0));
488 world.run_system_once(count_up).unwrap();
489 assert_eq!(*world.resource::<Counter>(), Counter(1));
490 world.run_system_once(count_up).unwrap();
491 assert_eq!(*world.resource::<Counter>(), Counter(2));
492 }
493
494 #[derive(Component)]
495 struct A;
496
497 fn spawn_entity(mut commands: Commands) {
498 commands.spawn(A);
499 }
500
501 #[test]
502 fn command_processing() {
503 let mut world = World::new();
504 assert_eq!(world.entities.count_spawned(), 0);
505 world.run_system_once(spawn_entity).unwrap();
506 assert_eq!(world.entities.count_spawned(), 1);
507 }
508
509 #[test]
510 fn non_send_resources() {
511 fn non_send_count_down(mut ns: NonSendMut<Counter>) {
512 ns.0 -= 1;
513 }
514
515 let mut world = World::new();
516 world.insert_non_send_resource(Counter(10));
517 assert_eq!(*world.non_send_resource::<Counter>(), Counter(10));
518 world.run_system_once(non_send_count_down).unwrap();
519 assert_eq!(*world.non_send_resource::<Counter>(), Counter(9));
520 }
521
522 #[test]
523 fn run_system_once_invalid_params() {
524 #[derive(Resource)]
525 struct T;
526
527 fn system(_: Res<T>) {}
528
529 let mut world = World::default();
530 // This fails because `T` has not been added to the world yet.
531 let result = world.run_system_once(system);
532
533 assert!(matches!(result, Err(RunSystemError::Failed { .. })));
534
535 let expected = "Resource does not exist";
536 let actual = result.unwrap_err().to_string();
537
538 assert!(
539 actual.contains(expected),
540 "Expected error message to contain `{}` but got `{}`",
541 expected,
542 actual
543 );
544 }
545}