#![expect(1clippy::module_inception,2reason = "This instance of module inception is being discussed; see #17353."3)]4use bevy_utils::prelude::DebugName;5use bitflags::bitflags;6use core::fmt::{Debug, Display};7use log::warn;89use crate::{10component::{CheckChangeTicks, Tick},11error::BevyError,12query::FilteredAccessSet,13schedule::InternedSystemSet,14system::{input::SystemInput, SystemIn},15world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},16};1718use alloc::{boxed::Box, vec::Vec};19use core::any::{Any, TypeId};2021use super::{IntoSystem, SystemParamValidationError};2223bitflags! {24/// Bitflags representing system states and requirements.25#[derive(Clone, Copy, PartialEq, Eq, Hash)]26pub struct SystemStateFlags: u8 {27/// Set if system cannot be sent across threads28const NON_SEND = 1 << 0;29/// Set if system requires exclusive World access30const EXCLUSIVE = 1 << 1;31/// Set if system has deferred buffers.32const DEFERRED = 1 << 2;33}34}35/// An ECS system that can be added to a [`Schedule`](crate::schedule::Schedule)36///37/// Systems are functions with all arguments implementing38/// [`SystemParam`](crate::system::SystemParam).39///40/// Systems are added to an application using `App::add_systems(Update, my_system)`41/// or similar methods, and will generally run once per pass of the main loop.42///43/// Systems are executed in parallel, in opportunistic order; data access is managed automatically.44/// It's possible to specify explicit execution order between specific systems,45/// see [`IntoScheduleConfigs`](crate::schedule::IntoScheduleConfigs).46#[diagnostic::on_unimplemented(message = "`{Self}` is not a system", label = "invalid system")]47pub trait System: Send + Sync + 'static {48/// The system's input.49type In: SystemInput;50/// The system's output.51type Out;5253/// Returns the system's name.54fn name(&self) -> DebugName;55/// Returns the [`TypeId`] of the underlying system type.56#[inline]57fn type_id(&self) -> TypeId {58TypeId::of::<Self>()59}6061/// Returns the [`SystemStateFlags`] of the system.62fn flags(&self) -> SystemStateFlags;6364/// Returns true if the system is [`Send`].65#[inline]66fn is_send(&self) -> bool {67!self.flags().intersects(SystemStateFlags::NON_SEND)68}6970/// Returns true if the system must be run exclusively.71#[inline]72fn is_exclusive(&self) -> bool {73self.flags().intersects(SystemStateFlags::EXCLUSIVE)74}7576/// Returns true if system has deferred buffers.77#[inline]78fn has_deferred(&self) -> bool {79self.flags().intersects(SystemStateFlags::DEFERRED)80}8182/// Runs the system with the given input in the world. Unlike [`System::run`], this function83/// can be called in parallel with other systems and may break Rust's aliasing rules84/// if used incorrectly, making it unsafe to call.85///86/// Unlike [`System::run`], this will not apply deferred parameters, which must be independently87/// applied by calling [`System::apply_deferred`] at later point in time.88///89/// # Safety90///91/// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data92/// registered in the access returned from [`System::initialize`]. There must be no conflicting93/// simultaneous accesses while the system is running.94/// - If [`System::is_exclusive`] returns `true`, then it must be valid to call95/// [`UnsafeWorldCell::world_mut`] on `world`.96unsafe fn run_unsafe(97&mut self,98input: SystemIn<'_, Self>,99world: UnsafeWorldCell,100) -> Result<Self::Out, RunSystemError>;101102/// Refresh the inner pointer based on the latest hot patch jump table103#[cfg(feature = "hotpatching")]104fn refresh_hotpatch(&mut self);105106/// Runs the system with the given input in the world.107///108/// For [read-only](ReadOnlySystem) systems, see [`run_readonly`], which can be called using `&World`.109///110/// Unlike [`System::run_unsafe`], this will apply deferred parameters *immediately*.111///112/// [`run_readonly`]: ReadOnlySystem::run_readonly113fn run(114&mut self,115input: SystemIn<'_, Self>,116world: &mut World,117) -> Result<Self::Out, RunSystemError> {118let ret = self.run_without_applying_deferred(input, world)?;119self.apply_deferred(world);120Ok(ret)121}122123/// Runs the system with the given input in the world.124///125/// [`run_readonly`]: ReadOnlySystem::run_readonly126fn run_without_applying_deferred(127&mut self,128input: SystemIn<'_, Self>,129world: &mut World,130) -> Result<Self::Out, RunSystemError> {131let world_cell = world.as_unsafe_world_cell();132// SAFETY:133// - We have exclusive access to the entire world.134unsafe { self.validate_param_unsafe(world_cell) }?;135// SAFETY:136// - We have exclusive access to the entire world.137// - `update_archetype_component_access` has been called.138unsafe { self.run_unsafe(input, world_cell) }139}140141/// 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.144fn apply_deferred(&mut self, world: &mut World);145146/// Enqueues any [`Deferred`](crate::system::Deferred) system parameters (or other system buffers)147/// of this system into the world's command buffer.148fn queue_deferred(&mut self, world: DeferredWorld);149150/// 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 variant154/// 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/// # Safety162///163/// - The caller must ensure that [`world`](UnsafeWorldCell) has permission to access any world data164/// registered in the access returned from [`System::initialize`]. There must be no conflicting165/// simultaneous accesses while the system is running.166unsafe fn validate_param_unsafe(167&mut self,168world: UnsafeWorldCell,169) -> Result<(), SystemParamValidationError>;170171/// Safe version of [`System::validate_param_unsafe`].172/// that runs on exclusive, single-threaded `world` pointer.173fn validate_param(&mut self, world: &World) -> Result<(), SystemParamValidationError> {174let world_cell = world.as_unsafe_world_cell_readonly();175// SAFETY:176// - We have exclusive access to the entire world.177unsafe { self.validate_param_unsafe(world_cell) }178}179180/// Initialize the system.181///182/// Returns a [`FilteredAccessSet`] with the access required to run the system.183fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet;184185/// 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.189fn check_change_tick(&mut self, check: CheckChangeTicks);190191/// Returns the system's default [system sets](crate::schedule::SystemSet).192///193/// Each system will create a default system set that contains the system.194fn default_system_sets(&self) -> Vec<InternedSystemSet> {195Vec::new()196}197198/// Gets the tick indicating the last time this system ran.199fn get_last_run(&self) -> Tick;200201/// Overwrites the tick indicating the last time this system ran.202///203/// # Warning204/// 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.207fn set_last_run(&mut self, last_run: Tick);208}209210/// [`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::ReadOnlySystemParam217/// [`Commands`]: crate::system::Commands218///219/// # Safety220///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(224message = "`{Self}` is not a read-only system",225label = "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.232fn run_readonly(233&mut self,234input: SystemIn<'_, Self>,235world: &World,236) -> Result<Self::Out, RunSystemError> {237let world = world.as_unsafe_world_cell_readonly();238// SAFETY:239// - We have read-only access to the entire world.240unsafe { self.validate_param_unsafe(world) }?;241// SAFETY:242// - We have read-only access to the entire world.243// - `update_archetype_component_access` has been called.244unsafe { self.run_unsafe(input, world) }245}246}247248/// A convenience type alias for a boxed [`System`] trait object.249pub type BoxedSystem<In = (), Out = ()> = Box<dyn System<In = In, Out = Out>>;250251/// A convenience type alias for a boxed [`ReadOnlySystem`] trait object.252pub type BoxedReadOnlySystem<In = (), Out = ()> = Box<dyn ReadOnlySystem<In = In, Out = Out>>;253254pub(crate) fn check_system_change_tick(255last_run: &mut Tick,256check: CheckChangeTicks,257system_name: DebugName,258) {259if last_run.check_tick(check) {260let age = check.present_tick().relative_to(*last_run).get();261warn!(262"System '{system_name}' has not run for {age} ticks. \263Changes older than {} ticks will not be detected.",264Tick::MAX.get() - 1,265);266}267}268269impl<In, Out> Debug for dyn System<In = In, Out = Out>270where271In: SystemInput + 'static,272Out: 'static,273{274fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {275f.debug_struct("System")276.field("name", &self.name())277.field("is_exclusive", &self.is_exclusive())278.field("is_send", &self.is_send())279.finish_non_exhaustive()280}281}282283/// Trait used to run a system immediately on a [`World`].284///285/// # Warning286/// This function is not an efficient method of running systems and it's meant to be used as a utility287/// for testing and/or diagnostics.288///289/// Systems called through [`run_system_once`](RunSystemOnce::run_system_once) do not hold onto any state,290/// as they are created and destroyed every time [`run_system_once`](RunSystemOnce::run_system_once) is called.291/// Practically, this means that [`Local`](crate::system::Local) variables are292/// reset on every run and change detection does not work.293///294/// ```295/// # use bevy_ecs::prelude::*;296/// # use bevy_ecs::system::RunSystemOnce;297/// #[derive(Resource, Default)]298/// struct Counter(u8);299///300/// fn increment(mut counter: Local<Counter>) {301/// counter.0 += 1;302/// println!("{}", counter.0);303/// }304///305/// let mut world = World::default();306/// world.run_system_once(increment); // prints 1307/// world.run_system_once(increment); // still prints 1308/// ```309///310/// If you do need systems to hold onto state between runs, use [`World::run_system_cached`](World::run_system_cached)311/// or [`World::run_system`](World::run_system).312///313/// # Usage314/// Typically, to test a system, or to extract specific diagnostics information from a world,315/// you'd need a [`Schedule`](crate::schedule::Schedule) to run the system. This can create redundant boilerplate code316/// when writing tests or trying to quickly iterate on debug specific systems.317///318/// For these situations, this function can be useful because it allows you to execute a system319/// immediately with some custom input and retrieve its output without requiring the necessary boilerplate.320///321/// # Examples322///323/// ## Immediate Command Execution324///325/// This usage is helpful when trying to test systems or functions that operate on [`Commands`](crate::system::Commands):326/// ```327/// # use bevy_ecs::prelude::*;328/// # use bevy_ecs::system::RunSystemOnce;329/// let mut world = World::default();330/// let entity = world.run_system_once(|mut commands: Commands| {331/// commands.spawn_empty().id()332/// }).unwrap();333/// # assert!(world.get_entity(entity).is_ok());334/// ```335///336/// ## Immediate Queries337///338/// This usage is helpful when trying to run an arbitrary query on a world for testing or debugging purposes:339/// ```340/// # use bevy_ecs::prelude::*;341/// # use bevy_ecs::system::RunSystemOnce;342///343/// #[derive(Component)]344/// struct T(usize);345///346/// let mut world = World::default();347/// world.spawn(T(0));348/// world.spawn(T(1));349/// world.spawn(T(1));350/// let count = world.run_system_once(|query: Query<&T>| {351/// query.iter().filter(|t| t.0 == 1).count()352/// }).unwrap();353///354/// # assert_eq!(count, 2);355/// ```356///357/// Note that instead of closures you can also pass in regular functions as systems:358///359/// ```360/// # use bevy_ecs::prelude::*;361/// # use bevy_ecs::system::RunSystemOnce;362///363/// #[derive(Component)]364/// struct T(usize);365///366/// fn count(query: Query<&T>) -> usize {367/// query.iter().filter(|t| t.0 == 1).count()368/// }369///370/// let mut world = World::default();371/// world.spawn(T(0));372/// world.spawn(T(1));373/// world.spawn(T(1));374/// let count = world.run_system_once(count).unwrap();375///376/// # assert_eq!(count, 2);377/// ```378pub trait RunSystemOnce: Sized {379/// Tries to run a system and apply its deferred parameters.380fn run_system_once<T, Out, Marker>(self, system: T) -> Result<Out, RunSystemError>381where382T: IntoSystem<(), Out, Marker>,383{384self.run_system_once_with(system, ())385}386387/// Tries to run a system with given input and apply deferred parameters.388fn run_system_once_with<T, In, Out, Marker>(389self,390system: T,391input: SystemIn<'_, T::System>,392) -> Result<Out, RunSystemError>393where394T: IntoSystem<In, Out, Marker>,395In: SystemInput;396}397398impl RunSystemOnce for &mut World {399fn run_system_once_with<T, In, Out, Marker>(400self,401system: T,402input: SystemIn<'_, T::System>,403) -> Result<Out, RunSystemError>404where405T: IntoSystem<In, Out, Marker>,406In: SystemInput,407{408let mut system: T::System = IntoSystem::into_system(system);409system.initialize(self);410system.run(input, self)411}412}413414/// Running system failed.415#[derive(Debug)]416pub enum RunSystemError {417/// System could not be run due to parameters that failed validation.418/// This is not considered an error.419Skipped(SystemParamValidationError),420/// System returned an error or failed required parameter validation.421Failed(BevyError),422}423424impl Display for RunSystemError {425fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {426match self {427Self::Skipped(err) => write!(428f,429"System did not run due to failed parameter validation: {err}"430),431Self::Failed(err) => write!(f, "{err}"),432}433}434}435436impl<E: Any> From<E> for RunSystemError437where438BevyError: From<E>,439{440fn from(mut value: E) -> Self {441// Specialize the impl so that a skipped `SystemParamValidationError`442// is converted to `Skipped` instead of `Failed`.443// Note that the `downcast_mut` check is based on the static type,444// and can be optimized out after monomorphization.445let any: &mut dyn Any = &mut value;446if let Some(err) = any.downcast_mut::<SystemParamValidationError>() {447if err.skipped {448return Self::Skipped(core::mem::replace(err, SystemParamValidationError::EMPTY));449}450}451Self::Failed(From::from(value))452}453}454455#[cfg(test)]456mod tests {457use super::*;458use crate::prelude::*;459use alloc::string::ToString;460461#[test]462fn run_system_once() {463struct T(usize);464465impl Resource for T {}466467fn system(In(n): In<usize>, mut commands: Commands) -> usize {468commands.insert_resource(T(n));469n + 1470}471472let mut world = World::default();473let n = world.run_system_once_with(system, 1).unwrap();474assert_eq!(n, 2);475assert_eq!(world.resource::<T>().0, 1);476}477478#[derive(Resource, Default, PartialEq, Debug)]479struct Counter(u8);480481fn count_up(mut counter: ResMut<Counter>) {482counter.0 += 1;483}484485#[test]486fn run_two_systems() {487let mut world = World::new();488world.init_resource::<Counter>();489assert_eq!(*world.resource::<Counter>(), Counter(0));490world.run_system_once(count_up).unwrap();491assert_eq!(*world.resource::<Counter>(), Counter(1));492world.run_system_once(count_up).unwrap();493assert_eq!(*world.resource::<Counter>(), Counter(2));494}495496#[derive(Component)]497struct A;498499fn spawn_entity(mut commands: Commands) {500commands.spawn(A);501}502503#[test]504fn command_processing() {505let mut world = World::new();506assert_eq!(world.query::<&A>().query(&world).count(), 0);507world.run_system_once(spawn_entity).unwrap();508assert_eq!(world.query::<&A>().query(&world).count(), 1);509}510511#[test]512fn non_send_resources() {513fn non_send_count_down(mut ns: NonSendMut<Counter>) {514ns.0 -= 1;515}516517let mut world = World::new();518world.insert_non_send_resource(Counter(10));519assert_eq!(*world.non_send_resource::<Counter>(), Counter(10));520world.run_system_once(non_send_count_down).unwrap();521assert_eq!(*world.non_send_resource::<Counter>(), Counter(9));522}523524#[test]525fn run_system_once_invalid_params() {526struct T;527impl Resource for T {}528fn system(_: Res<T>) {}529530let mut world = World::default();531// This fails because `T` has not been added to the world yet.532let result = world.run_system_once(system);533534assert!(matches!(result, Err(RunSystemError::Failed { .. })));535536let expected = "Resource does not exist";537let actual = result.unwrap_err().to_string();538539assert!(540actual.contains(expected),541"Expected error message to contain `{}` but got `{}`",542expected,543actual544);545}546}547548549