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