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