Skip to main content

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