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