Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/src/world/mod.rs
9501 views
1
#![expect(
2
unsafe_op_in_unsafe_fn,
3
reason = "See #11590. To be removed once all applicable unsafe code has an unsafe block with a safety comment."
4
)]
5
6
//! Defines the [`World`] and APIs for accessing it directly.
7
8
pub(crate) mod command_queue;
9
mod deferred_world;
10
mod entity_access;
11
mod entity_fetch;
12
mod filtered_resource;
13
mod identifier;
14
mod spawn_batch;
15
16
pub mod error;
17
#[cfg(feature = "bevy_reflect")]
18
pub mod reflect;
19
pub mod unsafe_world_cell;
20
21
pub use crate::{
22
change_detection::{Mut, Ref, CHECK_TICK_THRESHOLD},
23
world::command_queue::CommandQueue,
24
};
25
pub use bevy_ecs_macros::FromWorld;
26
pub use deferred_world::DeferredWorld;
27
pub use entity_access::{
28
ComponentEntry, DynamicComponentFetch, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept,
29
EntityWorldMut, FilteredEntityMut, FilteredEntityRef, OccupiedComponentEntry,
30
TryFromFilteredError, UnsafeFilteredEntityMut, VacantComponentEntry,
31
};
32
pub use entity_fetch::{EntityFetcher, WorldEntityFetch};
33
pub use filtered_resource::*;
34
pub use identifier::WorldId;
35
pub use spawn_batch::*;
36
37
use crate::{
38
archetype::{ArchetypeId, Archetypes},
39
bundle::{
40
Bundle, BundleId, BundleInfo, BundleInserter, BundleSpawner, Bundles, DynamicBundle,
41
InsertMode, NoBundleEffect,
42
},
43
change_detection::{
44
CheckChangeTicks, ComponentTicks, ComponentTicksMut, MaybeLocation, MutUntyped, Tick,
45
},
46
component::{
47
Component, ComponentDescriptor, ComponentId, ComponentIds, ComponentInfo, Components,
48
ComponentsQueuedRegistrator, ComponentsRegistrator, Mutable, RequiredComponents,
49
RequiredComponentsError,
50
},
51
entity::{Entities, Entity, EntityAllocator, EntityNotSpawnedError, SpawnError},
52
entity_disabling::DefaultQueryFilters,
53
error::{DefaultErrorHandler, ErrorHandler},
54
lifecycle::{ComponentHooks, RemovedComponentMessages, ADD, DESPAWN, DISCARD, INSERT, REMOVE},
55
message::{Message, MessageId, Messages, WriteBatchIds},
56
observer::Observers,
57
prelude::{Add, Despawn, DetectChangesMut, Discard, Insert, Remove},
58
query::{DebugCheckedUnwrap, QueryData, QueryFilter, QueryState},
59
relationship::RelationshipHookMode,
60
resource::{IsResource, Resource, ResourceEntities, IS_RESOURCE},
61
schedule::{Schedule, ScheduleLabel, Schedules},
62
storage::{NonSendData, Storages},
63
system::Commands,
64
world::{
65
command_queue::RawCommandQueue,
66
error::{
67
EntityDespawnError, EntityMutableFetchError, TryInsertBatchError, TryRunScheduleError,
68
},
69
},
70
};
71
use alloc::{boxed::Box, vec::Vec};
72
use bevy_platform::sync::atomic::{AtomicU32, Ordering};
73
use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr, Ptr};
74
use bevy_utils::prelude::DebugName;
75
use core::{any::TypeId, fmt, mem::ManuallyDrop};
76
use log::warn;
77
use unsafe_world_cell::{UnsafeEntityCell, UnsafeWorldCell};
78
79
/// Stores and exposes operations on [entities](Entity), [components](Component), resources,
80
/// and their associated metadata.
81
///
82
/// Each [`Entity`] has a set of unique components, based on their type.
83
/// Entity components can be created, updated, removed, and queried using a given [`World`].
84
///
85
/// For complex access patterns involving [`SystemParam`](crate::system::SystemParam),
86
/// consider using [`SystemState`](crate::system::SystemState).
87
///
88
/// To mutate different parts of the world simultaneously,
89
/// use [`World::resource_scope`] or [`SystemState`](crate::system::SystemState).
90
///
91
/// ## Resources
92
///
93
/// Worlds can also store [`Resource`]s,
94
/// which are unique instances of a given type that belong to a specific unique Entity.
95
/// There are also *non send resources*, which can only be accessed on the main thread.
96
/// These are stored outside of the ECS.
97
/// See [`Resource`] for usage.
98
pub struct World {
99
id: WorldId,
100
pub(crate) entities: Entities,
101
pub(crate) entity_allocator: EntityAllocator,
102
pub(crate) components: Components,
103
pub(crate) component_ids: ComponentIds,
104
pub(crate) resource_entities: ResourceEntities,
105
pub(crate) archetypes: Archetypes,
106
pub(crate) storages: Storages,
107
pub(crate) bundles: Bundles,
108
pub(crate) observers: Observers,
109
pub(crate) removed_components: RemovedComponentMessages,
110
pub(crate) change_tick: AtomicU32,
111
pub(crate) last_change_tick: Tick,
112
pub(crate) last_check_tick: Tick,
113
pub(crate) last_trigger_id: u32,
114
pub(crate) command_queue: RawCommandQueue,
115
}
116
117
impl Default for World {
118
fn default() -> Self {
119
let mut world = Self {
120
id: WorldId::new().expect("More `bevy` `World`s have been created than is supported"),
121
entities: Entities::new(),
122
entity_allocator: EntityAllocator::default(),
123
components: Default::default(),
124
resource_entities: Default::default(),
125
archetypes: Archetypes::new(),
126
storages: Default::default(),
127
bundles: Default::default(),
128
observers: Observers::default(),
129
removed_components: Default::default(),
130
// Default value is `1`, and `last_change_tick`s default to `0`, such that changes
131
// are detected on first system runs and for direct world queries.
132
change_tick: AtomicU32::new(1),
133
last_change_tick: Tick::new(0),
134
last_check_tick: Tick::new(0),
135
last_trigger_id: 0,
136
command_queue: RawCommandQueue::new(),
137
component_ids: ComponentIds::default(),
138
};
139
world.bootstrap();
140
world
141
}
142
}
143
144
impl Drop for World {
145
fn drop(&mut self) {
146
// SAFETY: Not passing a pointer so the argument is always valid
147
unsafe { self.command_queue.apply_or_drop_queued(None) };
148
// SAFETY: Pointers in internal command queue are only invalidated here
149
drop(unsafe { Box::from_raw(self.command_queue.bytes.as_ptr()) });
150
// SAFETY: Pointers in internal command queue are only invalidated here
151
drop(unsafe { Box::from_raw(self.command_queue.cursor.as_ptr()) });
152
// SAFETY: Pointers in internal command queue are only invalidated here
153
drop(unsafe { Box::from_raw(self.command_queue.panic_recovery.as_ptr()) });
154
}
155
}
156
157
impl World {
158
/// This performs initialization that _must_ happen for every [`World`] immediately upon creation (such as claiming specific component ids).
159
/// This _must_ be run as part of constructing a [`World`], before it is returned to the caller.
160
#[inline]
161
fn bootstrap(&mut self) {
162
// The order that we register these events is vital to ensure that the constants are correct!
163
let on_add = self.register_event_key::<Add>();
164
assert_eq!(ADD, on_add);
165
166
let on_insert = self.register_event_key::<Insert>();
167
assert_eq!(INSERT, on_insert);
168
169
let on_discard = self.register_event_key::<Discard>();
170
assert_eq!(DISCARD, on_discard);
171
172
let on_remove = self.register_event_key::<Remove>();
173
assert_eq!(REMOVE, on_remove);
174
175
let on_despawn = self.register_event_key::<Despawn>();
176
assert_eq!(DESPAWN, on_despawn);
177
178
let is_resource = self.register_component::<IsResource>();
179
assert_eq!(IS_RESOURCE, is_resource);
180
181
// This sets up `Disabled` as a disabling component, via the FromWorld impl
182
self.init_resource::<DefaultQueryFilters>();
183
}
184
/// Creates a new empty [`World`].
185
///
186
/// # Panics
187
///
188
/// If [`usize::MAX`] [`World`]s have been created.
189
/// This guarantee allows System Parameters to safely uniquely identify a [`World`],
190
/// since its [`WorldId`] is unique
191
#[inline]
192
pub fn new() -> World {
193
World::default()
194
}
195
196
/// Retrieves this [`World`]'s unique ID
197
#[inline]
198
pub fn id(&self) -> WorldId {
199
self.id
200
}
201
202
/// Creates a new [`UnsafeWorldCell`] view with complete read+write access.
203
#[inline]
204
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
205
UnsafeWorldCell::new_mutable(self)
206
}
207
208
/// Creates a new [`UnsafeWorldCell`] view with only read access to everything.
209
#[inline]
210
pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_> {
211
UnsafeWorldCell::new_readonly(self)
212
}
213
214
/// Retrieves this world's [`Entities`] collection.
215
#[inline]
216
pub fn entities(&self) -> &Entities {
217
&self.entities
218
}
219
220
/// Retrieves this world's [`EntityAllocator`] collection.
221
#[inline]
222
pub fn entity_allocator(&self) -> &EntityAllocator {
223
&self.entity_allocator
224
}
225
226
/// Retrieves this world's [`EntityAllocator`] collection mutably.
227
#[inline]
228
pub fn entity_allocator_mut(&mut self) -> &mut EntityAllocator {
229
&mut self.entity_allocator
230
}
231
232
/// Retrieves this world's [`Entities`] collection mutably.
233
///
234
/// # Safety
235
/// Mutable reference must not be used to put the [`Entities`] data
236
/// in an invalid state for this [`World`]
237
#[inline]
238
pub unsafe fn entities_mut(&mut self) -> &mut Entities {
239
&mut self.entities
240
}
241
242
/// Retrieves the number of [`Entities`] in the world.
243
///
244
/// This is helpful as a diagnostic, but it can also be used effectively in tests.
245
#[inline]
246
pub fn entity_count(&self) -> u32 {
247
self.entities.count_spawned()
248
}
249
250
/// Retrieves this world's [`Archetypes`] collection.
251
#[inline]
252
pub fn archetypes(&self) -> &Archetypes {
253
&self.archetypes
254
}
255
256
/// Retrieves this world's [`Components`] collection.
257
#[inline]
258
pub fn components(&self) -> &Components {
259
&self.components
260
}
261
262
/// Retrieves this world's [`ResourceEntities`].
263
#[inline]
264
pub fn resource_entities(&self) -> &ResourceEntities {
265
&self.resource_entities
266
}
267
268
/// Prepares a [`ComponentsQueuedRegistrator`] for the world.
269
/// **NOTE:** [`ComponentsQueuedRegistrator`] is easily misused.
270
/// See its docs for important notes on when and how it should be used.
271
#[inline]
272
pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_> {
273
// SAFETY: These are from the same world.
274
unsafe { ComponentsQueuedRegistrator::new(&self.components, &self.component_ids) }
275
}
276
277
/// Prepares a [`ComponentsRegistrator`] for the world.
278
#[inline]
279
pub fn components_registrator(&mut self) -> ComponentsRegistrator<'_> {
280
// SAFETY: These are from the same world.
281
unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }
282
}
283
284
/// Retrieves this world's [`Storages`] collection.
285
#[inline]
286
pub fn storages(&self) -> &Storages {
287
&self.storages
288
}
289
290
/// Retrieves this world's [`Bundles`] collection.
291
#[inline]
292
pub fn bundles(&self) -> &Bundles {
293
&self.bundles
294
}
295
296
/// Retrieves this world's [`RemovedComponentMessages`] collection
297
#[inline]
298
pub fn removed_components(&self) -> &RemovedComponentMessages {
299
&self.removed_components
300
}
301
302
/// Retrieves this world's [`Observers`] list
303
#[inline]
304
pub fn observers(&self) -> &Observers {
305
&self.observers
306
}
307
308
/// Creates a new [`Commands`] instance that writes to the world's command queue
309
/// Use [`World::flush`] to apply all queued commands
310
#[inline]
311
pub fn commands(&mut self) -> Commands<'_, '_> {
312
// SAFETY: command_queue is stored on world and always valid while the world exists
313
unsafe {
314
Commands::new_raw_from_entities(
315
self.command_queue.clone(),
316
&self.entity_allocator,
317
&self.entities,
318
)
319
}
320
}
321
322
/// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
323
///
324
/// # Usage Notes
325
/// In most cases, you don't need to call this method directly since component registration
326
/// happens automatically during system initialization.
327
pub fn register_component<T: Component>(&mut self) -> ComponentId {
328
self.components_registrator().register_component::<T>()
329
}
330
331
/// Registers a component type as "disabling",
332
/// using [default query filters](DefaultQueryFilters) to exclude entities with the component from queries.
333
pub fn register_disabling_component<C: Component>(&mut self) {
334
let component_id = self.register_component::<C>();
335
let mut dqf = self.resource_mut::<DefaultQueryFilters>();
336
dqf.register_disabling_component(component_id);
337
}
338
339
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] type.
340
///
341
/// Will panic if `T` exists in any archetypes.
342
#[must_use]
343
pub fn register_component_hooks<T: Component>(&mut self) -> &mut ComponentHooks {
344
let index = self.register_component::<T>();
345
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if {} may already be in use", core::any::type_name::<T>());
346
// SAFETY: We just created this component
347
unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() }
348
}
349
350
/// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] with the given id if it exists.
351
///
352
/// Will panic if `id` exists in any archetypes.
353
pub fn register_component_hooks_by_id(
354
&mut self,
355
id: ComponentId,
356
) -> Option<&mut ComponentHooks> {
357
assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(id)), "Components hooks cannot be modified if the component already exists in an archetype, use register_component if the component with id {id:?} may already be in use");
358
self.components.get_hooks_mut(id)
359
}
360
361
/// Registers the given component `R` as a [required component] for `T`.
362
///
363
/// When `T` is added to an entity, `R` and its own required components will also be added
364
/// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
365
/// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
366
///
367
/// For the non-panicking version, see [`World::try_register_required_components`].
368
///
369
/// Note that requirements must currently be registered before `T` is inserted into the world
370
/// for the first time. This limitation may be fixed in the future.
371
///
372
/// [required component]: Component#required-components
373
///
374
/// # Panics
375
///
376
/// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
377
/// on an entity before the registration.
378
///
379
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
380
/// will only be overwritten if the new requirement is more specific.
381
///
382
/// # Example
383
///
384
/// ```
385
/// # use bevy_ecs::prelude::*;
386
/// #[derive(Component)]
387
/// struct A;
388
///
389
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
390
/// struct B(usize);
391
///
392
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
393
/// struct C(u32);
394
///
395
/// # let mut world = World::default();
396
/// // Register B as required by A and C as required by B.
397
/// world.register_required_components::<A, B>();
398
/// world.register_required_components::<B, C>();
399
///
400
/// // This will implicitly also insert B and C with their Default constructors.
401
/// let id = world.spawn(A).id();
402
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
403
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
404
/// ```
405
pub fn register_required_components<T: Component, R: Component + Default>(&mut self) {
406
self.try_register_required_components::<T, R>().unwrap();
407
}
408
409
/// Registers the given component `R` as a [required component] for `T`.
410
///
411
/// When `T` is added to an entity, `R` and its own required components will also be added
412
/// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
413
/// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
414
///
415
/// For the non-panicking version, see [`World::try_register_required_components_with`].
416
///
417
/// Note that requirements must currently be registered before `T` is inserted into the world
418
/// for the first time. This limitation may be fixed in the future.
419
///
420
/// [required component]: Component#required-components
421
///
422
/// # Panics
423
///
424
/// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
425
/// on an entity before the registration.
426
///
427
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
428
/// will only be overwritten if the new requirement is more specific.
429
///
430
/// # Example
431
///
432
/// ```
433
/// # use bevy_ecs::prelude::*;
434
/// #[derive(Component)]
435
/// struct A;
436
///
437
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
438
/// struct B(usize);
439
///
440
/// #[derive(Component, PartialEq, Eq, Debug)]
441
/// struct C(u32);
442
///
443
/// # let mut world = World::default();
444
/// // Register B and C as required by A and C as required by B.
445
/// // A requiring C directly will overwrite the indirect requirement through B.
446
/// world.register_required_components::<A, B>();
447
/// world.register_required_components_with::<B, C>(|| C(1));
448
/// world.register_required_components_with::<A, C>(|| C(2));
449
///
450
/// // This will implicitly also insert B with its Default constructor and C
451
/// // with the custom constructor defined by A.
452
/// let id = world.spawn(A).id();
453
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
454
/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
455
/// ```
456
pub fn register_required_components_with<T: Component, R: Component>(
457
&mut self,
458
constructor: fn() -> R,
459
) {
460
self.try_register_required_components_with::<T, R>(constructor)
461
.unwrap();
462
}
463
464
/// Tries to register the given component `R` as a [required component] for `T`.
465
///
466
/// When `T` is added to an entity, `R` and its own required components will also be added
467
/// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
468
/// If a custom constructor is desired, use [`World::register_required_components_with`] instead.
469
///
470
/// For the panicking version, see [`World::register_required_components`].
471
///
472
/// Note that requirements must currently be registered before `T` is inserted into the world
473
/// for the first time. This limitation may be fixed in the future.
474
///
475
/// [required component]: Component#required-components
476
///
477
/// # Errors
478
///
479
/// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
480
/// on an entity before the registration.
481
///
482
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
483
/// will only be overwritten if the new requirement is more specific.
484
///
485
/// # Example
486
///
487
/// ```
488
/// # use bevy_ecs::prelude::*;
489
/// #[derive(Component)]
490
/// struct A;
491
///
492
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
493
/// struct B(usize);
494
///
495
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
496
/// struct C(u32);
497
///
498
/// # let mut world = World::default();
499
/// // Register B as required by A and C as required by B.
500
/// world.register_required_components::<A, B>();
501
/// world.register_required_components::<B, C>();
502
///
503
/// // Duplicate registration! This will fail.
504
/// assert!(world.try_register_required_components::<A, B>().is_err());
505
///
506
/// // This will implicitly also insert B and C with their Default constructors.
507
/// let id = world.spawn(A).id();
508
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
509
/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
510
/// ```
511
pub fn try_register_required_components<T: Component, R: Component + Default>(
512
&mut self,
513
) -> Result<(), RequiredComponentsError> {
514
self.try_register_required_components_with::<T, R>(R::default)
515
}
516
517
/// Tries to register the given component `R` as a [required component] for `T`.
518
///
519
/// When `T` is added to an entity, `R` and its own required components will also be added
520
/// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
521
/// If a [`Default`] constructor is desired, use [`World::register_required_components`] instead.
522
///
523
/// For the panicking version, see [`World::register_required_components_with`].
524
///
525
/// Note that requirements must currently be registered before `T` is inserted into the world
526
/// for the first time. This limitation may be fixed in the future.
527
///
528
/// [required component]: Component#required-components
529
///
530
/// # Errors
531
///
532
/// Returns a [`RequiredComponentsError`] if `R` is already a directly required component for `T`, or if `T` has ever been added
533
/// on an entity before the registration.
534
///
535
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
536
/// will only be overwritten if the new requirement is more specific.
537
///
538
/// # Example
539
///
540
/// ```
541
/// # use bevy_ecs::prelude::*;
542
/// #[derive(Component)]
543
/// struct A;
544
///
545
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
546
/// struct B(usize);
547
///
548
/// #[derive(Component, PartialEq, Eq, Debug)]
549
/// struct C(u32);
550
///
551
/// # let mut world = World::default();
552
/// // Register B and C as required by A and C as required by B.
553
/// // A requiring C directly will overwrite the indirect requirement through B.
554
/// world.register_required_components::<A, B>();
555
/// world.register_required_components_with::<B, C>(|| C(1));
556
/// world.register_required_components_with::<A, C>(|| C(2));
557
///
558
/// // Duplicate registration! Even if the constructors were different, this would fail.
559
/// assert!(world.try_register_required_components_with::<B, C>(|| C(1)).is_err());
560
///
561
/// // This will implicitly also insert B with its Default constructor and C
562
/// // with the custom constructor defined by A.
563
/// let id = world.spawn(A).id();
564
/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
565
/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
566
/// ```
567
pub fn try_register_required_components_with<T: Component, R: Component>(
568
&mut self,
569
constructor: fn() -> R,
570
) -> Result<(), RequiredComponentsError> {
571
let requiree = self.register_component::<T>();
572
573
// TODO: Remove this panic and update archetype edges accordingly when required components are added
574
if self.archetypes().component_index().contains_key(&requiree) {
575
return Err(RequiredComponentsError::ArchetypeExists(requiree));
576
}
577
578
let required = self.register_component::<R>();
579
580
// SAFETY: We just created the `required` and `requiree` components.
581
unsafe {
582
self.components
583
.register_required_components::<R>(requiree, required, constructor)
584
}
585
}
586
587
/// Retrieves the [required components](RequiredComponents) for the given component type, if it exists.
588
pub fn get_required_components<C: Component>(&self) -> Option<&RequiredComponents> {
589
let id = self.components().valid_component_id::<C>()?;
590
let component_info = self.components().get_info(id)?;
591
Some(component_info.required_components())
592
}
593
594
/// Retrieves the [required components](RequiredComponents) for the component of the given [`ComponentId`], if it exists.
595
pub fn get_required_components_by_id(&self, id: ComponentId) -> Option<&RequiredComponents> {
596
let component_info = self.components().get_info(id)?;
597
Some(component_info.required_components())
598
}
599
600
/// Registers a new [`Component`] type and returns the [`ComponentId`] created for it.
601
///
602
/// This method differs from [`World::register_component`] in that it uses a [`ComponentDescriptor`]
603
/// to register the new component type instead of statically available type information. This
604
/// enables the dynamic registration of new component definitions at runtime for advanced use cases.
605
///
606
/// While the option to register a component from a descriptor is useful in type-erased
607
/// contexts, the standard [`World::register_component`] function should always be used instead
608
/// when type information is available at compile time.
609
pub fn register_component_with_descriptor(
610
&mut self,
611
descriptor: ComponentDescriptor,
612
) -> ComponentId {
613
self.components_registrator()
614
.register_component_with_descriptor(descriptor)
615
}
616
617
/// Returns the [`ComponentId`] of the given [`Component`] type `T`.
618
///
619
/// The returned `ComponentId` is specific to the `World` instance
620
/// it was retrieved from and should not be used with another `World` instance.
621
///
622
/// Returns [`None`] if the `Component` type has not yet been initialized within
623
/// the `World` using [`World::register_component`].
624
///
625
/// ```
626
/// use bevy_ecs::prelude::*;
627
///
628
/// let mut world = World::new();
629
///
630
/// #[derive(Component)]
631
/// struct ComponentA;
632
///
633
/// let component_a_id = world.register_component::<ComponentA>();
634
///
635
/// assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
636
/// ```
637
///
638
/// # See also
639
///
640
/// * [`ComponentIdFor`](crate::component::ComponentIdFor)
641
/// * [`Components::component_id()`]
642
/// * [`Components::get_id()`]
643
#[inline]
644
pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
645
self.components.component_id::<T>()
646
}
647
648
/// Registers a new [`Resource`] type and returns the [`ComponentId`] created for it.
649
///
650
/// The [`Resource`] doesn't have a value in the [`World`], it's only registered. If you want
651
/// to insert the [`Resource`] in the [`World`], use [`World::init_resource`] or
652
/// [`World::insert_resource`] instead.
653
pub fn register_resource<R: Resource>(&mut self) -> ComponentId {
654
self.components_registrator().register_component::<R>()
655
}
656
657
/// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
658
///
659
/// The returned [`ComponentId`] is specific to the [`World`] instance it was retrieved from
660
/// and should not be used with another [`World`] instance.
661
///
662
/// Returns [`None`] if the [`Resource`] type has not yet been initialized within the
663
/// [`World`] using [`World::register_resource`], [`World::init_resource`] or [`World::insert_resource`].
664
#[deprecated(since = "0.19.0", note = "use component_id")]
665
pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
666
self.components.get_id(TypeId::of::<T>())
667
}
668
669
/// Returns [`EntityRef`]s that expose read-only operations for the given
670
/// `entities`. This will panic if any of the given entities do not exist. Use
671
/// [`World::get_entity`] if you want to check for entity existence instead
672
/// of implicitly panicking.
673
///
674
/// This function supports fetching a single entity or multiple entities:
675
/// - Pass an [`Entity`] to receive a single [`EntityRef`].
676
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
677
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
678
///
679
/// # Panics
680
///
681
/// If any of the given `entities` do not exist in the world.
682
///
683
/// # Examples
684
///
685
/// ## Single [`Entity`]
686
///
687
/// ```
688
/// # use bevy_ecs::prelude::*;
689
/// #[derive(Component)]
690
/// struct Position {
691
/// x: f32,
692
/// y: f32,
693
/// }
694
///
695
/// let mut world = World::new();
696
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
697
///
698
/// let position = world.entity(entity).get::<Position>().unwrap();
699
/// assert_eq!(position.x, 0.0);
700
/// ```
701
///
702
/// ## Array of [`Entity`]s
703
///
704
/// ```
705
/// # use bevy_ecs::prelude::*;
706
/// #[derive(Component)]
707
/// struct Position {
708
/// x: f32,
709
/// y: f32,
710
/// }
711
///
712
/// let mut world = World::new();
713
/// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
714
/// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
715
///
716
/// let [e1_ref, e2_ref] = world.entity([e1, e2]);
717
/// let e1_position = e1_ref.get::<Position>().unwrap();
718
/// assert_eq!(e1_position.x, 0.0);
719
/// let e2_position = e2_ref.get::<Position>().unwrap();
720
/// assert_eq!(e2_position.x, 1.0);
721
/// ```
722
///
723
/// ## Slice of [`Entity`]s
724
///
725
/// ```
726
/// # use bevy_ecs::prelude::*;
727
/// #[derive(Component)]
728
/// struct Position {
729
/// x: f32,
730
/// y: f32,
731
/// }
732
///
733
/// let mut world = World::new();
734
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
735
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
736
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
737
///
738
/// let ids = vec![e1, e2, e3];
739
/// for eref in world.entity(&ids[..]) {
740
/// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
741
/// }
742
/// ```
743
///
744
/// ## [`EntityHashSet`](crate::entity::EntityHashSet)
745
///
746
/// ```
747
/// # use bevy_ecs::{prelude::*, entity::EntityHashSet};
748
/// #[derive(Component)]
749
/// struct Position {
750
/// x: f32,
751
/// y: f32,
752
/// }
753
///
754
/// let mut world = World::new();
755
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
756
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
757
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
758
///
759
/// let ids = EntityHashSet::from_iter([e1, e2, e3]);
760
/// for (_id, eref) in world.entity(&ids) {
761
/// assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
762
/// }
763
/// ```
764
///
765
/// [`EntityHashSet`]: crate::entity::EntityHashSet
766
#[inline]
767
#[track_caller]
768
pub fn entity<F: WorldEntityFetch>(&self, entities: F) -> F::Ref<'_> {
769
match self.get_entity(entities) {
770
Ok(res) => res,
771
Err(err) => panic!("{err}"),
772
}
773
}
774
775
/// Returns [`EntityMut`]s that expose read and write operations for the
776
/// given `entities`. This will panic if any of the given entities do not
777
/// exist. Use [`World::get_entity_mut`] if you want to check for entity
778
/// existence instead of implicitly panicking.
779
///
780
/// This function supports fetching a single entity or multiple entities:
781
/// - Pass an [`Entity`] to receive a single [`EntityWorldMut`].
782
/// - This reference type allows for structural changes to the entity,
783
/// such as adding or removing components, or despawning the entity.
784
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
785
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
786
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
787
/// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
788
///
789
/// In order to perform structural changes on the returned entity reference,
790
/// such as adding or removing components, or despawning the entity, only a
791
/// single [`Entity`] can be passed to this function. Allowing multiple
792
/// entities at the same time with structural access would lead to undefined
793
/// behavior, so [`EntityMut`] is returned when requesting multiple entities.
794
///
795
/// # Panics
796
///
797
/// If any of the given `entities` do not exist in the world.
798
///
799
/// # Examples
800
///
801
/// ## Single [`Entity`]
802
///
803
/// ```
804
/// # use bevy_ecs::prelude::*;
805
/// #[derive(Component)]
806
/// struct Position {
807
/// x: f32,
808
/// y: f32,
809
/// }
810
///
811
/// let mut world = World::new();
812
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
813
///
814
/// let mut entity_mut = world.entity_mut(entity);
815
/// let mut position = entity_mut.get_mut::<Position>().unwrap();
816
/// position.y = 1.0;
817
/// assert_eq!(position.x, 0.0);
818
/// entity_mut.despawn();
819
/// # assert!(world.get_entity_mut(entity).is_err());
820
/// ```
821
///
822
/// ## Array of [`Entity`]s
823
///
824
/// ```
825
/// # use bevy_ecs::prelude::*;
826
/// #[derive(Component)]
827
/// struct Position {
828
/// x: f32,
829
/// y: f32,
830
/// }
831
///
832
/// let mut world = World::new();
833
/// let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
834
/// let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
835
///
836
/// let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
837
/// let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
838
/// e1_position.x = 1.0;
839
/// assert_eq!(e1_position.x, 1.0);
840
/// let mut e2_position = e2_ref.get_mut::<Position>().unwrap();
841
/// e2_position.x = 2.0;
842
/// assert_eq!(e2_position.x, 2.0);
843
/// ```
844
///
845
/// ## Slice of [`Entity`]s
846
///
847
/// ```
848
/// # use bevy_ecs::prelude::*;
849
/// #[derive(Component)]
850
/// struct Position {
851
/// x: f32,
852
/// y: f32,
853
/// }
854
///
855
/// let mut world = World::new();
856
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
857
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
858
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
859
///
860
/// let ids = vec![e1, e2, e3];
861
/// for mut eref in world.entity_mut(&ids[..]) {
862
/// let mut pos = eref.get_mut::<Position>().unwrap();
863
/// pos.y = 2.0;
864
/// assert_eq!(pos.y, 2.0);
865
/// }
866
/// ```
867
///
868
/// ## [`EntityHashSet`](crate::entity::EntityHashSet)
869
///
870
/// ```
871
/// # use bevy_ecs::{prelude::*, entity::EntityHashSet};
872
/// #[derive(Component)]
873
/// struct Position {
874
/// x: f32,
875
/// y: f32,
876
/// }
877
///
878
/// let mut world = World::new();
879
/// let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
880
/// let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
881
/// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
882
///
883
/// let ids = EntityHashSet::from_iter([e1, e2, e3]);
884
/// for (_id, mut eref) in world.entity_mut(&ids) {
885
/// let mut pos = eref.get_mut::<Position>().unwrap();
886
/// pos.y = 2.0;
887
/// assert_eq!(pos.y, 2.0);
888
/// }
889
/// ```
890
///
891
/// [`EntityHashSet`]: crate::entity::EntityHashSet
892
#[inline]
893
#[track_caller]
894
pub fn entity_mut<F: WorldEntityFetch>(&mut self, entities: F) -> F::Mut<'_> {
895
#[inline(never)]
896
#[cold]
897
#[track_caller]
898
fn panic_on_err(e: EntityMutableFetchError) -> ! {
899
panic!("{e}");
900
}
901
902
match self.get_entity_mut(entities) {
903
Ok(fetched) => fetched,
904
Err(e) => panic_on_err(e),
905
}
906
}
907
908
/// Returns the components of an [`Entity`] through [`ComponentInfo`].
909
#[inline]
910
pub fn inspect_entity(
911
&self,
912
entity: Entity,
913
) -> Result<impl Iterator<Item = &ComponentInfo>, EntityNotSpawnedError> {
914
let entity_location = self.entities().get_spawned(entity)?;
915
916
let archetype = self
917
.archetypes()
918
.get(entity_location.archetype_id)
919
.expect("ArchetypeId was retrieved from an EntityLocation and should correspond to an Archetype");
920
921
Ok(archetype
922
.iter_components()
923
.filter_map(|id| self.components().get_info(id)))
924
}
925
926
/// Returns [`EntityRef`]s that expose read-only operations for the given
927
/// `entities`, returning [`Err`] if any of the given entities do not exist.
928
/// Instead of immediately unwrapping the value returned from this function,
929
/// prefer [`World::entity`].
930
///
931
/// This function supports fetching a single entity or multiple entities:
932
/// - Pass an [`Entity`] to receive a single [`EntityRef`].
933
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityRef>`].
934
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityRef`]s.
935
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
936
/// [`EntityHashMap<EntityRef>`](crate::entity::EntityHashMap).
937
///
938
/// # Errors
939
///
940
/// If any of the given `entities` do not exist in the world, the first
941
/// [`Entity`] found to be missing will return an [`EntityNotSpawnedError`].
942
///
943
/// # Examples
944
///
945
/// For examples, see [`World::entity`].
946
///
947
/// [`EntityHashSet`]: crate::entity::EntityHashSet
948
#[inline]
949
pub fn get_entity<F: WorldEntityFetch>(
950
&self,
951
entities: F,
952
) -> Result<F::Ref<'_>, EntityNotSpawnedError> {
953
let cell = self.as_unsafe_world_cell_readonly();
954
// SAFETY: `&self` gives read access to the entire world, and prevents mutable access.
955
unsafe { entities.fetch_ref(cell) }
956
}
957
958
/// Returns [`EntityMut`]s that expose read and write operations for the
959
/// given `entities`, returning [`Err`] if any of the given entities do not
960
/// exist. Instead of immediately unwrapping the value returned from this
961
/// function, prefer [`World::entity_mut`].
962
///
963
/// This function supports fetching a single entity or multiple entities:
964
/// - Pass an [`Entity`] to receive a single [`EntityWorldMut`].
965
/// - This reference type allows for structural changes to the entity,
966
/// such as adding or removing components, or despawning the entity.
967
/// - Pass a slice of [`Entity`]s to receive a [`Vec<EntityMut>`].
968
/// - Pass an array of [`Entity`]s to receive an equally-sized array of [`EntityMut`]s.
969
/// - Pass a reference to a [`EntityHashSet`](crate::entity::EntityHashMap) to receive an
970
/// [`EntityHashMap<EntityMut>`](crate::entity::EntityHashMap).
971
///
972
/// In order to perform structural changes on the returned entity reference,
973
/// such as adding or removing components, or despawning the entity, only a
974
/// single [`Entity`] can be passed to this function. Allowing multiple
975
/// entities at the same time with structural access would lead to undefined
976
/// behavior, so [`EntityMut`] is returned when requesting multiple entities.
977
///
978
/// # Errors
979
///
980
/// - Returns [`EntityMutableFetchError::NotSpawned`] if any of the given `entities` do not exist in the world.
981
/// - Only the first entity found to be missing will be returned.
982
/// - Returns [`EntityMutableFetchError::AliasedMutability`] if the same entity is requested multiple times.
983
///
984
/// # Examples
985
///
986
/// For examples, see [`World::entity_mut`].
987
///
988
/// [`EntityHashSet`]: crate::entity::EntityHashSet
989
#[inline]
990
pub fn get_entity_mut<F: WorldEntityFetch>(
991
&mut self,
992
entities: F,
993
) -> Result<F::Mut<'_>, EntityMutableFetchError> {
994
let cell = self.as_unsafe_world_cell();
995
// SAFETY: `&mut self` gives mutable access to the entire world,
996
// and prevents any other access to the world.
997
unsafe { entities.fetch_mut(cell) }
998
}
999
1000
/// Returns an [`Entity`] iterator of current entities.
1001
///
1002
/// This is useful in contexts where you only have immutable access to the [`World`].
1003
/// If you have mutable access to the [`World`], use
1004
/// [`query()::<EntityRef>().iter(&world)`](World::query()) instead.
1005
///
1006
/// Note that this does iterate through *all* entities, including resource entities.
1007
#[inline]
1008
pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>> + '_ {
1009
self.archetypes.iter().flat_map(|archetype| {
1010
archetype
1011
.entities_with_location()
1012
.map(|(entity, location)| {
1013
// SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
1014
let cell = UnsafeEntityCell::new(
1015
self.as_unsafe_world_cell_readonly(),
1016
entity,
1017
location,
1018
self.last_change_tick,
1019
self.read_change_tick(),
1020
);
1021
// SAFETY: `&self` gives read access to the entire world.
1022
unsafe { EntityRef::new(cell) }
1023
})
1024
})
1025
}
1026
1027
/// Simultaneously provides access to entity data and a command queue, which
1028
/// will be applied when the world is next flushed.
1029
///
1030
/// This allows using borrowed entity data to construct commands where the
1031
/// borrow checker would otherwise prevent it.
1032
///
1033
/// See [`DeferredWorld::entities_and_commands`] for the deferred version.
1034
///
1035
/// # Example
1036
///
1037
/// ```rust
1038
/// # use bevy_ecs::{prelude::*, world::DeferredWorld};
1039
/// #[derive(Component)]
1040
/// struct Targets(Vec<Entity>);
1041
/// #[derive(Component)]
1042
/// struct TargetedBy(Entity);
1043
///
1044
/// let mut world: World = // ...
1045
/// # World::new();
1046
/// # let e1 = world.spawn_empty().id();
1047
/// # let e2 = world.spawn_empty().id();
1048
/// # let eid = world.spawn(Targets(vec![e1, e2])).id();
1049
/// let (entities, mut commands) = world.entities_and_commands();
1050
///
1051
/// let entity = entities.get(eid).unwrap();
1052
/// for &target in entity.get::<Targets>().unwrap().0.iter() {
1053
/// commands.entity(target).insert(TargetedBy(eid));
1054
/// }
1055
/// # world.flush();
1056
/// # assert_eq!(world.get::<TargetedBy>(e1).unwrap().0, eid);
1057
/// # assert_eq!(world.get::<TargetedBy>(e2).unwrap().0, eid);
1058
/// ```
1059
pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>) {
1060
let cell = self.as_unsafe_world_cell();
1061
// SAFETY: `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
1062
let fetcher = unsafe { EntityFetcher::new(cell) };
1063
// SAFETY:
1064
// - `&mut self` gives mutable access to the entire world, and prevents simultaneous access.
1065
// - Command queue access does not conflict with entity access.
1066
let raw_queue = unsafe { cell.get_raw_command_queue() };
1067
// SAFETY: `&mut self` ensures the commands does not outlive the world.
1068
let commands = unsafe {
1069
Commands::new_raw_from_entities(raw_queue, cell.entity_allocator(), cell.entities())
1070
};
1071
1072
(fetcher, commands)
1073
}
1074
1075
/// Spawns the bundle on the valid but not spawned entity.
1076
/// If the entity can not be spawned for any reason, returns an error.
1077
///
1078
/// If it succeeds, this declares the entity to have this bundle.
1079
///
1080
/// In general, you should prefer [`spawn`](Self::spawn).
1081
/// Spawn internally calls this method, but it takes care of finding a suitable [`Entity`] for you.
1082
/// This is made available for advanced use, which you can see at [`EntityAllocator::alloc`].
1083
///
1084
/// # Risk
1085
///
1086
/// It is possible to spawn an `entity` that has not been allocated yet;
1087
/// however, doing so is currently a bad idea as the allocator may hand out this entity index in the future, assuming it to be not spawned.
1088
/// This would cause a panic.
1089
///
1090
/// Manual spawning is a powerful tool, but must be used carefully.
1091
///
1092
/// # Example
1093
///
1094
/// Currently, this is primarily used to spawn entities that come from [`EntityAllocator::alloc`].
1095
/// See that for an example.
1096
#[track_caller]
1097
pub fn spawn_at<B: Bundle>(
1098
&mut self,
1099
entity: Entity,
1100
bundle: B,
1101
) -> Result<EntityWorldMut<'_>, SpawnError> {
1102
move_as_ptr!(bundle);
1103
self.spawn_at_with_caller(entity, bundle, MaybeLocation::caller())
1104
}
1105
1106
pub(crate) fn spawn_at_with_caller<B: Bundle>(
1107
&mut self,
1108
entity: Entity,
1109
bundle: MovingPtr<'_, B>,
1110
caller: MaybeLocation,
1111
) -> Result<EntityWorldMut<'_>, SpawnError> {
1112
self.entities.check_can_spawn_at(entity)?;
1113
Ok(self.spawn_at_unchecked(entity, bundle, caller))
1114
}
1115
1116
/// Spawns `bundle` on `entity`.
1117
///
1118
/// # Panics
1119
///
1120
/// Panics if the entity index is already constructed
1121
pub(crate) fn spawn_at_unchecked<B: Bundle>(
1122
&mut self,
1123
entity: Entity,
1124
bundle: MovingPtr<'_, B>,
1125
caller: MaybeLocation,
1126
) -> EntityWorldMut<'_> {
1127
let change_tick = self.change_tick();
1128
let mut bundle_spawner = BundleSpawner::new::<B>(self, change_tick);
1129
let (bundle, entity_location) = bundle.partial_move(|bundle| {
1130
// SAFETY:
1131
// - `B` matches `bundle_spawner`'s type
1132
// - `entity` is allocated but non-existent
1133
// - `B::Effect` is unconstrained, and `B::apply_effect` is called exactly once on the bundle after this call.
1134
// - This function ensures that the value pointed to by `bundle` must not be accessed for anything afterwards by consuming
1135
// the `MovingPtr`. The value is otherwise only used to call `apply_effect` within this function, and the safety invariants
1136
// of `DynamicBundle` ensure that only the elements that have not been moved out of by this call are accessed.
1137
unsafe { bundle_spawner.spawn_at::<B>(entity, bundle, caller) }
1138
});
1139
1140
let mut entity_location = Some(entity_location);
1141
1142
// SAFETY: command_queue is not referenced anywhere else
1143
if !unsafe { self.command_queue.is_empty() } {
1144
self.flush();
1145
entity_location = self.entities().get_spawned(entity).ok();
1146
}
1147
1148
// SAFETY: The entity and location started as valid.
1149
// If they were changed by commands, the location was updated to match.
1150
let mut entity = unsafe { EntityWorldMut::new(self, entity, entity_location) };
1151
// SAFETY:
1152
// - This is called exactly once after `get_components` has been called in `spawn_non_existent`.
1153
// - `bundle` had it's `get_components` function called exactly once inside `spawn_non_existent`.
1154
unsafe { B::apply_effect(bundle, &mut entity) };
1155
entity
1156
}
1157
1158
/// A faster version of [`spawn_at`](Self::spawn_at) for the empty bundle.
1159
#[track_caller]
1160
pub fn spawn_empty_at(&mut self, entity: Entity) -> Result<EntityWorldMut<'_>, SpawnError> {
1161
self.spawn_empty_at_with_caller(entity, MaybeLocation::caller())
1162
}
1163
1164
pub(crate) fn spawn_empty_at_with_caller(
1165
&mut self,
1166
entity: Entity,
1167
caller: MaybeLocation,
1168
) -> Result<EntityWorldMut<'_>, SpawnError> {
1169
self.entities.check_can_spawn_at(entity)?;
1170
Ok(self.spawn_empty_at_unchecked(entity, caller))
1171
}
1172
1173
/// A faster version of [`spawn_at_unchecked`](Self::spawn_at_unchecked) for the empty bundle.
1174
///
1175
/// # Panics
1176
///
1177
/// Panics if the entity index is already spawned
1178
pub(crate) fn spawn_empty_at_unchecked(
1179
&mut self,
1180
entity: Entity,
1181
caller: MaybeLocation,
1182
) -> EntityWorldMut<'_> {
1183
// SAFETY: Locations are immediately made valid
1184
unsafe {
1185
let archetype = self.archetypes.empty_mut();
1186
// PERF: consider avoiding allocating entities in the empty archetype unless needed
1187
let table_row = self.storages.tables[archetype.table_id()].allocate(entity);
1188
// SAFETY: no components are allocated by archetype.allocate() because the archetype is
1189
// empty
1190
let location = archetype.allocate(entity, table_row);
1191
let change_tick = self.change_tick();
1192
let was_at = self.entities.set_location(entity.index(), Some(location));
1193
assert!(
1194
was_at.is_none(),
1195
"Attempting to construct an empty entity, but it was already constructed."
1196
);
1197
self.entities
1198
.mark_spawned_or_despawned(entity.index(), caller, change_tick);
1199
1200
EntityWorldMut::new(self, entity, Some(location))
1201
}
1202
}
1203
1204
/// Spawns a new [`Entity`] with a given [`Bundle`] of [components](`Component`) and returns
1205
/// a corresponding [`EntityWorldMut`], which can be used to add components to the entity or
1206
/// retrieve its id. In case large batches of entities need to be spawned, consider using
1207
/// [`World::spawn_batch`] instead.
1208
///
1209
/// ```
1210
/// use bevy_ecs::{bundle::Bundle, component::Component, world::World};
1211
///
1212
/// #[derive(Component)]
1213
/// struct Position {
1214
/// x: f32,
1215
/// y: f32,
1216
/// }
1217
///
1218
/// #[derive(Component)]
1219
/// struct Velocity {
1220
/// x: f32,
1221
/// y: f32,
1222
/// };
1223
///
1224
/// #[derive(Component)]
1225
/// struct Name(&'static str);
1226
///
1227
/// #[derive(Bundle)]
1228
/// struct PhysicsBundle {
1229
/// position: Position,
1230
/// velocity: Velocity,
1231
/// }
1232
///
1233
/// let mut world = World::new();
1234
///
1235
/// // `spawn` can accept a single component:
1236
/// world.spawn(Position { x: 0.0, y: 0.0 });
1237
///
1238
/// // It can also accept a tuple of components:
1239
/// world.spawn((
1240
/// Position { x: 0.0, y: 0.0 },
1241
/// Velocity { x: 1.0, y: 1.0 },
1242
/// ));
1243
///
1244
/// // Or it can accept a pre-defined Bundle of components:
1245
/// world.spawn(PhysicsBundle {
1246
/// position: Position { x: 2.0, y: 2.0 },
1247
/// velocity: Velocity { x: 0.0, y: 4.0 },
1248
/// });
1249
///
1250
/// let entity = world
1251
/// // Tuples can also mix Bundles and Components
1252
/// .spawn((
1253
/// PhysicsBundle {
1254
/// position: Position { x: 2.0, y: 2.0 },
1255
/// velocity: Velocity { x: 0.0, y: 4.0 },
1256
/// },
1257
/// Name("Elaina Proctor"),
1258
/// ))
1259
/// // Calling id() will return the unique identifier for the spawned entity
1260
/// .id();
1261
/// let position = world.entity(entity).get::<Position>().unwrap();
1262
/// assert_eq!(position.x, 2.0);
1263
/// ```
1264
#[track_caller]
1265
pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityWorldMut<'_> {
1266
move_as_ptr!(bundle);
1267
self.spawn_with_caller(bundle, MaybeLocation::caller())
1268
}
1269
1270
pub(crate) fn spawn_with_caller<B: Bundle>(
1271
&mut self,
1272
bundle: MovingPtr<'_, B>,
1273
caller: MaybeLocation,
1274
) -> EntityWorldMut<'_> {
1275
let entity = self.entity_allocator.alloc();
1276
// This was just spawned from null, so it shouldn't panic.
1277
self.spawn_at_unchecked(entity, bundle, caller)
1278
}
1279
1280
/// Spawns a new [`Entity`] and returns a corresponding [`EntityWorldMut`], which can be used
1281
/// to add components to the entity or retrieve its id.
1282
///
1283
/// ```
1284
/// use bevy_ecs::{component::Component, world::World};
1285
///
1286
/// #[derive(Component)]
1287
/// struct Position {
1288
/// x: f32,
1289
/// y: f32,
1290
/// }
1291
/// #[derive(Component)]
1292
/// struct Label(&'static str);
1293
/// #[derive(Component)]
1294
/// struct Num(u32);
1295
///
1296
/// let mut world = World::new();
1297
/// let entity = world.spawn_empty()
1298
/// .insert(Position { x: 0.0, y: 0.0 }) // add a single component
1299
/// .insert((Num(1), Label("hello"))) // add a bundle of components
1300
/// .id();
1301
///
1302
/// let position = world.entity(entity).get::<Position>().unwrap();
1303
/// assert_eq!(position.x, 0.0);
1304
/// ```
1305
#[track_caller]
1306
pub fn spawn_empty(&mut self) -> EntityWorldMut<'_> {
1307
self.spawn_empty_with_caller(MaybeLocation::caller())
1308
}
1309
1310
pub(crate) fn spawn_empty_with_caller(&mut self, caller: MaybeLocation) -> EntityWorldMut<'_> {
1311
let entity = self.entity_allocator.alloc();
1312
// This was just spawned from null, so it shouldn't panic.
1313
self.spawn_empty_at_unchecked(entity, caller)
1314
}
1315
1316
/// Spawns a batch of entities with the same component [`Bundle`] type. Takes a given
1317
/// [`Bundle`] iterator and returns a corresponding [`Entity`] iterator.
1318
/// This is more efficient than spawning entities and adding components to them individually
1319
/// using [`World::spawn`], but it is limited to spawning entities with the same [`Bundle`]
1320
/// type, whereas spawning individually is more flexible.
1321
///
1322
/// ```
1323
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
1324
///
1325
/// #[derive(Component)]
1326
/// struct Str(&'static str);
1327
/// #[derive(Component)]
1328
/// struct Num(u32);
1329
///
1330
/// let mut world = World::new();
1331
/// let entities = world.spawn_batch(vec![
1332
/// (Str("a"), Num(0)), // the first entity
1333
/// (Str("b"), Num(1)), // the second entity
1334
/// ]).collect::<Vec<Entity>>();
1335
///
1336
/// assert_eq!(entities.len(), 2);
1337
/// ```
1338
#[track_caller]
1339
pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
1340
where
1341
I: IntoIterator,
1342
I::Item: Bundle<Effect: NoBundleEffect>,
1343
{
1344
SpawnBatchIter::new(self, iter.into_iter(), MaybeLocation::caller())
1345
}
1346
1347
/// Retrieves a reference to the given `entity`'s [`Component`] of the given type.
1348
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1349
/// ```
1350
/// use bevy_ecs::{component::Component, world::World};
1351
///
1352
/// #[derive(Component)]
1353
/// struct Position {
1354
/// x: f32,
1355
/// y: f32,
1356
/// }
1357
///
1358
/// let mut world = World::new();
1359
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1360
/// let position = world.get::<Position>(entity).unwrap();
1361
/// assert_eq!(position.x, 0.0);
1362
/// ```
1363
#[inline]
1364
pub fn get<T: Component>(&self, entity: Entity) -> Option<&T> {
1365
self.get_entity(entity).ok()?.get()
1366
}
1367
1368
/// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given type.
1369
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1370
/// ```
1371
/// use bevy_ecs::{component::Component, world::World};
1372
///
1373
/// #[derive(Component)]
1374
/// struct Position {
1375
/// x: f32,
1376
/// y: f32,
1377
/// }
1378
///
1379
/// let mut world = World::new();
1380
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1381
/// let mut position = world.get_mut::<Position>(entity).unwrap();
1382
/// position.x = 1.0;
1383
/// ```
1384
#[inline]
1385
pub fn get_mut<T: Component<Mutability = Mutable>>(
1386
&mut self,
1387
entity: Entity,
1388
) -> Option<Mut<'_, T>> {
1389
self.get_entity_mut(entity).ok()?.into_mut()
1390
}
1391
1392
/// Temporarily removes a [`Component`] `T` from the provided [`Entity`] and
1393
/// runs the provided closure on it, returning the result if `T` was available.
1394
/// This will trigger the `Remove` and `Discard` component hooks without
1395
/// causing an archetype move.
1396
///
1397
/// This is most useful with immutable components, where removal and reinsertion
1398
/// is the only way to modify a value.
1399
///
1400
/// If you do not need to ensure the above hooks are triggered, and your component
1401
/// is mutable, prefer using [`get_mut`](World::get_mut).
1402
///
1403
/// # Examples
1404
///
1405
/// ```rust
1406
/// # use bevy_ecs::prelude::*;
1407
/// #
1408
/// #[derive(Component, PartialEq, Eq, Debug)]
1409
/// #[component(immutable)]
1410
/// struct Foo(bool);
1411
///
1412
/// # let mut world = World::default();
1413
/// # world.register_component::<Foo>();
1414
/// #
1415
/// # let entity = world.spawn(Foo(false)).id();
1416
/// #
1417
/// world.modify_component(entity, |foo: &mut Foo| {
1418
/// foo.0 = true;
1419
/// });
1420
/// #
1421
/// # assert_eq!(world.get::<Foo>(entity), Some(&Foo(true)));
1422
/// ```
1423
#[inline]
1424
#[track_caller]
1425
pub fn modify_component<T: Component, R>(
1426
&mut self,
1427
entity: Entity,
1428
f: impl FnOnce(&mut T) -> R,
1429
) -> Result<Option<R>, EntityMutableFetchError> {
1430
let mut world = DeferredWorld::from(&mut *self);
1431
1432
let result = world.modify_component_with_relationship_hook_mode(
1433
entity,
1434
RelationshipHookMode::Run,
1435
f,
1436
)?;
1437
1438
self.flush();
1439
Ok(result)
1440
}
1441
1442
/// Temporarily removes a [`Component`] identified by the provided
1443
/// [`ComponentId`] from the provided [`Entity`] and runs the provided
1444
/// closure on it, returning the result if the component was available.
1445
/// This will trigger the `Remove` and `Discard` component hooks without
1446
/// causing an archetype move.
1447
///
1448
/// This is most useful with immutable components, where removal and reinsertion
1449
/// is the only way to modify a value.
1450
///
1451
/// If you do not need to ensure the above hooks are triggered, and your component
1452
/// is mutable, prefer using [`get_mut_by_id`](World::get_mut_by_id).
1453
///
1454
/// You should prefer the typed [`modify_component`](World::modify_component)
1455
/// whenever possible.
1456
#[inline]
1457
#[track_caller]
1458
pub fn modify_component_by_id<R>(
1459
&mut self,
1460
entity: Entity,
1461
component_id: ComponentId,
1462
f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
1463
) -> Result<Option<R>, EntityMutableFetchError> {
1464
let mut world = DeferredWorld::from(&mut *self);
1465
1466
let result = world.modify_component_by_id_with_relationship_hook_mode(
1467
entity,
1468
component_id,
1469
RelationshipHookMode::Run,
1470
f,
1471
)?;
1472
1473
self.flush();
1474
Ok(result)
1475
}
1476
1477
/// Despawns the given [`Entity`], if it exists.
1478
/// This will also remove all of the entity's [`Components`](Component).
1479
///
1480
/// Returns `true` if the entity is successfully despawned and `false` if
1481
/// the entity does not exist.
1482
/// This counts despawning a not constructed entity as a success, and frees it to the allocator.
1483
/// See [entity](crate::entity) module docs for more about construction.
1484
///
1485
/// # Note
1486
///
1487
/// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1488
/// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1489
///
1490
/// ```
1491
/// use bevy_ecs::{component::Component, world::World};
1492
///
1493
/// #[derive(Component)]
1494
/// struct Position {
1495
/// x: f32,
1496
/// y: f32,
1497
/// }
1498
///
1499
/// let mut world = World::new();
1500
/// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1501
/// assert!(world.despawn(entity));
1502
/// assert!(world.get_entity(entity).is_err());
1503
/// assert!(world.get::<Position>(entity).is_none());
1504
/// ```
1505
#[track_caller]
1506
#[inline]
1507
pub fn despawn(&mut self, entity: Entity) -> bool {
1508
if let Err(error) = self.despawn_with_caller(entity, MaybeLocation::caller()) {
1509
warn!("{error}");
1510
false
1511
} else {
1512
true
1513
}
1514
}
1515
1516
/// Despawns the given `entity`, if it exists. This will also remove all of the entity's
1517
/// [`Components`](Component).
1518
///
1519
/// Returns an [`EntityDespawnError`] if the entity is not spawned to be despawned.
1520
///
1521
/// # Note
1522
///
1523
/// This will also despawn the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1524
/// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1525
#[track_caller]
1526
#[inline]
1527
pub fn try_despawn(&mut self, entity: Entity) -> Result<(), EntityDespawnError> {
1528
self.despawn_with_caller(entity, MaybeLocation::caller())
1529
}
1530
1531
#[inline]
1532
pub(crate) fn despawn_with_caller(
1533
&mut self,
1534
entity: Entity,
1535
caller: MaybeLocation,
1536
) -> Result<(), EntityDespawnError> {
1537
match self.get_entity_mut(entity) {
1538
Ok(entity) => {
1539
entity.despawn_with_caller(caller);
1540
Ok(())
1541
}
1542
// Only one entity.
1543
Err(EntityMutableFetchError::AliasedMutability(_)) => unreachable!(),
1544
Err(EntityMutableFetchError::NotSpawned(err)) => Err(EntityDespawnError(err)),
1545
}
1546
}
1547
1548
/// Performs [`try_despawn_no_free`](Self::try_despawn_no_free), warning on errors.
1549
/// See that method for more information.
1550
#[track_caller]
1551
#[inline]
1552
pub fn despawn_no_free(&mut self, entity: Entity) -> Option<Entity> {
1553
match self.despawn_no_free_with_caller(entity, MaybeLocation::caller()) {
1554
Ok(entity) => Some(entity),
1555
Err(error) => {
1556
warn!("{error}");
1557
None
1558
}
1559
}
1560
}
1561
1562
/// Despawns the given `entity`, if it exists.
1563
/// This will also remove all of the entity's [`Component`]s.
1564
///
1565
/// The *only* difference between this and [despawning](Self::despawn) an entity is that this does not release the `entity` to be reused.
1566
/// It is up to the caller to either re-spawn or free the `entity`; otherwise, the [`EntityIndex`](crate::entity::EntityIndex) will not be able to be reused.
1567
/// In general, [`despawn`](Self::despawn) should be used instead, which automatically allows the row to be reused.
1568
///
1569
/// Returns the new [`Entity`] if of the despawned [`EntityIndex`](crate::entity::EntityIndex), which should eventually either be re-spawned or freed to the allocator.
1570
/// Returns an [`EntityDespawnError`] if the entity is not spawned.
1571
///
1572
/// # Note
1573
///
1574
/// This will also *despawn* the entities in any [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1575
/// to despawn descendants. For example, this will recursively despawn [`Children`](crate::hierarchy::Children).
1576
///
1577
/// # Example
1578
///
1579
/// There is no simple example in which this would be practical, but one use for this is a custom entity allocator.
1580
/// Despawning internally calls this and frees the entity id to Bevy's default entity allocator.
1581
/// The same principal can be used to create custom allocators with additional properties.
1582
/// For example, this could be used to make an allocator that yields groups of consecutive [`EntityIndex`](crate::entity::EntityIndex)s, etc.
1583
/// See [`EntityAllocator::alloc`] for more on this.
1584
#[track_caller]
1585
#[inline]
1586
pub fn try_despawn_no_free(&mut self, entity: Entity) -> Result<Entity, EntityDespawnError> {
1587
self.despawn_no_free_with_caller(entity, MaybeLocation::caller())
1588
}
1589
1590
#[inline]
1591
pub(crate) fn despawn_no_free_with_caller(
1592
&mut self,
1593
entity: Entity,
1594
caller: MaybeLocation,
1595
) -> Result<Entity, EntityDespawnError> {
1596
let mut entity = self.get_entity_mut(entity).map_err(|err| match err {
1597
EntityMutableFetchError::NotSpawned(err) => err,
1598
// Only one entity.
1599
EntityMutableFetchError::AliasedMutability(_) => unreachable!(),
1600
})?;
1601
entity.despawn_no_free_with_caller(caller);
1602
Ok(entity.id())
1603
}
1604
1605
/// Clears the internal component tracker state.
1606
///
1607
/// The world maintains some internal state about changed and removed components. This state
1608
/// is used by [`RemovedComponents`] to provide access to the entities that had a specific type
1609
/// of component removed since last tick.
1610
///
1611
/// The state is also used for change detection when accessing components and resources outside
1612
/// of a system, for example via [`World::get_mut()`] or [`World::get_resource_mut()`].
1613
///
1614
/// By clearing this internal state, the world "forgets" about those changes, allowing a new round
1615
/// of detection to be recorded.
1616
///
1617
/// When using `bevy_ecs` as part of the full Bevy engine, this method is called automatically
1618
/// by `bevy_app::App::update` and `bevy_app::SubApp::update`, so you don't need to call it manually.
1619
/// When using `bevy_ecs` as a separate standalone crate however, you do need to call this manually.
1620
///
1621
/// ```
1622
/// # use bevy_ecs::prelude::*;
1623
/// # #[derive(Component, Default)]
1624
/// # struct Transform;
1625
/// // a whole new world
1626
/// let mut world = World::new();
1627
///
1628
/// // you changed it
1629
/// let entity = world.spawn(Transform::default()).id();
1630
///
1631
/// // change is detected
1632
/// let transform = world.get_mut::<Transform>(entity).unwrap();
1633
/// assert!(transform.is_changed());
1634
///
1635
/// // update the last change tick
1636
/// world.clear_trackers();
1637
///
1638
/// // change is no longer detected
1639
/// let transform = world.get_mut::<Transform>(entity).unwrap();
1640
/// assert!(!transform.is_changed());
1641
/// ```
1642
///
1643
/// [`RemovedComponents`]: crate::lifecycle::RemovedComponents
1644
pub fn clear_trackers(&mut self) {
1645
self.removed_components.update();
1646
self.last_change_tick = self.increment_change_tick();
1647
}
1648
1649
/// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1650
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
1651
/// ```
1652
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
1653
///
1654
/// #[derive(Component, Debug, PartialEq)]
1655
/// struct Position {
1656
/// x: f32,
1657
/// y: f32,
1658
/// }
1659
///
1660
/// #[derive(Component)]
1661
/// struct Velocity {
1662
/// x: f32,
1663
/// y: f32,
1664
/// }
1665
///
1666
/// let mut world = World::new();
1667
/// let entities = world.spawn_batch(vec![
1668
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
1669
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
1670
/// ]).collect::<Vec<Entity>>();
1671
///
1672
/// let mut query = world.query::<(&mut Position, &Velocity)>();
1673
/// for (mut position, velocity) in query.iter_mut(&mut world) {
1674
/// position.x += velocity.x;
1675
/// position.y += velocity.y;
1676
/// }
1677
///
1678
/// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
1679
/// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
1680
/// ```
1681
///
1682
/// To iterate over entities in a deterministic order,
1683
/// sort the results of the query using the desired component as a key.
1684
/// Note that this requires fetching the whole result set from the query
1685
/// and allocation of a [`Vec`] to store it.
1686
///
1687
/// ```
1688
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
1689
///
1690
/// #[derive(Component, PartialEq, Eq, PartialOrd, Ord, Debug)]
1691
/// struct Order(i32);
1692
/// #[derive(Component, PartialEq, Debug)]
1693
/// struct Label(&'static str);
1694
///
1695
/// let mut world = World::new();
1696
/// let a = world.spawn((Order(2), Label("second"))).id();
1697
/// let b = world.spawn((Order(3), Label("third"))).id();
1698
/// let c = world.spawn((Order(1), Label("first"))).id();
1699
/// let mut entities = world.query::<(Entity, &Order, &Label)>()
1700
/// .iter(&world)
1701
/// .collect::<Vec<_>>();
1702
/// // Sort the query results by their `Order` component before comparing
1703
/// // to expected results. Query iteration order should not be relied on.
1704
/// entities.sort_by_key(|e| e.1);
1705
/// assert_eq!(entities, vec![
1706
/// (c, &Order(1), &Label("first")),
1707
/// (a, &Order(2), &Label("second")),
1708
/// (b, &Order(3), &Label("third")),
1709
/// ]);
1710
/// ```
1711
#[inline]
1712
pub fn query<D: QueryData>(&mut self) -> QueryState<D, ()> {
1713
self.query_filtered::<D, ()>()
1714
}
1715
1716
/// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1717
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
1718
/// ```
1719
/// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1720
///
1721
/// #[derive(Component)]
1722
/// struct A;
1723
/// #[derive(Component)]
1724
/// struct B;
1725
///
1726
/// let mut world = World::new();
1727
/// let e1 = world.spawn(A).id();
1728
/// let e2 = world.spawn((A, B)).id();
1729
///
1730
/// let mut query = world.query_filtered::<Entity, With<B>>();
1731
/// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1732
///
1733
/// assert_eq!(matching_entities, vec![e2]);
1734
/// ```
1735
#[inline]
1736
pub fn query_filtered<D: QueryData, F: QueryFilter>(&mut self) -> QueryState<D, F> {
1737
QueryState::new(self)
1738
}
1739
1740
/// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1741
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
1742
/// ```
1743
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
1744
///
1745
/// #[derive(Component, Debug, PartialEq)]
1746
/// struct Position {
1747
/// x: f32,
1748
/// y: f32,
1749
/// }
1750
///
1751
/// let mut world = World::new();
1752
/// world.spawn_batch(vec![
1753
/// Position { x: 0.0, y: 0.0 },
1754
/// Position { x: 1.0, y: 1.0 },
1755
/// ]);
1756
///
1757
/// fn get_positions(world: &World) -> Vec<(Entity, &Position)> {
1758
/// let mut query = world.try_query::<(Entity, &Position)>().unwrap();
1759
/// query.iter(world).collect()
1760
/// }
1761
///
1762
/// let positions = get_positions(&world);
1763
///
1764
/// assert_eq!(world.get::<Position>(positions[0].0).unwrap(), positions[0].1);
1765
/// assert_eq!(world.get::<Position>(positions[1].0).unwrap(), positions[1].1);
1766
/// ```
1767
///
1768
/// Requires only an immutable world reference, but may fail if, for example,
1769
/// the components that make up this query have not been registered into the world.
1770
/// ```
1771
/// use bevy_ecs::{component::Component, entity::Entity, world::World};
1772
///
1773
/// #[derive(Component)]
1774
/// struct A;
1775
///
1776
/// let mut world = World::new();
1777
///
1778
/// let none_query = world.try_query::<&A>();
1779
/// assert!(none_query.is_none());
1780
///
1781
/// world.register_component::<A>();
1782
///
1783
/// let some_query = world.try_query::<&A>();
1784
/// assert!(some_query.is_some());
1785
/// ```
1786
#[inline]
1787
pub fn try_query<D: QueryData>(&self) -> Option<QueryState<D, ()>> {
1788
self.try_query_filtered::<D, ()>()
1789
}
1790
1791
/// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1792
/// run queries on the [`World`] by storing and reusing the [`QueryState`].
1793
/// ```
1794
/// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1795
///
1796
/// #[derive(Component)]
1797
/// struct A;
1798
/// #[derive(Component)]
1799
/// struct B;
1800
///
1801
/// let mut world = World::new();
1802
/// let e1 = world.spawn(A).id();
1803
/// let e2 = world.spawn((A, B)).id();
1804
///
1805
/// let mut query = world.try_query_filtered::<Entity, With<B>>().unwrap();
1806
/// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1807
///
1808
/// assert_eq!(matching_entities, vec![e2]);
1809
/// ```
1810
///
1811
/// Requires only an immutable world reference, but may fail if, for example,
1812
/// the components that make up this query have not been registered into the world.
1813
#[inline]
1814
pub fn try_query_filtered<D: QueryData, F: QueryFilter>(&self) -> Option<QueryState<D, F>> {
1815
QueryState::try_new(self)
1816
}
1817
1818
/// Returns an iterator of entities that had components of type `T` removed
1819
/// since the last call to [`World::clear_trackers`].
1820
pub fn removed<T: Component>(&self) -> impl Iterator<Item = Entity> + '_ {
1821
self.components
1822
.get_valid_id(TypeId::of::<T>())
1823
.map(|component_id| self.removed_with_id(component_id))
1824
.into_iter()
1825
.flatten()
1826
}
1827
1828
/// Returns an iterator of entities that had components with the given `component_id` removed
1829
/// since the last call to [`World::clear_trackers`].
1830
pub fn removed_with_id(&self, component_id: ComponentId) -> impl Iterator<Item = Entity> + '_ {
1831
self.removed_components
1832
.get(component_id)
1833
.map(|removed| removed.iter_current_update_messages().cloned())
1834
.into_iter()
1835
.flatten()
1836
.map(Into::into)
1837
}
1838
1839
/// Registers a new non-send resource type and returns the [`ComponentId`] created for it.
1840
///
1841
/// This enables the dynamic registration of new non-send resources definitions at runtime for
1842
/// advanced use cases.
1843
///
1844
/// # Note
1845
///
1846
/// Registering a non-send resource does not insert it into [`World`]. For insertion, you could use
1847
/// [`World::insert_non_send_by_id`].
1848
pub fn register_non_send_with_descriptor(
1849
&mut self,
1850
descriptor: ComponentDescriptor,
1851
) -> ComponentId {
1852
self.components_registrator()
1853
.register_component_with_descriptor(descriptor)
1854
}
1855
1856
fn insert_resource_if_not_exists_with_caller<R: Resource>(
1857
&mut self,
1858
func: impl FnOnce(&mut World) -> R,
1859
caller: MaybeLocation,
1860
) -> (ComponentId, EntityWorldMut<'_>) {
1861
let resource_id = self.register_resource::<R>();
1862
1863
if let Some(&entity) = self.resource_entities.get(resource_id) {
1864
let entity_ref = self.get_entity(entity).expect("ResourceCache is in sync");
1865
if !entity_ref.contains_id(resource_id) {
1866
let resource = func(self);
1867
move_as_ptr!(resource);
1868
self.entity_mut(entity).insert_with_caller(
1869
resource,
1870
InsertMode::Replace,
1871
caller,
1872
RelationshipHookMode::Run,
1873
);
1874
}
1875
return (resource_id, self.entity_mut(entity));
1876
}
1877
1878
let resource = func(self);
1879
move_as_ptr!(resource);
1880
let entity_mut = self.spawn_with_caller(resource, caller); // ResourceCache is updated automatically
1881
(resource_id, entity_mut)
1882
}
1883
1884
/// Initializes a new resource and returns the [`ComponentId`] created for it.
1885
///
1886
/// If the resource already exists, nothing happens.
1887
///
1888
/// The value given by the [`FromWorld::from_world`] method will be used.
1889
/// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
1890
/// and those default values will be here instead.
1891
#[inline]
1892
#[track_caller]
1893
pub fn init_resource<R: Resource + FromWorld>(&mut self) -> ComponentId {
1894
let caller = MaybeLocation::caller();
1895
self.insert_resource_if_not_exists_with_caller(R::from_world, caller)
1896
.0
1897
}
1898
1899
/// Inserts a new resource with the given `value`.
1900
///
1901
/// Resources are "unique" data of a given type.
1902
/// If you insert a resource of a type that already exists,
1903
/// you will overwrite any existing data.
1904
#[inline]
1905
#[track_caller]
1906
pub fn insert_resource<R: Resource>(&mut self, value: R) {
1907
self.insert_resource_with_caller(value, MaybeLocation::caller());
1908
}
1909
1910
/// Split into a new function so we can pass the calling location into the function when using
1911
/// as a command.
1912
#[inline]
1913
pub(crate) fn insert_resource_with_caller<R: Resource>(
1914
&mut self,
1915
value: R,
1916
caller: MaybeLocation,
1917
) {
1918
let component_id = self.components_registrator().register_component::<R>();
1919
OwningPtr::make(value, |ptr| {
1920
// SAFETY: component_id was just initialized and corresponds to resource of type R.
1921
unsafe {
1922
self.insert_resource_by_id(component_id, ptr, caller);
1923
}
1924
});
1925
}
1926
1927
/// Initializes a new non-send resource and returns the [`ComponentId`] created for it.
1928
#[deprecated(since = "0.19.0", note = "use World::init_non_send")]
1929
pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> ComponentId {
1930
self.init_non_send::<R>()
1931
}
1932
1933
/// Initializes new non-send data and returns the [`ComponentId`] created for it.
1934
///
1935
/// If the data already exists, nothing happens.
1936
///
1937
/// The value given by the [`FromWorld::from_world`] method will be used.
1938
/// Note that any non-send data with the `Default` trait automatically implements
1939
/// `FromWorld`, and those default values will be here instead.
1940
///
1941
/// # Panics
1942
///
1943
/// Panics if called from a thread other than the main thread.
1944
#[inline]
1945
#[track_caller]
1946
pub fn init_non_send<R: 'static + FromWorld>(&mut self) -> ComponentId {
1947
let caller = MaybeLocation::caller();
1948
let component_id = self.components_registrator().register_non_send::<R>();
1949
if self
1950
.storages
1951
.non_sends
1952
.get(component_id)
1953
.is_none_or(|data| !data.is_present())
1954
{
1955
let value = R::from_world(self);
1956
OwningPtr::make(value, |ptr| {
1957
// SAFETY: component_id was just initialized and corresponds to resource of type R.
1958
unsafe {
1959
self.insert_non_send_by_id(component_id, ptr, caller);
1960
}
1961
});
1962
}
1963
component_id
1964
}
1965
1966
/// Inserts a new non-send resource with the given `value`.
1967
#[deprecated(since = "0.19.0", note = "use World::insert_non_send")]
1968
pub fn insert_non_send_resource<R: 'static>(&mut self, value: R) {
1969
self.insert_non_send(value);
1970
}
1971
1972
/// Inserts new non-send data with the given `value`.
1973
///
1974
/// `NonSend` data cannot be sent across threads,
1975
/// and do not need the `Send + Sync` bounds.
1976
/// Systems with `NonSend` resources are always scheduled on the main thread.
1977
///
1978
/// # Panics
1979
/// If a value is already present, this function will panic if called
1980
/// from a different thread than where the original value was inserted from.
1981
#[inline]
1982
#[track_caller]
1983
pub fn insert_non_send<R: 'static>(&mut self, value: R) {
1984
let caller = MaybeLocation::caller();
1985
let component_id = self.components_registrator().register_non_send::<R>();
1986
OwningPtr::make(value, |ptr| {
1987
// SAFETY: component_id was just initialized and corresponds to the data of type R.
1988
unsafe {
1989
self.insert_non_send_by_id(component_id, ptr, caller);
1990
}
1991
});
1992
}
1993
1994
/// Removes the resource of a given type and returns it, if it exists. Otherwise returns `None`.
1995
#[inline]
1996
pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
1997
let resource_id = self.component_id::<R>()?;
1998
let entity = *self.resource_entities.get(resource_id)?;
1999
let value = self
2000
.get_entity_mut(entity)
2001
.expect("ResourceCache is in sync")
2002
.take::<R>()?;
2003
Some(value)
2004
}
2005
2006
/// Removes a `!Send` resource from the world and returns it, if present.
2007
#[deprecated(since = "0.19.0", note = "use World::remove_non_send")]
2008
pub fn remove_non_send_resource<R: 'static>(&mut self) -> Option<R> {
2009
self.remove_non_send::<R>()
2010
}
2011
2012
/// Removes `!Send` data from the world and returns it, if present.
2013
///
2014
/// `NonSend` resources cannot be sent across threads,
2015
/// and do not need the `Send + Sync` bounds.
2016
/// Systems with `NonSend` data are always scheduled on the main thread.
2017
///
2018
/// Returns `None` if a value was not previously present.
2019
///
2020
/// # Panics
2021
/// If a value is present, this function will panic if called from a different
2022
/// thread than where the value was inserted from.
2023
#[inline]
2024
pub fn remove_non_send<R: 'static>(&mut self) -> Option<R> {
2025
let component_id = self.components.get_valid_id(TypeId::of::<R>())?;
2026
let (ptr, _, _) = self.storages.non_sends.get_mut(component_id)?.remove()?;
2027
// SAFETY: `component_id` was gotten via looking up the `R` type
2028
unsafe { Some(ptr.read::<R>()) }
2029
}
2030
2031
/// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
2032
#[inline]
2033
pub fn contains_resource<R: Resource>(&self) -> bool {
2034
self.components
2035
.get_valid_id(TypeId::of::<R>())
2036
.is_some_and(|component_id| self.contains_resource_by_id(component_id))
2037
}
2038
2039
/// Returns `true` if a resource with provided `component_id` exists. Otherwise returns `false`.
2040
#[inline]
2041
pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool {
2042
if let Some(entity) = self.resource_entities.get(component_id)
2043
&& let Ok(entity_ref) = self.get_entity(*entity)
2044
{
2045
return entity_ref.contains_id(component_id);
2046
}
2047
false
2048
}
2049
2050
/// Returns `true` if `!Send` data of type `R` exists. Otherwise returns `false`.
2051
#[inline]
2052
pub fn contains_non_send<R: 'static>(&self) -> bool {
2053
self.components
2054
.get_valid_id(TypeId::of::<R>())
2055
.and_then(|component_id| self.storages.non_sends.get(component_id))
2056
.is_some_and(NonSendData::is_present)
2057
}
2058
2059
/// Returns `true` if `!Send` data with `component_id` exists. Otherwise returns `false`.
2060
#[inline]
2061
pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool {
2062
self.storages
2063
.non_sends
2064
.get(component_id)
2065
.is_some_and(NonSendData::is_present)
2066
}
2067
2068
/// Returns `true` if a resource of type `R` exists and was added since the world's
2069
/// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2070
///
2071
/// This means that:
2072
/// - When called from an exclusive system, this will check for additions since the system last ran.
2073
/// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2074
/// was called.
2075
pub fn is_resource_added<R: Resource>(&self) -> bool {
2076
self.components
2077
.get_valid_id(TypeId::of::<R>())
2078
.is_some_and(|component_id| self.is_resource_added_by_id(component_id))
2079
}
2080
2081
/// Returns `true` if a resource with id `component_id` exists and was added since the world's
2082
/// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2083
///
2084
/// This means that:
2085
/// - When called from an exclusive system, this will check for additions since the system last ran.
2086
/// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
2087
/// was called.
2088
pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool {
2089
self.get_resource_change_ticks_by_id(component_id)
2090
.is_some_and(|ticks| ticks.is_added(self.last_change_tick(), self.read_change_tick()))
2091
}
2092
2093
/// Returns `true` if a resource of type `R` exists and was modified since the world's
2094
/// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2095
///
2096
/// This means that:
2097
/// - When called from an exclusive system, this will check for changes since the system last ran.
2098
/// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2099
/// was called.
2100
pub fn is_resource_changed<R: Resource>(&self) -> bool {
2101
self.components
2102
.get_valid_id(TypeId::of::<R>())
2103
.is_some_and(|component_id| self.is_resource_changed_by_id(component_id))
2104
}
2105
2106
/// Returns `true` if a resource with id `component_id` exists and was modified since the world's
2107
/// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
2108
///
2109
/// This means that:
2110
/// - When called from an exclusive system, this will check for changes since the system last ran.
2111
/// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
2112
/// was called.
2113
pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool {
2114
self.get_resource_change_ticks_by_id(component_id)
2115
.is_some_and(|ticks| ticks.is_changed(self.last_change_tick(), self.read_change_tick()))
2116
}
2117
2118
/// Retrieves the change ticks for the given resource.
2119
pub fn get_resource_change_ticks<R: Resource>(&self) -> Option<ComponentTicks> {
2120
self.components
2121
.get_valid_id(TypeId::of::<R>())
2122
.and_then(|component_id| self.get_resource_change_ticks_by_id(component_id))
2123
}
2124
2125
/// Retrieves the change ticks for the given [`ComponentId`].
2126
///
2127
/// **You should prefer to use the typed API [`World::get_resource_change_ticks`] where possible.**
2128
pub fn get_resource_change_ticks_by_id(
2129
&self,
2130
component_id: ComponentId,
2131
) -> Option<ComponentTicks> {
2132
let entity = self.resource_entities.get(component_id)?;
2133
let entity_ref = self.get_entity(*entity).ok()?;
2134
entity_ref.get_change_ticks_by_id(component_id)
2135
}
2136
2137
/// Gets a reference to the resource of the given type
2138
///
2139
/// # Panics
2140
///
2141
/// Panics if the resource does not exist.
2142
/// Use [`get_resource`](World::get_resource) instead if you want to handle this case.
2143
///
2144
/// If you want to instead insert a value if the resource does not exist,
2145
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2146
#[inline]
2147
#[track_caller]
2148
pub fn resource<R: Resource>(&self) -> &R {
2149
match self.get_resource() {
2150
Some(x) => x,
2151
None => panic!(
2152
"Requested resource {} does not exist in the `World`.
2153
Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2154
Resources are also implicitly added via `app.add_message`,
2155
and can be added by plugins.",
2156
DebugName::type_name::<R>()
2157
),
2158
}
2159
}
2160
2161
/// Gets a reference to the resource of the given type
2162
///
2163
/// # Panics
2164
///
2165
/// Panics if the resource does not exist.
2166
/// Use [`get_resource_ref`](World::get_resource_ref) instead if you want to handle this case.
2167
///
2168
/// If you want to instead insert a value if the resource does not exist,
2169
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2170
#[inline]
2171
#[track_caller]
2172
pub fn resource_ref<R: Resource>(&self) -> Ref<'_, R> {
2173
match self.get_resource_ref() {
2174
Some(x) => x,
2175
None => panic!(
2176
"Requested resource {} does not exist in the `World`.
2177
Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2178
Resources are also implicitly added via `app.add_message`,
2179
and can be added by plugins.",
2180
DebugName::type_name::<R>()
2181
),
2182
}
2183
}
2184
2185
/// Gets a mutable reference to the resource of the given type
2186
///
2187
/// # Panics
2188
///
2189
/// Panics if the resource does not exist.
2190
/// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
2191
///
2192
/// If you want to instead insert a value if the resource does not exist,
2193
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
2194
#[inline]
2195
#[track_caller]
2196
pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
2197
match self.get_resource_mut() {
2198
Some(x) => x,
2199
None => panic!(
2200
"Requested resource {} does not exist in the `World`.
2201
Did you forget to add it using `app.insert_resource` / `app.init_resource`?
2202
Resources are also implicitly added via `app.add_message`,
2203
and can be added by plugins.",
2204
DebugName::type_name::<R>()
2205
),
2206
}
2207
}
2208
2209
/// Gets a reference to the resource of the given type if it exists
2210
#[inline]
2211
pub fn get_resource<R: Resource>(&self) -> Option<&R> {
2212
// SAFETY:
2213
// - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2214
// - `&self` ensures nothing in world is borrowed mutably
2215
unsafe { self.as_unsafe_world_cell_readonly().get_resource() }
2216
}
2217
2218
/// Gets a reference including change detection to the resource of the given type if it exists.
2219
#[inline]
2220
pub fn get_resource_ref<R: Resource>(&self) -> Option<Ref<'_, R>> {
2221
// SAFETY:
2222
// - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
2223
// - `&self` ensures nothing in world is borrowed mutably
2224
unsafe { self.as_unsafe_world_cell_readonly().get_resource_ref() }
2225
}
2226
2227
/// Gets a mutable reference to the resource of the given type if it exists
2228
#[inline]
2229
pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
2230
// SAFETY:
2231
// - `as_unsafe_world_cell` gives permission to access everything mutably
2232
// - `&mut self` ensures nothing in world is borrowed
2233
unsafe { self.as_unsafe_world_cell().get_resource_mut() }
2234
}
2235
2236
/// Gets a mutable reference to the resource of type `T` if it exists,
2237
/// otherwise inserts the resource using the result of calling `func`.
2238
///
2239
/// # Example
2240
///
2241
/// ```
2242
/// # use bevy_ecs::prelude::*;
2243
/// #
2244
/// #[derive(Resource)]
2245
/// struct MyResource(i32);
2246
///
2247
/// # let mut world = World::new();
2248
/// let my_res = world.get_resource_or_insert_with(|| MyResource(10));
2249
/// assert_eq!(my_res.0, 10);
2250
/// ```
2251
#[inline]
2252
#[track_caller]
2253
pub fn get_resource_or_insert_with<R: Resource>(
2254
&mut self,
2255
func: impl FnOnce() -> R,
2256
) -> Mut<'_, R> {
2257
let caller = MaybeLocation::caller();
2258
let (resource_id, entity) =
2259
self.insert_resource_if_not_exists_with_caller(|_world: &mut World| func(), caller);
2260
let untyped = entity
2261
.into_mut_by_id(resource_id)
2262
.expect("Resource must exist");
2263
// SAFETY: resource is of type R
2264
unsafe { untyped.with_type() }
2265
}
2266
2267
/// Gets a mutable reference to the resource of type `T` if it exists,
2268
/// otherwise initializes the resource by calling its [`FromWorld`]
2269
/// implementation.
2270
///
2271
/// # Example
2272
///
2273
/// ```
2274
/// # use bevy_ecs::prelude::*;
2275
/// #
2276
/// #[derive(Resource)]
2277
/// struct Foo(i32);
2278
///
2279
/// impl Default for Foo {
2280
/// fn default() -> Self {
2281
/// Self(15)
2282
/// }
2283
/// }
2284
///
2285
/// #[derive(Resource)]
2286
/// struct MyResource(i32);
2287
///
2288
/// impl FromWorld for MyResource {
2289
/// fn from_world(world: &mut World) -> Self {
2290
/// let foo = world.get_resource_or_init::<Foo>();
2291
/// Self(foo.0 * 2)
2292
/// }
2293
/// }
2294
///
2295
/// # let mut world = World::new();
2296
/// let my_res = world.get_resource_or_init::<MyResource>();
2297
/// assert_eq!(my_res.0, 30);
2298
/// ```
2299
#[track_caller]
2300
pub fn get_resource_or_init<R: Resource + FromWorld>(&mut self) -> Mut<'_, R> {
2301
let caller = MaybeLocation::caller();
2302
let (resource_id, entity) =
2303
self.insert_resource_if_not_exists_with_caller(R::from_world, caller);
2304
let untyped = entity
2305
.into_mut_by_id(resource_id)
2306
.expect("Resource must exist");
2307
// SAFETY: resource is of type R
2308
unsafe { untyped.with_type() }
2309
}
2310
2311
/// Gets an immutable reference to a non-send resource of the given type, if it exists.
2312
#[deprecated(since = "0.19.0", note = "use World::non_send")]
2313
pub fn non_send_resource<R: 'static>(&self) -> &R {
2314
self.non_send::<R>()
2315
}
2316
2317
/// Gets an immutable reference to the non-send data of the given type, if it exists.
2318
///
2319
/// # Panics
2320
///
2321
/// Panics if the data does not exist.
2322
/// Use [`get_non_send`](World::get_non_send) instead if you want to handle this case.
2323
///
2324
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
2325
#[inline]
2326
#[track_caller]
2327
pub fn non_send<R: 'static>(&self) -> &R {
2328
match self.get_non_send() {
2329
Some(x) => x,
2330
None => panic!(
2331
"Requested non-send resource {} does not exist in the `World`.
2332
Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2333
Non-send resources can also be added by plugins.",
2334
DebugName::type_name::<R>()
2335
),
2336
}
2337
}
2338
2339
/// Gets a mutable reference to a non-send resource of the given type, if it exists.
2340
#[deprecated(since = "0.19.0", note = "use World::non_send_mut")]
2341
pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2342
self.non_send_mut::<R>()
2343
}
2344
2345
/// Gets a mutable reference to the non-send data of the given type, if it exists.
2346
///
2347
/// # Panics
2348
///
2349
/// Panics if the data does not exist.
2350
/// Use [`get_non_send_mut`](World::get_non_send_mut) instead if you want to handle this case.
2351
///
2352
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
2353
#[inline]
2354
#[track_caller]
2355
pub fn non_send_mut<R: 'static>(&mut self) -> Mut<'_, R> {
2356
match self.get_non_send_mut() {
2357
Some(x) => x,
2358
None => panic!(
2359
"Requested non-send resource {} does not exist in the `World`.
2360
Did you forget to add it using `app.insert_non_send` / `app.init_non_send`?
2361
Non-send resources can also be added by plugins.",
2362
DebugName::type_name::<R>()
2363
),
2364
}
2365
}
2366
2367
/// Gets a reference to a non-send resource of the given type, if it exists.
2368
/// Otherwise returns `None`.
2369
#[deprecated(since = "0.19.0", note = "use World::get_non_send")]
2370
pub fn get_non_send_resource<R: 'static>(&self) -> Option<&R> {
2371
self.get_non_send::<R>()
2372
}
2373
2374
/// Gets a reference to the non-send data of the given type, if it exists.
2375
/// Otherwise returns `None`.
2376
///
2377
/// # Panics
2378
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
2379
#[inline]
2380
pub fn get_non_send<R: 'static>(&self) -> Option<&R> {
2381
// SAFETY:
2382
// - `as_unsafe_world_cell_readonly` gives permission to access the entire world immutably
2383
// - `&self` ensures that there are no mutable borrows of world data
2384
unsafe { self.as_unsafe_world_cell_readonly().get_non_send() }
2385
}
2386
2387
/// Gets a mutable reference to a non-send resource of the given type, if it exists.
2388
/// Otherwise returns `None`.
2389
#[deprecated(since = "0.19.0", note = "use World::get_non_send_mut")]
2390
pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2391
self.get_non_send_mut::<R>()
2392
}
2393
2394
/// Gets a mutable reference to the non-send data of the given type, if it exists.
2395
/// Otherwise returns `None`.
2396
///
2397
/// # Panics
2398
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
2399
#[inline]
2400
pub fn get_non_send_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
2401
// SAFETY:
2402
// - `as_unsafe_world_cell` gives permission to access the entire world mutably
2403
// - `&mut self` ensures that there are no borrows of world data
2404
unsafe { self.as_unsafe_world_cell().get_non_send_mut() }
2405
}
2406
2407
/// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2408
/// adds the `Bundle` of components to each `Entity`.
2409
/// This is faster than doing equivalent operations one-by-one.
2410
///
2411
/// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2412
/// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2413
///
2414
/// This will overwrite any previous values of components shared by the `Bundle`.
2415
/// See [`World::insert_batch_if_new`] to keep the old values instead.
2416
///
2417
/// # Panics
2418
///
2419
/// This function will panic if any of the associated entities do not exist.
2420
///
2421
/// For the fallible version, see [`World::try_insert_batch`].
2422
#[track_caller]
2423
pub fn insert_batch<I, B>(&mut self, batch: I)
2424
where
2425
I: IntoIterator,
2426
I::IntoIter: Iterator<Item = (Entity, B)>,
2427
B: Bundle<Effect: NoBundleEffect>,
2428
{
2429
self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller());
2430
}
2431
2432
/// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2433
/// adds the `Bundle` of components to each `Entity` without overwriting.
2434
/// This is faster than doing equivalent operations one-by-one.
2435
///
2436
/// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2437
/// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2438
///
2439
/// This is the same as [`World::insert_batch`], but in case of duplicate
2440
/// components it will leave the old values instead of replacing them with new ones.
2441
///
2442
/// # Panics
2443
///
2444
/// This function will panic if any of the associated entities do not exist.
2445
///
2446
/// For the fallible version, see [`World::try_insert_batch_if_new`].
2447
#[track_caller]
2448
pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
2449
where
2450
I: IntoIterator,
2451
I::IntoIter: Iterator<Item = (Entity, B)>,
2452
B: Bundle<Effect: NoBundleEffect>,
2453
{
2454
self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller());
2455
}
2456
2457
/// Split into a new function so we can differentiate the calling location.
2458
///
2459
/// This can be called by:
2460
/// - [`World::insert_batch`]
2461
/// - [`World::insert_batch_if_new`]
2462
#[inline]
2463
pub(crate) fn insert_batch_with_caller<I, B>(
2464
&mut self,
2465
batch: I,
2466
insert_mode: InsertMode,
2467
caller: MaybeLocation,
2468
) where
2469
I: IntoIterator,
2470
I::IntoIter: Iterator<Item = (Entity, B)>,
2471
B: Bundle<Effect: NoBundleEffect>,
2472
{
2473
struct InserterArchetypeCache<'w> {
2474
inserter: BundleInserter<'w>,
2475
archetype_id: ArchetypeId,
2476
}
2477
2478
let change_tick = self.change_tick();
2479
let bundle_id = self.register_bundle_info::<B>();
2480
2481
let mut batch_iter = batch.into_iter();
2482
2483
if let Some((first_entity, first_bundle)) = batch_iter.next() {
2484
match self.entities().get_spawned(first_entity) {
2485
Err(err) => {
2486
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {first_entity} because: {err}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>());
2487
}
2488
Ok(first_location) => {
2489
let mut cache = InserterArchetypeCache {
2490
// SAFETY: we initialized this bundle_id in `register_info`
2491
inserter: unsafe {
2492
BundleInserter::new_with_id(
2493
self,
2494
first_location.archetype_id,
2495
bundle_id,
2496
change_tick,
2497
)
2498
},
2499
archetype_id: first_location.archetype_id,
2500
};
2501
move_as_ptr!(first_bundle);
2502
// SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2503
unsafe {
2504
cache.inserter.insert(
2505
first_entity,
2506
first_location,
2507
first_bundle,
2508
insert_mode,
2509
caller,
2510
RelationshipHookMode::Run,
2511
)
2512
};
2513
2514
for (entity, bundle) in batch_iter {
2515
match cache.inserter.entities().get_spawned(entity) {
2516
Ok(location) => {
2517
if location.archetype_id != cache.archetype_id {
2518
cache = InserterArchetypeCache {
2519
// SAFETY: we initialized this bundle_id in `register_info`
2520
inserter: unsafe {
2521
BundleInserter::new_with_id(
2522
self,
2523
location.archetype_id,
2524
bundle_id,
2525
change_tick,
2526
)
2527
},
2528
archetype_id: location.archetype_id,
2529
}
2530
}
2531
move_as_ptr!(bundle);
2532
// SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2533
unsafe {
2534
cache.inserter.insert(
2535
entity,
2536
location,
2537
bundle,
2538
insert_mode,
2539
caller,
2540
RelationshipHookMode::Run,
2541
)
2542
};
2543
}
2544
Err(err) => {
2545
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {entity} because: {err}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>());
2546
}
2547
}
2548
}
2549
}
2550
}
2551
}
2552
}
2553
2554
/// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2555
/// adds the `Bundle` of components to each `Entity`.
2556
/// This is faster than doing equivalent operations one-by-one.
2557
///
2558
/// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2559
/// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2560
///
2561
/// This will overwrite any previous values of components shared by the `Bundle`.
2562
/// See [`World::try_insert_batch_if_new`] to keep the old values instead.
2563
///
2564
/// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2565
///
2566
/// For the panicking version, see [`World::insert_batch`].
2567
#[track_caller]
2568
pub fn try_insert_batch<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2569
where
2570
I: IntoIterator,
2571
I::IntoIter: Iterator<Item = (Entity, B)>,
2572
B: Bundle<Effect: NoBundleEffect>,
2573
{
2574
self.try_insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller())
2575
}
2576
/// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2577
/// adds the `Bundle` of components to each `Entity` without overwriting.
2578
/// This is faster than doing equivalent operations one-by-one.
2579
///
2580
/// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2581
/// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2582
///
2583
/// This is the same as [`World::try_insert_batch`], but in case of duplicate
2584
/// components it will leave the old values instead of replacing them with new ones.
2585
///
2586
/// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2587
///
2588
/// For the panicking version, see [`World::insert_batch_if_new`].
2589
#[track_caller]
2590
pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2591
where
2592
I: IntoIterator,
2593
I::IntoIter: Iterator<Item = (Entity, B)>,
2594
B: Bundle<Effect: NoBundleEffect>,
2595
{
2596
self.try_insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller())
2597
}
2598
2599
/// Split into a new function so we can differentiate the calling location.
2600
///
2601
/// This can be called by:
2602
/// - [`World::try_insert_batch`]
2603
/// - [`World::try_insert_batch_if_new`]
2604
/// - [`Commands::insert_batch`]
2605
/// - [`Commands::insert_batch_if_new`]
2606
/// - [`Commands::try_insert_batch`]
2607
/// - [`Commands::try_insert_batch_if_new`]
2608
#[inline]
2609
pub(crate) fn try_insert_batch_with_caller<I, B>(
2610
&mut self,
2611
batch: I,
2612
insert_mode: InsertMode,
2613
caller: MaybeLocation,
2614
) -> Result<(), TryInsertBatchError>
2615
where
2616
I: IntoIterator,
2617
I::IntoIter: Iterator<Item = (Entity, B)>,
2618
B: Bundle<Effect: NoBundleEffect>,
2619
{
2620
struct InserterArchetypeCache<'w> {
2621
inserter: BundleInserter<'w>,
2622
archetype_id: ArchetypeId,
2623
}
2624
2625
let change_tick = self.change_tick();
2626
let bundle_id = self.register_bundle_info::<B>();
2627
2628
let mut invalid_entities = Vec::<Entity>::new();
2629
let mut batch_iter = batch.into_iter();
2630
2631
// We need to find the first valid entity so we can initialize the bundle inserter.
2632
// This differs from `insert_batch_with_caller` because that method can just panic
2633
// if the first entity is invalid, whereas this method needs to keep going.
2634
let cache = loop {
2635
if let Some((first_entity, first_bundle)) = batch_iter.next() {
2636
if let Ok(first_location) = self.entities().get_spawned(first_entity) {
2637
let mut cache = InserterArchetypeCache {
2638
// SAFETY: we initialized this bundle_id in `register_bundle_info`
2639
inserter: unsafe {
2640
BundleInserter::new_with_id(
2641
self,
2642
first_location.archetype_id,
2643
bundle_id,
2644
change_tick,
2645
)
2646
},
2647
archetype_id: first_location.archetype_id,
2648
};
2649
2650
move_as_ptr!(first_bundle);
2651
// SAFETY:
2652
// - `entity` is valid, `location` matches entity, bundle matches inserter
2653
// - `apply_effect` is never called on this bundle.
2654
// - `first_bundle` is not be accessed or dropped after this.
2655
unsafe {
2656
cache.inserter.insert(
2657
first_entity,
2658
first_location,
2659
first_bundle,
2660
insert_mode,
2661
caller,
2662
RelationshipHookMode::Run,
2663
)
2664
};
2665
break Some(cache);
2666
}
2667
invalid_entities.push(first_entity);
2668
} else {
2669
// We reached the end of the entities the caller provided and none were valid.
2670
break None;
2671
}
2672
};
2673
2674
if let Some(mut cache) = cache {
2675
for (entity, bundle) in batch_iter {
2676
if let Ok(location) = cache.inserter.entities().get_spawned(entity) {
2677
if location.archetype_id != cache.archetype_id {
2678
cache = InserterArchetypeCache {
2679
// SAFETY: we initialized this bundle_id in `register_info`
2680
inserter: unsafe {
2681
BundleInserter::new_with_id(
2682
self,
2683
location.archetype_id,
2684
bundle_id,
2685
change_tick,
2686
)
2687
},
2688
archetype_id: location.archetype_id,
2689
}
2690
}
2691
2692
move_as_ptr!(bundle);
2693
// SAFETY:
2694
// - `entity` is valid, `location` matches entity, bundle matches inserter
2695
// - `apply_effect` is never called on this bundle.
2696
// - `bundle` is not be accessed or dropped after this.
2697
unsafe {
2698
cache.inserter.insert(
2699
entity,
2700
location,
2701
bundle,
2702
insert_mode,
2703
caller,
2704
RelationshipHookMode::Run,
2705
)
2706
};
2707
} else {
2708
invalid_entities.push(entity);
2709
}
2710
}
2711
}
2712
2713
if invalid_entities.is_empty() {
2714
Ok(())
2715
} else {
2716
Err(TryInsertBatchError {
2717
bundle_type: DebugName::type_name::<B>(),
2718
entities: invalid_entities,
2719
})
2720
}
2721
}
2722
2723
/// Temporarily removes the requested resource from this [`World`], runs custom user code,
2724
/// then re-adds the resource before returning.
2725
///
2726
/// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2727
/// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2728
///
2729
/// # Panics
2730
///
2731
/// Panics if the resource does not exist.
2732
/// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
2733
///
2734
/// # Example
2735
/// ```
2736
/// use bevy_ecs::prelude::*;
2737
/// #[derive(Resource)]
2738
/// struct A(u32);
2739
/// #[derive(Component)]
2740
/// struct B(u32);
2741
/// let mut world = World::new();
2742
/// world.insert_resource(A(1));
2743
/// let entity = world.spawn(B(1)).id();
2744
///
2745
/// world.resource_scope(|world, mut a: Mut<A>| {
2746
/// let b = world.get_mut::<B>(entity).unwrap();
2747
/// a.0 += b.0;
2748
/// });
2749
/// assert_eq!(world.get_resource::<A>().unwrap().0, 2);
2750
/// ```
2751
///
2752
/// # Note
2753
///
2754
/// If the world's resource metadata is cleared within the scope, such as by calling
2755
/// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2756
/// at the end of the scope.
2757
#[track_caller]
2758
pub fn resource_scope<R: Resource, U>(&mut self, f: impl FnOnce(&mut World, Mut<R>) -> U) -> U {
2759
self.try_resource_scope(f)
2760
.unwrap_or_else(|| panic!("resource does not exist: {}", DebugName::type_name::<R>()))
2761
}
2762
2763
/// Temporarily removes the requested resource from this [`World`] if it exists, runs custom user code,
2764
/// then re-adds the resource before returning. Returns `None` if the resource does not exist in this [`World`].
2765
///
2766
/// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2767
/// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2768
///
2769
/// See also [`resource_scope`](Self::resource_scope).
2770
///
2771
/// # Note
2772
///
2773
/// If the world's resource metadata is cleared within the scope, such as by calling
2774
/// [`World::clear_resources`] or [`World::clear_all`], the resource will *not* be re-inserted
2775
/// at the end of the scope.
2776
pub fn try_resource_scope<R: Resource, U>(
2777
&mut self,
2778
f: impl FnOnce(&mut World, Mut<R>) -> U,
2779
) -> Option<U> {
2780
let last_change_tick = self.last_change_tick();
2781
let change_tick = self.change_tick();
2782
2783
let component_id = self.components.valid_component_id::<R>()?;
2784
let entity = *self.resource_entities.get(component_id)?;
2785
let mut entity_mut = self.get_entity_mut(entity).ok()?;
2786
2787
let mut ticks = entity_mut.get_change_ticks::<R>()?;
2788
let mut changed_by = entity_mut.get_changed_by::<R>()?;
2789
let value = entity_mut.take::<R>()?;
2790
2791
// type used to manage reinserting the resource at the end of the scope. use of a drop impl means that
2792
// the resource is inserted even if the user-provided closure unwinds.
2793
// this facilitates localized panic recovery and makes app shutdown in response to a panic more graceful
2794
// by avoiding knock-on errors.
2795
struct ReinsertGuard<'a, R: Resource> {
2796
world: &'a mut World,
2797
entity: Entity,
2798
component_id: ComponentId,
2799
value: ManuallyDrop<R>,
2800
ticks: ComponentTicks,
2801
caller: MaybeLocation,
2802
}
2803
impl<R: Resource> Drop for ReinsertGuard<'_, R> {
2804
fn drop(&mut self) {
2805
// take ownership of the value first so it'll get dropped if we return early
2806
// SAFETY: drop semantics ensure that `self.value` will never be accessed again after this call
2807
let value = unsafe { ManuallyDrop::take(&mut self.value) };
2808
2809
let Ok(mut entity_mut) = self.world.get_entity_mut(self.entity) else {
2810
return;
2811
};
2812
2813
// in debug mode, raise a panic if user code re-inserted a resource of this type within the scope.
2814
// resource insertion usually indicates a logic error in user code, which is useful to catch at dev time,
2815
// however it does not inherently lead to corrupted state, so we avoid introducing an unnecessary crash
2816
// for production builds.
2817
if entity_mut.contains_id(self.component_id) {
2818
#[cfg(debug_assertions)]
2819
{
2820
// if we're already panicking, log an error instead of panicking, as double-panics result in an abort
2821
#[cfg(feature = "std")]
2822
if std::thread::panicking() {
2823
log::error!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2824
In release builds, the value inserted will be overwritten at the end of the scope.",
2825
DebugName::type_name::<R>());
2826
// return early to maintain consistent behavior with non-panicking calls in debug builds
2827
return;
2828
}
2829
2830
panic!("Resource `{}` was inserted during a call to World::resource_scope, which may result in unexpected behavior.\n\
2831
In release builds, the value inserted will be overwritten at the end of the scope.",
2832
DebugName::type_name::<R>());
2833
}
2834
#[cfg(not(debug_assertions))]
2835
{
2836
#[cold]
2837
#[inline(never)]
2838
fn warn_reinsert(resource_name: &str) {
2839
warn!(
2840
"Resource `{resource_name}` was inserted during a call to World::resource_scope: the inserted value will be overwritten.",
2841
);
2842
}
2843
2844
warn_reinsert(&DebugName::type_name::<R>());
2845
}
2846
}
2847
2848
move_as_ptr!(value);
2849
2850
// See EntityWorldMut::insert_with_caller for the original code.
2851
// This is copied here to update the change ticks. This way we can ensure that the commands
2852
// ran during self.flush(), interact with the correct ticks on the resource component.
2853
{
2854
let location = entity_mut.location();
2855
let mut bundle_inserter = BundleInserter::new::<R>(
2856
// SAFETY: We update the entity location like in EntityWorldMut::insert_with_caller
2857
unsafe { entity_mut.world_mut() },
2858
location.archetype_id,
2859
self.ticks.changed,
2860
);
2861
// SAFETY:
2862
// - `location` matches current entity and thus must currently exist in the source
2863
// archetype for this inserter and its location within the archetype.
2864
// - `T` matches the type used to create the `BundleInserter`.
2865
// - `apply_effect` is called exactly once after this function.
2866
// - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
2867
// and the caller ensures that the value is not accessed or dropped after this function
2868
// returns.
2869
let (bundle, _) = value.partial_move(|bundle| unsafe {
2870
bundle_inserter.insert(
2871
self.entity,
2872
location,
2873
bundle,
2874
InsertMode::Replace,
2875
self.caller,
2876
RelationshipHookMode::Run,
2877
)
2878
});
2879
entity_mut.update_location();
2880
2881
// Set the added tick to the original.
2882
entity_mut
2883
.get_mut::<R>()
2884
.unwrap()
2885
.set_last_added(self.ticks.added);
2886
2887
// SAFETY: We update the entity location afterwards.
2888
unsafe { entity_mut.world_mut() }.flush();
2889
2890
entity_mut.update_location();
2891
// SAFETY:
2892
// - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
2893
// - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
2894
unsafe { R::apply_effect(bundle, &mut entity_mut) };
2895
}
2896
}
2897
}
2898
2899
let mut guard = ReinsertGuard {
2900
world: self,
2901
entity,
2902
component_id,
2903
value: ManuallyDrop::new(value),
2904
ticks,
2905
caller: changed_by,
2906
};
2907
2908
let value_mut = Mut {
2909
value: &mut *guard.value,
2910
ticks: ComponentTicksMut {
2911
added: &mut ticks.added,
2912
changed: &mut ticks.changed,
2913
changed_by: changed_by.as_mut(),
2914
last_run: last_change_tick,
2915
this_run: change_tick,
2916
},
2917
};
2918
2919
let result = f(guard.world, value_mut);
2920
2921
Some(result)
2922
}
2923
2924
/// Writes a [`Message`].
2925
/// This method returns the [`MessageId`] of the written `message`,
2926
/// or [`None`] if the `message` could not be written.
2927
#[inline]
2928
pub fn write_message<M: Message>(&mut self, message: M) -> Option<MessageId<M>> {
2929
self.write_message_batch(core::iter::once(message))?.next()
2930
}
2931
2932
/// Writes the default value of the [`Message`] of type `M`.
2933
/// This method returns the [`MessageId`] of the written message,
2934
/// or [`None`] if the `event` could not be written.
2935
#[inline]
2936
pub fn write_message_default<M: Message + Default>(&mut self) -> Option<MessageId<M>> {
2937
self.write_message(M::default())
2938
}
2939
2940
/// Writes a batch of [`Message`]s from an iterator.
2941
/// This method returns the [IDs](`MessageId`) of the written `messages`,
2942
/// or [`None`] if the `events` could not be written.
2943
#[inline]
2944
pub fn write_message_batch<M: Message>(
2945
&mut self,
2946
messages: impl IntoIterator<Item = M>,
2947
) -> Option<WriteBatchIds<M>> {
2948
let Some(mut events_resource) = self.get_resource_mut::<Messages<M>>() else {
2949
log::error!(
2950
"Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_message ",
2951
DebugName::type_name::<M>()
2952
);
2953
return None;
2954
};
2955
Some(events_resource.write_batch(messages))
2956
}
2957
2958
/// Inserts a new resource with the given `value`. Will replace the value if it already existed.
2959
///
2960
/// **You should prefer to use the typed API [`World::insert_resource`] where possible and only
2961
/// use this in cases where the actual types are not known at compile time.**
2962
///
2963
/// # Safety
2964
/// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
2965
#[inline]
2966
#[track_caller]
2967
pub unsafe fn insert_resource_by_id(
2968
&mut self,
2969
component_id: ComponentId,
2970
value: OwningPtr<'_>,
2971
caller: MaybeLocation,
2972
) {
2973
// if the resource already exists, we replace it on the same entity
2974
let mut entity_mut = if let Some(entity) = self.resource_entities.get(component_id) {
2975
self.get_entity_mut(*entity)
2976
.expect("ResourceCache is in sync")
2977
} else {
2978
self.spawn_empty()
2979
};
2980
entity_mut.insert_by_id_with_caller(
2981
component_id,
2982
value,
2983
InsertMode::Replace,
2984
caller,
2985
RelationshipHookMode::Run,
2986
);
2987
}
2988
2989
/// Inserts new `!Send` data with the given `value`. Will replace the value if it already
2990
/// existed.
2991
///
2992
/// **You should prefer to use the typed API [`World::insert_non_send`] where possible and only
2993
/// use this in cases where the actual types are not known at compile time.**
2994
///
2995
/// # Panics
2996
/// If a value is already present, this function will panic if not called from the same
2997
/// thread that the original value was inserted from.
2998
///
2999
/// # Safety
3000
/// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
3001
#[inline]
3002
#[track_caller]
3003
pub unsafe fn insert_non_send_by_id(
3004
&mut self,
3005
component_id: ComponentId,
3006
value: OwningPtr<'_>,
3007
caller: MaybeLocation,
3008
) {
3009
let change_tick = self.change_tick();
3010
3011
let resource = self.initialize_non_send_internal(component_id);
3012
// SAFETY: `value` is valid for `component_id`, ensured by caller
3013
unsafe {
3014
resource.insert(value, change_tick, caller);
3015
}
3016
}
3017
3018
/// # Panics
3019
/// Panics if `component_id` is not registered in this world
3020
#[inline]
3021
pub(crate) fn initialize_non_send_internal(
3022
&mut self,
3023
component_id: ComponentId,
3024
) -> &mut NonSendData {
3025
self.flush_components();
3026
self.storages
3027
.non_sends
3028
.initialize_with(component_id, &self.components)
3029
}
3030
3031
/// Applies any commands in the world's internal [`CommandQueue`].
3032
/// This does not apply commands from any systems, only those stored in the world.
3033
///
3034
/// # Panics
3035
/// This will panic if any of the queued commands are [`spawn`](Commands::spawn).
3036
/// If this is possible, you should instead use [`flush`](Self::flush).
3037
pub(crate) fn flush_commands(&mut self) {
3038
// SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3039
if !unsafe { self.command_queue.is_empty() } {
3040
// SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
3041
unsafe {
3042
self.command_queue
3043
.clone()
3044
.apply_or_drop_queued(Some(self.into()));
3045
};
3046
}
3047
}
3048
3049
/// Applies any queued component registration.
3050
/// For spawning vanilla rust component types and resources, this is not strictly necessary.
3051
/// However, flushing components can make information available more quickly, and can have performance benefits.
3052
/// Additionally, for components and resources registered dynamically through a raw descriptor or similar,
3053
/// this is the only way to complete their registration.
3054
pub(crate) fn flush_components(&mut self) {
3055
self.components_registrator().apply_queued_registrations();
3056
}
3057
3058
/// Flushes queued entities and commands.
3059
///
3060
/// Queued entities will be spawned, and then commands will be applied.
3061
#[inline]
3062
#[track_caller]
3063
pub fn flush(&mut self) {
3064
self.flush_components();
3065
self.flush_commands();
3066
}
3067
3068
/// Increments the world's current change tick and returns the old value.
3069
///
3070
/// If you need to call this method, but do not have `&mut` access to the world,
3071
/// consider using [`as_unsafe_world_cell_readonly`](Self::as_unsafe_world_cell_readonly)
3072
/// to obtain an [`UnsafeWorldCell`] and calling [`increment_change_tick`](UnsafeWorldCell::increment_change_tick) on that.
3073
/// Note that this *can* be done in safe code, despite the name of the type.
3074
#[inline]
3075
pub fn increment_change_tick(&mut self) -> Tick {
3076
let change_tick = self.change_tick.get_mut();
3077
let prev_tick = *change_tick;
3078
*change_tick = change_tick.wrapping_add(1);
3079
Tick::new(prev_tick)
3080
}
3081
3082
/// Reads the current change tick of this world.
3083
///
3084
/// If you have exclusive (`&mut`) access to the world, consider using [`change_tick()`](Self::change_tick),
3085
/// which is more efficient since it does not require atomic synchronization.
3086
#[inline]
3087
pub fn read_change_tick(&self) -> Tick {
3088
let tick = self.change_tick.load(Ordering::Acquire);
3089
Tick::new(tick)
3090
}
3091
3092
/// Reads the current change tick of this world.
3093
///
3094
/// This does the same thing as [`read_change_tick()`](Self::read_change_tick), only this method
3095
/// is more efficient since it does not require atomic synchronization.
3096
#[inline]
3097
pub fn change_tick(&mut self) -> Tick {
3098
let tick = *self.change_tick.get_mut();
3099
Tick::new(tick)
3100
}
3101
3102
/// When called from within an exclusive system (a [`System`] that takes `&mut World` as its first
3103
/// parameter), this method returns the [`Tick`] indicating the last time the exclusive system was run.
3104
///
3105
/// Otherwise, this returns the `Tick` indicating the last time that [`World::clear_trackers`] was called.
3106
///
3107
/// [`System`]: crate::system::System
3108
#[inline]
3109
pub fn last_change_tick(&self) -> Tick {
3110
self.last_change_tick
3111
}
3112
3113
/// Returns the id of the last ECS event that was fired.
3114
/// Used internally to ensure observers don't trigger multiple times for the same event.
3115
#[inline]
3116
pub(crate) fn last_trigger_id(&self) -> u32 {
3117
self.last_trigger_id
3118
}
3119
3120
/// Sets [`World::last_change_tick()`] to the specified value during a scope.
3121
/// When the scope terminates, it will return to its old value.
3122
///
3123
/// This is useful if you need a region of code to be able to react to earlier changes made in the same system.
3124
///
3125
/// # Examples
3126
///
3127
/// ```
3128
/// # use bevy_ecs::prelude::*;
3129
/// // This function runs an update loop repeatedly, allowing each iteration of the loop
3130
/// // to react to changes made in the previous loop iteration.
3131
/// fn update_loop(
3132
/// world: &mut World,
3133
/// mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
3134
/// ) {
3135
/// let mut last_change_tick = world.last_change_tick();
3136
///
3137
/// // Repeatedly run the update function until it requests a break.
3138
/// loop {
3139
/// let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
3140
/// // Increment the change tick so we can detect changes from the previous update.
3141
/// last_change_tick = world.change_tick();
3142
/// world.increment_change_tick();
3143
///
3144
/// // Update once.
3145
/// update_fn(world)
3146
/// });
3147
///
3148
/// // End the loop when the closure returns `ControlFlow::Break`.
3149
/// if control_flow.is_break() {
3150
/// break;
3151
/// }
3152
/// }
3153
/// }
3154
/// #
3155
/// # #[derive(Resource)] struct Count(u32);
3156
/// # let mut world = World::new();
3157
/// # world.insert_resource(Count(0));
3158
/// # let saved_last_tick = world.last_change_tick();
3159
/// # let mut num_updates = 0;
3160
/// # update_loop(&mut world, |world| {
3161
/// # let mut c = world.resource_mut::<Count>();
3162
/// # match c.0 {
3163
/// # 0 => {
3164
/// # assert_eq!(num_updates, 0);
3165
/// # assert!(c.is_added());
3166
/// # c.0 = 1;
3167
/// # }
3168
/// # 1 => {
3169
/// # assert_eq!(num_updates, 1);
3170
/// # assert!(!c.is_added());
3171
/// # assert!(c.is_changed());
3172
/// # c.0 = 2;
3173
/// # }
3174
/// # 2 if c.is_changed() => {
3175
/// # assert_eq!(num_updates, 2);
3176
/// # assert!(!c.is_added());
3177
/// # }
3178
/// # 2 => {
3179
/// # assert_eq!(num_updates, 3);
3180
/// # assert!(!c.is_changed());
3181
/// # world.remove_resource::<Count>();
3182
/// # world.insert_resource(Count(3));
3183
/// # }
3184
/// # 3 if c.is_changed() => {
3185
/// # assert_eq!(num_updates, 4);
3186
/// # assert!(c.is_added());
3187
/// # }
3188
/// # 3 => {
3189
/// # assert_eq!(num_updates, 5);
3190
/// # assert!(!c.is_added());
3191
/// # c.0 = 4;
3192
/// # return std::ops::ControlFlow::Break(());
3193
/// # }
3194
/// # _ => unreachable!(),
3195
/// # }
3196
/// # num_updates += 1;
3197
/// # std::ops::ControlFlow::Continue(())
3198
/// # });
3199
/// # assert_eq!(num_updates, 5);
3200
/// # assert_eq!(world.resource::<Count>().0, 4);
3201
/// # assert_eq!(world.last_change_tick(), saved_last_tick);
3202
/// ```
3203
pub fn last_change_tick_scope<T>(
3204
&mut self,
3205
last_change_tick: Tick,
3206
f: impl FnOnce(&mut World) -> T,
3207
) -> T {
3208
struct LastTickGuard<'a> {
3209
world: &'a mut World,
3210
last_tick: Tick,
3211
}
3212
3213
// By setting the change tick in the drop impl, we ensure that
3214
// the change tick gets reset even if a panic occurs during the scope.
3215
impl Drop for LastTickGuard<'_> {
3216
fn drop(&mut self) {
3217
self.world.last_change_tick = self.last_tick;
3218
}
3219
}
3220
3221
let guard = LastTickGuard {
3222
last_tick: self.last_change_tick,
3223
world: self,
3224
};
3225
3226
guard.world.last_change_tick = last_change_tick;
3227
3228
f(guard.world)
3229
}
3230
3231
/// Iterates all component change ticks and clamps any older than [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
3232
/// This also triggers [`CheckChangeTicks`] observers and returns the same event here.
3233
///
3234
/// Calling this method prevents [`Tick`]s overflowing and thus prevents false positives when comparing them.
3235
///
3236
/// **Note:** Does nothing and returns `None` if the [`World`] counter has not been incremented at least [`CHECK_TICK_THRESHOLD`]
3237
/// times since the previous pass.
3238
// TODO: benchmark and optimize
3239
pub fn check_change_ticks(&mut self) -> Option<CheckChangeTicks> {
3240
let change_tick = self.change_tick();
3241
if change_tick.relative_to(self.last_check_tick).get() < CHECK_TICK_THRESHOLD {
3242
return None;
3243
}
3244
3245
let check = CheckChangeTicks(change_tick);
3246
3247
let Storages {
3248
ref mut tables,
3249
ref mut sparse_sets,
3250
ref mut non_sends,
3251
} = self.storages;
3252
3253
#[cfg(feature = "trace")]
3254
let _span = tracing::info_span!("check component ticks").entered();
3255
tables.check_change_ticks(check);
3256
sparse_sets.check_change_ticks(check);
3257
non_sends.check_change_ticks(check);
3258
self.entities.check_change_ticks(check);
3259
3260
if let Some(mut schedules) = self.get_resource_mut::<Schedules>() {
3261
schedules.check_change_ticks(check);
3262
}
3263
3264
self.trigger(check);
3265
self.flush();
3266
3267
self.last_check_tick = change_tick;
3268
3269
Some(check)
3270
}
3271
3272
/// Clears all entities, resources, and non-send data.
3273
/// This invalidates all [`Entity`] and resource fetches such as [`Res`](crate::system::Res),
3274
/// [`ResMut`](crate::system::ResMut)
3275
pub fn clear_all(&mut self) {
3276
self.clear_entities();
3277
self.clear_non_send();
3278
}
3279
3280
/// Despawns all entities in this [`World`].
3281
///
3282
/// **Note:** This includes all resources, as they are stored as components.
3283
/// Any resource fetch to this [`World`] will fail unless they are re-initialized,
3284
/// including engine-internal resources that are only initialized on app/world construction.
3285
///
3286
/// This can easily cause systems expecting certain resources to immediately start panicking.
3287
/// Use with caution.
3288
pub fn clear_entities(&mut self) {
3289
self.storages.tables.clear();
3290
self.storages.sparse_sets.clear_entities();
3291
self.archetypes.clear_entities();
3292
self.entities.clear();
3293
self.entity_allocator.restart();
3294
}
3295
3296
/// Clears all resources in this [`World`].
3297
///
3298
/// **Note:** Any resource fetch to this [`World`] will fail unless they are re-initialized,
3299
/// including engine-internal resources that are only initialized on app/world construction.
3300
///
3301
/// This can easily cause systems expecting certain resources to immediately start panicking.
3302
/// Use with caution.
3303
pub fn clear_resources(&mut self) {
3304
let pairs: Vec<(ComponentId, Entity)> = self
3305
.resource_entities()
3306
.iter()
3307
.map(|(id, entity)| (*id, *entity))
3308
.collect();
3309
for (component_id, entity) in pairs {
3310
self.entity_mut(entity).remove_by_id(component_id);
3311
}
3312
}
3313
3314
/// Clears all non-send data in this [`World`].
3315
pub fn clear_non_send(&mut self) {
3316
self.storages.non_sends.clear();
3317
}
3318
3319
/// Registers all of the components in the given [`Bundle`] and returns both the component
3320
/// ids and the bundle id.
3321
///
3322
/// This is largely equivalent to calling [`register_component`](Self::register_component) on each
3323
/// component in the bundle.
3324
#[inline]
3325
pub fn register_bundle<B: Bundle>(&mut self) -> &BundleInfo {
3326
let id = self.register_bundle_info::<B>();
3327
3328
// SAFETY: We just initialized the bundle so its id should definitely be valid.
3329
unsafe { self.bundles.get(id).debug_checked_unwrap() }
3330
}
3331
3332
pub(crate) fn register_bundle_info<B: Bundle>(&mut self) -> BundleId {
3333
// SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3334
let mut registrator =
3335
unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3336
3337
// SAFETY: `registrator`, `self.storages` and `self.bundles` all come from this world.
3338
unsafe {
3339
self.bundles
3340
.register_info::<B>(&mut registrator, &mut self.storages)
3341
}
3342
}
3343
3344
pub(crate) fn register_contributed_bundle_info<B: Bundle>(&mut self) -> BundleId {
3345
// SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3346
let mut registrator =
3347
unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3348
3349
// SAFETY: `registrator`, `self.bundles` and `self.storages` are all from this world.
3350
unsafe {
3351
self.bundles
3352
.register_contributed_bundle_info::<B>(&mut registrator, &mut self.storages)
3353
}
3354
}
3355
3356
/// Registers the given [`ComponentId`]s as a dynamic bundle and returns both the required component ids and the bundle id.
3357
///
3358
/// Note that the components need to be registered first, this function only creates a bundle combining them. Components
3359
/// can be registered with [`World::register_component`]/[`_with_descriptor`](World::register_component_with_descriptor).
3360
///
3361
/// **You should prefer to use the typed API [`World::register_bundle`] where possible and only use this in cases where
3362
/// not all of the actual types are known at compile time.**
3363
///
3364
/// # Panics
3365
/// This function will panic if any of the provided component ids do not belong to a component known to this [`World`].
3366
#[inline]
3367
pub fn register_dynamic_bundle(&mut self, component_ids: &[ComponentId]) -> &BundleInfo {
3368
let id =
3369
self.bundles
3370
.init_dynamic_info(&mut self.storages, &self.components, component_ids);
3371
// SAFETY: We just initialized the bundle so its id should definitely be valid.
3372
unsafe { self.bundles.get(id).debug_checked_unwrap() }
3373
}
3374
3375
/// Convenience method for accessing the world's default error handler,
3376
/// which can be overwritten with [`DefaultErrorHandler`].
3377
#[inline]
3378
pub fn default_error_handler(&self) -> ErrorHandler {
3379
self.get_resource::<DefaultErrorHandler>()
3380
.copied()
3381
.unwrap_or_default()
3382
.0
3383
}
3384
}
3385
3386
impl World {
3387
/// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3388
/// The returned pointer must not be used to modify the resource, and must not be
3389
/// dereferenced after the immutable borrow of the [`World`] ends.
3390
///
3391
/// **You should prefer to use the typed API [`World::get_resource`] where possible and only
3392
/// use this in cases where the actual types are not known at compile time.**
3393
#[inline]
3394
pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3395
// SAFETY:
3396
// - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3397
// - `&self` ensures there are no mutable borrows on world data
3398
unsafe {
3399
self.as_unsafe_world_cell_readonly()
3400
.get_resource_by_id(component_id)
3401
}
3402
}
3403
3404
/// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3405
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
3406
/// of the [`World`] is still valid.
3407
///
3408
/// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
3409
/// use this in cases where the actual types are not known at compile time.**
3410
#[inline]
3411
pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3412
// SAFETY:
3413
// - `&mut self` ensures that all accessed data is unaliased
3414
// - `as_unsafe_world_cell` provides mutable permission to the whole world
3415
unsafe {
3416
self.as_unsafe_world_cell()
3417
.get_resource_mut_by_id(component_id)
3418
}
3419
}
3420
3421
/// Iterates over all resources in the world.
3422
///
3423
/// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents
3424
/// of each resource will require the use of unsafe code.
3425
///
3426
/// # Examples
3427
///
3428
/// ## Printing the size of all resources
3429
///
3430
/// ```
3431
/// # use bevy_ecs::prelude::*;
3432
/// # #[derive(Resource)]
3433
/// # struct A(u32);
3434
/// # #[derive(Resource)]
3435
/// # struct B(u32);
3436
/// #
3437
/// # let mut world = World::new();
3438
/// # world.remove_resource::<bevy_ecs::entity_disabling::DefaultQueryFilters>();
3439
/// # world.insert_resource(A(1));
3440
/// # world.insert_resource(B(2));
3441
/// let mut total = 0;
3442
/// for (info, _) in world.iter_resources() {
3443
/// println!("Resource: {}", info.name());
3444
/// println!("Size: {} bytes", info.layout().size());
3445
/// total += info.layout().size();
3446
/// }
3447
/// println!("Total size: {} bytes", total);
3448
/// # assert_eq!(total, size_of::<A>() + size_of::<B>());
3449
/// ```
3450
///
3451
/// ## Dynamically running closures for resources matching specific `TypeId`s
3452
///
3453
/// ```
3454
/// # use bevy_ecs::prelude::*;
3455
/// # use std::collections::HashMap;
3456
/// # use std::any::TypeId;
3457
/// # use bevy_ptr::Ptr;
3458
/// # #[derive(Resource)]
3459
/// # struct A(u32);
3460
/// # #[derive(Resource)]
3461
/// # struct B(u32);
3462
/// #
3463
/// # let mut world = World::new();
3464
/// # world.insert_resource(A(1));
3465
/// # world.insert_resource(B(2));
3466
/// #
3467
/// // In this example, `A` and `B` are resources. We deliberately do not use the
3468
/// // `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
3469
/// // probably use something like `ReflectFromPtr` in a real-world scenario.
3470
///
3471
/// // Create the hash map that will store the closures for each resource type
3472
/// let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();
3473
///
3474
/// // Add closure for `A`
3475
/// closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
3476
/// // SAFETY: We assert ptr is the same type of A with TypeId of A
3477
/// let a = unsafe { &ptr.deref::<A>() };
3478
/// # assert_eq!(a.0, 1);
3479
/// // ... do something with `a` here
3480
/// }));
3481
///
3482
/// // Add closure for `B`
3483
/// closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
3484
/// // SAFETY: We assert ptr is the same type of B with TypeId of B
3485
/// let b = unsafe { &ptr.deref::<B>() };
3486
/// # assert_eq!(b.0, 2);
3487
/// // ... do something with `b` here
3488
/// }));
3489
///
3490
/// // Iterate all resources, in order to run the closures for each matching resource type
3491
/// for (info, ptr) in world.iter_resources() {
3492
/// let Some(type_id) = info.type_id() else {
3493
/// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3494
/// // dynamically inserted via a scripting language) in which case we can't match them.
3495
/// continue;
3496
/// };
3497
///
3498
/// let Some(closure) = closures.get(&type_id) else {
3499
/// // No closure for this resource type, skip it.
3500
/// continue;
3501
/// };
3502
///
3503
/// // Run the closure for the resource
3504
/// closure(&ptr);
3505
/// }
3506
/// ```
3507
#[inline]
3508
pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)> {
3509
self.resource_entities
3510
.indices()
3511
.iter()
3512
.filter_map(|component_id| {
3513
let component_info = self.components().get_info(*component_id)?;
3514
let resource = self.get_resource_by_id(*component_id)?;
3515
Some((component_info, resource))
3516
})
3517
}
3518
3519
/// Mutably iterates over all resources in the world.
3520
///
3521
/// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading from or writing
3522
/// to the contents of each resource will require the use of unsafe code.
3523
///
3524
/// # Example
3525
///
3526
/// ```
3527
/// # use bevy_ecs::prelude::*;
3528
/// # use bevy_ecs::change_detection::MutUntyped;
3529
/// # use std::collections::HashMap;
3530
/// # use std::any::TypeId;
3531
/// # #[derive(Resource)]
3532
/// # struct A(u32);
3533
/// # #[derive(Resource)]
3534
/// # struct B(u32);
3535
/// #
3536
/// # let mut world = World::new();
3537
/// # world.insert_resource(A(1));
3538
/// # world.insert_resource(B(2));
3539
/// #
3540
/// // In this example, `A` and `B` are resources. We deliberately do not use the
3541
/// // `bevy_reflect` crate here to showcase the low-level `MutUntyped` usage. You should
3542
/// // probably use something like `ReflectFromPtr` in a real-world scenario.
3543
///
3544
/// // Create the hash map that will store the mutator closures for each resource type
3545
/// let mut mutators: HashMap<TypeId, Box<dyn Fn(&mut MutUntyped<'_>)>> = HashMap::default();
3546
///
3547
/// // Add mutator closure for `A`
3548
/// mutators.insert(TypeId::of::<A>(), Box::new(|mut_untyped| {
3549
/// // Note: `MutUntyped::as_mut()` automatically marks the resource as changed
3550
/// // for ECS change detection, and gives us a `PtrMut` we can use to mutate the resource.
3551
/// // SAFETY: We assert ptr is the same type of A with TypeId of A
3552
/// let a = unsafe { &mut mut_untyped.as_mut().deref_mut::<A>() };
3553
/// # a.0 += 1;
3554
/// // ... mutate `a` here
3555
/// }));
3556
///
3557
/// // Add mutator closure for `B`
3558
/// mutators.insert(TypeId::of::<B>(), Box::new(|mut_untyped| {
3559
/// // SAFETY: We assert ptr is the same type of B with TypeId of B
3560
/// let b = unsafe { &mut mut_untyped.as_mut().deref_mut::<B>() };
3561
/// # b.0 += 1;
3562
/// // ... mutate `b` here
3563
/// }));
3564
///
3565
/// // Iterate all resources, in order to run the mutator closures for each matching resource type
3566
/// for (info, mut mut_untyped) in world.iter_resources_mut() {
3567
/// let Some(type_id) = info.type_id() else {
3568
/// // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3569
/// // dynamically inserted via a scripting language) in which case we can't match them.
3570
/// continue;
3571
/// };
3572
///
3573
/// let Some(mutator) = mutators.get(&type_id) else {
3574
/// // No mutator closure for this resource type, skip it.
3575
/// continue;
3576
/// };
3577
///
3578
/// // Run the mutator closure for the resource
3579
/// mutator(&mut mut_untyped);
3580
/// }
3581
/// # assert_eq!(world.resource::<A>().0, 2);
3582
/// # assert_eq!(world.resource::<B>().0, 3);
3583
/// ```
3584
pub fn iter_resources_mut(&mut self) -> impl Iterator<Item = (&ComponentInfo, MutUntyped<'_>)> {
3585
let unsafe_world = self.as_unsafe_world_cell();
3586
// SAFETY: exclusive world access to all resources
3587
let resource_entities = unsafe { unsafe_world.resource_entities() };
3588
let components = unsafe_world.components();
3589
3590
resource_entities
3591
.iter()
3592
.map(|(component_id, entity)| (*component_id, *entity))
3593
.filter_map(move |(component_id, entity)| {
3594
// SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
3595
let component_info =
3596
unsafe { components.get_info(component_id).debug_checked_unwrap() };
3597
3598
let entity_cell = unsafe_world.get_entity(entity).ok()?;
3599
3600
// SAFETY:
3601
// - We have exclusive world access
3602
// - `UnsafeEntityCell::get_mut_by_id` doesn't access components
3603
// or resource_entities mutably
3604
// - `resource_entities` doesn't contain duplicate entities, so
3605
// no duplicate references are created
3606
let mut_untyped = unsafe { entity_cell.get_mut_by_id(component_id).ok()? };
3607
3608
Some((component_info, mut_untyped))
3609
})
3610
}
3611
3612
/// Gets a pointer to `!Send` data with the id [`ComponentId`] if it exists.
3613
/// The returned pointer must not be used to modify the resource, and must not be
3614
/// dereferenced after the immutable borrow of the [`World`] ends.
3615
///
3616
/// **You should prefer to use the typed API [`World::get_non_send`] where possible and only
3617
/// use this in cases where the actual types are not known at compile time.**
3618
///
3619
/// # Panics
3620
/// This function will panic if it isn't called from the same thread that the data was inserted from.
3621
#[inline]
3622
pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3623
// SAFETY:
3624
// - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3625
// - `&self` ensures there are no mutable borrows on world data
3626
unsafe {
3627
self.as_unsafe_world_cell_readonly()
3628
.get_non_send_by_id(component_id)
3629
}
3630
}
3631
3632
/// Gets mutable access to `!Send` data with the id [`ComponentId`] if it exists.
3633
/// The returned pointer may be used to modify the data, as long as the mutable borrow
3634
/// of the [`World`] is still valid.
3635
///
3636
/// **You should prefer to use the typed API [`World::get_non_send_mut`] where possible and only
3637
/// use this in cases where the actual types are not known at compile time.**
3638
///
3639
/// # Panics
3640
/// This function will panic if it isn't called from the same thread that the data was inserted from.
3641
#[inline]
3642
pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3643
// SAFETY:
3644
// - `&mut self` ensures that all accessed data is unaliased
3645
// - `as_unsafe_world_cell` provides mutable permission to the whole world
3646
unsafe {
3647
self.as_unsafe_world_cell()
3648
.get_non_send_mut_by_id(component_id)
3649
}
3650
}
3651
3652
/// Removes the resource of a given type, if it exists.
3653
/// Returns `true` if the resource is successfully removed and `false` if
3654
/// the entity does not exist.
3655
///
3656
/// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
3657
/// use this in cases where the actual types are not known at compile time.**
3658
pub fn remove_resource_by_id(&mut self, component_id: ComponentId) -> bool {
3659
if let Some(entity) = self.resource_entities.remove(component_id)
3660
&& let Ok(mut entity_mut) = self.get_entity_mut(entity)
3661
&& entity_mut.contains_id(component_id)
3662
{
3663
entity_mut.remove_by_id(component_id);
3664
true
3665
} else {
3666
false
3667
}
3668
}
3669
3670
/// Removes the non-send data of a given type, if it exists. Otherwise returns `None`.
3671
///
3672
/// **You should prefer to use the typed API [`World::remove_non_send`] where possible and only
3673
/// use this in cases where the actual types are not known at compile time.**
3674
///
3675
/// # Panics
3676
/// This function will panic if it isn't called from the same thread that the data was inserted from.
3677
pub fn remove_non_send_by_id(&mut self, component_id: ComponentId) -> Option<()> {
3678
self.storages
3679
.non_sends
3680
.get_mut(component_id)?
3681
.remove_and_drop();
3682
Some(())
3683
}
3684
3685
/// Retrieves an immutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3686
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3687
///
3688
/// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3689
/// use this in cases where the actual types are not known at compile time.**
3690
///
3691
/// # Panics
3692
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
3693
#[inline]
3694
pub fn get_by_id(&self, entity: Entity, component_id: ComponentId) -> Option<Ptr<'_>> {
3695
self.get_entity(entity).ok()?.get_by_id(component_id).ok()
3696
}
3697
3698
/// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3699
/// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3700
///
3701
/// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3702
/// use this in cases where the actual types are not known at compile time.**
3703
#[inline]
3704
pub fn get_mut_by_id(
3705
&mut self,
3706
entity: Entity,
3707
component_id: ComponentId,
3708
) -> Option<MutUntyped<'_>> {
3709
self.get_entity_mut(entity)
3710
.ok()?
3711
.into_mut_by_id(component_id)
3712
.ok()
3713
}
3714
}
3715
3716
// Schedule-related methods
3717
impl World {
3718
/// Adds the specified [`Schedule`] to the world.
3719
/// If a schedule already exists with the same [label](Schedule::label), it will be replaced.
3720
///
3721
/// The schedule can later be run
3722
/// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
3723
/// accessing the [`Schedules`] resource.
3724
///
3725
/// The `Schedules` resource will be initialized if it does not already exist.
3726
///
3727
/// An alternative to this is to call [`Schedules::add_systems()`] with some
3728
/// [`ScheduleLabel`] and let the schedule for that label be created if it
3729
/// does not already exist.
3730
pub fn add_schedule(&mut self, schedule: Schedule) {
3731
let mut schedules = self.get_resource_or_init::<Schedules>();
3732
schedules.insert(schedule);
3733
}
3734
3735
/// Temporarily removes the schedule associated with `label` from the world,
3736
/// runs user code, and finally re-adds the schedule.
3737
/// This returns a [`TryRunScheduleError`] if there is no schedule
3738
/// associated with `label`.
3739
///
3740
/// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3741
/// and system state is cached.
3742
///
3743
/// For simple cases where you just need to call the schedule once,
3744
/// consider using [`World::try_run_schedule`] instead.
3745
/// For other use cases, see the example on [`World::schedule_scope`].
3746
pub fn try_schedule_scope<R>(
3747
&mut self,
3748
label: impl ScheduleLabel,
3749
f: impl FnOnce(&mut World, &mut Schedule) -> R,
3750
) -> Result<R, TryRunScheduleError> {
3751
let label = label.intern();
3752
let Some(mut schedule) = self
3753
.get_resource_mut::<Schedules>()
3754
.and_then(|mut s| s.remove(label))
3755
else {
3756
return Err(TryRunScheduleError(label));
3757
};
3758
3759
let value = f(self, &mut schedule);
3760
3761
let old = self.resource_mut::<Schedules>().insert(schedule);
3762
if old.is_some() {
3763
warn!("Schedule `{label:?}` was inserted during a call to `World::schedule_scope`: its value has been overwritten");
3764
}
3765
3766
Ok(value)
3767
}
3768
3769
/// Temporarily removes the schedule associated with `label` from the world,
3770
/// runs user code, and finally re-adds the schedule.
3771
///
3772
/// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3773
/// and system state is cached.
3774
///
3775
/// # Examples
3776
///
3777
/// ```
3778
/// # use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
3779
/// # #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)]
3780
/// # pub struct MySchedule;
3781
/// # #[derive(Resource)]
3782
/// # struct Counter(usize);
3783
/// #
3784
/// # let mut world = World::new();
3785
/// # world.insert_resource(Counter(0));
3786
/// # let mut schedule = Schedule::new(MySchedule);
3787
/// # schedule.add_systems(tick_counter);
3788
/// # world.init_resource::<Schedules>();
3789
/// # world.add_schedule(schedule);
3790
/// # fn tick_counter(mut counter: ResMut<Counter>) { counter.0 += 1; }
3791
/// // Run the schedule five times.
3792
/// world.schedule_scope(MySchedule, |world, schedule| {
3793
/// for _ in 0..5 {
3794
/// schedule.run(world);
3795
/// }
3796
/// });
3797
/// # assert_eq!(world.resource::<Counter>().0, 5);
3798
/// ```
3799
///
3800
/// For simple cases where you just need to call the schedule once,
3801
/// consider using [`World::run_schedule`] instead.
3802
///
3803
/// # Panics
3804
///
3805
/// If the requested schedule does not exist.
3806
pub fn schedule_scope<R>(
3807
&mut self,
3808
label: impl ScheduleLabel,
3809
f: impl FnOnce(&mut World, &mut Schedule) -> R,
3810
) -> R {
3811
self.try_schedule_scope(label, f)
3812
.unwrap_or_else(|e| panic!("{e}"))
3813
}
3814
3815
/// Attempts to run the [`Schedule`] associated with the `label` a single time,
3816
/// and returns a [`TryRunScheduleError`] if the schedule does not exist.
3817
///
3818
/// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3819
/// and system state is cached.
3820
///
3821
/// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3822
pub fn try_run_schedule(
3823
&mut self,
3824
label: impl ScheduleLabel,
3825
) -> Result<(), TryRunScheduleError> {
3826
self.try_schedule_scope(label, |world, sched| sched.run(world))
3827
}
3828
3829
/// Runs the [`Schedule`] associated with the `label` a single time.
3830
///
3831
/// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3832
/// and system state is cached.
3833
///
3834
/// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3835
/// This avoids the need to create a unique [`ScheduleLabel`].
3836
///
3837
/// # Panics
3838
///
3839
/// If the requested schedule does not exist.
3840
pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
3841
self.schedule_scope(label, |world, sched| sched.run(world));
3842
}
3843
3844
/// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
3845
pub fn allow_ambiguous_component<T: Component>(&mut self) {
3846
let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3847
schedules.allow_ambiguous_component::<T>(self);
3848
self.insert_resource(schedules);
3849
}
3850
3851
/// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
3852
pub fn allow_ambiguous_resource<T: Resource>(&mut self) {
3853
let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3854
schedules.allow_ambiguous_resource::<T>(self);
3855
self.insert_resource(schedules);
3856
}
3857
}
3858
3859
impl fmt::Debug for World {
3860
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3861
// SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
3862
// Accessing any data stored in the world would be unsound.
3863
f.debug_struct("World")
3864
.field("id", &self.id)
3865
.field("entity_count", &self.entities.count_spawned())
3866
.field("archetype_count", &self.archetypes.len())
3867
.field("component_count", &self.components.len())
3868
.field("resource_count", &self.resource_entities.len())
3869
.finish()
3870
}
3871
}
3872
3873
// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3874
unsafe impl Send for World {}
3875
// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3876
unsafe impl Sync for World {}
3877
3878
/// Creates an instance of the type this trait is implemented for
3879
/// using data from the supplied [`World`].
3880
///
3881
/// This can be helpful for complex initialization or context-aware defaults.
3882
///
3883
/// [`FromWorld`] is automatically implemented for any type implementing [`Default`]
3884
/// and may also be derived for:
3885
/// - any struct whose fields all implement `FromWorld`
3886
/// - any enum where one variant has the attribute `#[from_world]`
3887
///
3888
/// ```rs
3889
///
3890
/// #[derive(Default)]
3891
/// struct A;
3892
///
3893
/// #[derive(Default)]
3894
/// struct B(Option<u32>)
3895
///
3896
/// struct C;
3897
///
3898
/// impl FromWorld for C {
3899
/// fn from_world(_world: &mut World) -> Self {
3900
/// Self
3901
/// }
3902
/// }
3903
///
3904
/// #[derive(FromWorld)]
3905
/// struct D(A, B, C);
3906
///
3907
/// #[derive(FromWorld)]
3908
/// enum E {
3909
/// #[from_world]
3910
/// F,
3911
/// G
3912
/// }
3913
/// ```
3914
pub trait FromWorld {
3915
/// Creates `Self` using data from the given [`World`].
3916
fn from_world(world: &mut World) -> Self;
3917
}
3918
3919
impl<T: Default> FromWorld for T {
3920
/// Creates `Self` using [`default()`](`Default::default`).
3921
#[track_caller]
3922
fn from_world(_world: &mut World) -> Self {
3923
T::default()
3924
}
3925
}
3926
3927
#[cfg(test)]
3928
#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
3929
mod tests {
3930
use super::{FromWorld, World};
3931
use crate::{
3932
change_detection::{DetectChangesMut, MaybeLocation},
3933
component::{ComponentCloneBehavior, ComponentDescriptor, ComponentInfo, StorageType},
3934
entity::EntityHashSet,
3935
entity_disabling::{DefaultQueryFilters, Disabled},
3936
prelude::{Event, Mut, On, Res},
3937
ptr::OwningPtr,
3938
resource::Resource,
3939
world::{error::EntityMutableFetchError, DeferredWorld},
3940
};
3941
use alloc::{
3942
borrow::ToOwned,
3943
string::{String, ToString},
3944
sync::Arc,
3945
vec,
3946
vec::Vec,
3947
};
3948
use bevy_ecs_macros::Component;
3949
use bevy_platform::collections::{HashMap, HashSet};
3950
use bevy_utils::prelude::DebugName;
3951
use core::{
3952
any::TypeId,
3953
panic,
3954
sync::atomic::{AtomicBool, AtomicU32, Ordering},
3955
};
3956
use std::{println, sync::Mutex};
3957
3958
type ID = u8;
3959
3960
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3961
enum DropLogItem {
3962
Create(ID),
3963
Drop(ID),
3964
}
3965
3966
#[derive(Component)]
3967
struct MayPanicInDrop {
3968
drop_log: Arc<Mutex<Vec<DropLogItem>>>,
3969
expected_panic_flag: Arc<AtomicBool>,
3970
should_panic: bool,
3971
id: u8,
3972
}
3973
3974
impl MayPanicInDrop {
3975
fn new(
3976
drop_log: &Arc<Mutex<Vec<DropLogItem>>>,
3977
expected_panic_flag: &Arc<AtomicBool>,
3978
should_panic: bool,
3979
id: u8,
3980
) -> Self {
3981
println!("creating component with id {id}");
3982
drop_log.lock().unwrap().push(DropLogItem::Create(id));
3983
3984
Self {
3985
drop_log: Arc::clone(drop_log),
3986
expected_panic_flag: Arc::clone(expected_panic_flag),
3987
should_panic,
3988
id,
3989
}
3990
}
3991
}
3992
3993
impl Drop for MayPanicInDrop {
3994
fn drop(&mut self) {
3995
println!("dropping component with id {}", self.id);
3996
3997
{
3998
let mut drop_log = self.drop_log.lock().unwrap();
3999
drop_log.push(DropLogItem::Drop(self.id));
4000
// Don't keep the mutex while panicking, or we'll poison it.
4001
drop(drop_log);
4002
}
4003
4004
if self.should_panic {
4005
self.expected_panic_flag.store(true, Ordering::SeqCst);
4006
panic!("testing what happens on panic inside drop");
4007
}
4008
}
4009
}
4010
4011
struct DropTestHelper {
4012
drop_log: Arc<Mutex<Vec<DropLogItem>>>,
4013
/// Set to `true` right before we intentionally panic, so that if we get
4014
/// a panic, we know if it was intended or not.
4015
expected_panic_flag: Arc<AtomicBool>,
4016
}
4017
4018
impl DropTestHelper {
4019
pub fn new() -> Self {
4020
Self {
4021
drop_log: Arc::new(Mutex::new(Vec::<DropLogItem>::new())),
4022
expected_panic_flag: Arc::new(AtomicBool::new(false)),
4023
}
4024
}
4025
4026
pub fn make_component(&self, should_panic: bool, id: ID) -> MayPanicInDrop {
4027
MayPanicInDrop::new(&self.drop_log, &self.expected_panic_flag, should_panic, id)
4028
}
4029
4030
pub fn finish(self, panic_res: std::thread::Result<()>) -> Vec<DropLogItem> {
4031
let drop_log = self.drop_log.lock().unwrap();
4032
let expected_panic_flag = self.expected_panic_flag.load(Ordering::SeqCst);
4033
4034
if !expected_panic_flag {
4035
match panic_res {
4036
Ok(()) => panic!("Expected a panic but it didn't happen"),
4037
Err(e) => std::panic::resume_unwind(e),
4038
}
4039
}
4040
4041
drop_log.to_owned()
4042
}
4043
}
4044
4045
#[test]
4046
fn panic_while_overwriting_component() {
4047
let helper = DropTestHelper::new();
4048
4049
let res = std::panic::catch_unwind(|| {
4050
let mut world = World::new();
4051
world
4052
.spawn_empty()
4053
.insert(helper.make_component(true, 0))
4054
.insert(helper.make_component(false, 1));
4055
4056
println!("Done inserting! Dropping world...");
4057
});
4058
4059
let drop_log = helper.finish(res);
4060
4061
assert_eq!(
4062
&*drop_log,
4063
[
4064
DropLogItem::Create(0),
4065
DropLogItem::Create(1),
4066
DropLogItem::Drop(0),
4067
DropLogItem::Drop(1),
4068
]
4069
);
4070
}
4071
4072
#[derive(Resource)]
4073
struct TestResource(u32);
4074
4075
#[derive(Resource)]
4076
struct TestResource2(String);
4077
4078
#[derive(Resource)]
4079
struct TestResource3;
4080
4081
#[test]
4082
fn get_resource_by_id() {
4083
let mut world = World::new();
4084
world.insert_resource(TestResource(42));
4085
let component_id = world
4086
.components()
4087
.get_valid_id(TypeId::of::<TestResource>())
4088
.unwrap();
4089
4090
let resource = world.get_resource_by_id(component_id).unwrap();
4091
// SAFETY: `TestResource` is the correct resource type
4092
let resource = unsafe { resource.deref::<TestResource>() };
4093
4094
assert_eq!(resource.0, 42);
4095
}
4096
4097
#[test]
4098
fn get_resource_mut_by_id() {
4099
let mut world = World::new();
4100
world.insert_resource(TestResource(42));
4101
let component_id = world
4102
.components()
4103
.get_valid_id(TypeId::of::<TestResource>())
4104
.unwrap();
4105
4106
{
4107
let mut resource = world.get_resource_mut_by_id(component_id).unwrap();
4108
resource.set_changed();
4109
// SAFETY: `TestResource` is the correct resource type
4110
let resource = unsafe { resource.into_inner().deref_mut::<TestResource>() };
4111
resource.0 = 43;
4112
}
4113
4114
let resource = world.get_resource_by_id(component_id).unwrap();
4115
// SAFETY: `TestResource` is the correct resource type
4116
let resource = unsafe { resource.deref::<TestResource>() };
4117
4118
assert_eq!(resource.0, 43);
4119
}
4120
4121
#[test]
4122
fn iter_resources() {
4123
let mut world = World::new();
4124
// Remove DefaultQueryFilters so it doesn't show up in the iterator
4125
world.remove_resource::<DefaultQueryFilters>();
4126
world.insert_resource(TestResource(42));
4127
world.insert_resource(TestResource2("Hello, world!".to_string()));
4128
world.insert_resource(TestResource3);
4129
world.remove_resource::<TestResource3>();
4130
4131
let mut iter = world.iter_resources();
4132
4133
let (info, ptr) = iter.next().unwrap();
4134
assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4135
// SAFETY: We know that the resource is of type `TestResource`
4136
assert_eq!(unsafe { ptr.deref::<TestResource>().0 }, 42);
4137
4138
let (info, ptr) = iter.next().unwrap();
4139
assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4140
assert_eq!(
4141
// SAFETY: We know that the resource is of type `TestResource2`
4142
unsafe { &ptr.deref::<TestResource2>().0 },
4143
&"Hello, world!".to_string()
4144
);
4145
4146
assert!(iter.next().is_none());
4147
}
4148
4149
#[test]
4150
fn iter_resources_mut() {
4151
let mut world = World::new();
4152
// Remove DefaultQueryFilters so it doesn't show up in the iterator
4153
world.remove_resource::<DefaultQueryFilters>();
4154
world.insert_resource(TestResource(42));
4155
world.insert_resource(TestResource2("Hello, world!".to_string()));
4156
world.insert_resource(TestResource3);
4157
world.remove_resource::<TestResource3>();
4158
4159
let mut iter = world.iter_resources_mut();
4160
4161
let (info, mut mut_untyped) = iter.next().unwrap();
4162
assert_eq!(info.name(), DebugName::type_name::<TestResource>());
4163
// SAFETY: We know that the resource is of type `TestResource`
4164
unsafe {
4165
mut_untyped.as_mut().deref_mut::<TestResource>().0 = 43;
4166
};
4167
4168
let (info, mut mut_untyped) = iter.next().unwrap();
4169
assert_eq!(info.name(), DebugName::type_name::<TestResource2>());
4170
// SAFETY: We know that the resource is of type `TestResource2`
4171
unsafe {
4172
mut_untyped.as_mut().deref_mut::<TestResource2>().0 = "Hello, world?".to_string();
4173
};
4174
4175
assert!(iter.next().is_none());
4176
drop(iter);
4177
4178
assert_eq!(world.resource::<TestResource>().0, 43);
4179
assert_eq!(
4180
world.resource::<TestResource2>().0,
4181
"Hello, world?".to_string()
4182
);
4183
}
4184
4185
#[test]
4186
fn custom_non_send_with_layout() {
4187
static DROP_COUNT: AtomicU32 = AtomicU32::new(0);
4188
4189
let mut world = World::new();
4190
4191
// SAFETY: the drop function is valid for the layout and the data will be safe to access from any thread
4192
let descriptor = unsafe {
4193
ComponentDescriptor::new_with_layout(
4194
"Custom Test Component".to_string(),
4195
StorageType::Table,
4196
core::alloc::Layout::new::<[u8; 8]>(),
4197
Some(|ptr| {
4198
let data = ptr.read::<[u8; 8]>();
4199
assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]);
4200
DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4201
}),
4202
true,
4203
ComponentCloneBehavior::Default,
4204
None,
4205
)
4206
};
4207
4208
let component_id = world.register_component_with_descriptor(descriptor);
4209
4210
let value: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
4211
OwningPtr::make(value, |ptr| {
4212
// SAFETY: value is valid for the component layout
4213
unsafe {
4214
world.insert_non_send_by_id(component_id, ptr, MaybeLocation::caller());
4215
}
4216
});
4217
4218
// SAFETY: [u8; 8] is the correct type for the resource
4219
let data = unsafe {
4220
world
4221
.get_non_send_by_id(component_id)
4222
.unwrap()
4223
.deref::<[u8; 8]>()
4224
};
4225
assert_eq!(*data, [0, 1, 2, 3, 4, 5, 6, 7]);
4226
4227
assert!(world.remove_non_send_by_id(component_id).is_some());
4228
4229
assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
4230
}
4231
4232
#[derive(Resource)]
4233
struct TestFromWorld(u32);
4234
impl FromWorld for TestFromWorld {
4235
fn from_world(world: &mut World) -> Self {
4236
let b = world.resource::<TestResource>();
4237
Self(b.0)
4238
}
4239
}
4240
4241
#[test]
4242
fn init_resource_does_not_overwrite() {
4243
let mut world = World::new();
4244
world.insert_resource(TestResource(0));
4245
world.init_resource::<TestFromWorld>();
4246
world.insert_resource(TestResource(1));
4247
world.init_resource::<TestFromWorld>();
4248
4249
let resource = world.resource::<TestFromWorld>();
4250
4251
assert_eq!(resource.0, 0);
4252
}
4253
4254
#[test]
4255
fn init_non_send_does_not_overwrite() {
4256
let mut world = World::new();
4257
world.insert_resource(TestResource(0));
4258
world.init_non_send::<TestFromWorld>();
4259
world.insert_resource(TestResource(1));
4260
world.init_non_send::<TestFromWorld>();
4261
4262
let resource = world.non_send::<TestFromWorld>();
4263
4264
assert_eq!(resource.0, 0);
4265
}
4266
4267
#[derive(Component)]
4268
struct Foo;
4269
4270
#[derive(Component)]
4271
struct Bar;
4272
4273
#[derive(Component)]
4274
struct Baz;
4275
4276
#[test]
4277
fn inspect_entity_components() {
4278
let mut world = World::new();
4279
let ent0 = world.spawn((Foo, Bar, Baz)).id();
4280
let ent1 = world.spawn((Foo, Bar)).id();
4281
let ent2 = world.spawn((Bar, Baz)).id();
4282
let ent3 = world.spawn((Foo, Baz)).id();
4283
let ent4 = world.spawn(Foo).id();
4284
let ent5 = world.spawn(Bar).id();
4285
let ent6 = world.spawn(Baz).id();
4286
4287
fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
4288
component_infos
4289
.into_iter()
4290
.map(ComponentInfo::type_id)
4291
.collect()
4292
}
4293
4294
let foo_id = TypeId::of::<Foo>();
4295
let bar_id = TypeId::of::<Bar>();
4296
let baz_id = TypeId::of::<Baz>();
4297
assert_eq!(
4298
to_type_ids(world.inspect_entity(ent0).unwrap().collect()),
4299
[Some(foo_id), Some(bar_id), Some(baz_id)]
4300
.into_iter()
4301
.collect::<HashSet<_>>()
4302
);
4303
assert_eq!(
4304
to_type_ids(world.inspect_entity(ent1).unwrap().collect()),
4305
[Some(foo_id), Some(bar_id)]
4306
.into_iter()
4307
.collect::<HashSet<_>>()
4308
);
4309
assert_eq!(
4310
to_type_ids(world.inspect_entity(ent2).unwrap().collect()),
4311
[Some(bar_id), Some(baz_id)]
4312
.into_iter()
4313
.collect::<HashSet<_>>()
4314
);
4315
assert_eq!(
4316
to_type_ids(world.inspect_entity(ent3).unwrap().collect()),
4317
[Some(foo_id), Some(baz_id)]
4318
.into_iter()
4319
.collect::<HashSet<_>>()
4320
);
4321
assert_eq!(
4322
to_type_ids(world.inspect_entity(ent4).unwrap().collect()),
4323
[Some(foo_id)].into_iter().collect::<HashSet<_>>()
4324
);
4325
assert_eq!(
4326
to_type_ids(world.inspect_entity(ent5).unwrap().collect()),
4327
[Some(bar_id)].into_iter().collect::<HashSet<_>>()
4328
);
4329
assert_eq!(
4330
to_type_ids(world.inspect_entity(ent6).unwrap().collect()),
4331
[Some(baz_id)].into_iter().collect::<HashSet<_>>()
4332
);
4333
}
4334
4335
#[test]
4336
fn iterate_entities() {
4337
let mut world = World::new();
4338
let mut entity_counters = <HashMap<_, _>>::default();
4339
4340
let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
4341
entity_counters.clear();
4342
for entity in world.iter_entities() {
4343
let counter = entity_counters.entry(entity.id()).or_insert(0);
4344
*counter += 1;
4345
}
4346
};
4347
4348
// Adding one entity and validating iteration
4349
let ent0 = world.spawn((Foo, Bar, Baz)).id();
4350
4351
iterate_and_count_entities(&world, &mut entity_counters);
4352
assert_eq!(entity_counters[&ent0], 1);
4353
assert_eq!(entity_counters.len(), 2);
4354
4355
// Spawning three more entities and then validating iteration
4356
let ent1 = world.spawn((Foo, Bar)).id();
4357
let ent2 = world.spawn((Bar, Baz)).id();
4358
let ent3 = world.spawn((Foo, Baz)).id();
4359
4360
iterate_and_count_entities(&world, &mut entity_counters);
4361
4362
assert_eq!(entity_counters[&ent0], 1);
4363
assert_eq!(entity_counters[&ent1], 1);
4364
assert_eq!(entity_counters[&ent2], 1);
4365
assert_eq!(entity_counters[&ent3], 1);
4366
assert_eq!(entity_counters.len(), 5);
4367
4368
// Despawning first entity and then validating the iteration
4369
assert!(world.despawn(ent0));
4370
4371
iterate_and_count_entities(&world, &mut entity_counters);
4372
4373
assert_eq!(entity_counters[&ent1], 1);
4374
assert_eq!(entity_counters[&ent2], 1);
4375
assert_eq!(entity_counters[&ent3], 1);
4376
assert_eq!(entity_counters.len(), 4);
4377
4378
// Spawning three more entities, despawning three and then validating the iteration
4379
let ent4 = world.spawn(Foo).id();
4380
let ent5 = world.spawn(Bar).id();
4381
let ent6 = world.spawn(Baz).id();
4382
4383
assert!(world.despawn(ent2));
4384
assert!(world.despawn(ent3));
4385
assert!(world.despawn(ent4));
4386
4387
iterate_and_count_entities(&world, &mut entity_counters);
4388
4389
assert_eq!(entity_counters[&ent1], 1);
4390
assert_eq!(entity_counters[&ent5], 1);
4391
assert_eq!(entity_counters[&ent6], 1);
4392
assert_eq!(entity_counters.len(), 4);
4393
4394
// Despawning remaining entities and then validating the iteration
4395
assert!(world.despawn(ent1));
4396
assert!(world.despawn(ent5));
4397
assert!(world.despawn(ent6));
4398
4399
iterate_and_count_entities(&world, &mut entity_counters);
4400
4401
assert_eq!(entity_counters.len(), 1);
4402
}
4403
4404
#[test]
4405
fn spawn_empty_bundle() {
4406
let mut world = World::new();
4407
world.spawn(());
4408
}
4409
4410
#[test]
4411
fn get_entity() {
4412
let mut world = World::new();
4413
4414
let e1 = world.spawn_empty().id();
4415
let e2 = world.spawn_empty().id();
4416
4417
assert!(world.get_entity(e1).is_ok());
4418
assert!(world.get_entity([e1, e2]).is_ok());
4419
assert!(world
4420
.get_entity(&[e1, e2] /* this is an array not a slice */)
4421
.is_ok());
4422
assert!(world.get_entity(&vec![e1, e2][..]).is_ok());
4423
assert!(world
4424
.get_entity(&EntityHashSet::from_iter([e1, e2]))
4425
.is_ok());
4426
4427
world.entity_mut(e1).despawn();
4428
4429
assert_eq!(
4430
Err(e1),
4431
world.get_entity(e1).map(|_| {}).map_err(|e| e.entity())
4432
);
4433
assert_eq!(
4434
Err(e1),
4435
world
4436
.get_entity([e1, e2])
4437
.map(|_| {})
4438
.map_err(|e| e.entity())
4439
);
4440
assert_eq!(
4441
Err(e1),
4442
world
4443
.get_entity(&[e1, e2] /* this is an array not a slice */)
4444
.map(|_| {})
4445
.map_err(|e| e.entity())
4446
);
4447
assert_eq!(
4448
Err(e1),
4449
world
4450
.get_entity(&vec![e1, e2][..])
4451
.map(|_| {})
4452
.map_err(|e| e.entity())
4453
);
4454
assert_eq!(
4455
Err(e1),
4456
world
4457
.get_entity(&EntityHashSet::from_iter([e1, e2]))
4458
.map(|_| {})
4459
.map_err(|e| e.entity())
4460
);
4461
}
4462
4463
#[test]
4464
fn get_entity_mut() {
4465
let mut world = World::new();
4466
4467
let e1 = world.spawn_empty().id();
4468
let e2 = world.spawn_empty().id();
4469
4470
assert!(world.get_entity_mut(e1).is_ok());
4471
assert!(world.get_entity_mut([e1, e2]).is_ok());
4472
assert!(world
4473
.get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4474
.is_ok());
4475
assert!(world.get_entity_mut(&vec![e1, e2][..]).is_ok());
4476
assert!(world
4477
.get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4478
.is_ok());
4479
4480
assert_eq!(
4481
Err(EntityMutableFetchError::AliasedMutability(e1)),
4482
world.get_entity_mut([e1, e2, e1]).map(|_| {})
4483
);
4484
assert_eq!(
4485
Err(EntityMutableFetchError::AliasedMutability(e1)),
4486
world
4487
.get_entity_mut(&[e1, e2, e1] /* this is an array not a slice */)
4488
.map(|_| {})
4489
);
4490
assert_eq!(
4491
Err(EntityMutableFetchError::AliasedMutability(e1)),
4492
world.get_entity_mut(&vec![e1, e2, e1][..]).map(|_| {})
4493
);
4494
// Aliased mutability isn't allowed by HashSets
4495
assert!(world
4496
.get_entity_mut(&EntityHashSet::from_iter([e1, e2, e1]))
4497
.is_ok());
4498
4499
world.entity_mut(e1).despawn();
4500
assert!(world.get_entity_mut(e2).is_ok());
4501
4502
assert!(matches!(
4503
world.get_entity_mut(e1).map(|_| {}),
4504
Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1
4505
));
4506
assert!(matches!(
4507
world.get_entity_mut([e1, e2]).map(|_| {}),
4508
Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4509
assert!(matches!(
4510
world
4511
.get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4512
.map(|_| {}),
4513
Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4514
assert!(matches!(
4515
world.get_entity_mut(&vec![e1, e2][..]).map(|_| {}),
4516
Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1,
4517
));
4518
assert!(matches!(
4519
world
4520
.get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4521
.map(|_| {}),
4522
Err(EntityMutableFetchError::NotSpawned(e)) if e.entity() == e1));
4523
}
4524
4525
#[test]
4526
#[track_caller]
4527
fn entity_spawn_despawn_tracking() {
4528
use core::panic::Location;
4529
4530
let mut world = World::new();
4531
let entity = world.spawn_empty().id();
4532
assert_eq!(
4533
world.entities.entity_get_spawned_or_despawned_by(entity),
4534
MaybeLocation::new(Some(Location::caller()))
4535
);
4536
assert_eq!(
4537
world.entities.entity_get_spawn_or_despawn_tick(entity),
4538
Some(world.change_tick())
4539
);
4540
let new = world.despawn_no_free(entity).unwrap();
4541
assert_eq!(
4542
world.entities.entity_get_spawned_or_despawned_by(entity),
4543
MaybeLocation::new(Some(Location::caller()))
4544
);
4545
assert_eq!(
4546
world.entities.entity_get_spawn_or_despawn_tick(entity),
4547
Some(world.change_tick())
4548
);
4549
4550
world.spawn_empty_at(new).unwrap();
4551
assert_eq!(entity.index(), new.index());
4552
assert_eq!(
4553
world.entities.entity_get_spawned_or_despawned_by(entity),
4554
MaybeLocation::new(None)
4555
);
4556
assert_eq!(
4557
world.entities.entity_get_spawn_or_despawn_tick(entity),
4558
None
4559
);
4560
world.despawn(new);
4561
assert_eq!(
4562
world.entities.entity_get_spawned_or_despawned_by(entity),
4563
MaybeLocation::new(None)
4564
);
4565
assert_eq!(
4566
world.entities.entity_get_spawn_or_despawn_tick(entity),
4567
None
4568
);
4569
}
4570
4571
#[test]
4572
fn new_world_has_disabling() {
4573
let mut world = World::new();
4574
world.spawn(Foo);
4575
world.spawn((Foo, Disabled));
4576
assert_eq!(1, world.query::<&Foo>().iter(&world).count());
4577
4578
// If we explicitly remove the resource, no entities should be filtered anymore
4579
world.remove_resource::<DefaultQueryFilters>();
4580
assert_eq!(2, world.query::<&Foo>().iter(&world).count());
4581
}
4582
4583
#[test]
4584
fn entities_and_commands() {
4585
#[derive(Component, PartialEq, Debug)]
4586
struct Foo(u32);
4587
4588
let mut world = World::new();
4589
4590
let eid = world.spawn(Foo(35)).id();
4591
4592
let (mut fetcher, mut commands) = world.entities_and_commands();
4593
let emut = fetcher.get_mut(eid).unwrap();
4594
commands.entity(eid).despawn();
4595
assert_eq!(emut.get::<Foo>().unwrap(), &Foo(35));
4596
4597
world.flush();
4598
4599
assert!(world.get_entity(eid).is_err());
4600
}
4601
4602
#[test]
4603
fn resource_query_after_resource_scope() {
4604
#[derive(Event)]
4605
struct EventA;
4606
4607
#[derive(Resource)]
4608
struct ResourceA;
4609
4610
let mut world = World::default();
4611
4612
world.insert_resource(ResourceA);
4613
world.add_observer(move |_event: On<EventA>, _res: Res<ResourceA>| {});
4614
world.resource_scope(|world, _res: Mut<ResourceA>| {
4615
// since we use commands, this should trigger outside of the resource_scope, so the observer should work.
4616
world.commands().trigger(EventA);
4617
});
4618
}
4619
4620
#[test]
4621
fn entities_and_commands_deferred() {
4622
#[derive(Component, PartialEq, Debug)]
4623
struct Foo(u32);
4624
4625
let mut world = World::new();
4626
4627
let eid = world.spawn(Foo(1)).id();
4628
4629
let mut dworld = DeferredWorld::from(&mut world);
4630
4631
let (mut fetcher, mut commands) = dworld.entities_and_commands();
4632
let emut = fetcher.get_mut(eid).unwrap();
4633
commands.entity(eid).despawn();
4634
assert_eq!(emut.get::<Foo>().unwrap(), &Foo(1));
4635
4636
world.flush();
4637
4638
assert!(world.get_entity(eid).is_err());
4639
}
4640
}
4641
4642