bevy_ecs/system/
system.rs

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