bevy_ecs/system/commands/
mod.rs

1pub mod command;
2pub mod entity_command;
3
4#[cfg(feature = "std")]
5mod parallel_scope;
6
7use bevy_ptr::move_as_ptr;
8pub use command::Command;
9pub use entity_command::EntityCommand;
10
11#[cfg(feature = "std")]
12pub use parallel_scope::*;
13
14use alloc::boxed::Box;
15use core::marker::PhantomData;
16
17use crate::{
18    self as bevy_ecs,
19    bundle::{Bundle, InsertMode, NoBundleEffect},
20    change_detection::{MaybeLocation, Mut},
21    component::{Component, ComponentId, Mutable},
22    entity::{
23        Entities, Entity, EntityAllocator, EntityClonerBuilder, EntityNotSpawnedError,
24        InvalidEntityError, OptIn, OptOut,
25    },
26    error::{warn, BevyError, CommandWithEntity, ErrorContext, HandleError},
27    event::{EntityEvent, Event},
28    message::Message,
29    observer::Observer,
30    resource::Resource,
31    schedule::ScheduleLabel,
32    system::{
33        Deferred, IntoObserverSystem, IntoSystem, RegisteredSystem, SystemId, SystemInput,
34        SystemParamValidationError,
35    },
36    world::{
37        command_queue::RawCommandQueue, unsafe_world_cell::UnsafeWorldCell, CommandQueue,
38        EntityWorldMut, FromWorld, World,
39    },
40};
41
42/// A [`Command`] queue to perform structural changes to the [`World`].
43///
44/// Since each command requires exclusive access to the `World`,
45/// all queued commands are automatically applied in sequence
46/// when the `ApplyDeferred` system runs (see [`ApplyDeferred`] documentation for more details).
47///
48/// Each command can be used to modify the [`World`] in arbitrary ways:
49/// * spawning or despawning entities
50/// * inserting components on new or existing entities
51/// * inserting resources
52/// * etc.
53///
54/// For a version of [`Commands`] that works in parallel contexts (such as
55/// within [`Query::par_iter`](crate::system::Query::par_iter)) see
56/// [`ParallelCommands`]
57///
58/// # Usage
59///
60/// Add `mut commands: Commands` as a function argument to your system to get a
61/// copy of this struct that will be applied the next time a copy of [`ApplyDeferred`] runs.
62/// Commands are almost always used as a [`SystemParam`](crate::system::SystemParam).
63///
64/// ```
65/// # use bevy_ecs::prelude::*;
66/// fn my_system(mut commands: Commands) {
67///    // ...
68/// }
69/// # bevy_ecs::system::assert_is_system(my_system);
70/// ```
71///
72/// # Implementing
73///
74/// Each built-in command is implemented as a separate method, e.g. [`Commands::spawn`].
75/// In addition to the pre-defined command methods, you can add commands with any arbitrary
76/// behavior using [`Commands::queue`], which accepts any type implementing [`Command`].
77///
78/// Since closures and other functions implement this trait automatically, this allows one-shot,
79/// anonymous custom commands.
80///
81/// ```
82/// # use bevy_ecs::prelude::*;
83/// # fn foo(mut commands: Commands) {
84/// // NOTE: type inference fails here, so annotations are required on the closure.
85/// commands.queue(|w: &mut World| {
86///     // Mutate the world however you want...
87/// });
88/// # }
89/// ```
90///
91/// # Error handling
92///
93/// A [`Command`] can return a [`Result`](crate::error::Result),
94/// which will be passed to an [error handler](crate::error) if the `Result` is an error.
95///
96/// The default error handler panics. It can be configured via
97/// the [`DefaultErrorHandler`](crate::error::DefaultErrorHandler) resource.
98///
99/// Alternatively, you can customize the error handler for a specific command
100/// by calling [`Commands::queue_handled`].
101///
102/// The [`error`](crate::error) module provides some simple error handlers for convenience.
103///
104/// [`ApplyDeferred`]: crate::schedule::ApplyDeferred
105pub struct Commands<'w, 's> {
106    queue: InternalQueue<'s>,
107    entities: &'w Entities,
108    allocator: &'w EntityAllocator,
109}
110
111// SAFETY: All commands [`Command`] implement [`Send`]
112unsafe impl Send for Commands<'_, '_> {}
113
114// SAFETY: `Commands` never gives access to the inner commands.
115unsafe impl Sync for Commands<'_, '_> {}
116
117const _: () = {
118    type __StructFieldsAlias<'w, 's> = (
119        Deferred<'s, CommandQueue>,
120        &'w EntityAllocator,
121        &'w Entities,
122    );
123    #[doc(hidden)]
124    pub struct FetchState {
125        state: <__StructFieldsAlias<'static, 'static> as bevy_ecs::system::SystemParam>::State,
126    }
127    // SAFETY: Only reads Entities
128    unsafe impl bevy_ecs::system::SystemParam for Commands<'_, '_> {
129        type State = FetchState;
130
131        type Item<'w, 's> = Commands<'w, 's>;
132
133        fn init_state(world: &mut World) -> Self::State {
134            FetchState {
135                state: <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_state(
136                    world,
137                ),
138            }
139        }
140
141        fn init_access(
142            state: &Self::State,
143            system_meta: &mut bevy_ecs::system::SystemMeta,
144            component_access_set: &mut bevy_ecs::query::FilteredAccessSet,
145            world: &mut World,
146        ) {
147            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_access(
148                &state.state,
149                system_meta,
150                component_access_set,
151                world,
152            );
153        }
154
155        fn apply(
156            state: &mut Self::State,
157            system_meta: &bevy_ecs::system::SystemMeta,
158            world: &mut World,
159        ) {
160            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::apply(
161                &mut state.state,
162                system_meta,
163                world,
164            );
165        }
166
167        fn queue(
168            state: &mut Self::State,
169            system_meta: &bevy_ecs::system::SystemMeta,
170            world: bevy_ecs::world::DeferredWorld,
171        ) {
172            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::queue(
173                &mut state.state,
174                system_meta,
175                world,
176            );
177        }
178
179        #[inline]
180        unsafe fn validate_param(
181            state: &mut Self::State,
182            system_meta: &bevy_ecs::system::SystemMeta,
183            world: UnsafeWorldCell,
184        ) -> Result<(), SystemParamValidationError> {
185            // SAFETY: Upheld by caller
186            unsafe {
187                <__StructFieldsAlias as bevy_ecs::system::SystemParam>::validate_param(
188                    &mut state.state,
189                    system_meta,
190                    world,
191                )
192            }
193        }
194
195        #[inline]
196        unsafe fn get_param<'w, 's>(
197            state: &'s mut Self::State,
198            system_meta: &bevy_ecs::system::SystemMeta,
199            world: UnsafeWorldCell<'w>,
200            change_tick: bevy_ecs::change_detection::Tick,
201        ) -> Self::Item<'w, 's> {
202            // SAFETY: Upheld by caller
203            let params = unsafe {
204                <__StructFieldsAlias as bevy_ecs::system::SystemParam>::get_param(
205                    &mut state.state,
206                    system_meta,
207                    world,
208                    change_tick,
209                )
210            };
211            Commands {
212                queue: InternalQueue::CommandQueue(params.0),
213                allocator: params.1,
214                entities: params.2,
215            }
216        }
217    }
218    // SAFETY: Only reads Entities
219    unsafe impl<'w, 's> bevy_ecs::system::ReadOnlySystemParam for Commands<'w, 's>
220    where
221        Deferred<'s, CommandQueue>: bevy_ecs::system::ReadOnlySystemParam,
222        &'w Entities: bevy_ecs::system::ReadOnlySystemParam,
223    {
224    }
225};
226
227enum InternalQueue<'s> {
228    CommandQueue(Deferred<'s, CommandQueue>),
229    RawCommandQueue(RawCommandQueue),
230}
231
232impl<'w, 's> Commands<'w, 's> {
233    /// Returns a new `Commands` instance from a [`CommandQueue`] and a [`World`].
234    pub fn new(queue: &'s mut CommandQueue, world: &'w World) -> Self {
235        Self::new_from_entities(queue, &world.allocator, &world.entities)
236    }
237
238    /// Returns a new `Commands` instance from a [`CommandQueue`] and an [`Entities`] reference.
239    pub fn new_from_entities(
240        queue: &'s mut CommandQueue,
241        allocator: &'w EntityAllocator,
242        entities: &'w Entities,
243    ) -> Self {
244        Self {
245            queue: InternalQueue::CommandQueue(Deferred(queue)),
246            allocator,
247            entities,
248        }
249    }
250
251    /// Returns a new `Commands` instance from a [`RawCommandQueue`] and an [`Entities`] reference.
252    ///
253    /// This is used when constructing [`Commands`] from a [`DeferredWorld`](crate::world::DeferredWorld).
254    ///
255    /// # Safety
256    ///
257    /// * Caller ensures that `queue` must outlive `'w`
258    pub(crate) unsafe fn new_raw_from_entities(
259        queue: RawCommandQueue,
260        allocator: &'w EntityAllocator,
261        entities: &'w Entities,
262    ) -> Self {
263        Self {
264            queue: InternalQueue::RawCommandQueue(queue),
265            allocator,
266            entities,
267        }
268    }
269
270    /// Returns a [`Commands`] with a smaller lifetime.
271    ///
272    /// This is useful if you have `&mut Commands` but need `Commands`.
273    ///
274    /// # Example
275    ///
276    /// ```
277    /// # use bevy_ecs::prelude::*;
278    /// fn my_system(mut commands: Commands) {
279    ///     // We do our initialization in a separate function,
280    ///     // which expects an owned `Commands`.
281    ///     do_initialization(commands.reborrow());
282    ///
283    ///     // Since we only reborrowed the commands instead of moving them, we can still use them.
284    ///     commands.spawn_empty();
285    /// }
286    /// #
287    /// # fn do_initialization(_: Commands) {}
288    /// ```
289    pub fn reborrow(&mut self) -> Commands<'w, '_> {
290        Commands {
291            queue: match &mut self.queue {
292                InternalQueue::CommandQueue(queue) => InternalQueue::CommandQueue(queue.reborrow()),
293                InternalQueue::RawCommandQueue(queue) => {
294                    InternalQueue::RawCommandQueue(queue.clone())
295                }
296            },
297            allocator: self.allocator,
298            entities: self.entities,
299        }
300    }
301
302    /// Take all commands from `other` and append them to `self`, leaving `other` empty.
303    pub fn append(&mut self, other: &mut CommandQueue) {
304        match &mut self.queue {
305            InternalQueue::CommandQueue(queue) => queue.bytes.append(&mut other.bytes),
306            InternalQueue::RawCommandQueue(queue) => {
307                // SAFETY: Pointers in `RawCommandQueue` are never null
308                unsafe { queue.bytes.as_mut() }.append(&mut other.bytes);
309            }
310        }
311    }
312
313    /// Spawns a new empty [`Entity`] and returns its corresponding [`EntityCommands`].
314    ///
315    /// # Example
316    ///
317    /// ```
318    /// # use bevy_ecs::prelude::*;
319    /// #[derive(Component)]
320    /// struct Label(&'static str);
321    /// #[derive(Component)]
322    /// struct Strength(u32);
323    /// #[derive(Component)]
324    /// struct Agility(u32);
325    ///
326    /// fn example_system(mut commands: Commands) {
327    ///     // Create a new empty entity.
328    ///     commands.spawn_empty();
329    ///
330    ///     // Create another empty entity.
331    ///     commands.spawn_empty()
332    ///         // Add a new component bundle to the entity.
333    ///         .insert((Strength(1), Agility(2)))
334    ///         // Add a single component to the entity.
335    ///         .insert(Label("hello world"));
336    /// }
337    /// # bevy_ecs::system::assert_is_system(example_system);
338    /// ```
339    ///
340    /// # See also
341    ///
342    /// - [`spawn`](Self::spawn) to spawn an entity with components.
343    /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities
344    ///   with the same combination of components.
345    #[track_caller]
346    pub fn spawn_empty(&mut self) -> EntityCommands<'_> {
347        let entity = self.allocator.alloc();
348        let caller = MaybeLocation::caller();
349        self.queue(move |world: &mut World| {
350            world.spawn_empty_at_with_caller(entity, caller).map(|_| ())
351        });
352        self.entity(entity)
353    }
354
355    /// Spawns a new [`Entity`] with the given components
356    /// and returns the entity's corresponding [`EntityCommands`].
357    ///
358    /// To spawn many entities with the same combination of components,
359    /// [`spawn_batch`](Self::spawn_batch) can be used for better performance.
360    ///
361    /// # Example
362    ///
363    /// ```
364    /// # use bevy_ecs::prelude::*;
365    /// #[derive(Component)]
366    /// struct ComponentA(u32);
367    /// #[derive(Component)]
368    /// struct ComponentB(u32);
369    ///
370    /// #[derive(Bundle)]
371    /// struct ExampleBundle {
372    ///     a: ComponentA,
373    ///     b: ComponentB,
374    /// }
375    ///
376    /// fn example_system(mut commands: Commands) {
377    ///     // Create a new entity with a single component.
378    ///     commands.spawn(ComponentA(1));
379    ///
380    ///     // Create a new entity with two components using a "tuple bundle".
381    ///     commands.spawn((ComponentA(2), ComponentB(1)));
382    ///
383    ///     // Create a new entity with a component bundle.
384    ///     commands.spawn(ExampleBundle {
385    ///         a: ComponentA(3),
386    ///         b: ComponentB(2),
387    ///     });
388    /// }
389    /// # bevy_ecs::system::assert_is_system(example_system);
390    /// ```
391    ///
392    /// # See also
393    ///
394    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without any components.
395    /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities
396    ///   with the same combination of components.
397    #[track_caller]
398    pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands<'_> {
399        let entity = self.allocator.alloc();
400        let caller = MaybeLocation::caller();
401        self.queue(move |world: &mut World| {
402            move_as_ptr!(bundle);
403            world
404                .spawn_at_with_caller(entity, bundle, caller)
405                .map(|_| ())
406        });
407        self.entity(entity)
408    }
409
410    /// Returns the [`EntityCommands`] for the given [`Entity`].
411    ///
412    /// This method does not guarantee that commands queued by the returned `EntityCommands`
413    /// will be successful, since the entity could be despawned before they are executed.
414    ///
415    /// # Example
416    ///
417    /// ```
418    /// # use bevy_ecs::prelude::*;
419    /// #[derive(Resource)]
420    /// struct PlayerEntity {
421    ///     entity: Entity
422    /// }
423    ///
424    /// #[derive(Component)]
425    /// struct Label(&'static str);
426    ///
427    /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) {
428    ///     // Get the entity and add a component.
429    ///     commands.entity(player.entity).insert(Label("hello world"));
430    /// }
431    /// # bevy_ecs::system::assert_is_system(example_system);
432    /// ```
433    ///
434    /// # See also
435    ///
436    /// - [`get_entity`](Self::get_entity) for the fallible version.
437    #[inline]
438    #[track_caller]
439    pub fn entity(&mut self, entity: Entity) -> EntityCommands<'_> {
440        EntityCommands {
441            entity,
442            commands: self.reborrow(),
443        }
444    }
445
446    /// Returns the [`EntityCommands`] for the requested [`Entity`] if it is valid.
447    /// This method does not guarantee that commands queued by the returned `EntityCommands`
448    /// will be successful, since the entity could be despawned before they are executed.
449    /// This also does not error when the entity has not been spawned.
450    /// For that behavior, see [`get_spawned_entity`](Self::get_spawned_entity),
451    /// which should be preferred for accessing entities you expect to already be spawned, like those found from a query.
452    /// For details on entity spawning vs validity, see [`entity`](crate::entity) module docs.
453    ///
454    /// # Errors
455    ///
456    /// Returns [`InvalidEntityError`] if the requested entity does not exist.
457    ///
458    /// # Example
459    ///
460    /// ```
461    /// # use bevy_ecs::prelude::*;
462    /// #[derive(Resource)]
463    /// struct PlayerEntity {
464    ///     entity: Entity
465    /// }
466    ///
467    /// #[derive(Component)]
468    /// struct Label(&'static str);
469    ///
470    /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) -> Result {
471    ///     // Get the entity if it still exists and store the `EntityCommands`.
472    ///     // If it doesn't exist, the `?` operator will propagate the returned error
473    ///     // to the system, and the system will pass it to an error handler.
474    ///     let mut entity_commands = commands.get_entity(player.entity)?;
475    ///
476    ///     // Add a component to the entity.
477    ///     entity_commands.insert(Label("hello world"));
478    ///
479    ///     // Return from the system successfully.
480    ///     Ok(())
481    /// }
482    /// # bevy_ecs::system::assert_is_system::<(), (), _>(example_system);
483    /// ```
484    ///
485    /// # See also
486    ///
487    /// - [`entity`](Self::entity) for the infallible version.
488    #[inline]
489    #[track_caller]
490    pub fn get_entity(&mut self, entity: Entity) -> Result<EntityCommands<'_>, InvalidEntityError> {
491        let _location = self.entities.get(entity)?;
492        Ok(EntityCommands {
493            entity,
494            commands: self.reborrow(),
495        })
496    }
497
498    /// Returns the [`EntityCommands`] for the requested [`Entity`] if it spawned in the world *now*.
499    /// Note that for entities that have not been spawned *yet*, like ones from [`spawn`](Self::spawn), this will error.
500    /// If that is not desired, try [`get_entity`](Self::get_entity).
501    /// This should be used over [`get_entity`](Self::get_entity) when you expect the entity to already be spawned in the world.
502    /// If the entity is valid but not yet spawned, this will error that information, where [`get_entity`](Self::get_entity) would succeed, leading to potentially surprising results.
503    /// For details on entity spawning vs validity, see [`entity`](crate::entity) module docs.
504    ///
505    /// This method does not guarantee that commands queued by the returned `EntityCommands`
506    /// will be successful, since the entity could be despawned before they are executed.
507    ///
508    /// # Errors
509    ///
510    /// Returns [`EntityNotSpawnedError`] if the requested entity does not exist.
511    ///
512    /// # Example
513    ///
514    /// ```
515    /// # use bevy_ecs::prelude::*;
516    /// #[derive(Resource)]
517    /// struct PlayerEntity {
518    ///     entity: Entity
519    /// }
520    ///
521    /// #[derive(Component)]
522    /// struct Label(&'static str);
523    ///
524    /// fn example_system(mut commands: Commands, player: Res<PlayerEntity>) -> Result {
525    ///     // Get the entity if it still exists and store the `EntityCommands`.
526    ///     // If it doesn't exist, the `?` operator will propagate the returned error
527    ///     // to the system, and the system will pass it to an error handler.
528    ///     let mut entity_commands = commands.get_spawned_entity(player.entity)?;
529    ///
530    ///     // Add a component to the entity.
531    ///     entity_commands.insert(Label("hello world"));
532    ///
533    ///     // Return from the system successfully.
534    ///     Ok(())
535    /// }
536    /// # bevy_ecs::system::assert_is_system::<(), (), _>(example_system);
537    /// ```
538    ///
539    /// # See also
540    ///
541    /// - [`entity`](Self::entity) for the infallible version.
542    #[inline]
543    #[track_caller]
544    pub fn get_spawned_entity(
545        &mut self,
546        entity: Entity,
547    ) -> Result<EntityCommands<'_>, EntityNotSpawnedError> {
548        let _location = self.entities.get_spawned(entity)?;
549        Ok(EntityCommands {
550            entity,
551            commands: self.reborrow(),
552        })
553    }
554
555    /// Spawns multiple entities with the same combination of components,
556    /// based on a batch of [`Bundles`](Bundle).
557    ///
558    /// A batch can be any type that implements [`IntoIterator`] and contains bundles,
559    /// such as a [`Vec<Bundle>`](alloc::vec::Vec) or an array `[Bundle; N]`.
560    ///
561    /// This method is equivalent to iterating the batch
562    /// and calling [`spawn`](Self::spawn) for each bundle,
563    /// but is faster by pre-allocating memory and having exclusive [`World`] access.
564    ///
565    /// # Example
566    ///
567    /// ```
568    /// use bevy_ecs::prelude::*;
569    ///
570    /// #[derive(Component)]
571    /// struct Score(u32);
572    ///
573    /// fn example_system(mut commands: Commands) {
574    ///     commands.spawn_batch([
575    ///         (Name::new("Alice"), Score(0)),
576    ///         (Name::new("Bob"), Score(0)),
577    ///     ]);
578    /// }
579    /// # bevy_ecs::system::assert_is_system(example_system);
580    /// ```
581    ///
582    /// # See also
583    ///
584    /// - [`spawn`](Self::spawn) to spawn an entity with components.
585    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without components.
586    #[track_caller]
587    pub fn spawn_batch<I>(&mut self, batch: I)
588    where
589        I: IntoIterator + Send + Sync + 'static,
590        I::Item: Bundle<Effect: NoBundleEffect>,
591    {
592        self.queue(command::spawn_batch(batch));
593    }
594
595    /// Pushes a generic [`Command`] to the command queue.
596    ///
597    /// If the [`Command`] returns a [`Result`],
598    /// it will be handled using the [default error handler](crate::error::DefaultErrorHandler).
599    ///
600    /// To use a custom error handler, see [`Commands::queue_handled`].
601    ///
602    /// The command can be:
603    /// - A custom struct that implements [`Command`].
604    /// - A closure or function that matches one of the following signatures:
605    ///   - [`(&mut World)`](World)
606    /// - A built-in command from the [`command`] module.
607    ///
608    /// # Example
609    ///
610    /// ```
611    /// # use bevy_ecs::prelude::*;
612    /// #[derive(Resource, Default)]
613    /// struct Counter(u64);
614    ///
615    /// struct AddToCounter(String);
616    ///
617    /// impl Command<Result> for AddToCounter {
618    ///     fn apply(self, world: &mut World) -> Result {
619    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
620    ///         let amount: u64 = self.0.parse()?;
621    ///         counter.0 += amount;
622    ///         Ok(())
623    ///     }
624    /// }
625    ///
626    /// fn add_three_to_counter_system(mut commands: Commands) {
627    ///     commands.queue(AddToCounter("3".to_string()));
628    /// }
629    ///
630    /// fn add_twenty_five_to_counter_system(mut commands: Commands) {
631    ///     commands.queue(|world: &mut World| {
632    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
633    ///         counter.0 += 25;
634    ///     });
635    /// }
636    /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system);
637    /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system);
638    /// ```
639    pub fn queue<C: Command<T> + HandleError<T>, T>(&mut self, command: C) {
640        self.queue_internal(command.handle_error());
641    }
642
643    /// Pushes a generic [`Command`] to the command queue.
644    ///
645    /// If the [`Command`] returns a [`Result`],
646    /// the given `error_handler` will be used to handle error cases.
647    ///
648    /// To implicitly use the default error handler, see [`Commands::queue`].
649    ///
650    /// The command can be:
651    /// - A custom struct that implements [`Command`].
652    /// - A closure or function that matches one of the following signatures:
653    ///   - [`(&mut World)`](World)
654    ///   - [`(&mut World)`](World) `->` [`Result`]
655    /// - A built-in command from the [`command`] module.
656    ///
657    /// # Example
658    ///
659    /// ```
660    /// # use bevy_ecs::prelude::*;
661    /// use bevy_ecs::error::warn;
662    ///
663    /// #[derive(Resource, Default)]
664    /// struct Counter(u64);
665    ///
666    /// struct AddToCounter(String);
667    ///
668    /// impl Command<Result> for AddToCounter {
669    ///     fn apply(self, world: &mut World) -> Result {
670    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
671    ///         let amount: u64 = self.0.parse()?;
672    ///         counter.0 += amount;
673    ///         Ok(())
674    ///     }
675    /// }
676    ///
677    /// fn add_three_to_counter_system(mut commands: Commands) {
678    ///     commands.queue_handled(AddToCounter("3".to_string()), warn);
679    /// }
680    ///
681    /// fn add_twenty_five_to_counter_system(mut commands: Commands) {
682    ///     commands.queue(|world: &mut World| {
683    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
684    ///         counter.0 += 25;
685    ///     });
686    /// }
687    /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system);
688    /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system);
689    /// ```
690    pub fn queue_handled<C: Command<T> + HandleError<T>, T>(
691        &mut self,
692        command: C,
693        error_handler: fn(BevyError, ErrorContext),
694    ) {
695        self.queue_internal(command.handle_error_with(error_handler));
696    }
697
698    /// Pushes a generic [`Command`] to the queue like [`Commands::queue_handled`], but instead silently ignores any errors.
699    pub fn queue_silenced<C: Command<T> + HandleError<T>, T>(&mut self, command: C) {
700        self.queue_internal(command.ignore_error());
701    }
702
703    fn queue_internal(&mut self, command: impl Command) {
704        match &mut self.queue {
705            InternalQueue::CommandQueue(queue) => {
706                queue.push(command);
707            }
708            InternalQueue::RawCommandQueue(queue) => {
709                // SAFETY: `RawCommandQueue` is only every constructed in `Commands::new_raw_from_entities`
710                // where the caller of that has ensured that `queue` outlives `self`
711                unsafe {
712                    queue.push(command);
713                }
714            }
715        }
716    }
717
718    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
719    /// based on a batch of `(Entity, Bundle)` pairs.
720    ///
721    /// A batch can be any type that implements [`IntoIterator`]
722    /// and contains `(Entity, Bundle)` tuples,
723    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
724    /// or an array `[(Entity, Bundle); N]`.
725    ///
726    /// This will overwrite any pre-existing components shared by the [`Bundle`] type.
727    /// Use [`Commands::insert_batch_if_new`] to keep the pre-existing components instead.
728    ///
729    /// This method is equivalent to iterating the batch
730    /// and calling [`insert`](EntityCommands::insert) for each pair,
731    /// but is faster by caching data that is shared between entities.
732    ///
733    /// # Fallible
734    ///
735    /// This command will fail if any of the given entities do not exist.
736    ///
737    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
738    /// which will be handled by the [default error handler](crate::error::DefaultErrorHandler).
739    #[track_caller]
740    pub fn insert_batch<I, B>(&mut self, batch: I)
741    where
742        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
743        B: Bundle<Effect: NoBundleEffect>,
744    {
745        self.queue(command::insert_batch(batch, InsertMode::Replace));
746    }
747
748    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
749    /// based on a batch of `(Entity, Bundle)` pairs.
750    ///
751    /// A batch can be any type that implements [`IntoIterator`]
752    /// and contains `(Entity, Bundle)` tuples,
753    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
754    /// or an array `[(Entity, Bundle); N]`.
755    ///
756    /// This will keep any pre-existing components shared by the [`Bundle`] type
757    /// and discard the new values.
758    /// Use [`Commands::insert_batch`] to overwrite the pre-existing components instead.
759    ///
760    /// This method is equivalent to iterating the batch
761    /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair,
762    /// but is faster by caching data that is shared between entities.
763    ///
764    /// # Fallible
765    ///
766    /// This command will fail if any of the given entities do not exist.
767    ///
768    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
769    /// which will be handled by the [default error handler](crate::error::DefaultErrorHandler).
770    #[track_caller]
771    pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
772    where
773        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
774        B: Bundle<Effect: NoBundleEffect>,
775    {
776        self.queue(command::insert_batch(batch, InsertMode::Keep));
777    }
778
779    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
780    /// based on a batch of `(Entity, Bundle)` pairs.
781    ///
782    /// A batch can be any type that implements [`IntoIterator`]
783    /// and contains `(Entity, Bundle)` tuples,
784    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
785    /// or an array `[(Entity, Bundle); N]`.
786    ///
787    /// This will overwrite any pre-existing components shared by the [`Bundle`] type.
788    /// Use [`Commands::try_insert_batch_if_new`] to keep the pre-existing components instead.
789    ///
790    /// This method is equivalent to iterating the batch
791    /// and calling [`insert`](EntityCommands::insert) for each pair,
792    /// but is faster by caching data that is shared between entities.
793    ///
794    /// # Fallible
795    ///
796    /// This command will fail if any of the given entities do not exist.
797    ///
798    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
799    /// which will be handled by [logging the error at the `warn` level](warn).
800    #[track_caller]
801    pub fn try_insert_batch<I, B>(&mut self, batch: I)
802    where
803        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
804        B: Bundle<Effect: NoBundleEffect>,
805    {
806        self.queue(command::insert_batch(batch, InsertMode::Replace).handle_error_with(warn));
807    }
808
809    /// Adds a series of [`Bundles`](Bundle) to each [`Entity`] they are paired with,
810    /// based on a batch of `(Entity, Bundle)` pairs.
811    ///
812    /// A batch can be any type that implements [`IntoIterator`]
813    /// and contains `(Entity, Bundle)` tuples,
814    /// such as a [`Vec<(Entity, Bundle)>`](alloc::vec::Vec)
815    /// or an array `[(Entity, Bundle); N]`.
816    ///
817    /// This will keep any pre-existing components shared by the [`Bundle`] type
818    /// and discard the new values.
819    /// Use [`Commands::try_insert_batch`] to overwrite the pre-existing components instead.
820    ///
821    /// This method is equivalent to iterating the batch
822    /// and calling [`insert_if_new`](EntityCommands::insert_if_new) for each pair,
823    /// but is faster by caching data that is shared between entities.
824    ///
825    /// # Fallible
826    ///
827    /// This command will fail if any of the given entities do not exist.
828    ///
829    /// It will internally return a [`TryInsertBatchError`](crate::world::error::TryInsertBatchError),
830    /// which will be handled by [logging the error at the `warn` level](warn).
831    #[track_caller]
832    pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I)
833    where
834        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
835        B: Bundle<Effect: NoBundleEffect>,
836    {
837        self.queue(command::insert_batch(batch, InsertMode::Keep).handle_error_with(warn));
838    }
839
840    /// Inserts a [`Resource`] into the [`World`] with an inferred value.
841    ///
842    /// The inferred value is determined by the [`FromWorld`] trait of the resource.
843    /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
844    /// and those default values will be used.
845    ///
846    /// If the resource already exists when the command is applied, nothing happens.
847    ///
848    /// # Example
849    ///
850    /// ```
851    /// # use bevy_ecs::prelude::*;
852    /// #[derive(Resource, Default)]
853    /// struct Scoreboard {
854    ///     current_score: u32,
855    ///     high_score: u32,
856    /// }
857    ///
858    /// fn initialize_scoreboard(mut commands: Commands) {
859    ///     commands.init_resource::<Scoreboard>();
860    /// }
861    /// # bevy_ecs::system::assert_is_system(initialize_scoreboard);
862    /// ```
863    #[track_caller]
864    pub fn init_resource<R: Resource + FromWorld>(&mut self) {
865        self.queue(command::init_resource::<R>());
866    }
867
868    /// Inserts a [`Resource`] into the [`World`] with a specific value.
869    ///
870    /// This will overwrite any previous value of the same resource type.
871    ///
872    /// # Example
873    ///
874    /// ```
875    /// # use bevy_ecs::prelude::*;
876    /// #[derive(Resource)]
877    /// struct Scoreboard {
878    ///     current_score: u32,
879    ///     high_score: u32,
880    /// }
881    ///
882    /// fn system(mut commands: Commands) {
883    ///     commands.insert_resource(Scoreboard {
884    ///         current_score: 0,
885    ///         high_score: 0,
886    ///     });
887    /// }
888    /// # bevy_ecs::system::assert_is_system(system);
889    /// ```
890    #[track_caller]
891    pub fn insert_resource<R: Resource>(&mut self, resource: R) {
892        self.queue(command::insert_resource(resource));
893    }
894
895    /// Removes a [`Resource`] from the [`World`].
896    ///
897    /// # Example
898    ///
899    /// ```
900    /// # use bevy_ecs::prelude::*;
901    /// #[derive(Resource)]
902    /// struct Scoreboard {
903    ///     current_score: u32,
904    ///     high_score: u32,
905    /// }
906    ///
907    /// fn system(mut commands: Commands) {
908    ///     commands.remove_resource::<Scoreboard>();
909    /// }
910    /// # bevy_ecs::system::assert_is_system(system);
911    /// ```
912    pub fn remove_resource<R: Resource>(&mut self) {
913        self.queue(command::remove_resource::<R>());
914    }
915
916    /// Runs the system corresponding to the given [`SystemId`].
917    /// Before running a system, it must first be registered via
918    /// [`Commands::register_system`] or [`World::register_system`].
919    ///
920    /// The system is run in an exclusive and single-threaded way.
921    /// Running slow systems can become a bottleneck.
922    ///
923    /// There is no way to get the output of a system when run as a command, because the
924    /// execution of the system happens later. To get the output of a system, use
925    /// [`World::run_system`] or [`World::run_system_with`] instead of running the system as a command.
926    ///
927    /// # Fallible
928    ///
929    /// This command will fail if the given [`SystemId`]
930    /// does not correspond to a [`System`](crate::system::System).
931    ///
932    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
933    /// which will be handled by [logging the error at the `warn` level](warn).
934    pub fn run_system(&mut self, id: SystemId) {
935        self.queue(command::run_system(id).handle_error_with(warn));
936    }
937
938    /// Runs the system corresponding to the given [`SystemId`] with input.
939    /// Before running a system, it must first be registered via
940    /// [`Commands::register_system`] or [`World::register_system`].
941    ///
942    /// The system is run in an exclusive and single-threaded way.
943    /// Running slow systems can become a bottleneck.
944    ///
945    /// There is no way to get the output of a system when run as a command, because the
946    /// execution of the system happens later. To get the output of a system, use
947    /// [`World::run_system`] or [`World::run_system_with`] instead of running the system as a command.
948    ///
949    /// # Fallible
950    ///
951    /// This command will fail if the given [`SystemId`]
952    /// does not correspond to a [`System`](crate::system::System).
953    ///
954    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
955    /// which will be handled by [logging the error at the `warn` level](warn).
956    pub fn run_system_with<I>(&mut self, id: SystemId<I>, input: I::Inner<'static>)
957    where
958        I: SystemInput<Inner<'static>: Send> + 'static,
959    {
960        self.queue(command::run_system_with(id, input).handle_error_with(warn));
961    }
962
963    /// Registers a system and returns its [`SystemId`] so it can later be called by
964    /// [`Commands::run_system`] or [`World::run_system`].
965    ///
966    /// This is different from adding systems to a [`Schedule`](crate::schedule::Schedule),
967    /// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system.
968    ///
969    /// Using a [`Schedule`](crate::schedule::Schedule) is still preferred for most cases
970    /// due to its better performance and ability to run non-conflicting systems simultaneously.
971    ///
972    /// # Note
973    ///
974    /// If the same system is registered more than once,
975    /// each registration will be considered a different system,
976    /// and they will each be given their own [`SystemId`].
977    ///
978    /// If you want to avoid registering the same system multiple times,
979    /// consider using [`Commands::run_system_cached`] or storing the [`SystemId`]
980    /// in a [`Local`](crate::system::Local).
981    ///
982    /// # Example
983    ///
984    /// ```
985    /// # use bevy_ecs::{prelude::*, world::CommandQueue, system::SystemId};
986    /// #[derive(Resource)]
987    /// struct Counter(i32);
988    ///
989    /// fn register_system(
990    ///     mut commands: Commands,
991    ///     mut local_system: Local<Option<SystemId>>,
992    /// ) {
993    ///     if let Some(system) = *local_system {
994    ///         commands.run_system(system);
995    ///     } else {
996    ///         *local_system = Some(commands.register_system(increment_counter));
997    ///     }
998    /// }
999    ///
1000    /// fn increment_counter(mut value: ResMut<Counter>) {
1001    ///     value.0 += 1;
1002    /// }
1003    ///
1004    /// # let mut world = World::default();
1005    /// # world.insert_resource(Counter(0));
1006    /// # let mut queue_1 = CommandQueue::default();
1007    /// # let systemid = {
1008    /// #   let mut commands = Commands::new(&mut queue_1, &world);
1009    /// #   commands.register_system(increment_counter)
1010    /// # };
1011    /// # let mut queue_2 = CommandQueue::default();
1012    /// # {
1013    /// #   let mut commands = Commands::new(&mut queue_2, &world);
1014    /// #   commands.run_system(systemid);
1015    /// # }
1016    /// # queue_1.append(&mut queue_2);
1017    /// # queue_1.apply(&mut world);
1018    /// # assert_eq!(1, world.resource::<Counter>().0);
1019    /// # bevy_ecs::system::assert_is_system(register_system);
1020    /// ```
1021    pub fn register_system<I, O, M>(
1022        &mut self,
1023        system: impl IntoSystem<I, O, M> + 'static,
1024    ) -> SystemId<I, O>
1025    where
1026        I: SystemInput + Send + 'static,
1027        O: Send + 'static,
1028    {
1029        let entity = self.spawn_empty().id();
1030        let system = RegisteredSystem::<I, O>::new(Box::new(IntoSystem::into_system(system)));
1031        self.entity(entity).insert(system);
1032        SystemId::from_entity(entity)
1033    }
1034
1035    /// Removes a system previously registered with [`Commands::register_system`]
1036    /// or [`World::register_system`].
1037    ///
1038    /// After removing a system, the [`SystemId`] becomes invalid
1039    /// and attempting to use it afterwards will result in an error.
1040    /// Re-adding the removed system will register it with a new `SystemId`.
1041    ///
1042    /// # Fallible
1043    ///
1044    /// This command will fail if the given [`SystemId`]
1045    /// does not correspond to a [`System`](crate::system::System).
1046    ///
1047    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
1048    /// which will be handled by [logging the error at the `warn` level](warn).
1049    pub fn unregister_system<I, O>(&mut self, system_id: SystemId<I, O>)
1050    where
1051        I: SystemInput + Send + 'static,
1052        O: Send + 'static,
1053    {
1054        self.queue(command::unregister_system(system_id).handle_error_with(warn));
1055    }
1056
1057    /// Removes a system previously registered with one of the following:
1058    /// - [`Commands::run_system_cached`]
1059    /// - [`World::run_system_cached`]
1060    /// - [`World::register_system_cached`]
1061    ///
1062    /// # Fallible
1063    ///
1064    /// This command will fail if the given system
1065    /// is not currently cached in a [`CachedSystemId`](crate::system::CachedSystemId) resource.
1066    ///
1067    /// It will internally return a [`RegisteredSystemError`](crate::system::system_registry::RegisteredSystemError),
1068    /// which will be handled by [logging the error at the `warn` level](warn).
1069    pub fn unregister_system_cached<I, O, M, S>(&mut self, system: S)
1070    where
1071        I: SystemInput + Send + 'static,
1072        O: 'static,
1073        M: 'static,
1074        S: IntoSystem<I, O, M> + Send + 'static,
1075    {
1076        self.queue(command::unregister_system_cached(system).handle_error_with(warn));
1077    }
1078
1079    /// Runs a cached system, registering it if necessary.
1080    ///
1081    /// Unlike [`Commands::run_system`], this method does not require manual registration.
1082    ///
1083    /// The first time this method is called for a particular system,
1084    /// it will register the system and store its [`SystemId`] in a
1085    /// [`CachedSystemId`](crate::system::CachedSystemId) resource for later.
1086    ///
1087    /// If you would rather manage the [`SystemId`] yourself,
1088    /// or register multiple copies of the same system,
1089    /// use [`Commands::register_system`] instead.
1090    ///
1091    /// # Limitations
1092    ///
1093    /// This method only accepts ZST (zero-sized) systems to guarantee that any two systems of
1094    /// the same type must be equal. This means that closures that capture the environment, and
1095    /// function pointers, are not accepted.
1096    ///
1097    /// If you want to access values from the environment within a system,
1098    /// consider passing them in as inputs via [`Commands::run_system_cached_with`].
1099    ///
1100    /// If that's not an option, consider [`Commands::register_system`] instead.
1101    pub fn run_system_cached<M, S>(&mut self, system: S)
1102    where
1103        M: 'static,
1104        S: IntoSystem<(), (), M> + Send + 'static,
1105    {
1106        self.queue(command::run_system_cached(system).handle_error_with(warn));
1107    }
1108
1109    /// Runs a cached system with an input, registering it if necessary.
1110    ///
1111    /// Unlike [`Commands::run_system_with`], this method does not require manual registration.
1112    ///
1113    /// The first time this method is called for a particular system,
1114    /// it will register the system and store its [`SystemId`] in a
1115    /// [`CachedSystemId`](crate::system::CachedSystemId) resource for later.
1116    ///
1117    /// If you would rather manage the [`SystemId`] yourself,
1118    /// or register multiple copies of the same system,
1119    /// use [`Commands::register_system`] instead.
1120    ///
1121    /// # Limitations
1122    ///
1123    /// This method only accepts ZST (zero-sized) systems to guarantee that any two systems of
1124    /// the same type must be equal. This means that closures that capture the environment, and
1125    /// function pointers, are not accepted.
1126    ///
1127    /// If you want to access values from the environment within a system,
1128    /// consider passing them in as inputs.
1129    ///
1130    /// If that's not an option, consider [`Commands::register_system`] instead.
1131    pub fn run_system_cached_with<I, M, S>(&mut self, system: S, input: I::Inner<'static>)
1132    where
1133        I: SystemInput<Inner<'static>: Send> + Send + 'static,
1134        M: 'static,
1135        S: IntoSystem<I, (), M> + Send + 'static,
1136    {
1137        self.queue(command::run_system_cached_with(system, input).handle_error_with(warn));
1138    }
1139
1140    /// Triggers the given [`Event`], which will run any [`Observer`]s watching for it.
1141    ///
1142    /// [`Observer`]: crate::observer::Observer
1143    #[track_caller]
1144    pub fn trigger<'a>(&mut self, event: impl Event<Trigger<'a>: Default>) {
1145        self.queue(command::trigger(event));
1146    }
1147
1148    /// Triggers the given [`Event`] using the given [`Trigger`], which will run any [`Observer`]s watching for it.
1149    ///
1150    /// [`Trigger`]: crate::event::Trigger
1151    /// [`Observer`]: crate::observer::Observer
1152    #[track_caller]
1153    pub fn trigger_with<E: Event<Trigger<'static>: Send + Sync>>(
1154        &mut self,
1155        event: E,
1156        trigger: E::Trigger<'static>,
1157    ) {
1158        self.queue(command::trigger_with(event, trigger));
1159    }
1160
1161    /// Spawns an [`Observer`] and returns the [`EntityCommands`] associated
1162    /// with the entity that stores the observer.
1163    ///
1164    /// `observer` can be any system whose first parameter is [`On`].
1165    ///
1166    /// **Calling [`observe`](EntityCommands::observe) on the returned
1167    /// [`EntityCommands`] will observe the observer itself, which you very
1168    /// likely do not want.**
1169    ///
1170    /// # Panics
1171    ///
1172    /// Panics if the given system is an exclusive system.
1173    ///
1174    /// [`On`]: crate::observer::On
1175    pub fn add_observer<E: Event, B: Bundle, M>(
1176        &mut self,
1177        observer: impl IntoObserverSystem<E, B, M>,
1178    ) -> EntityCommands<'_> {
1179        self.spawn(Observer::new(observer))
1180    }
1181
1182    /// Writes an arbitrary [`Message`].
1183    ///
1184    /// This is a convenience method for writing messages
1185    /// without requiring a [`MessageWriter`](crate::message::MessageWriter).
1186    ///
1187    /// # Performance
1188    ///
1189    /// Since this is a command, exclusive world access is used, which means that it will not profit from
1190    /// system-level parallelism on supported platforms.
1191    ///
1192    /// If these messages are performance-critical or very frequently sent,
1193    /// consider using a [`MessageWriter`](crate::message::MessageWriter) instead.
1194    #[track_caller]
1195    pub fn write_message<M: Message>(&mut self, message: M) -> &mut Self {
1196        self.queue(command::write_message(message));
1197        self
1198    }
1199
1200    /// Runs the schedule corresponding to the given [`ScheduleLabel`].
1201    ///
1202    /// Calls [`World::try_run_schedule`](World::try_run_schedule).
1203    ///
1204    /// # Fallible
1205    ///
1206    /// This command will fail if the given [`ScheduleLabel`]
1207    /// does not correspond to a [`Schedule`](crate::schedule::Schedule).
1208    ///
1209    /// It will internally return a [`TryRunScheduleError`](crate::world::error::TryRunScheduleError),
1210    /// which will be handled by [logging the error at the `warn` level](warn).
1211    ///
1212    /// # Example
1213    ///
1214    /// ```
1215    /// # use bevy_ecs::prelude::*;
1216    /// # use bevy_ecs::schedule::ScheduleLabel;
1217    /// # #[derive(Default, Resource)]
1218    /// # struct Counter(u32);
1219    /// #[derive(ScheduleLabel, Hash, Debug, PartialEq, Eq, Clone, Copy)]
1220    /// struct FooSchedule;
1221    ///
1222    /// # fn foo_system(mut counter: ResMut<Counter>) {
1223    /// #     counter.0 += 1;
1224    /// # }
1225    /// #
1226    /// # let mut schedule = Schedule::new(FooSchedule);
1227    /// # schedule.add_systems(foo_system);
1228    /// #
1229    /// # let mut world = World::default();
1230    /// #
1231    /// # world.init_resource::<Counter>();
1232    /// # world.add_schedule(schedule);
1233    /// #
1234    /// # assert_eq!(world.resource::<Counter>().0, 0);
1235    /// #
1236    /// # let mut commands = world.commands();
1237    /// commands.run_schedule(FooSchedule);
1238    /// #
1239    /// # world.flush();
1240    /// #
1241    /// # assert_eq!(world.resource::<Counter>().0, 1);
1242    /// ```
1243    pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
1244        self.queue(command::run_schedule(label).handle_error_with(warn));
1245    }
1246}
1247
1248/// A list of commands that will be run to modify an [`Entity`].
1249///
1250/// # Note
1251///
1252/// Most [`Commands`] (and thereby [`EntityCommands`]) are deferred:
1253/// when you call the command, if it requires mutable access to the [`World`]
1254/// (that is, if it removes, adds, or changes something), it's not executed immediately.
1255///
1256/// Instead, the command is added to a "command queue."
1257/// The command queue is applied later
1258/// when the [`ApplyDeferred`](crate::schedule::ApplyDeferred) system runs.
1259/// Commands are executed one-by-one so that
1260/// each command can have exclusive access to the `World`.
1261///
1262/// # Fallible
1263///
1264/// Due to their deferred nature, an entity you're trying to change with an [`EntityCommand`]
1265/// can be despawned by the time the command is executed.
1266///
1267/// All deferred entity commands will check whether the entity exists at the time of execution
1268/// and will return an error if it doesn't.
1269///
1270/// # Error handling
1271///
1272/// An [`EntityCommand`] can return a [`Result`](crate::error::Result),
1273/// which will be passed to an [error handler](crate::error) if the `Result` is an error.
1274///
1275/// The default error handler panics. It can be configured via
1276/// the [`DefaultErrorHandler`](crate::error::DefaultErrorHandler) resource.
1277///
1278/// Alternatively, you can customize the error handler for a specific command
1279/// by calling [`EntityCommands::queue_handled`].
1280///
1281/// The [`error`](crate::error) module provides some simple error handlers for convenience.
1282pub struct EntityCommands<'a> {
1283    pub(crate) entity: Entity,
1284    pub(crate) commands: Commands<'a, 'a>,
1285}
1286
1287impl<'a> EntityCommands<'a> {
1288    /// Returns the [`Entity`] id of the entity.
1289    ///
1290    /// # Example
1291    ///
1292    /// ```
1293    /// # use bevy_ecs::prelude::*;
1294    /// #
1295    /// fn my_system(mut commands: Commands) {
1296    ///     let entity_id = commands.spawn_empty().id();
1297    /// }
1298    /// # bevy_ecs::system::assert_is_system(my_system);
1299    /// ```
1300    #[inline]
1301    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
1302    pub fn id(&self) -> Entity {
1303        self.entity
1304    }
1305
1306    /// Returns an [`EntityCommands`] with a smaller lifetime.
1307    ///
1308    /// This is useful if you have `&mut EntityCommands` but you need `EntityCommands`.
1309    pub fn reborrow(&mut self) -> EntityCommands<'_> {
1310        EntityCommands {
1311            entity: self.entity,
1312            commands: self.commands.reborrow(),
1313        }
1314    }
1315
1316    /// Get an [`EntityEntryCommands`] for the [`Component`] `T`,
1317    /// allowing you to modify it or insert it if it isn't already present.
1318    ///
1319    /// See also [`insert_if_new`](Self::insert_if_new),
1320    /// which lets you insert a [`Bundle`] without overwriting it.
1321    ///
1322    /// # Example
1323    ///
1324    /// ```
1325    /// # use bevy_ecs::prelude::*;
1326    /// # #[derive(Resource)]
1327    /// # struct PlayerEntity { entity: Entity }
1328    /// #[derive(Component)]
1329    /// struct Level(u32);
1330    ///
1331    ///
1332    /// #[derive(Component, Default)]
1333    /// struct Mana {
1334    ///     max: u32,
1335    ///     current: u32,
1336    /// }
1337    ///
1338    /// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
1339    ///     // If a component already exists then modify it, otherwise insert a default value
1340    ///     commands
1341    ///         .entity(player.entity)
1342    ///         .entry::<Level>()
1343    ///         .and_modify(|mut lvl| lvl.0 += 1)
1344    ///         .or_insert(Level(0));
1345    ///
1346    ///     // Add a default value if none exists, and then modify the existing or new value
1347    ///     commands
1348    ///         .entity(player.entity)
1349    ///         .entry::<Mana>()
1350    ///         .or_default()
1351    ///         .and_modify(|mut mana| {
1352    ///             mana.max += 10;
1353    ///             mana.current = mana.max;
1354    ///     });
1355    /// }
1356    ///
1357    /// # bevy_ecs::system::assert_is_system(level_up_system);
1358    /// ```
1359    pub fn entry<T: Component>(&mut self) -> EntityEntryCommands<'_, T> {
1360        EntityEntryCommands {
1361            entity_commands: self.reborrow(),
1362            marker: PhantomData,
1363        }
1364    }
1365
1366    /// Adds a [`Bundle`] of components to the entity.
1367    ///
1368    /// This will overwrite any previous value(s) of the same component type.
1369    /// See [`EntityCommands::insert_if_new`] to keep the old value instead.
1370    ///
1371    /// # Example
1372    ///
1373    /// ```
1374    /// # use bevy_ecs::prelude::*;
1375    /// # #[derive(Resource)]
1376    /// # struct PlayerEntity { entity: Entity }
1377    /// #[derive(Component)]
1378    /// struct Health(u32);
1379    /// #[derive(Component)]
1380    /// struct Strength(u32);
1381    /// #[derive(Component)]
1382    /// struct Defense(u32);
1383    ///
1384    /// #[derive(Bundle)]
1385    /// struct CombatBundle {
1386    ///     health: Health,
1387    ///     strength: Strength,
1388    /// }
1389    ///
1390    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1391    ///     commands
1392    ///         .entity(player.entity)
1393    ///         // You can insert individual components:
1394    ///         .insert(Defense(10))
1395    ///         // You can also insert pre-defined bundles of components:
1396    ///         .insert(CombatBundle {
1397    ///             health: Health(100),
1398    ///             strength: Strength(40),
1399    ///         })
1400    ///         // You can also insert tuples of components and bundles.
1401    ///         // This is equivalent to the calls above:
1402    ///         .insert((
1403    ///             Defense(10),
1404    ///             CombatBundle {
1405    ///                 health: Health(100),
1406    ///                 strength: Strength(40),
1407    ///             },
1408    ///         ));
1409    /// }
1410    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
1411    /// ```
1412    #[track_caller]
1413    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
1414        self.queue(entity_command::insert(bundle, InsertMode::Replace))
1415    }
1416
1417    /// Adds a [`Bundle`] of components to the entity if the predicate returns true.
1418    ///
1419    /// This is useful for chaining method calls.
1420    ///
1421    /// # Example
1422    ///
1423    /// ```
1424    /// # use bevy_ecs::prelude::*;
1425    /// # #[derive(Resource)]
1426    /// # struct PlayerEntity { entity: Entity }
1427    /// # impl PlayerEntity { fn is_spectator(&self) -> bool { true } }
1428    /// #[derive(Component)]
1429    /// struct StillLoadingStats;
1430    /// #[derive(Component)]
1431    /// struct Health(u32);
1432    ///
1433    /// fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
1434    ///     commands
1435    ///         .entity(player.entity)
1436    ///         .insert_if(Health(10), || !player.is_spectator())
1437    ///         .remove::<StillLoadingStats>();
1438    /// }
1439    /// # bevy_ecs::system::assert_is_system(add_health_system);
1440    /// ```
1441    #[track_caller]
1442    pub fn insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1443    where
1444        F: FnOnce() -> bool,
1445    {
1446        if condition() {
1447            self.insert(bundle)
1448        } else {
1449            self
1450        }
1451    }
1452
1453    /// Adds a [`Bundle`] of components to the entity without overwriting.
1454    ///
1455    /// This is the same as [`EntityCommands::insert`], but in case of duplicate
1456    /// components will leave the old values instead of replacing them with new ones.
1457    ///
1458    /// See also [`entry`](Self::entry), which lets you modify a [`Component`] if it's present,
1459    /// as well as initialize it with a default value.
1460    #[track_caller]
1461    pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
1462        self.queue(entity_command::insert(bundle, InsertMode::Keep))
1463    }
1464
1465    /// Adds a [`Bundle`] of components to the entity without overwriting if the
1466    /// predicate returns true.
1467    ///
1468    /// This is the same as [`EntityCommands::insert_if`], but in case of duplicate
1469    /// components will leave the old values instead of replacing them with new ones.
1470    #[track_caller]
1471    pub fn insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1472    where
1473        F: FnOnce() -> bool,
1474    {
1475        if condition() {
1476            self.insert_if_new(bundle)
1477        } else {
1478            self
1479        }
1480    }
1481
1482    /// Adds a dynamic [`Component`] to the entity.
1483    ///
1484    /// This will overwrite any previous value(s) of the same component type.
1485    ///
1486    /// You should prefer to use the typed API [`EntityCommands::insert`] where possible.
1487    ///
1488    /// # Safety
1489    ///
1490    /// - [`ComponentId`] must be from the same world as `self`.
1491    /// - `T` must have the same layout as the one passed during `component_id` creation.
1492    #[track_caller]
1493    pub unsafe fn insert_by_id<T: Send + 'static>(
1494        &mut self,
1495        component_id: ComponentId,
1496        value: T,
1497    ) -> &mut Self {
1498        self.queue(
1499            // SAFETY:
1500            // - `ComponentId` safety is ensured by the caller.
1501            // - `T` safety is ensured by the caller.
1502            unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
1503        )
1504    }
1505
1506    /// Adds a dynamic [`Component`] to the entity.
1507    ///
1508    /// This will overwrite any previous value(s) of the same component type.
1509    ///
1510    /// You should prefer to use the typed API [`EntityCommands::try_insert`] where possible.
1511    ///
1512    /// # Note
1513    ///
1514    /// If the entity does not exist when this command is executed,
1515    /// the resulting error will be ignored.
1516    ///
1517    /// # Safety
1518    ///
1519    /// - [`ComponentId`] must be from the same world as `self`.
1520    /// - `T` must have the same layout as the one passed during `component_id` creation.
1521    #[track_caller]
1522    pub unsafe fn try_insert_by_id<T: Send + 'static>(
1523        &mut self,
1524        component_id: ComponentId,
1525        value: T,
1526    ) -> &mut Self {
1527        self.queue_silenced(
1528            // SAFETY:
1529            // - `ComponentId` safety is ensured by the caller.
1530            // - `T` safety is ensured by the caller.
1531            unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
1532        )
1533    }
1534
1535    /// Adds a [`Bundle`] of components to the entity.
1536    ///
1537    /// This will overwrite any previous value(s) of the same component type.
1538    ///
1539    /// # Note
1540    ///
1541    /// If the entity does not exist when this command is executed,
1542    /// the resulting error will be ignored.
1543    ///
1544    /// # Example
1545    ///
1546    /// ```
1547    /// # use bevy_ecs::prelude::*;
1548    /// # #[derive(Resource)]
1549    /// # struct PlayerEntity { entity: Entity }
1550    /// #[derive(Component)]
1551    /// struct Health(u32);
1552    /// #[derive(Component)]
1553    /// struct Strength(u32);
1554    /// #[derive(Component)]
1555    /// struct Defense(u32);
1556    ///
1557    /// #[derive(Bundle)]
1558    /// struct CombatBundle {
1559    ///     health: Health,
1560    ///     strength: Strength,
1561    /// }
1562    ///
1563    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1564    ///     commands.entity(player.entity)
1565    ///         // You can insert individual components:
1566    ///         .try_insert(Defense(10))
1567    ///         // You can also insert tuples of components:
1568    ///         .try_insert(CombatBundle {
1569    ///             health: Health(100),
1570    ///             strength: Strength(40),
1571    ///         });
1572    ///
1573    ///     // Suppose this occurs in a parallel adjacent system or process.
1574    ///     commands.entity(player.entity).despawn();
1575    ///
1576    ///     // This will not panic nor will it add the component.
1577    ///     commands.entity(player.entity).try_insert(Defense(5));
1578    /// }
1579    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
1580    /// ```
1581    #[track_caller]
1582    pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut Self {
1583        self.queue_silenced(entity_command::insert(bundle, InsertMode::Replace))
1584    }
1585
1586    /// Adds a [`Bundle`] of components to the entity if the predicate returns true.
1587    ///
1588    /// This is useful for chaining method calls.
1589    ///
1590    /// # Note
1591    ///
1592    /// If the entity does not exist when this command is executed,
1593    /// the resulting error will be ignored.
1594    #[track_caller]
1595    pub fn try_insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1596    where
1597        F: FnOnce() -> bool,
1598    {
1599        if condition() {
1600            self.try_insert(bundle)
1601        } else {
1602            self
1603        }
1604    }
1605
1606    /// Adds a [`Bundle`] of components to the entity without overwriting if the
1607    /// predicate returns true.
1608    ///
1609    /// This is the same as [`EntityCommands::try_insert_if`], but in case of duplicate
1610    /// components will leave the old values instead of replacing them with new ones.
1611    ///
1612    /// # Note
1613    ///
1614    /// If the entity does not exist when this command is executed,
1615    /// the resulting error will be ignored.
1616    #[track_caller]
1617    pub fn try_insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
1618    where
1619        F: FnOnce() -> bool,
1620    {
1621        if condition() {
1622            self.try_insert_if_new(bundle)
1623        } else {
1624            self
1625        }
1626    }
1627
1628    /// Adds a [`Bundle`] of components to the entity without overwriting.
1629    ///
1630    /// This is the same as [`EntityCommands::try_insert`], but in case of duplicate
1631    /// components will leave the old values instead of replacing them with new ones.
1632    ///
1633    /// # Note
1634    ///
1635    /// If the entity does not exist when this command is executed,
1636    /// the resulting error will be ignored.
1637    #[track_caller]
1638    pub fn try_insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
1639        self.queue_silenced(entity_command::insert(bundle, InsertMode::Keep))
1640    }
1641
1642    /// Removes a [`Bundle`] of components from the entity.
1643    ///
1644    /// This will remove all components that intersect with the provided bundle;
1645    /// the entity does not need to have all the components in the bundle.
1646    ///
1647    /// This will emit a warning if the entity does not exist.
1648    ///
1649    /// # Example
1650    ///
1651    /// ```
1652    /// # use bevy_ecs::prelude::*;
1653    /// # #[derive(Resource)]
1654    /// # struct PlayerEntity { entity: Entity }
1655    /// #[derive(Component)]
1656    /// struct Health(u32);
1657    /// #[derive(Component)]
1658    /// struct Strength(u32);
1659    /// #[derive(Component)]
1660    /// struct Defense(u32);
1661    ///
1662    /// #[derive(Bundle)]
1663    /// struct CombatBundle {
1664    ///     health: Health,
1665    ///     strength: Strength,
1666    /// }
1667    ///
1668    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1669    ///     commands
1670    ///         .entity(player.entity)
1671    ///         // You can remove individual components:
1672    ///         .remove::<Defense>()
1673    ///         // You can also remove pre-defined bundles of components:
1674    ///         .remove::<CombatBundle>()
1675    ///         // You can also remove tuples of components and bundles.
1676    ///         // This is equivalent to the calls above:
1677    ///         .remove::<(Defense, CombatBundle)>();
1678    /// }
1679    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1680    /// ```
1681    #[track_caller]
1682    pub fn remove<B: Bundle>(&mut self) -> &mut Self {
1683        self.queue_handled(entity_command::remove::<B>(), warn)
1684    }
1685
1686    /// Removes a [`Bundle`] of components from the entity if the predicate returns true.
1687    ///
1688    /// This is useful for chaining method calls.
1689    ///
1690    /// # Example
1691    ///
1692    /// ```
1693    /// # use bevy_ecs::prelude::*;
1694    /// # #[derive(Resource)]
1695    /// # struct PlayerEntity { entity: Entity }
1696    /// # impl PlayerEntity { fn is_spectator(&self) -> bool { true } }
1697    /// #[derive(Component)]
1698    /// struct Health(u32);
1699    /// #[derive(Component)]
1700    /// struct Strength(u32);
1701    /// #[derive(Component)]
1702    /// struct Defense(u32);
1703    ///
1704    /// #[derive(Bundle)]
1705    /// struct CombatBundle {
1706    ///     health: Health,
1707    ///     strength: Strength,
1708    /// }
1709    ///
1710    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1711    ///     commands
1712    ///         .entity(player.entity)
1713    ///         .remove_if::<(Defense, CombatBundle)>(|| !player.is_spectator());
1714    /// }
1715    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1716    /// ```
1717    #[track_caller]
1718    pub fn remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
1719        if condition() {
1720            self.remove::<B>()
1721        } else {
1722            self
1723        }
1724    }
1725
1726    /// Removes a [`Bundle`] of components from the entity if the predicate returns true.
1727    ///
1728    /// This is useful for chaining method calls.
1729    ///
1730    /// # Note
1731    ///
1732    /// If the entity does not exist when this command is executed,
1733    /// the resulting error will be ignored.
1734    #[track_caller]
1735    pub fn try_remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
1736        if condition() {
1737            self.try_remove::<B>()
1738        } else {
1739            self
1740        }
1741    }
1742
1743    /// Removes a [`Bundle`] of components from the entity.
1744    ///
1745    /// This will remove all components that intersect with the provided bundle;
1746    /// the entity does not need to have all the components in the bundle.
1747    ///
1748    /// Unlike [`Self::remove`],
1749    /// this will not emit a warning if the entity does not exist.
1750    ///
1751    /// # Example
1752    ///
1753    /// ```
1754    /// # use bevy_ecs::prelude::*;
1755    /// # #[derive(Resource)]
1756    /// # struct PlayerEntity { entity: Entity }
1757    /// #[derive(Component)]
1758    /// struct Health(u32);
1759    /// #[derive(Component)]
1760    /// struct Strength(u32);
1761    /// #[derive(Component)]
1762    /// struct Defense(u32);
1763    ///
1764    /// #[derive(Bundle)]
1765    /// struct CombatBundle {
1766    ///     health: Health,
1767    ///     strength: Strength,
1768    /// }
1769    ///
1770    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1771    ///     commands
1772    ///         .entity(player.entity)
1773    ///         // You can remove individual components:
1774    ///         .try_remove::<Defense>()
1775    ///         // You can also remove pre-defined bundles of components:
1776    ///         .try_remove::<CombatBundle>()
1777    ///         // You can also remove tuples of components and bundles.
1778    ///         // This is equivalent to the calls above:
1779    ///         .try_remove::<(Defense, CombatBundle)>();
1780    /// }
1781    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1782    /// ```
1783    pub fn try_remove<B: Bundle>(&mut self) -> &mut Self {
1784        self.queue_silenced(entity_command::remove::<B>())
1785    }
1786
1787    /// Removes a [`Bundle`] of components from the entity,
1788    /// and also removes any components required by the components in the bundle.
1789    ///
1790    /// This will remove all components that intersect with the provided bundle;
1791    /// the entity does not need to have all the components in the bundle.
1792    ///
1793    /// # Example
1794    ///
1795    /// ```
1796    /// # use bevy_ecs::prelude::*;
1797    /// # #[derive(Resource)]
1798    /// # struct PlayerEntity { entity: Entity }
1799    /// #
1800    /// #[derive(Component)]
1801    /// #[require(B)]
1802    /// struct A;
1803    /// #[derive(Component, Default)]
1804    /// struct B;
1805    ///
1806    /// fn remove_with_requires_system(mut commands: Commands, player: Res<PlayerEntity>) {
1807    ///     commands
1808    ///         .entity(player.entity)
1809    ///         // Removes both A and B from the entity, because B is required by A.
1810    ///         .remove_with_requires::<A>();
1811    /// }
1812    /// # bevy_ecs::system::assert_is_system(remove_with_requires_system);
1813    /// ```
1814    #[track_caller]
1815    pub fn remove_with_requires<B: Bundle>(&mut self) -> &mut Self {
1816        self.queue(entity_command::remove_with_requires::<B>())
1817    }
1818
1819    /// Removes a dynamic [`Component`] from the entity if it exists.
1820    ///
1821    /// # Panics
1822    ///
1823    /// Panics if the provided [`ComponentId`] does not exist in the [`World`].
1824    #[track_caller]
1825    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1826        self.queue(entity_command::remove_by_id(component_id))
1827    }
1828
1829    /// Removes all components associated with the entity.
1830    #[track_caller]
1831    pub fn clear(&mut self) -> &mut Self {
1832        self.queue(entity_command::clear())
1833    }
1834
1835    /// Despawns the entity.
1836    ///
1837    /// This will emit a warning if the entity does not exist.
1838    ///
1839    /// # Note
1840    ///
1841    /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget)
1842    /// that is configured to despawn descendants.
1843    ///
1844    /// For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1845    ///
1846    /// # Example
1847    ///
1848    /// ```
1849    /// # use bevy_ecs::prelude::*;
1850    /// # #[derive(Resource)]
1851    /// # struct CharacterToRemove { entity: Entity }
1852    /// #
1853    /// fn remove_character_system(
1854    ///     mut commands: Commands,
1855    ///     character_to_remove: Res<CharacterToRemove>
1856    /// ) {
1857    ///     commands.entity(character_to_remove.entity).despawn();
1858    /// }
1859    /// # bevy_ecs::system::assert_is_system(remove_character_system);
1860    /// ```
1861    #[track_caller]
1862    pub fn despawn(&mut self) {
1863        self.queue_handled(entity_command::despawn(), warn);
1864    }
1865
1866    /// Despawns the entity.
1867    ///
1868    /// Unlike [`Self::despawn`],
1869    /// this will not emit a warning if the entity does not exist.
1870    ///
1871    /// # Note
1872    ///
1873    /// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget)
1874    /// that is configured to despawn descendants.
1875    ///
1876    /// For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1877    pub fn try_despawn(&mut self) {
1878        self.queue_silenced(entity_command::despawn());
1879    }
1880
1881    /// Pushes an [`EntityCommand`] to the queue,
1882    /// which will get executed for the current [`Entity`].
1883    ///
1884    /// The [default error handler](crate::error::DefaultErrorHandler)
1885    /// will be used to handle error cases.
1886    /// Every [`EntityCommand`] checks whether the entity exists at the time of execution
1887    /// and returns an error if it does not.
1888    ///
1889    /// To use a custom error handler, see [`EntityCommands::queue_handled`].
1890    ///
1891    /// The command can be:
1892    /// - A custom struct that implements [`EntityCommand`].
1893    /// - A closure or function that matches the following signature:
1894    ///   - [`(EntityWorldMut)`](EntityWorldMut)
1895    ///   - [`(EntityWorldMut)`](EntityWorldMut) `->` [`Result`]
1896    /// - A built-in command from the [`entity_command`] module.
1897    ///
1898    /// # Example
1899    ///
1900    /// ```
1901    /// # use bevy_ecs::prelude::*;
1902    /// # fn my_system(mut commands: Commands) {
1903    /// commands
1904    ///     .spawn_empty()
1905    ///     // Closures with this signature implement `EntityCommand`.
1906    ///     .queue(|entity: EntityWorldMut| {
1907    ///         println!("Executed an EntityCommand for {}", entity.id());
1908    ///     });
1909    /// # }
1910    /// # bevy_ecs::system::assert_is_system(my_system);
1911    /// ```
1912    pub fn queue<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
1913        &mut self,
1914        command: C,
1915    ) -> &mut Self {
1916        self.commands.queue(command.with_entity(self.entity));
1917        self
1918    }
1919
1920    /// Pushes an [`EntityCommand`] to the queue,
1921    /// which will get executed for the current [`Entity`].
1922    ///
1923    /// The given `error_handler` will be used to handle error cases.
1924    /// Every [`EntityCommand`] checks whether the entity exists at the time of execution
1925    /// and returns an error if it does not.
1926    ///
1927    /// To implicitly use the default error handler, see [`EntityCommands::queue`].
1928    ///
1929    /// The command can be:
1930    /// - A custom struct that implements [`EntityCommand`].
1931    /// - A closure or function that matches the following signature:
1932    ///   - [`(EntityWorldMut)`](EntityWorldMut)
1933    ///   - [`(EntityWorldMut)`](EntityWorldMut) `->` [`Result`]
1934    /// - A built-in command from the [`entity_command`] module.
1935    ///
1936    /// # Example
1937    ///
1938    /// ```
1939    /// # use bevy_ecs::prelude::*;
1940    /// # fn my_system(mut commands: Commands) {
1941    /// use bevy_ecs::error::warn;
1942    ///
1943    /// commands
1944    ///     .spawn_empty()
1945    ///     // Closures with this signature implement `EntityCommand`.
1946    ///     .queue_handled(
1947    ///         |entity: EntityWorldMut| -> Result {
1948    ///             let value: usize = "100".parse()?;
1949    ///             println!("Successfully parsed the value {} for entity {}", value, entity.id());
1950    ///             Ok(())
1951    ///         },
1952    ///         warn
1953    ///     );
1954    /// # }
1955    /// # bevy_ecs::system::assert_is_system(my_system);
1956    /// ```
1957    pub fn queue_handled<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
1958        &mut self,
1959        command: C,
1960        error_handler: fn(BevyError, ErrorContext),
1961    ) -> &mut Self {
1962        self.commands
1963            .queue_handled(command.with_entity(self.entity), error_handler);
1964        self
1965    }
1966
1967    /// Pushes an [`EntityCommand`] to the queue, which will get executed for the current [`Entity`].
1968    ///
1969    /// Unlike [`EntityCommands::queue_handled`], this will completely ignore any errors that occur.
1970    pub fn queue_silenced<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
1971        &mut self,
1972        command: C,
1973    ) -> &mut Self {
1974        self.commands
1975            .queue_silenced(command.with_entity(self.entity));
1976        self
1977    }
1978
1979    /// Removes all components except the given [`Bundle`] from the entity.
1980    ///
1981    /// # Example
1982    ///
1983    /// ```
1984    /// # use bevy_ecs::prelude::*;
1985    /// # #[derive(Resource)]
1986    /// # struct PlayerEntity { entity: Entity }
1987    /// #[derive(Component)]
1988    /// struct Health(u32);
1989    /// #[derive(Component)]
1990    /// struct Strength(u32);
1991    /// #[derive(Component)]
1992    /// struct Defense(u32);
1993    ///
1994    /// #[derive(Bundle)]
1995    /// struct CombatBundle {
1996    ///     health: Health,
1997    ///     strength: Strength,
1998    /// }
1999    ///
2000    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
2001    ///     commands
2002    ///         .entity(player.entity)
2003    ///         // You can retain a pre-defined Bundle of components,
2004    ///         // with this removing only the Defense component.
2005    ///         .retain::<CombatBundle>()
2006    ///         // You can also retain only a single component.
2007    ///         .retain::<Health>();
2008    /// }
2009    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
2010    /// ```
2011    #[track_caller]
2012    pub fn retain<B: Bundle>(&mut self) -> &mut Self {
2013        self.queue(entity_command::retain::<B>())
2014    }
2015
2016    /// Logs the components of the entity at the [`info`](log::info) level.
2017    pub fn log_components(&mut self) -> &mut Self {
2018        self.queue(entity_command::log_components())
2019    }
2020
2021    /// Returns the underlying [`Commands`].
2022    pub fn commands(&mut self) -> Commands<'_, '_> {
2023        self.commands.reborrow()
2024    }
2025
2026    /// Returns a mutable reference to the underlying [`Commands`].
2027    pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a> {
2028        &mut self.commands
2029    }
2030
2031    /// Creates an [`Observer`] watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`]
2032    /// targets this entity.
2033    pub fn observe<E: EntityEvent, B: Bundle, M>(
2034        &mut self,
2035        observer: impl IntoObserverSystem<E, B, M>,
2036    ) -> &mut Self {
2037        self.queue(entity_command::observe(observer))
2038    }
2039
2040    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2041    /// configured through [`EntityClonerBuilder`].
2042    ///
2043    /// The other entity will receive all the components of the original that implement
2044    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2045    /// [denied](EntityClonerBuilder::deny) in the `config`.
2046    ///
2047    /// # Panics
2048    ///
2049    /// The command will panic when applied if the target entity does not exist.
2050    ///
2051    /// # Example
2052    ///
2053    /// Configure through [`EntityClonerBuilder<OptOut>`] as follows:
2054    /// ```
2055    /// # use bevy_ecs::prelude::*;
2056    /// #[derive(Component, Clone)]
2057    /// struct ComponentA(u32);
2058    /// #[derive(Component, Clone)]
2059    /// struct ComponentB(u32);
2060    ///
2061    /// fn example_system(mut commands: Commands) {
2062    ///     // Create an empty entity.
2063    ///     let target = commands.spawn_empty().id();
2064    ///
2065    ///     // Create a new entity and keep its EntityCommands.
2066    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2067    ///
2068    ///     // Clone ComponentA but not ComponentB onto the target.
2069    ///     entity.clone_with_opt_out(target, |builder| {
2070    ///         builder.deny::<ComponentB>();
2071    ///     });
2072    /// }
2073    /// # bevy_ecs::system::assert_is_system(example_system);
2074    /// ```
2075    ///
2076    /// See [`EntityClonerBuilder`] for more options.
2077    pub fn clone_with_opt_out(
2078        &mut self,
2079        target: Entity,
2080        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2081    ) -> &mut Self {
2082        self.queue(entity_command::clone_with_opt_out(target, config))
2083    }
2084
2085    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2086    /// configured through [`EntityClonerBuilder`].
2087    ///
2088    /// The other entity will receive only the components of the original that implement
2089    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2090    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2091    ///
2092    /// # Panics
2093    ///
2094    /// The command will panic when applied if the target entity does not exist.
2095    ///
2096    /// # Example
2097    ///
2098    /// Configure through [`EntityClonerBuilder<OptIn>`] as follows:
2099    /// ```
2100    /// # use bevy_ecs::prelude::*;
2101    /// #[derive(Component, Clone)]
2102    /// struct ComponentA(u32);
2103    /// #[derive(Component, Clone)]
2104    /// struct ComponentB(u32);
2105    ///
2106    /// fn example_system(mut commands: Commands) {
2107    ///     // Create an empty entity.
2108    ///     let target = commands.spawn_empty().id();
2109    ///
2110    ///     // Create a new entity and keep its EntityCommands.
2111    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2112    ///
2113    ///     // Clone ComponentA but not ComponentB onto the target.
2114    ///     entity.clone_with_opt_in(target, |builder| {
2115    ///         builder.allow::<ComponentA>();
2116    ///     });
2117    /// }
2118    /// # bevy_ecs::system::assert_is_system(example_system);
2119    /// ```
2120    ///
2121    /// See [`EntityClonerBuilder`] for more options.
2122    pub fn clone_with_opt_in(
2123        &mut self,
2124        target: Entity,
2125        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2126    ) -> &mut Self {
2127        self.queue(entity_command::clone_with_opt_in(target, config))
2128    }
2129
2130    /// Spawns a clone of this entity and returns the [`EntityCommands`] of the clone.
2131    ///
2132    /// The clone will receive all the components of the original that implement
2133    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2134    ///
2135    /// To configure cloning behavior (such as only cloning certain components),
2136    /// use [`EntityCommands::clone_and_spawn_with_opt_out`]/
2137    /// [`opt_out`](EntityCommands::clone_and_spawn_with_opt_out).
2138    ///
2139    /// # Note
2140    ///
2141    /// If the original entity does not exist when this command is applied,
2142    /// the returned entity will have no components.
2143    ///
2144    /// # Example
2145    ///
2146    /// ```
2147    /// # use bevy_ecs::prelude::*;
2148    /// #[derive(Component, Clone)]
2149    /// struct ComponentA(u32);
2150    /// #[derive(Component, Clone)]
2151    /// struct ComponentB(u32);
2152    ///
2153    /// fn example_system(mut commands: Commands) {
2154    ///     // Create a new entity and store its EntityCommands.
2155    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2156    ///
2157    ///     // Create a clone of the entity.
2158    ///     let mut entity_clone = entity.clone_and_spawn();
2159    /// }
2160    /// # bevy_ecs::system::assert_is_system(example_system);
2161    pub fn clone_and_spawn(&mut self) -> EntityCommands<'_> {
2162        self.clone_and_spawn_with_opt_out(|_| {})
2163    }
2164
2165    /// Spawns a clone of this entity and allows configuring cloning behavior
2166    /// using [`EntityClonerBuilder`], returning the [`EntityCommands`] of the clone.
2167    ///
2168    /// The clone will receive all the components of the original that implement
2169    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2170    /// [denied](EntityClonerBuilder::deny) in the `config`.
2171    ///
2172    /// See the methods on [`EntityClonerBuilder<OptOut>`] for more options.
2173    ///
2174    /// # Note
2175    ///
2176    /// If the original entity does not exist when this command is applied,
2177    /// the returned entity will have no components.
2178    ///
2179    /// # Example
2180    ///
2181    /// ```
2182    /// # use bevy_ecs::prelude::*;
2183    /// #[derive(Component, Clone)]
2184    /// struct ComponentA(u32);
2185    /// #[derive(Component, Clone)]
2186    /// struct ComponentB(u32);
2187    ///
2188    /// fn example_system(mut commands: Commands) {
2189    ///     // Create a new entity and store its EntityCommands.
2190    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2191    ///
2192    ///     // Create a clone of the entity with ComponentA but without ComponentB.
2193    ///     let mut entity_clone = entity.clone_and_spawn_with_opt_out(|builder| {
2194    ///         builder.deny::<ComponentB>();
2195    ///     });
2196    /// }
2197    /// # bevy_ecs::system::assert_is_system(example_system);
2198    pub fn clone_and_spawn_with_opt_out(
2199        &mut self,
2200        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2201    ) -> EntityCommands<'_> {
2202        let entity_clone = self.commands().spawn_empty().id();
2203        self.clone_with_opt_out(entity_clone, config);
2204        EntityCommands {
2205            commands: self.commands_mut().reborrow(),
2206            entity: entity_clone,
2207        }
2208    }
2209
2210    /// Spawns a clone of this entity and allows configuring cloning behavior
2211    /// using [`EntityClonerBuilder`], returning the [`EntityCommands`] of the clone.
2212    ///
2213    /// The clone will receive only the components of the original that implement
2214    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2215    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2216    ///
2217    /// See the methods on [`EntityClonerBuilder<OptIn>`] for more options.
2218    ///
2219    /// # Note
2220    ///
2221    /// If the original entity does not exist when this command is applied,
2222    /// the returned entity will have no components.
2223    ///
2224    /// # Example
2225    ///
2226    /// ```
2227    /// # use bevy_ecs::prelude::*;
2228    /// #[derive(Component, Clone)]
2229    /// struct ComponentA(u32);
2230    /// #[derive(Component, Clone)]
2231    /// struct ComponentB(u32);
2232    ///
2233    /// fn example_system(mut commands: Commands) {
2234    ///     // Create a new entity and store its EntityCommands.
2235    ///     let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
2236    ///
2237    ///     // Create a clone of the entity with ComponentA but without ComponentB.
2238    ///     let mut entity_clone = entity.clone_and_spawn_with_opt_in(|builder| {
2239    ///         builder.allow::<ComponentA>();
2240    ///     });
2241    /// }
2242    /// # bevy_ecs::system::assert_is_system(example_system);
2243    pub fn clone_and_spawn_with_opt_in(
2244        &mut self,
2245        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2246    ) -> EntityCommands<'_> {
2247        let entity_clone = self.commands().spawn_empty().id();
2248        self.clone_with_opt_in(entity_clone, config);
2249        EntityCommands {
2250            commands: self.commands_mut().reborrow(),
2251            entity: entity_clone,
2252        }
2253    }
2254
2255    /// Clones the specified components of this entity and inserts them into another entity.
2256    ///
2257    /// Components can only be cloned if they implement
2258    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2259    ///
2260    /// # Panics
2261    ///
2262    /// The command will panic when applied if the target entity does not exist.
2263    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2264        self.queue(entity_command::clone_components::<B>(target))
2265    }
2266
2267    /// Moves the specified components of this entity into another entity.
2268    ///
2269    /// Components with [`Ignore`] clone behavior will not be moved, while components that
2270    /// have a [`Custom`] clone behavior will be cloned using it and then removed from the source entity.
2271    /// All other components will be moved without any other special handling.
2272    ///
2273    /// Note that this will trigger `on_remove` hooks/observers on this entity and `on_insert`/`on_add` hooks/observers on the target entity.
2274    ///
2275    /// # Panics
2276    ///
2277    /// The command will panic when applied if the target entity does not exist.
2278    ///
2279    /// [`Ignore`]: crate::component::ComponentCloneBehavior::Ignore
2280    /// [`Custom`]: crate::component::ComponentCloneBehavior::Custom
2281    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2282        self.queue(entity_command::move_components::<B>(target))
2283    }
2284
2285    /// Passes the current entity into the given function, and triggers the [`EntityEvent`] returned by that function.
2286    ///
2287    /// # Example
2288    ///
2289    /// A surprising number of functions meet the trait bounds for `event_fn`:
2290    ///
2291    /// ```rust
2292    /// # use bevy_ecs::prelude::*;
2293    ///
2294    /// #[derive(EntityEvent)]
2295    /// struct Explode(Entity);
2296    ///
2297    /// impl From<Entity> for Explode {
2298    ///    fn from(entity: Entity) -> Self {
2299    ///       Explode(entity)
2300    ///    }
2301    /// }
2302    ///
2303    ///
2304    /// fn trigger_via_constructor(mut commands: Commands) {
2305    ///     // The fact that `Explode` is a single-field tuple struct
2306    ///     // ensures that `Explode(entity)` is a function that generates
2307    ///     // an EntityEvent, meeting the trait bounds for `event_fn`.
2308    ///     commands.spawn_empty().trigger(Explode);
2309    ///
2310    /// }
2311    ///
2312    ///
2313    /// fn trigger_via_from_trait(mut commands: Commands) {
2314    ///     // This variant also works for events like `struct Explode { entity: Entity }`
2315    ///     commands.spawn_empty().trigger(Explode::from);
2316    /// }
2317    ///
2318    /// fn trigger_via_closure(mut commands: Commands) {
2319    ///     commands.spawn_empty().trigger(|entity| Explode(entity));
2320    /// }
2321    /// ```
2322    #[track_caller]
2323    pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
2324        &mut self,
2325        event_fn: impl FnOnce(Entity) -> E,
2326    ) -> &mut Self {
2327        let event = (event_fn)(self.entity);
2328        self.commands.trigger(event);
2329        self
2330    }
2331}
2332
2333/// A wrapper around [`EntityCommands`] with convenience methods for working with a specified component type.
2334pub struct EntityEntryCommands<'a, T> {
2335    entity_commands: EntityCommands<'a>,
2336    marker: PhantomData<T>,
2337}
2338
2339impl<'a, T: Component<Mutability = Mutable>> EntityEntryCommands<'a, T> {
2340    /// Modify the component `T` if it exists, using the function `modify`.
2341    pub fn and_modify(&mut self, modify: impl FnOnce(Mut<T>) + Send + Sync + 'static) -> &mut Self {
2342        self.entity_commands
2343            .queue(move |mut entity: EntityWorldMut| {
2344                if let Some(value) = entity.get_mut() {
2345                    modify(value);
2346                }
2347            });
2348        self
2349    }
2350}
2351
2352impl<'a, T: Component> EntityEntryCommands<'a, T> {
2353    /// [Insert](EntityCommands::insert) `default` into this entity,
2354    /// if `T` is not already present.
2355    #[track_caller]
2356    pub fn or_insert(&mut self, default: T) -> &mut Self {
2357        self.entity_commands.insert_if_new(default);
2358        self
2359    }
2360
2361    /// [Insert](EntityCommands::insert) `default` into this entity,
2362    /// if `T` is not already present.
2363    ///
2364    /// # Note
2365    ///
2366    /// If the entity does not exist when this command is executed,
2367    /// the resulting error will be ignored.
2368    #[track_caller]
2369    pub fn or_try_insert(&mut self, default: T) -> &mut Self {
2370        self.entity_commands.try_insert_if_new(default);
2371        self
2372    }
2373
2374    /// [Insert](EntityCommands::insert) the value returned from `default` into this entity,
2375    /// if `T` is not already present.
2376    ///
2377    /// `default` will only be invoked if the component will actually be inserted.
2378    #[track_caller]
2379    pub fn or_insert_with<F>(&mut self, default: F) -> &mut Self
2380    where
2381        F: FnOnce() -> T + Send + 'static,
2382    {
2383        self.entity_commands
2384            .queue(entity_command::insert_with(default, InsertMode::Keep));
2385        self
2386    }
2387
2388    /// [Insert](EntityCommands::insert) the value returned from `default` into this entity,
2389    /// if `T` is not already present.
2390    ///
2391    /// `default` will only be invoked if the component will actually be inserted.
2392    ///
2393    /// # Note
2394    ///
2395    /// If the entity does not exist when this command is executed,
2396    /// the resulting error will be ignored.
2397    #[track_caller]
2398    pub fn or_try_insert_with<F>(&mut self, default: F) -> &mut Self
2399    where
2400        F: FnOnce() -> T + Send + 'static,
2401    {
2402        self.entity_commands
2403            .queue_silenced(entity_command::insert_with(default, InsertMode::Keep));
2404        self
2405    }
2406
2407    /// [Insert](EntityCommands::insert) `T::default` into this entity,
2408    /// if `T` is not already present.
2409    ///
2410    /// `T::default` will only be invoked if the component will actually be inserted.
2411    #[track_caller]
2412    pub fn or_default(&mut self) -> &mut Self
2413    where
2414        T: Default,
2415    {
2416        self.or_insert_with(T::default)
2417    }
2418
2419    /// [Insert](EntityCommands::insert) `T::from_world` into this entity,
2420    /// if `T` is not already present.
2421    ///
2422    /// `T::from_world` will only be invoked if the component will actually be inserted.
2423    #[track_caller]
2424    pub fn or_from_world(&mut self) -> &mut Self
2425    where
2426        T: FromWorld,
2427    {
2428        self.entity_commands
2429            .queue(entity_command::insert_from_world::<T>(InsertMode::Keep));
2430        self
2431    }
2432
2433    /// Get the [`EntityCommands`] from which the [`EntityEntryCommands`] was initiated.
2434    ///
2435    /// This allows you to continue chaining method calls after calling [`EntityCommands::entry`].
2436    ///
2437    /// # Example
2438    ///
2439    /// ```
2440    /// # use bevy_ecs::prelude::*;
2441    /// # #[derive(Resource)]
2442    /// # struct PlayerEntity { entity: Entity }
2443    /// #[derive(Component)]
2444    /// struct Level(u32);
2445    ///
2446    /// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
2447    ///     commands
2448    ///         .entity(player.entity)
2449    ///         .entry::<Level>()
2450    ///         // Modify the component if it exists.
2451    ///         .and_modify(|mut lvl| lvl.0 += 1)
2452    ///         // Otherwise, insert a default value.
2453    ///         .or_insert(Level(0))
2454    ///         // Return the EntityCommands for the entity.
2455    ///         .entity()
2456    ///         // Continue chaining method calls.
2457    ///         .insert(Name::new("Player"));
2458    /// }
2459    /// # bevy_ecs::system::assert_is_system(level_up_system);
2460    /// ```
2461    pub fn entity(&mut self) -> EntityCommands<'_> {
2462        self.entity_commands.reborrow()
2463    }
2464}
2465
2466#[cfg(test)]
2467mod tests {
2468    use crate::{
2469        component::Component,
2470        resource::Resource,
2471        system::Commands,
2472        world::{CommandQueue, FromWorld, World},
2473    };
2474    use alloc::{string::String, sync::Arc, vec, vec::Vec};
2475    use core::{
2476        any::TypeId,
2477        sync::atomic::{AtomicUsize, Ordering},
2478    };
2479
2480    #[expect(
2481        dead_code,
2482        reason = "This struct is used to test how `Drop` behavior works in regards to SparseSet storage, and as such is solely a wrapper around `DropCk` to make it use the SparseSet storage. Because of this, the inner field is intentionally never read."
2483    )]
2484    #[derive(Component)]
2485    #[component(storage = "SparseSet")]
2486    struct SparseDropCk(DropCk);
2487
2488    #[derive(Component)]
2489    struct DropCk(Arc<AtomicUsize>);
2490    impl DropCk {
2491        fn new_pair() -> (Self, Arc<AtomicUsize>) {
2492            let atomic = Arc::new(AtomicUsize::new(0));
2493            (DropCk(atomic.clone()), atomic)
2494        }
2495    }
2496
2497    impl Drop for DropCk {
2498        fn drop(&mut self) {
2499            self.0.as_ref().fetch_add(1, Ordering::Relaxed);
2500        }
2501    }
2502
2503    #[derive(Component)]
2504    struct W<T>(T);
2505
2506    #[derive(Resource)]
2507    struct V<T>(T);
2508
2509    fn simple_command(world: &mut World) {
2510        world.spawn((W(0u32), W(42u64)));
2511    }
2512
2513    impl FromWorld for W<String> {
2514        fn from_world(world: &mut World) -> Self {
2515            let v = world.resource::<V<usize>>();
2516            Self("*".repeat(v.0))
2517        }
2518    }
2519
2520    impl Default for W<u8> {
2521        fn default() -> Self {
2522            unreachable!()
2523        }
2524    }
2525
2526    #[test]
2527    fn entity_commands_entry() {
2528        let mut world = World::default();
2529        let mut queue = CommandQueue::default();
2530        let mut commands = Commands::new(&mut queue, &world);
2531        let entity = commands.spawn_empty().id();
2532        commands
2533            .entity(entity)
2534            .entry::<W<u32>>()
2535            .and_modify(|_| unreachable!());
2536        queue.apply(&mut world);
2537        assert!(!world.entity(entity).contains::<W<u32>>());
2538        let mut commands = Commands::new(&mut queue, &world);
2539        commands
2540            .entity(entity)
2541            .entry::<W<u32>>()
2542            .or_insert(W(0))
2543            .and_modify(|mut val| {
2544                val.0 = 21;
2545            });
2546        queue.apply(&mut world);
2547        assert_eq!(21, world.get::<W<u32>>(entity).unwrap().0);
2548        let mut commands = Commands::new(&mut queue, &world);
2549        commands
2550            .entity(entity)
2551            .entry::<W<u64>>()
2552            .and_modify(|_| unreachable!())
2553            .or_insert(W(42));
2554        queue.apply(&mut world);
2555        assert_eq!(42, world.get::<W<u64>>(entity).unwrap().0);
2556        world.insert_resource(V(5_usize));
2557        let mut commands = Commands::new(&mut queue, &world);
2558        commands.entity(entity).entry::<W<String>>().or_from_world();
2559        queue.apply(&mut world);
2560        assert_eq!("*****", &world.get::<W<String>>(entity).unwrap().0);
2561        let mut commands = Commands::new(&mut queue, &world);
2562        let id = commands.entity(entity).entry::<W<u64>>().entity().id();
2563        queue.apply(&mut world);
2564        assert_eq!(id, entity);
2565        let mut commands = Commands::new(&mut queue, &world);
2566        commands
2567            .entity(entity)
2568            .entry::<W<u8>>()
2569            .or_insert_with(|| W(5))
2570            .or_insert_with(|| unreachable!())
2571            .or_try_insert_with(|| unreachable!())
2572            .or_default()
2573            .or_from_world();
2574        queue.apply(&mut world);
2575        assert_eq!(5, world.get::<W<u8>>(entity).unwrap().0);
2576    }
2577
2578    #[test]
2579    fn commands() {
2580        let mut world = World::default();
2581        let mut command_queue = CommandQueue::default();
2582        let entity = Commands::new(&mut command_queue, &world)
2583            .spawn((W(1u32), W(2u64)))
2584            .id();
2585        command_queue.apply(&mut world);
2586        assert_eq!(world.query::<&W<u32>>().query(&world).count(), 1);
2587        let results = world
2588            .query::<(&W<u32>, &W<u64>)>()
2589            .iter(&world)
2590            .map(|(a, b)| (a.0, b.0))
2591            .collect::<Vec<_>>();
2592        assert_eq!(results, vec![(1u32, 2u64)]);
2593        // test entity despawn
2594        {
2595            let mut commands = Commands::new(&mut command_queue, &world);
2596            commands.entity(entity).despawn();
2597            commands.entity(entity).despawn(); // double despawn shouldn't panic
2598        }
2599        command_queue.apply(&mut world);
2600        let results2 = world
2601            .query::<(&W<u32>, &W<u64>)>()
2602            .iter(&world)
2603            .map(|(a, b)| (a.0, b.0))
2604            .collect::<Vec<_>>();
2605        assert_eq!(results2, vec![]);
2606
2607        // test adding simple (FnOnce) commands
2608        {
2609            let mut commands = Commands::new(&mut command_queue, &world);
2610
2611            // set up a simple command using a closure that adds one additional entity
2612            commands.queue(|world: &mut World| {
2613                world.spawn((W(42u32), W(0u64)));
2614            });
2615
2616            // set up a simple command using a function that adds one additional entity
2617            commands.queue(simple_command);
2618        }
2619        command_queue.apply(&mut world);
2620        let results3 = world
2621            .query::<(&W<u32>, &W<u64>)>()
2622            .iter(&world)
2623            .map(|(a, b)| (a.0, b.0))
2624            .collect::<Vec<_>>();
2625
2626        assert_eq!(results3, vec![(42u32, 0u64), (0u32, 42u64)]);
2627    }
2628
2629    #[test]
2630    fn insert_components() {
2631        let mut world = World::default();
2632        let mut command_queue1 = CommandQueue::default();
2633
2634        // insert components
2635        let entity = Commands::new(&mut command_queue1, &world)
2636            .spawn(())
2637            .insert_if(W(1u8), || true)
2638            .insert_if(W(2u8), || false)
2639            .insert_if_new(W(1u16))
2640            .insert_if_new(W(2u16))
2641            .insert_if_new_and(W(1u32), || false)
2642            .insert_if_new_and(W(2u32), || true)
2643            .insert_if_new_and(W(3u32), || true)
2644            .id();
2645        command_queue1.apply(&mut world);
2646
2647        let results = world
2648            .query::<(&W<u8>, &W<u16>, &W<u32>)>()
2649            .iter(&world)
2650            .map(|(a, b, c)| (a.0, b.0, c.0))
2651            .collect::<Vec<_>>();
2652        assert_eq!(results, vec![(1u8, 1u16, 2u32)]);
2653
2654        // try to insert components after despawning entity
2655        // in another command queue
2656        Commands::new(&mut command_queue1, &world)
2657            .entity(entity)
2658            .try_insert_if_new_and(W(1u64), || true);
2659
2660        let mut command_queue2 = CommandQueue::default();
2661        Commands::new(&mut command_queue2, &world)
2662            .entity(entity)
2663            .despawn();
2664        command_queue2.apply(&mut world);
2665        command_queue1.apply(&mut world);
2666    }
2667
2668    #[test]
2669    fn remove_components() {
2670        let mut world = World::default();
2671
2672        let mut command_queue = CommandQueue::default();
2673        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
2674        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
2675        let sparse_dropck = SparseDropCk(sparse_dropck);
2676
2677        let entity = Commands::new(&mut command_queue, &world)
2678            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
2679            .id();
2680        command_queue.apply(&mut world);
2681        let results_before = world
2682            .query::<(&W<u32>, &W<u64>)>()
2683            .iter(&world)
2684            .map(|(a, b)| (a.0, b.0))
2685            .collect::<Vec<_>>();
2686        assert_eq!(results_before, vec![(1u32, 2u64)]);
2687
2688        // test component removal
2689        Commands::new(&mut command_queue, &world)
2690            .entity(entity)
2691            .remove::<W<u32>>()
2692            .remove::<(W<u32>, W<u64>, SparseDropCk, DropCk)>();
2693
2694        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
2695        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
2696        command_queue.apply(&mut world);
2697        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
2698        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
2699
2700        let results_after = world
2701            .query::<(&W<u32>, &W<u64>)>()
2702            .iter(&world)
2703            .map(|(a, b)| (a.0, b.0))
2704            .collect::<Vec<_>>();
2705        assert_eq!(results_after, vec![]);
2706        let results_after_u64 = world
2707            .query::<&W<u64>>()
2708            .iter(&world)
2709            .map(|v| v.0)
2710            .collect::<Vec<_>>();
2711        assert_eq!(results_after_u64, vec![]);
2712    }
2713
2714    #[test]
2715    fn remove_components_by_id() {
2716        let mut world = World::default();
2717
2718        let mut command_queue = CommandQueue::default();
2719        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
2720        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
2721        let sparse_dropck = SparseDropCk(sparse_dropck);
2722
2723        let entity = Commands::new(&mut command_queue, &world)
2724            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
2725            .id();
2726        command_queue.apply(&mut world);
2727        let results_before = world
2728            .query::<(&W<u32>, &W<u64>)>()
2729            .iter(&world)
2730            .map(|(a, b)| (a.0, b.0))
2731            .collect::<Vec<_>>();
2732        assert_eq!(results_before, vec![(1u32, 2u64)]);
2733
2734        // test component removal
2735        Commands::new(&mut command_queue, &world)
2736            .entity(entity)
2737            .remove_by_id(world.components().get_id(TypeId::of::<W<u32>>()).unwrap())
2738            .remove_by_id(world.components().get_id(TypeId::of::<W<u64>>()).unwrap())
2739            .remove_by_id(world.components().get_id(TypeId::of::<DropCk>()).unwrap())
2740            .remove_by_id(
2741                world
2742                    .components()
2743                    .get_id(TypeId::of::<SparseDropCk>())
2744                    .unwrap(),
2745            );
2746
2747        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
2748        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
2749        command_queue.apply(&mut world);
2750        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
2751        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
2752
2753        let results_after = world
2754            .query::<(&W<u32>, &W<u64>)>()
2755            .iter(&world)
2756            .map(|(a, b)| (a.0, b.0))
2757            .collect::<Vec<_>>();
2758        assert_eq!(results_after, vec![]);
2759        let results_after_u64 = world
2760            .query::<&W<u64>>()
2761            .iter(&world)
2762            .map(|v| v.0)
2763            .collect::<Vec<_>>();
2764        assert_eq!(results_after_u64, vec![]);
2765    }
2766
2767    #[test]
2768    fn remove_resources() {
2769        let mut world = World::default();
2770        let mut queue = CommandQueue::default();
2771        {
2772            let mut commands = Commands::new(&mut queue, &world);
2773            commands.insert_resource(V(123i32));
2774            commands.insert_resource(V(456.0f64));
2775        }
2776
2777        queue.apply(&mut world);
2778        assert!(world.contains_resource::<V<i32>>());
2779        assert!(world.contains_resource::<V<f64>>());
2780
2781        {
2782            let mut commands = Commands::new(&mut queue, &world);
2783            // test resource removal
2784            commands.remove_resource::<V<i32>>();
2785        }
2786        queue.apply(&mut world);
2787        assert!(!world.contains_resource::<V<i32>>());
2788        assert!(world.contains_resource::<V<f64>>());
2789    }
2790
2791    #[test]
2792    fn remove_component_with_required_components() {
2793        #[derive(Component)]
2794        #[require(Y)]
2795        struct X;
2796
2797        #[derive(Component, Default)]
2798        struct Y;
2799
2800        #[derive(Component)]
2801        struct Z;
2802
2803        let mut world = World::default();
2804        let mut queue = CommandQueue::default();
2805        let e = {
2806            let mut commands = Commands::new(&mut queue, &world);
2807            commands.spawn((X, Z)).id()
2808        };
2809        queue.apply(&mut world);
2810
2811        assert!(world.get::<Y>(e).is_some());
2812        assert!(world.get::<X>(e).is_some());
2813        assert!(world.get::<Z>(e).is_some());
2814
2815        {
2816            let mut commands = Commands::new(&mut queue, &world);
2817            commands.entity(e).remove_with_requires::<X>();
2818        }
2819        queue.apply(&mut world);
2820
2821        assert!(world.get::<Y>(e).is_none());
2822        assert!(world.get::<X>(e).is_none());
2823
2824        assert!(world.get::<Z>(e).is_some());
2825    }
2826
2827    #[test]
2828    fn unregister_system_cached_commands() {
2829        let mut world = World::default();
2830        let mut queue = CommandQueue::default();
2831
2832        fn nothing() {}
2833
2834        let resources = world.iter_resources().count();
2835        let id = world.register_system_cached(nothing);
2836        assert_eq!(world.iter_resources().count(), resources + 1);
2837        assert!(world.get_entity(id.entity).is_ok());
2838
2839        let mut commands = Commands::new(&mut queue, &world);
2840        commands.unregister_system_cached(nothing);
2841        queue.apply(&mut world);
2842        assert_eq!(world.iter_resources().count(), resources);
2843        assert!(world.get_entity(id.entity).is_err());
2844    }
2845
2846    fn is_send<T: Send>() {}
2847    fn is_sync<T: Sync>() {}
2848
2849    #[test]
2850    fn test_commands_are_send_and_sync() {
2851        is_send::<Commands>();
2852        is_sync::<Commands>();
2853    }
2854
2855    #[test]
2856    fn append() {
2857        let mut world = World::default();
2858        let mut queue_1 = CommandQueue::default();
2859        {
2860            let mut commands = Commands::new(&mut queue_1, &world);
2861            commands.insert_resource(V(123i32));
2862        }
2863        let mut queue_2 = CommandQueue::default();
2864        {
2865            let mut commands = Commands::new(&mut queue_2, &world);
2866            commands.insert_resource(V(456.0f64));
2867        }
2868        queue_1.append(&mut queue_2);
2869        queue_1.apply(&mut world);
2870        assert!(world.contains_resource::<V<i32>>());
2871        assert!(world.contains_resource::<V<f64>>());
2872    }
2873
2874    #[test]
2875    fn track_spawn_ticks() {
2876        let mut world = World::default();
2877        world.increment_change_tick();
2878        let expected = world.change_tick();
2879        let id = world.commands().spawn_empty().id();
2880        world.flush();
2881        assert_eq!(
2882            Some(expected),
2883            world.entities().entity_get_spawn_or_despawn_tick(id)
2884        );
2885    }
2886}