bevy_ecs/system/commands/
mod.rs

1mod parallel_scope;
2
3use super::{Deferred, IntoObserverSystem, IntoSystem, RegisterSystem, Resource};
4use crate::{
5    self as bevy_ecs,
6    bundle::Bundle,
7    component::ComponentId,
8    entity::{Entities, Entity},
9    event::Event,
10    observer::{Observer, TriggerEvent, TriggerTargets},
11    system::{RunSystemWithInput, SystemId},
12    world::command_queue::RawCommandQueue,
13    world::{Command, CommandQueue, EntityWorldMut, FromWorld, World},
14};
15use bevy_utils::tracing::{error, info};
16pub use parallel_scope::*;
17use std::marker::PhantomData;
18
19/// A [`Command`] queue to perform structural changes to the [`World`].
20///
21/// Since each command requires exclusive access to the `World`,
22/// all queued commands are automatically applied in sequence
23/// when the `apply_deferred` system runs (see [`apply_deferred`] documentation for more details).
24///
25/// Each command can be used to modify the [`World`] in arbitrary ways:
26/// * spawning or despawning entities
27/// * inserting components on new or existing entities
28/// * inserting resources
29/// * etc.
30///
31/// For a version of [`Commands`] that works in parallel contexts (such as
32/// within [`Query::par_iter`](crate::system::Query::par_iter)) see
33/// [`ParallelCommands`]
34///
35/// # Usage
36///
37/// Add `mut commands: Commands` as a function argument to your system to get a copy of this struct that will be applied the next time a copy of [`apply_deferred`] runs.
38/// Commands are almost always used as a [`SystemParam`](crate::system::SystemParam).
39///
40/// ```
41/// # use bevy_ecs::prelude::*;
42/// #
43/// fn my_system(mut commands: Commands) {
44///    // ...
45/// }
46/// # bevy_ecs::system::assert_is_system(my_system);
47/// ```
48///
49/// # Implementing
50///
51/// Each built-in command is implemented as a separate method, e.g. [`Commands::spawn`].
52/// In addition to the pre-defined command methods, you can add commands with any arbitrary
53/// behavior using [`Commands::add`], which accepts any type implementing [`Command`].
54///
55/// Since closures and other functions implement this trait automatically, this allows one-shot,
56/// anonymous custom commands.
57///
58/// ```
59/// # use bevy_ecs::prelude::*;
60/// # fn foo(mut commands: Commands) {
61/// // NOTE: type inference fails here, so annotations are required on the closure.
62/// commands.add(|w: &mut World| {
63///     // Mutate the world however you want...
64///     # todo!();
65/// });
66/// # }
67/// ```
68///
69/// [`apply_deferred`]: crate::schedule::apply_deferred
70pub struct Commands<'w, 's> {
71    queue: InternalQueue<'s>,
72    entities: &'w Entities,
73}
74
75// SAFETY: All commands [`Command`] implement [`Send`]
76unsafe impl Send for Commands<'_, '_> {}
77
78// SAFETY: `Commands` never gives access to the inner commands.
79unsafe impl Sync for Commands<'_, '_> {}
80
81const _: () = {
82    type __StructFieldsAlias<'w, 's> = (Deferred<'s, CommandQueue>, &'w Entities);
83    #[doc(hidden)]
84    pub struct FetchState {
85        state: <__StructFieldsAlias<'static, 'static> as bevy_ecs::system::SystemParam>::State,
86    }
87    // SAFETY: Only reads Entities
88    unsafe impl bevy_ecs::system::SystemParam for Commands<'_, '_> {
89        type State = FetchState;
90        type Item<'w, 's> = Commands<'w, 's>;
91        fn init_state(
92            world: &mut bevy_ecs::world::World,
93            system_meta: &mut bevy_ecs::system::SystemMeta,
94        ) -> Self::State {
95            FetchState {
96                state: <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_state(
97                    world,
98                    system_meta,
99                ),
100            }
101        }
102        unsafe fn new_archetype(
103            state: &mut Self::State,
104            archetype: &bevy_ecs::archetype::Archetype,
105            system_meta: &mut bevy_ecs::system::SystemMeta,
106        ) {
107            // SAFETY: Caller guarantees the archetype is from the world used in `init_state`
108            unsafe {
109                <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::new_archetype(
110                    &mut state.state,
111                    archetype,
112                    system_meta,
113                );
114            };
115        }
116        fn apply(
117            state: &mut Self::State,
118            system_meta: &bevy_ecs::system::SystemMeta,
119            world: &mut bevy_ecs::world::World,
120        ) {
121            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::apply(
122                &mut state.state,
123                system_meta,
124                world,
125            );
126        }
127        fn queue(
128            state: &mut Self::State,
129            system_meta: &bevy_ecs::system::SystemMeta,
130            world: bevy_ecs::world::DeferredWorld,
131        ) {
132            <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::queue(
133                &mut state.state,
134                system_meta,
135                world,
136            );
137        }
138        unsafe fn get_param<'w, 's>(
139            state: &'s mut Self::State,
140            system_meta: &bevy_ecs::system::SystemMeta,
141            world: bevy_ecs::world::unsafe_world_cell::UnsafeWorldCell<'w>,
142            change_tick: bevy_ecs::component::Tick,
143        ) -> Self::Item<'w, 's> {
144            let(f0,f1,) =  <(Deferred<'s,CommandQueue> , &'w Entities,)as bevy_ecs::system::SystemParam> ::get_param(&mut state.state,system_meta,world,change_tick);
145            Commands {
146                queue: InternalQueue::CommandQueue(f0),
147                entities: f1,
148            }
149        }
150    }
151    // SAFETY: Only reads Entities
152    unsafe impl<'w, 's> bevy_ecs::system::ReadOnlySystemParam for Commands<'w, 's>
153    where
154        Deferred<'s, CommandQueue>: bevy_ecs::system::ReadOnlySystemParam,
155        &'w Entities: bevy_ecs::system::ReadOnlySystemParam,
156    {
157    }
158};
159
160enum InternalQueue<'s> {
161    CommandQueue(Deferred<'s, CommandQueue>),
162    RawCommandQueue(RawCommandQueue),
163}
164
165impl<'w, 's> Commands<'w, 's> {
166    /// Returns a new `Commands` instance from a [`CommandQueue`] and a [`World`].
167    ///
168    /// It is not required to call this constructor when using `Commands` as a [system parameter].
169    ///
170    /// [system parameter]: crate::system::SystemParam
171    pub fn new(queue: &'s mut CommandQueue, world: &'w World) -> Self {
172        Self::new_from_entities(queue, &world.entities)
173    }
174
175    /// Returns a new `Commands` instance from a [`CommandQueue`] and an [`Entities`] reference.
176    ///
177    /// It is not required to call this constructor when using `Commands` as a [system parameter].
178    ///
179    /// [system parameter]: crate::system::SystemParam
180    pub fn new_from_entities(queue: &'s mut CommandQueue, entities: &'w Entities) -> Self {
181        Self {
182            queue: InternalQueue::CommandQueue(Deferred(queue)),
183            entities,
184        }
185    }
186
187    /// Returns a new `Commands` instance from a [`RawCommandQueue`] and an [`Entities`] reference.
188    ///
189    /// This is used when constructing [`Commands`] from a [`DeferredWorld`](crate::world::DeferredWorld).
190    ///
191    /// # Safety
192    ///
193    /// * Caller ensures that `queue` must outlive 'w
194    pub(crate) unsafe fn new_raw_from_entities(
195        queue: RawCommandQueue,
196        entities: &'w Entities,
197    ) -> Self {
198        Self {
199            queue: InternalQueue::RawCommandQueue(queue),
200            entities,
201        }
202    }
203
204    /// Returns a [`Commands`] with a smaller lifetime.
205    /// This is useful if you have `&mut Commands` but need `Commands`.
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// # use bevy_ecs::prelude::*;
211    /// fn my_system(mut commands: Commands) {
212    ///     // We do our initialization in a separate function,
213    ///     // which expects an owned `Commands`.
214    ///     do_initialization(commands.reborrow());
215    ///
216    ///     // Since we only reborrowed the commands instead of moving them, we can still use them.
217    ///     commands.spawn_empty();
218    /// }
219    /// #
220    /// # fn do_initialization(_: Commands) {}
221    /// ```
222    pub fn reborrow(&mut self) -> Commands<'w, '_> {
223        Commands {
224            queue: match &mut self.queue {
225                InternalQueue::CommandQueue(queue) => InternalQueue::CommandQueue(queue.reborrow()),
226                InternalQueue::RawCommandQueue(queue) => {
227                    InternalQueue::RawCommandQueue(queue.clone())
228                }
229            },
230            entities: self.entities,
231        }
232    }
233
234    /// Take all commands from `other` and append them to `self`, leaving `other` empty
235    pub fn append(&mut self, other: &mut CommandQueue) {
236        match &mut self.queue {
237            InternalQueue::CommandQueue(queue) => queue.bytes.append(&mut other.bytes),
238            InternalQueue::RawCommandQueue(queue) => {
239                // SAFETY: Pointers in `RawCommandQueue` are never null
240                unsafe { queue.bytes.as_mut() }.append(&mut other.bytes);
241            }
242        }
243    }
244
245    /// Pushes a [`Command`] to the queue for creating a new empty [`Entity`],
246    /// and returns its corresponding [`EntityCommands`].
247    ///
248    /// See [`World::spawn_empty`] for more details.
249    ///
250    /// # Example
251    ///
252    /// ```
253    /// # use bevy_ecs::prelude::*;
254    ///
255    /// #[derive(Component)]
256    /// struct Label(&'static str);
257    /// #[derive(Component)]
258    /// struct Strength(u32);
259    /// #[derive(Component)]
260    /// struct Agility(u32);
261    ///
262    /// fn example_system(mut commands: Commands) {
263    ///     // Create a new empty entity and retrieve its id.
264    ///     let empty_entity = commands.spawn_empty().id();
265    ///
266    ///     // Create another empty entity, then add some component to it
267    ///     commands.spawn_empty()
268    ///         // adds a new component bundle to the entity
269    ///         .insert((Strength(1), Agility(2)))
270    ///         // adds a single component to the entity
271    ///         .insert(Label("hello world"));
272    /// }
273    /// # bevy_ecs::system::assert_is_system(example_system);
274    /// ```
275    ///
276    /// # See also
277    ///
278    /// - [`spawn`](Self::spawn) to spawn an entity with a bundle.
279    /// - [`spawn_batch`](Self::spawn_batch) to spawn entities with a bundle each.
280    pub fn spawn_empty(&mut self) -> EntityCommands {
281        let entity = self.entities.reserve_entity();
282        EntityCommands {
283            entity,
284            commands: self.reborrow(),
285        }
286    }
287
288    /// Pushes a [`Command`] to the queue for creating a new [`Entity`] if the given one does not exists,
289    /// and returns its corresponding [`EntityCommands`].
290    ///
291    /// This method silently fails by returning [`EntityCommands`]
292    /// even if the given `Entity` cannot be spawned.
293    ///
294    /// See [`World::get_or_spawn`] for more details.
295    ///
296    /// # Note
297    ///
298    /// Spawning a specific `entity` value is rarely the right choice. Most apps should favor
299    /// [`Commands::spawn`]. This method should generally only be used for sharing entities across
300    /// apps, and only when they have a scheme worked out to share an ID space (which doesn't happen
301    /// by default).
302    pub fn get_or_spawn(&mut self, entity: Entity) -> EntityCommands {
303        self.add(move |world: &mut World| {
304            world.get_or_spawn(entity);
305        });
306        EntityCommands {
307            entity,
308            commands: self.reborrow(),
309        }
310    }
311
312    /// Pushes a [`Command`] to the queue for creating a new entity with the given [`Bundle`]'s components,
313    /// and returns its corresponding [`EntityCommands`].
314    ///
315    /// # Example
316    ///
317    /// ```
318    /// use bevy_ecs::prelude::*;
319    ///
320    /// #[derive(Component)]
321    /// struct Component1;
322    /// #[derive(Component)]
323    /// struct Component2;
324    /// #[derive(Component)]
325    /// struct Label(&'static str);
326    /// #[derive(Component)]
327    /// struct Strength(u32);
328    /// #[derive(Component)]
329    /// struct Agility(u32);
330    ///
331    /// #[derive(Bundle)]
332    /// struct ExampleBundle {
333    ///     a: Component1,
334    ///     b: Component2,
335    /// }
336    ///
337    /// fn example_system(mut commands: Commands) {
338    ///     // Create a new entity with a single component.
339    ///     commands.spawn(Component1);
340    ///
341    ///     // Create a new entity with a component bundle.
342    ///     commands.spawn(ExampleBundle {
343    ///         a: Component1,
344    ///         b: Component2,
345    ///     });
346    ///
347    ///     commands
348    ///         // Create a new entity with two components using a "tuple bundle".
349    ///         .spawn((Component1, Component2))
350    ///         // `spawn returns a builder, so you can insert more bundles like this:
351    ///         .insert((Strength(1), Agility(2)))
352    ///         // or insert single components like this:
353    ///         .insert(Label("hello world"));
354    /// }
355    /// # bevy_ecs::system::assert_is_system(example_system);
356    /// ```
357    ///
358    /// # See also
359    ///
360    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without any components.
361    /// - [`spawn_batch`](Self::spawn_batch) to spawn entities with a bundle each.
362    pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands {
363        let mut e = self.spawn_empty();
364        e.insert(bundle);
365        e
366    }
367
368    /// Returns the [`EntityCommands`] for the requested [`Entity`].
369    ///
370    /// # Panics
371    ///
372    /// This method panics if the requested entity does not exist.
373    ///
374    /// # Example
375    ///
376    /// ```
377    /// use bevy_ecs::prelude::*;
378    ///
379    /// #[derive(Component)]
380    /// struct Label(&'static str);
381    /// #[derive(Component)]
382    /// struct Strength(u32);
383    /// #[derive(Component)]
384    /// struct Agility(u32);
385    ///
386    /// fn example_system(mut commands: Commands) {
387    ///     // Create a new, empty entity
388    ///     let entity = commands.spawn_empty().id();
389    ///
390    ///     commands.entity(entity)
391    ///         // adds a new component bundle to the entity
392    ///         .insert((Strength(1), Agility(2)))
393    ///         // adds a single component to the entity
394    ///         .insert(Label("hello world"));
395    /// }
396    /// # bevy_ecs::system::assert_is_system(example_system);
397    /// ```
398    ///
399    /// # See also
400    ///
401    /// - [`get_entity`](Self::get_entity) for the fallible version.
402    #[inline]
403    #[track_caller]
404    pub fn entity(&mut self, entity: Entity) -> EntityCommands {
405        #[inline(never)]
406        #[cold]
407        #[track_caller]
408        fn panic_no_entity(entity: Entity) -> ! {
409            panic!(
410                "Attempting to create an EntityCommands for entity {entity:?}, which doesn't exist.",
411            );
412        }
413
414        match self.get_entity(entity) {
415            Some(entity) => entity,
416            None => panic_no_entity(entity),
417        }
418    }
419
420    /// Returns the [`EntityCommands`] for the requested [`Entity`], if it exists.
421    ///
422    /// Returns `None` if the entity does not exist.
423    ///
424    /// This method does not guarantee that `EntityCommands` will be successfully applied,
425    /// since another command in the queue may delete the entity before them.
426    ///
427    /// # Example
428    ///
429    /// ```
430    /// use bevy_ecs::prelude::*;
431    ///
432    /// #[derive(Component)]
433    /// struct Label(&'static str);
434
435    /// fn example_system(mut commands: Commands) {
436    ///     // Create a new, empty entity
437    ///     let entity = commands.spawn_empty().id();
438    ///
439    ///     // Get the entity if it still exists, which it will in this case
440    ///     if let Some(mut entity_commands) = commands.get_entity(entity) {
441    ///         // adds a single component to the entity
442    ///         entity_commands.insert(Label("hello world"));
443    ///     }
444    /// }
445    /// # bevy_ecs::system::assert_is_system(example_system);
446    /// ```
447    ///
448    /// # See also
449    ///
450    /// - [`entity`](Self::entity) for the panicking version.
451    #[inline]
452    #[track_caller]
453    pub fn get_entity(&mut self, entity: Entity) -> Option<EntityCommands> {
454        self.entities.contains(entity).then_some(EntityCommands {
455            entity,
456            commands: self.reborrow(),
457        })
458    }
459
460    /// Pushes a [`Command`] to the queue for creating entities with a particular [`Bundle`] type.
461    ///
462    /// `bundles_iter` is a type that can be converted into a [`Bundle`] iterator
463    /// (it can also be a collection).
464    ///
465    /// This method is equivalent to iterating `bundles_iter`
466    /// and calling [`spawn`](Self::spawn) on each bundle,
467    /// but it is faster due to memory pre-allocation.
468    ///
469    /// # Example
470    ///
471    /// ```
472    /// # use bevy_ecs::prelude::*;
473    /// #
474    /// # #[derive(Component)]
475    /// # struct Name(String);
476    /// # #[derive(Component)]
477    /// # struct Score(u32);
478    /// #
479    /// # fn system(mut commands: Commands) {
480    /// commands.spawn_batch(vec![
481    ///     (
482    ///         Name("Alice".to_string()),
483    ///         Score(0),
484    ///     ),
485    ///     (
486    ///         Name("Bob".to_string()),
487    ///         Score(0),
488    ///     ),
489    /// ]);
490    /// # }
491    /// # bevy_ecs::system::assert_is_system(system);
492    /// ```
493    ///
494    /// # See also
495    ///
496    /// - [`spawn`](Self::spawn) to spawn an entity with a bundle.
497    /// - [`spawn_empty`](Self::spawn_empty) to spawn an entity without any components.
498    pub fn spawn_batch<I>(&mut self, bundles_iter: I)
499    where
500        I: IntoIterator + Send + Sync + 'static,
501        I::Item: Bundle,
502    {
503        self.push(spawn_batch(bundles_iter));
504    }
505
506    /// Push a [`Command`] onto the queue.
507    pub fn push<C: Command>(&mut self, command: C) {
508        match &mut self.queue {
509            InternalQueue::CommandQueue(queue) => {
510                queue.push(command);
511            }
512            InternalQueue::RawCommandQueue(queue) => {
513                // SAFETY: `RawCommandQueue` is only every constructed in `Commands::new_raw_from_entities`
514                // where the caller of that has ensured that `queue` outlives `self`
515                unsafe {
516                    queue.push(command);
517                }
518            }
519        }
520    }
521
522    /// Pushes a [`Command`] to the queue for creating entities, if needed,
523    /// and for adding a bundle to each entity.
524    ///
525    /// `bundles_iter` is a type that can be converted into an ([`Entity`], [`Bundle`]) iterator
526    /// (it can also be a collection).
527    ///
528    /// When the command is applied,
529    /// for each (`Entity`, `Bundle`) pair in the given `bundles_iter`,
530    /// the `Entity` is spawned, if it does not exist already.
531    /// Then, the `Bundle` is added to the entity.
532    ///
533    /// This method is equivalent to iterating `bundles_iter`,
534    /// calling [`get_or_spawn`](Self::get_or_spawn) for each bundle,
535    /// and passing it to [`insert`](EntityCommands::insert),
536    /// but it is faster due to memory pre-allocation.
537    ///
538    /// # Note
539    ///
540    /// Spawning a specific `entity` value is rarely the right choice. Most apps should use [`Commands::spawn_batch`].
541    /// This method should generally only be used for sharing entities across apps, and only when they have a scheme
542    /// worked out to share an ID space (which doesn't happen by default).
543    pub fn insert_or_spawn_batch<I, B>(&mut self, bundles_iter: I)
544    where
545        I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
546        B: Bundle,
547    {
548        self.push(insert_or_spawn_batch(bundles_iter));
549    }
550
551    /// Pushes a [`Command`] to the queue for inserting a [`Resource`] in the [`World`] with an inferred value.
552    ///
553    /// The inferred value is determined by the [`FromWorld`] trait of the resource.
554    /// When the command is applied,
555    /// if the resource already exists, nothing happens.
556    ///
557    /// See [`World::init_resource`] for more details.
558    ///
559    /// # Example
560    ///
561    /// ```
562    /// # use bevy_ecs::prelude::*;
563    /// #
564    /// # #[derive(Resource, Default)]
565    /// # struct Scoreboard {
566    /// #     current_score: u32,
567    /// #     high_score: u32,
568    /// # }
569    /// #
570    /// # fn initialise_scoreboard(mut commands: Commands) {
571    /// commands.init_resource::<Scoreboard>();
572    /// # }
573    /// # bevy_ecs::system::assert_is_system(initialise_scoreboard);
574    /// ```
575    pub fn init_resource<R: Resource + FromWorld>(&mut self) {
576        self.push(init_resource::<R>);
577    }
578
579    /// Pushes a [`Command`] to the queue for inserting a [`Resource`] in the [`World`] with a specific value.
580    ///
581    /// This will overwrite any previous value of the same resource type.
582    ///
583    /// See [`World::insert_resource`] for more details.
584    ///
585    /// # Example
586    ///
587    /// ```
588    /// # use bevy_ecs::prelude::*;
589    /// #
590    /// # #[derive(Resource)]
591    /// # struct Scoreboard {
592    /// #     current_score: u32,
593    /// #     high_score: u32,
594    /// # }
595    /// #
596    /// # fn system(mut commands: Commands) {
597    /// commands.insert_resource(Scoreboard {
598    ///     current_score: 0,
599    ///     high_score: 0,
600    /// });
601    /// # }
602    /// # bevy_ecs::system::assert_is_system(system);
603    /// ```
604    pub fn insert_resource<R: Resource>(&mut self, resource: R) {
605        self.push(insert_resource(resource));
606    }
607
608    /// Pushes a [`Command`] to the queue for removing a [`Resource`] from the [`World`].
609    ///
610    /// See [`World::remove_resource`] for more details.
611    ///
612    /// # Example
613    ///
614    /// ```
615    /// # use bevy_ecs::prelude::*;
616    /// #
617    /// # #[derive(Resource)]
618    /// # struct Scoreboard {
619    /// #     current_score: u32,
620    /// #     high_score: u32,
621    /// # }
622    /// #
623    /// # fn system(mut commands: Commands) {
624    /// commands.remove_resource::<Scoreboard>();
625    /// # }
626    /// # bevy_ecs::system::assert_is_system(system);
627    /// ```
628    pub fn remove_resource<R: Resource>(&mut self) {
629        self.push(remove_resource::<R>);
630    }
631
632    /// Runs the system corresponding to the given [`SystemId`].
633    /// Systems are ran in an exclusive and single threaded way.
634    /// Running slow systems can become a bottleneck.
635    ///
636    /// Calls [`World::run_system`](World::run_system).
637    ///
638    /// There is no way to get the output of a system when run as a command, because the
639    /// execution of the system happens later. To get the output of a system, use
640    /// [`World::run_system`] or [`World::run_system_with_input`] instead of running the system as a command.
641    pub fn run_system(&mut self, id: SystemId) {
642        self.run_system_with_input(id, ());
643    }
644
645    /// Runs the system corresponding to the given [`SystemId`].
646    /// Systems are ran in an exclusive and single threaded way.
647    /// Running slow systems can become a bottleneck.
648    ///
649    /// Calls [`World::run_system_with_input`](World::run_system_with_input).
650    ///
651    /// There is no way to get the output of a system when run as a command, because the
652    /// execution of the system happens later. To get the output of a system, use
653    /// [`World::run_system`] or [`World::run_system_with_input`] instead of running the system as a command.
654    pub fn run_system_with_input<I: 'static + Send>(&mut self, id: SystemId<I>, input: I) {
655        self.push(RunSystemWithInput::new_with_input(id, input));
656    }
657
658    /// Registers a system and returns a [`SystemId`] so it can later be called by [`World::run_system`].
659    ///
660    /// It's possible to register the same systems more than once, they'll be stored separately.
661    ///
662    /// This is different from adding systems to a [`Schedule`](crate::schedule::Schedule),
663    /// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system.
664    /// This allows for running systems in a push-based fashion.
665    /// Using a [`Schedule`](crate::schedule::Schedule) is still preferred for most cases
666    /// due to its better performance and ability to run non-conflicting systems simultaneously.
667    ///
668    /// If you want to prevent Commands from registering the same system multiple times, consider using [`Local`](crate::system::Local)
669    ///
670    /// # Example
671    ///
672    /// ```
673    /// # use bevy_ecs::{prelude::*, world::CommandQueue, system::SystemId};
674    ///
675    /// #[derive(Resource)]
676    /// struct Counter(i32);
677    ///
678    /// fn register_system(mut local_system: Local<Option<SystemId>>, mut commands: Commands) {
679    ///     if let Some(system) = *local_system {
680    ///         commands.run_system(system);
681    ///     } else {
682    ///         *local_system = Some(commands.register_one_shot_system(increment_counter));
683    ///     }
684    /// }
685    ///
686    /// fn increment_counter(mut value: ResMut<Counter>) {
687    ///     value.0 += 1;
688    /// }
689    ///
690    /// # let mut world = World::default();
691    /// # world.insert_resource(Counter(0));
692    /// # let mut queue_1 = CommandQueue::default();
693    /// # let systemid = {
694    /// #   let mut commands = Commands::new(&mut queue_1, &world);
695    /// #   commands.register_one_shot_system(increment_counter)
696    /// # };
697    /// # let mut queue_2 = CommandQueue::default();
698    /// # {
699    /// #   let mut commands = Commands::new(&mut queue_2, &world);
700    /// #   commands.run_system(systemid);
701    /// # }
702    /// # queue_1.append(&mut queue_2);
703    /// # queue_1.apply(&mut world);
704    /// # assert_eq!(1, world.resource::<Counter>().0);
705    /// # bevy_ecs::system::assert_is_system(register_system);
706    /// ```
707    pub fn register_one_shot_system<
708        I: 'static + Send,
709        O: 'static + Send,
710        M,
711        S: IntoSystem<I, O, M> + 'static,
712    >(
713        &mut self,
714        system: S,
715    ) -> SystemId<I, O> {
716        let entity = self.spawn_empty().id();
717        self.push(RegisterSystem::new(system, entity));
718        SystemId::from_entity(entity)
719    }
720
721    /// Pushes a generic [`Command`] to the command queue.
722    ///
723    /// `command` can be a built-in command, custom struct that implements [`Command`] or a closure
724    /// that takes [`&mut World`](World) as an argument.
725    /// # Example
726    ///
727    /// ```
728    /// # use bevy_ecs::{world::Command, prelude::*};
729    /// #[derive(Resource, Default)]
730    /// struct Counter(u64);
731    ///
732    /// struct AddToCounter(u64);
733    ///
734    /// impl Command for AddToCounter {
735    ///     fn apply(self, world: &mut World) {
736    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
737    ///         counter.0 += self.0;
738    ///     }
739    /// }
740    ///
741    /// fn add_three_to_counter_system(mut commands: Commands) {
742    ///     commands.add(AddToCounter(3));
743    /// }
744    /// fn add_twenty_five_to_counter_system(mut commands: Commands) {
745    ///     commands.add(|world: &mut World| {
746    ///         let mut counter = world.get_resource_or_insert_with(Counter::default);
747    ///         counter.0 += 25;
748    ///     });
749    /// }
750
751    /// # bevy_ecs::system::assert_is_system(add_three_to_counter_system);
752    /// # bevy_ecs::system::assert_is_system(add_twenty_five_to_counter_system);
753    /// ```
754    pub fn add<C: Command>(&mut self, command: C) {
755        self.push(command);
756    }
757
758    /// Sends a "global" [`Trigger`] without any targets. This will run any [`Observer`] of the `event` that
759    /// isn't scoped to specific targets.
760    pub fn trigger(&mut self, event: impl Event) {
761        self.add(TriggerEvent { event, targets: () });
762    }
763
764    /// Sends a [`Trigger`] for the given targets. This will run any [`Observer`] of the `event` that
765    /// watches those targets.
766    pub fn trigger_targets(&mut self, event: impl Event, targets: impl TriggerTargets) {
767        self.add(TriggerEvent { event, targets });
768    }
769
770    /// Spawn an [`Observer`] and returns the [`EntityCommands`] associated with the entity that stores the observer.  
771    pub fn observe<E: Event, B: Bundle, M>(
772        &mut self,
773        observer: impl IntoObserverSystem<E, B, M>,
774    ) -> EntityCommands {
775        self.spawn(Observer::new(observer))
776    }
777}
778
779/// A [`Command`] which gets executed for a given [`Entity`].
780///
781/// # Examples
782///
783/// ```
784/// # use std::collections::HashSet;
785/// # use bevy_ecs::prelude::*;
786/// use bevy_ecs::system::EntityCommand;
787/// #
788/// # #[derive(Component, PartialEq)]
789/// # struct Name(String);
790/// # impl Name {
791/// #   fn new(s: String) -> Self { Name(s) }
792/// #   fn as_str(&self) -> &str { &self.0 }
793/// # }
794///
795/// #[derive(Resource, Default)]
796/// struct Counter(i64);
797///
798/// /// A `Command` which names an entity based on a global counter.
799/// fn count_name(entity: Entity, world: &mut World) {
800///     // Get the current value of the counter, and increment it for next time.
801///     let mut counter = world.resource_mut::<Counter>();
802///     let i = counter.0;
803///     counter.0 += 1;
804///
805///     // Name the entity after the value of the counter.
806///     world.entity_mut(entity).insert(Name::new(format!("Entity #{i}")));
807/// }
808///
809/// // App creation boilerplate omitted...
810/// # let mut world = World::new();
811/// # world.init_resource::<Counter>();
812/// #
813/// # let mut setup_schedule = Schedule::default();
814/// # setup_schedule.add_systems(setup);
815/// # let mut assert_schedule = Schedule::default();
816/// # assert_schedule.add_systems(assert_names);
817/// #
818/// # setup_schedule.run(&mut world);
819/// # assert_schedule.run(&mut world);
820///
821/// fn setup(mut commands: Commands) {
822///     commands.spawn_empty().add(count_name);
823///     commands.spawn_empty().add(count_name);
824/// }
825///
826/// fn assert_names(named: Query<&Name>) {
827///     // We use a HashSet because we do not care about the order.
828///     let names: HashSet<_> = named.iter().map(Name::as_str).collect();
829///     assert_eq!(names, HashSet::from_iter(["Entity #0", "Entity #1"]));
830/// }
831/// ```
832pub trait EntityCommand<Marker = ()>: Send + 'static {
833    /// Executes this command for the given [`Entity`].
834    fn apply(self, id: Entity, world: &mut World);
835    /// Returns a [`Command`] which executes this [`EntityCommand`] for the given [`Entity`].
836    #[must_use = "commands do nothing unless applied to a `World`"]
837    fn with_entity(self, id: Entity) -> WithEntity<Marker, Self>
838    where
839        Self: Sized,
840    {
841        WithEntity {
842            cmd: self,
843            id,
844            marker: PhantomData,
845        }
846    }
847}
848
849/// Turns an [`EntityCommand`] type into a [`Command`] type.
850pub struct WithEntity<Marker, C: EntityCommand<Marker>> {
851    cmd: C,
852    id: Entity,
853    marker: PhantomData<fn() -> Marker>,
854}
855
856impl<M, C: EntityCommand<M>> Command for WithEntity<M, C>
857where
858    M: 'static,
859{
860    #[inline]
861    fn apply(self, world: &mut World) {
862        self.cmd.apply(self.id, world);
863    }
864}
865
866/// A list of commands that will be run to modify an [entity](crate::entity).
867pub struct EntityCommands<'a> {
868    pub(crate) entity: Entity,
869    pub(crate) commands: Commands<'a, 'a>,
870}
871
872impl EntityCommands<'_> {
873    /// Returns the [`Entity`] id of the entity.
874    ///
875    /// # Example
876    ///
877    /// ```
878    /// # use bevy_ecs::prelude::*;
879    /// #
880    /// fn my_system(mut commands: Commands) {
881    ///     let entity_id = commands.spawn_empty().id();
882    /// }
883    /// # bevy_ecs::system::assert_is_system(my_system);
884    /// ```
885    #[inline]
886    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
887    pub fn id(&self) -> Entity {
888        self.entity
889    }
890
891    /// Returns an [`EntityCommands`] with a smaller lifetime.
892    /// This is useful if you have `&mut EntityCommands` but you need `EntityCommands`.
893    pub fn reborrow(&mut self) -> EntityCommands {
894        EntityCommands {
895            entity: self.entity,
896            commands: self.commands.reborrow(),
897        }
898    }
899
900    /// Adds a [`Bundle`] of components to the entity.
901    ///
902    /// This will overwrite any previous value(s) of the same component type.
903    ///
904    /// # Panics
905    ///
906    /// The command will panic when applied if the associated entity does not exist.
907    ///
908    /// To avoid a panic in this case, use the command [`Self::try_insert`] instead.
909    ///
910    /// # Example
911    ///
912    /// ```
913    /// # use bevy_ecs::prelude::*;
914    /// # #[derive(Resource)]
915    /// # struct PlayerEntity { entity: Entity }
916    /// #[derive(Component)]
917    /// struct Health(u32);
918    /// #[derive(Component)]
919    /// struct Strength(u32);
920    /// #[derive(Component)]
921    /// struct Defense(u32);
922    ///
923    /// #[derive(Bundle)]
924    /// struct CombatBundle {
925    ///     health: Health,
926    ///     strength: Strength,
927    /// }
928    ///
929    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
930    ///     commands
931    ///         .entity(player.entity)
932    ///         // You can insert individual components:
933    ///         .insert(Defense(10))
934    ///         // You can also insert pre-defined bundles of components:
935    ///         .insert(CombatBundle {
936    ///             health: Health(100),
937    ///             strength: Strength(40),
938    ///         })
939    ///         // You can also insert tuples of components and bundles.
940    ///         // This is equivalent to the calls above:
941    ///         .insert((
942    ///             Defense(10),
943    ///             CombatBundle {
944    ///                 health: Health(100),
945    ///                 strength: Strength(40),
946    ///             },
947    ///         ));
948    /// }
949    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
950    /// ```
951    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
952        self.add(insert(bundle))
953    }
954
955    /// Tries to add a [`Bundle`] of components to the entity.
956    ///
957    /// This will overwrite any previous value(s) of the same component type.
958    ///
959    /// # Note
960    ///
961    /// Unlike [`Self::insert`], this will not panic if the associated entity does not exist.
962    ///
963    /// # Example
964    ///
965    /// ```
966    /// # use bevy_ecs::prelude::*;
967    /// # #[derive(Resource)]
968    /// # struct PlayerEntity { entity: Entity }
969    /// #[derive(Component)]
970    /// struct Health(u32);
971    /// #[derive(Component)]
972    /// struct Strength(u32);
973    /// #[derive(Component)]
974    /// struct Defense(u32);
975    ///
976    /// #[derive(Bundle)]
977    /// struct CombatBundle {
978    ///     health: Health,
979    ///     strength: Strength,
980    /// }
981    ///
982    /// fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
983    ///   commands.entity(player.entity)
984    ///    // You can try_insert individual components:
985    ///     .try_insert(Defense(10))
986    ///
987    ///    // You can also insert tuples of components:
988    ///     .try_insert(CombatBundle {
989    ///         health: Health(100),
990    ///         strength: Strength(40),
991    ///     });
992    ///
993    ///    // Suppose this occurs in a parallel adjacent system or process
994    ///    commands.entity(player.entity)
995    ///      .despawn();
996    ///
997    ///    commands.entity(player.entity)
998    ///    // This will not panic nor will it add the component
999    ///      .try_insert(Defense(5));
1000    /// }
1001    /// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
1002    /// ```
1003    pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut Self {
1004        self.add(try_insert(bundle))
1005    }
1006
1007    /// Removes a [`Bundle`] of components from the entity.
1008    ///
1009    /// # Example
1010    ///
1011    /// ```
1012    /// # use bevy_ecs::prelude::*;
1013    /// #
1014    /// # #[derive(Resource)]
1015    /// # struct PlayerEntity { entity: Entity }
1016    /// #[derive(Component)]
1017    /// struct Health(u32);
1018    /// #[derive(Component)]
1019    /// struct Strength(u32);
1020    /// #[derive(Component)]
1021    /// struct Defense(u32);
1022    ///
1023    /// #[derive(Bundle)]
1024    /// struct CombatBundle {
1025    ///     health: Health,
1026    ///     strength: Strength,
1027    /// }
1028    ///
1029    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1030    ///     commands
1031    ///         .entity(player.entity)
1032    ///         // You can remove individual components:
1033    ///         .remove::<Defense>()
1034    ///         // You can also remove pre-defined Bundles of components:
1035    ///         .remove::<CombatBundle>()
1036    ///         // You can also remove tuples of components and bundles.
1037    ///         // This is equivalent to the calls above:
1038    ///         .remove::<(Defense, CombatBundle)>();
1039    /// }
1040    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1041    /// ```
1042    pub fn remove<T>(&mut self) -> &mut Self
1043    where
1044        T: Bundle,
1045    {
1046        self.add(remove::<T>)
1047    }
1048
1049    /// Removes a component from the entity.
1050    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1051        self.add(remove_by_id(component_id))
1052    }
1053
1054    /// Removes all components associated with the entity.
1055    pub fn clear(&mut self) -> &mut Self {
1056        self.add(clear())
1057    }
1058
1059    /// Despawns the entity.
1060    /// This will emit a warning if the entity does not exist.
1061    ///
1062    /// See [`World::despawn`] for more details.
1063    ///
1064    /// # Note
1065    ///
1066    /// This won't clean up external references to the entity (such as parent-child relationships
1067    /// if you're using `bevy_hierarchy`), which may leave the world in an invalid state.
1068    ///
1069    /// # Example
1070    ///
1071    /// ```
1072    /// # use bevy_ecs::prelude::*;
1073    /// #
1074    /// # #[derive(Resource)]
1075    /// # struct CharacterToRemove { entity: Entity }
1076    /// #
1077    /// fn remove_character_system(
1078    ///     mut commands: Commands,
1079    ///     character_to_remove: Res<CharacterToRemove>
1080    /// )
1081    /// {
1082    ///     commands.entity(character_to_remove.entity).despawn();
1083    /// }
1084    /// # bevy_ecs::system::assert_is_system(remove_character_system);
1085    /// ```
1086    pub fn despawn(&mut self) {
1087        self.add(despawn);
1088    }
1089
1090    /// Pushes an [`EntityCommand`] to the queue, which will get executed for the current [`Entity`].
1091    ///
1092    /// # Examples
1093    ///
1094    /// ```
1095    /// # use bevy_ecs::prelude::*;
1096    /// # fn my_system(mut commands: Commands) {
1097    /// commands
1098    ///     .spawn_empty()
1099    ///     // Closures with this signature implement `EntityCommand`.
1100    ///     .add(|entity: EntityWorldMut| {
1101    ///         println!("Executed an EntityCommand for {:?}", entity.id());
1102    ///     });
1103    /// # }
1104    /// # bevy_ecs::system::assert_is_system(my_system);
1105    /// ```
1106    pub fn add<M: 'static>(&mut self, command: impl EntityCommand<M>) -> &mut Self {
1107        self.commands.add(command.with_entity(self.entity));
1108        self
1109    }
1110
1111    /// Removes all components except the given [`Bundle`] from the entity.
1112    ///
1113    /// This can also be used to remove all the components from the entity by passing it an empty Bundle.
1114    ///
1115    /// # Example
1116    ///
1117    /// ```
1118    /// # use bevy_ecs::prelude::*;
1119    /// #
1120    /// # #[derive(Resource)]
1121    /// # struct PlayerEntity { entity: Entity }
1122    /// #[derive(Component)]
1123    /// struct Health(u32);
1124    /// #[derive(Component)]
1125    /// struct Strength(u32);
1126    /// #[derive(Component)]
1127    /// struct Defense(u32);
1128    ///
1129    /// #[derive(Bundle)]
1130    /// struct CombatBundle {
1131    ///     health: Health,
1132    ///     strength: Strength,
1133    /// }
1134    ///
1135    /// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1136    ///     commands
1137    ///         .entity(player.entity)
1138    ///         // You can retain a pre-defined Bundle of components,
1139    ///         // with this removing only the Defense component
1140    ///         .retain::<CombatBundle>()
1141    ///         // You can also retain only a single component
1142    ///         .retain::<Health>()
1143    ///         // And you can remove all the components by passing in an empty Bundle
1144    ///         .retain::<()>();
1145    /// }
1146    /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1147    /// ```
1148    pub fn retain<T>(&mut self) -> &mut Self
1149    where
1150        T: Bundle,
1151    {
1152        self.add(retain::<T>)
1153    }
1154
1155    /// Logs the components of the entity at the info level.
1156    ///
1157    /// # Panics
1158    ///
1159    /// The command will panic when applied if the associated entity does not exist.
1160    pub fn log_components(&mut self) {
1161        self.add(log_components);
1162    }
1163
1164    /// Returns the underlying [`Commands`].
1165    pub fn commands(&mut self) -> Commands {
1166        self.commands.reborrow()
1167    }
1168
1169    /// Creates an [`Observer`](crate::observer::Observer) listening for a trigger of type `T` that targets this entity.
1170    pub fn observe<E: Event, B: Bundle, M>(
1171        &mut self,
1172        system: impl IntoObserverSystem<E, B, M>,
1173    ) -> &mut Self {
1174        self.add(observe(system));
1175        self
1176    }
1177}
1178
1179impl<F> Command for F
1180where
1181    F: FnOnce(&mut World) + Send + 'static,
1182{
1183    fn apply(self, world: &mut World) {
1184        self(world);
1185    }
1186}
1187
1188impl<F> EntityCommand<World> for F
1189where
1190    F: FnOnce(EntityWorldMut) + Send + 'static,
1191{
1192    fn apply(self, id: Entity, world: &mut World) {
1193        self(world.entity_mut(id));
1194    }
1195}
1196
1197impl<F> EntityCommand for F
1198where
1199    F: FnOnce(Entity, &mut World) + Send + 'static,
1200{
1201    fn apply(self, id: Entity, world: &mut World) {
1202        self(id, world);
1203    }
1204}
1205
1206/// A [`Command`] that consumes an iterator of [`Bundle`]s to spawn a series of entities.
1207///
1208/// This is more efficient than spawning the entities individually.
1209fn spawn_batch<I, B>(bundles_iter: I) -> impl Command
1210where
1211    I: IntoIterator<Item = B> + Send + Sync + 'static,
1212    B: Bundle,
1213{
1214    move |world: &mut World| {
1215        world.spawn_batch(bundles_iter);
1216    }
1217}
1218
1219/// A [`Command`] that consumes an iterator to add a series of [`Bundle`]s to a set of entities.
1220/// If any entities do not already exist in the world, they will be spawned.
1221///
1222/// This is more efficient than inserting the bundles individually.
1223fn insert_or_spawn_batch<I, B>(bundles_iter: I) -> impl Command
1224where
1225    I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
1226    B: Bundle,
1227{
1228    move |world: &mut World| {
1229        if let Err(invalid_entities) = world.insert_or_spawn_batch(bundles_iter) {
1230            error!(
1231                "Failed to 'insert or spawn' bundle of type {} into the following invalid entities: {:?}",
1232                std::any::type_name::<B>(),
1233                invalid_entities
1234            );
1235        }
1236    }
1237}
1238
1239/// A [`Command`] that despawns a specific entity.
1240/// This will emit a warning if the entity does not exist.
1241///
1242/// # Note
1243///
1244/// This won't clean up external references to the entity (such as parent-child relationships
1245/// if you're using `bevy_hierarchy`), which may leave the world in an invalid state.
1246fn despawn(entity: Entity, world: &mut World) {
1247    world.despawn(entity);
1248}
1249
1250/// An [`EntityCommand`] that adds the components in a [`Bundle`] to an entity.
1251fn insert<T: Bundle>(bundle: T) -> impl EntityCommand {
1252    move |entity: Entity, world: &mut World| {
1253        if let Some(mut entity) = world.get_entity_mut(entity) {
1254            entity.insert(bundle);
1255        } else {
1256            panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/#b0003", std::any::type_name::<T>(), entity);
1257        }
1258    }
1259}
1260
1261/// An [`EntityCommand`] that attempts to add the components in a [`Bundle`] to an entity.
1262fn try_insert(bundle: impl Bundle) -> impl EntityCommand {
1263    move |entity, world: &mut World| {
1264        if let Some(mut entity) = world.get_entity_mut(entity) {
1265            entity.insert(bundle);
1266        }
1267    }
1268}
1269
1270/// An [`EntityCommand`] that removes components from an entity.
1271/// For a [`Bundle`] type `T`, this will remove any components in the bundle.
1272/// Any components in the bundle that aren't found on the entity will be ignored.
1273fn remove<T: Bundle>(entity: Entity, world: &mut World) {
1274    if let Some(mut entity) = world.get_entity_mut(entity) {
1275        entity.remove::<T>();
1276    }
1277}
1278
1279/// An [`EntityCommand`] that removes components with a provided [`ComponentId`] from an entity.
1280/// # Panics
1281///
1282/// Panics if the provided [`ComponentId`] does not exist in the [`World`].
1283fn remove_by_id(component_id: ComponentId) -> impl EntityCommand {
1284    move |entity: Entity, world: &mut World| {
1285        if let Some(mut entity) = world.get_entity_mut(entity) {
1286            entity.remove_by_id(component_id);
1287        }
1288    }
1289}
1290
1291/// An [`EntityCommand`] that removes all components associated with a provided entity.
1292fn clear() -> impl EntityCommand {
1293    move |entity: Entity, world: &mut World| {
1294        if let Some(mut entity) = world.get_entity_mut(entity) {
1295            entity.clear();
1296        }
1297    }
1298}
1299
1300/// An [`EntityCommand`] that removes components from an entity.
1301/// For a [`Bundle`] type `T`, this will remove all components except those in the bundle.
1302/// Any components in the bundle that aren't found on the entity will be ignored.
1303fn retain<T: Bundle>(entity: Entity, world: &mut World) {
1304    if let Some(mut entity_mut) = world.get_entity_mut(entity) {
1305        entity_mut.retain::<T>();
1306    }
1307}
1308
1309/// A [`Command`] that inserts a [`Resource`] into the world using a value
1310/// created with the [`FromWorld`] trait.
1311fn init_resource<R: Resource + FromWorld>(world: &mut World) {
1312    world.init_resource::<R>();
1313}
1314
1315/// A [`Command`] that removes the [resource](Resource) `R` from the world.
1316fn remove_resource<R: Resource>(world: &mut World) {
1317    world.remove_resource::<R>();
1318}
1319
1320/// A [`Command`] that inserts a [`Resource`] into the world.
1321fn insert_resource<R: Resource>(resource: R) -> impl Command {
1322    move |world: &mut World| {
1323        world.insert_resource(resource);
1324    }
1325}
1326
1327/// [`EntityCommand`] to log the components of a given entity. See [`EntityCommands::log_components`].
1328fn log_components(entity: Entity, world: &mut World) {
1329    let debug_infos: Vec<_> = world
1330        .inspect_entity(entity)
1331        .into_iter()
1332        .map(|component_info| component_info.name())
1333        .collect();
1334    info!("Entity {entity}: {debug_infos:?}");
1335}
1336
1337fn observe<E: Event, B: Bundle, M>(
1338    observer: impl IntoObserverSystem<E, B, M>,
1339) -> impl EntityCommand {
1340    move |entity, world: &mut World| {
1341        if let Some(mut entity) = world.get_entity_mut(entity) {
1342            entity.observe(observer);
1343        }
1344    }
1345}
1346
1347#[cfg(test)]
1348#[allow(clippy::float_cmp, clippy::approx_constant)]
1349mod tests {
1350    use crate::{
1351        self as bevy_ecs,
1352        component::Component,
1353        system::{Commands, Resource},
1354        world::{CommandQueue, World},
1355    };
1356    use std::{
1357        any::TypeId,
1358        sync::{
1359            atomic::{AtomicUsize, Ordering},
1360            Arc,
1361        },
1362    };
1363
1364    #[allow(dead_code)]
1365    #[derive(Component)]
1366    #[component(storage = "SparseSet")]
1367    struct SparseDropCk(DropCk);
1368
1369    #[derive(Component)]
1370    struct DropCk(Arc<AtomicUsize>);
1371    impl DropCk {
1372        fn new_pair() -> (Self, Arc<AtomicUsize>) {
1373            let atomic = Arc::new(AtomicUsize::new(0));
1374            (DropCk(atomic.clone()), atomic)
1375        }
1376    }
1377
1378    impl Drop for DropCk {
1379        fn drop(&mut self) {
1380            self.0.as_ref().fetch_add(1, Ordering::Relaxed);
1381        }
1382    }
1383
1384    #[derive(Component, Resource)]
1385    struct W<T>(T);
1386
1387    fn simple_command(world: &mut World) {
1388        world.spawn((W(0u32), W(42u64)));
1389    }
1390
1391    #[test]
1392    fn commands() {
1393        let mut world = World::default();
1394        let mut command_queue = CommandQueue::default();
1395        let entity = Commands::new(&mut command_queue, &world)
1396            .spawn((W(1u32), W(2u64)))
1397            .id();
1398        command_queue.apply(&mut world);
1399        assert_eq!(world.entities().len(), 1);
1400        let results = world
1401            .query::<(&W<u32>, &W<u64>)>()
1402            .iter(&world)
1403            .map(|(a, b)| (a.0, b.0))
1404            .collect::<Vec<_>>();
1405        assert_eq!(results, vec![(1u32, 2u64)]);
1406        // test entity despawn
1407        {
1408            let mut commands = Commands::new(&mut command_queue, &world);
1409            commands.entity(entity).despawn();
1410            commands.entity(entity).despawn(); // double despawn shouldn't panic
1411        }
1412        command_queue.apply(&mut world);
1413        let results2 = world
1414            .query::<(&W<u32>, &W<u64>)>()
1415            .iter(&world)
1416            .map(|(a, b)| (a.0, b.0))
1417            .collect::<Vec<_>>();
1418        assert_eq!(results2, vec![]);
1419
1420        // test adding simple (FnOnce) commands
1421        {
1422            let mut commands = Commands::new(&mut command_queue, &world);
1423
1424            // set up a simple command using a closure that adds one additional entity
1425            commands.add(|world: &mut World| {
1426                world.spawn((W(42u32), W(0u64)));
1427            });
1428
1429            // set up a simple command using a function that adds one additional entity
1430            commands.add(simple_command);
1431        }
1432        command_queue.apply(&mut world);
1433        let results3 = world
1434            .query::<(&W<u32>, &W<u64>)>()
1435            .iter(&world)
1436            .map(|(a, b)| (a.0, b.0))
1437            .collect::<Vec<_>>();
1438
1439        assert_eq!(results3, vec![(42u32, 0u64), (0u32, 42u64)]);
1440    }
1441
1442    #[test]
1443    fn remove_components() {
1444        let mut world = World::default();
1445
1446        let mut command_queue = CommandQueue::default();
1447        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
1448        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
1449        let sparse_dropck = SparseDropCk(sparse_dropck);
1450
1451        let entity = Commands::new(&mut command_queue, &world)
1452            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
1453            .id();
1454        command_queue.apply(&mut world);
1455        let results_before = world
1456            .query::<(&W<u32>, &W<u64>)>()
1457            .iter(&world)
1458            .map(|(a, b)| (a.0, b.0))
1459            .collect::<Vec<_>>();
1460        assert_eq!(results_before, vec![(1u32, 2u64)]);
1461
1462        // test component removal
1463        Commands::new(&mut command_queue, &world)
1464            .entity(entity)
1465            .remove::<W<u32>>()
1466            .remove::<(W<u32>, W<u64>, SparseDropCk, DropCk)>();
1467
1468        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
1469        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
1470        command_queue.apply(&mut world);
1471        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
1472        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
1473
1474        let results_after = world
1475            .query::<(&W<u32>, &W<u64>)>()
1476            .iter(&world)
1477            .map(|(a, b)| (a.0, b.0))
1478            .collect::<Vec<_>>();
1479        assert_eq!(results_after, vec![]);
1480        let results_after_u64 = world
1481            .query::<&W<u64>>()
1482            .iter(&world)
1483            .map(|v| v.0)
1484            .collect::<Vec<_>>();
1485        assert_eq!(results_after_u64, vec![]);
1486    }
1487
1488    #[test]
1489    fn remove_components_by_id() {
1490        let mut world = World::default();
1491
1492        let mut command_queue = CommandQueue::default();
1493        let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
1494        let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
1495        let sparse_dropck = SparseDropCk(sparse_dropck);
1496
1497        let entity = Commands::new(&mut command_queue, &world)
1498            .spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
1499            .id();
1500        command_queue.apply(&mut world);
1501        let results_before = world
1502            .query::<(&W<u32>, &W<u64>)>()
1503            .iter(&world)
1504            .map(|(a, b)| (a.0, b.0))
1505            .collect::<Vec<_>>();
1506        assert_eq!(results_before, vec![(1u32, 2u64)]);
1507
1508        // test component removal
1509        Commands::new(&mut command_queue, &world)
1510            .entity(entity)
1511            .remove_by_id(world.components().get_id(TypeId::of::<W<u32>>()).unwrap())
1512            .remove_by_id(world.components().get_id(TypeId::of::<W<u64>>()).unwrap())
1513            .remove_by_id(world.components().get_id(TypeId::of::<DropCk>()).unwrap())
1514            .remove_by_id(
1515                world
1516                    .components()
1517                    .get_id(TypeId::of::<SparseDropCk>())
1518                    .unwrap(),
1519            );
1520
1521        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
1522        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
1523        command_queue.apply(&mut world);
1524        assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
1525        assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
1526
1527        let results_after = world
1528            .query::<(&W<u32>, &W<u64>)>()
1529            .iter(&world)
1530            .map(|(a, b)| (a.0, b.0))
1531            .collect::<Vec<_>>();
1532        assert_eq!(results_after, vec![]);
1533        let results_after_u64 = world
1534            .query::<&W<u64>>()
1535            .iter(&world)
1536            .map(|v| v.0)
1537            .collect::<Vec<_>>();
1538        assert_eq!(results_after_u64, vec![]);
1539    }
1540
1541    #[test]
1542    fn remove_resources() {
1543        let mut world = World::default();
1544        let mut queue = CommandQueue::default();
1545        {
1546            let mut commands = Commands::new(&mut queue, &world);
1547            commands.insert_resource(W(123i32));
1548            commands.insert_resource(W(456.0f64));
1549        }
1550
1551        queue.apply(&mut world);
1552        assert!(world.contains_resource::<W<i32>>());
1553        assert!(world.contains_resource::<W<f64>>());
1554
1555        {
1556            let mut commands = Commands::new(&mut queue, &world);
1557            // test resource removal
1558            commands.remove_resource::<W<i32>>();
1559        }
1560        queue.apply(&mut world);
1561        assert!(!world.contains_resource::<W<i32>>());
1562        assert!(world.contains_resource::<W<f64>>());
1563    }
1564
1565    fn is_send<T: Send>() {}
1566    fn is_sync<T: Sync>() {}
1567
1568    #[test]
1569    fn test_commands_are_send_and_sync() {
1570        is_send::<Commands>();
1571        is_sync::<Commands>();
1572    }
1573
1574    #[test]
1575    fn append() {
1576        let mut world = World::default();
1577        let mut queue_1 = CommandQueue::default();
1578        {
1579            let mut commands = Commands::new(&mut queue_1, &world);
1580            commands.insert_resource(W(123i32));
1581        }
1582        let mut queue_2 = CommandQueue::default();
1583        {
1584            let mut commands = Commands::new(&mut queue_2, &world);
1585            commands.insert_resource(W(456.0f64));
1586        }
1587        queue_1.append(&mut queue_2);
1588        queue_1.apply(&mut world);
1589        assert!(world.contains_resource::<W<i32>>());
1590        assert!(world.contains_resource::<W<f64>>());
1591    }
1592}