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::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::EntityHashMap)
693    ///
694    /// ```
695    /// # use bevy_ecs::{prelude::*, entity::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::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::EntityHashMap) to receive an
745    ///   [`EntityHashMap<EntityMut>`](crate::entity::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::EntityHashMap)
827    ///
828    /// ```
829    /// # use bevy_ecs::{prelude::*, entity::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::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::EntityHashMap) to receive an
897    ///   [`EntityHashMap<EntityRef>`](crate::entity::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::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::EntityHashMap) to receive an
931    ///   [`EntityHashMap<EntityMut>`](crate::entity::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::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        since = "0.16.0",
2257        note = "This can cause extreme performance problems when used with lots of arbitrary free entities. See #18054 on GitHub."
2258    )]
2259    pub fn insert_or_spawn_batch<I, B>(&mut self, iter: I) -> Result<(), Vec<Entity>>
2260    where
2261        I: IntoIterator,
2262        I::IntoIter: Iterator<Item = (Entity, B)>,
2263        B: Bundle<Effect: NoBundleEffect>,
2264    {
2265        #[expect(
2266            deprecated,
2267            reason = "This needs to be supported for now, and the outer function is deprecated too."
2268        )]
2269        self.insert_or_spawn_batch_with_caller(iter, MaybeLocation::caller())
2270    }
2271
2272    /// Split into a new function so we can pass the calling location into the function when using
2273    /// as a command.
2274    #[inline]
2275    #[deprecated(
2276        since = "0.16.0",
2277        note = "This can cause extreme performance problems when used with lots of arbitrary free entities. See #18054 on GitHub."
2278    )]
2279    pub(crate) fn insert_or_spawn_batch_with_caller<I, B>(
2280        &mut self,
2281        iter: I,
2282        caller: MaybeLocation,
2283    ) -> Result<(), Vec<Entity>>
2284    where
2285        I: IntoIterator,
2286        I::IntoIter: Iterator<Item = (Entity, B)>,
2287        B: Bundle<Effect: NoBundleEffect>,
2288    {
2289        self.flush();
2290        let change_tick = self.change_tick();
2291
2292        // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
2293        let mut registrator =
2294            unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
2295        let bundle_id = self
2296            .bundles
2297            .register_info::<B>(&mut registrator, &mut self.storages);
2298        enum SpawnOrInsert<'w> {
2299            Spawn(BundleSpawner<'w>),
2300            Insert(BundleInserter<'w>, ArchetypeId),
2301        }
2302
2303        impl<'w> SpawnOrInsert<'w> {
2304            fn entities(&mut self) -> &mut Entities {
2305                match self {
2306                    SpawnOrInsert::Spawn(spawner) => spawner.entities(),
2307                    SpawnOrInsert::Insert(inserter, _) => inserter.entities(),
2308                }
2309            }
2310        }
2311        // SAFETY: we initialized this bundle_id in `init_info`
2312        let mut spawn_or_insert = SpawnOrInsert::Spawn(unsafe {
2313            BundleSpawner::new_with_id(self, bundle_id, change_tick)
2314        });
2315
2316        let mut invalid_entities = Vec::new();
2317        for (entity, bundle) in iter {
2318            #[expect(
2319                deprecated,
2320                reason = "This needs to be supported for now, and the outer function is deprecated too."
2321            )]
2322            match spawn_or_insert
2323                .entities()
2324                .alloc_at_without_replacement(entity)
2325            {
2326                AllocAtWithoutReplacement::Exists(location) => {
2327                    match spawn_or_insert {
2328                        SpawnOrInsert::Insert(ref mut inserter, archetype)
2329                            if location.archetype_id == archetype =>
2330                        {
2331                            // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2332                            unsafe {
2333                                inserter.insert(
2334                                    entity,
2335                                    location,
2336                                    bundle,
2337                                    InsertMode::Replace,
2338                                    caller,
2339                                    RelationshipHookMode::Run,
2340                                )
2341                            };
2342                        }
2343                        _ => {
2344                            // SAFETY: we initialized this bundle_id in `init_info`
2345                            let mut inserter = unsafe {
2346                                BundleInserter::new_with_id(
2347                                    self,
2348                                    location.archetype_id,
2349                                    bundle_id,
2350                                    change_tick,
2351                                )
2352                            };
2353                            // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2354                            unsafe {
2355                                inserter.insert(
2356                                    entity,
2357                                    location,
2358                                    bundle,
2359                                    InsertMode::Replace,
2360                                    caller,
2361                                    RelationshipHookMode::Run,
2362                                )
2363                            };
2364                            spawn_or_insert =
2365                                SpawnOrInsert::Insert(inserter, location.archetype_id);
2366                        }
2367                    };
2368                }
2369                AllocAtWithoutReplacement::DidNotExist => {
2370                    if let SpawnOrInsert::Spawn(ref mut spawner) = spawn_or_insert {
2371                        // SAFETY: `entity` is allocated (but non existent), bundle matches inserter
2372                        unsafe { spawner.spawn_non_existent(entity, bundle, caller) };
2373                    } else {
2374                        // SAFETY: we initialized this bundle_id in `init_info`
2375                        let mut spawner =
2376                            unsafe { BundleSpawner::new_with_id(self, bundle_id, change_tick) };
2377                        // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2378                        unsafe { spawner.spawn_non_existent(entity, bundle, caller) };
2379                        spawn_or_insert = SpawnOrInsert::Spawn(spawner);
2380                    }
2381                }
2382                AllocAtWithoutReplacement::ExistsWithWrongGeneration => {
2383                    invalid_entities.push(entity);
2384                }
2385            }
2386        }
2387
2388        if invalid_entities.is_empty() {
2389            Ok(())
2390        } else {
2391            Err(invalid_entities)
2392        }
2393    }
2394
2395    /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2396    /// adds the `Bundle` of components to each `Entity`.
2397    /// This is faster than doing equivalent operations one-by-one.
2398    ///
2399    /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2400    /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2401    ///
2402    /// This will overwrite any previous values of components shared by the `Bundle`.
2403    /// See [`World::insert_batch_if_new`] to keep the old values instead.
2404    ///
2405    /// # Panics
2406    ///
2407    /// This function will panic if any of the associated entities do not exist.
2408    ///
2409    /// For the fallible version, see [`World::try_insert_batch`].
2410    #[track_caller]
2411    pub fn insert_batch<I, B>(&mut self, batch: I)
2412    where
2413        I: IntoIterator,
2414        I::IntoIter: Iterator<Item = (Entity, B)>,
2415        B: Bundle<Effect: NoBundleEffect>,
2416    {
2417        self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller());
2418    }
2419
2420    /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2421    /// adds the `Bundle` of components to each `Entity` without overwriting.
2422    /// This is faster than doing equivalent operations one-by-one.
2423    ///
2424    /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2425    /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2426    ///
2427    /// This is the same as [`World::insert_batch`], but in case of duplicate
2428    /// components it will leave the old values instead of replacing them with new ones.
2429    ///
2430    /// # Panics
2431    ///
2432    /// This function will panic if any of the associated entities do not exist.
2433    ///
2434    /// For the fallible version, see [`World::try_insert_batch_if_new`].
2435    #[track_caller]
2436    pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
2437    where
2438        I: IntoIterator,
2439        I::IntoIter: Iterator<Item = (Entity, B)>,
2440        B: Bundle<Effect: NoBundleEffect>,
2441    {
2442        self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller());
2443    }
2444
2445    /// Split into a new function so we can differentiate the calling location.
2446    ///
2447    /// This can be called by:
2448    /// - [`World::insert_batch`]
2449    /// - [`World::insert_batch_if_new`]
2450    #[inline]
2451    pub(crate) fn insert_batch_with_caller<I, B>(
2452        &mut self,
2453        batch: I,
2454        insert_mode: InsertMode,
2455        caller: MaybeLocation,
2456    ) where
2457        I: IntoIterator,
2458        I::IntoIter: Iterator<Item = (Entity, B)>,
2459        B: Bundle<Effect: NoBundleEffect>,
2460    {
2461        struct InserterArchetypeCache<'w> {
2462            inserter: BundleInserter<'w>,
2463            archetype_id: ArchetypeId,
2464        }
2465
2466        self.flush();
2467        let change_tick = self.change_tick();
2468        // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
2469        let mut registrator =
2470            unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
2471        let bundle_id = self
2472            .bundles
2473            .register_info::<B>(&mut registrator, &mut self.storages);
2474
2475        let mut batch_iter = batch.into_iter();
2476
2477        if let Some((first_entity, first_bundle)) = batch_iter.next() {
2478            if let Some(first_location) = self.entities().get(first_entity) {
2479                let mut cache = InserterArchetypeCache {
2480                    // SAFETY: we initialized this bundle_id in `register_info`
2481                    inserter: unsafe {
2482                        BundleInserter::new_with_id(
2483                            self,
2484                            first_location.archetype_id,
2485                            bundle_id,
2486                            change_tick,
2487                        )
2488                    },
2489                    archetype_id: first_location.archetype_id,
2490                };
2491                // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2492                unsafe {
2493                    cache.inserter.insert(
2494                        first_entity,
2495                        first_location,
2496                        first_bundle,
2497                        insert_mode,
2498                        caller,
2499                        RelationshipHookMode::Run,
2500                    )
2501                };
2502
2503                for (entity, bundle) in batch_iter {
2504                    if let Some(location) = cache.inserter.entities().get(entity) {
2505                        if location.archetype_id != cache.archetype_id {
2506                            cache = InserterArchetypeCache {
2507                                // SAFETY: we initialized this bundle_id in `register_info`
2508                                inserter: unsafe {
2509                                    BundleInserter::new_with_id(
2510                                        self,
2511                                        location.archetype_id,
2512                                        bundle_id,
2513                                        change_tick,
2514                                    )
2515                                },
2516                                archetype_id: location.archetype_id,
2517                            }
2518                        }
2519                        // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2520                        unsafe {
2521                            cache.inserter.insert(
2522                                entity,
2523                                location,
2524                                bundle,
2525                                insert_mode,
2526                                caller,
2527                                RelationshipHookMode::Run,
2528                            )
2529                        };
2530                    } else {
2531                        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));
2532                    }
2533                }
2534            } else {
2535                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));
2536            }
2537        }
2538    }
2539
2540    /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2541    /// adds the `Bundle` of components to each `Entity`.
2542    /// This is faster than doing equivalent operations one-by-one.
2543    ///
2544    /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2545    /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2546    ///
2547    /// This will overwrite any previous values of components shared by the `Bundle`.
2548    /// See [`World::try_insert_batch_if_new`] to keep the old values instead.
2549    ///
2550    /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2551    ///
2552    /// For the panicking version, see [`World::insert_batch`].
2553    #[track_caller]
2554    pub fn try_insert_batch<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2555    where
2556        I: IntoIterator,
2557        I::IntoIter: Iterator<Item = (Entity, B)>,
2558        B: Bundle<Effect: NoBundleEffect>,
2559    {
2560        self.try_insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller())
2561    }
2562    /// For a given batch of ([`Entity`], [`Bundle`]) pairs,
2563    /// adds the `Bundle` of components to each `Entity` without overwriting.
2564    /// This is faster than doing equivalent operations one-by-one.
2565    ///
2566    /// A batch can be any type that implements [`IntoIterator`] containing `(Entity, Bundle)` tuples,
2567    /// such as a [`Vec<(Entity, Bundle)>`] or an array `[(Entity, Bundle); N]`.
2568    ///
2569    /// This is the same as [`World::try_insert_batch`], but in case of duplicate
2570    /// components it will leave the old values instead of replacing them with new ones.
2571    ///
2572    /// Returns a [`TryInsertBatchError`] if any of the provided entities do not exist.
2573    ///
2574    /// For the panicking version, see [`World::insert_batch_if_new`].
2575    #[track_caller]
2576    pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I) -> Result<(), TryInsertBatchError>
2577    where
2578        I: IntoIterator,
2579        I::IntoIter: Iterator<Item = (Entity, B)>,
2580        B: Bundle<Effect: NoBundleEffect>,
2581    {
2582        self.try_insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller())
2583    }
2584
2585    /// Split into a new function so we can differentiate the calling location.
2586    ///
2587    /// This can be called by:
2588    /// - [`World::try_insert_batch`]
2589    /// - [`World::try_insert_batch_if_new`]
2590    /// - [`Commands::insert_batch`]
2591    /// - [`Commands::insert_batch_if_new`]
2592    /// - [`Commands::try_insert_batch`]
2593    /// - [`Commands::try_insert_batch_if_new`]
2594    #[inline]
2595    pub(crate) fn try_insert_batch_with_caller<I, B>(
2596        &mut self,
2597        batch: I,
2598        insert_mode: InsertMode,
2599        caller: MaybeLocation,
2600    ) -> Result<(), TryInsertBatchError>
2601    where
2602        I: IntoIterator,
2603        I::IntoIter: Iterator<Item = (Entity, B)>,
2604        B: Bundle<Effect: NoBundleEffect>,
2605    {
2606        struct InserterArchetypeCache<'w> {
2607            inserter: BundleInserter<'w>,
2608            archetype_id: ArchetypeId,
2609        }
2610
2611        self.flush();
2612        let change_tick = self.change_tick();
2613        // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
2614        let mut registrator =
2615            unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
2616        let bundle_id = self
2617            .bundles
2618            .register_info::<B>(&mut registrator, &mut self.storages);
2619
2620        let mut invalid_entities = Vec::<Entity>::new();
2621        let mut batch_iter = batch.into_iter();
2622
2623        // We need to find the first valid entity so we can initialize the bundle inserter.
2624        // This differs from `insert_batch_with_caller` because that method can just panic
2625        // if the first entity is invalid, whereas this method needs to keep going.
2626        let cache = loop {
2627            if let Some((first_entity, first_bundle)) = batch_iter.next() {
2628                if let Some(first_location) = self.entities().get(first_entity) {
2629                    let mut cache = InserterArchetypeCache {
2630                        // SAFETY: we initialized this bundle_id in `register_info`
2631                        inserter: unsafe {
2632                            BundleInserter::new_with_id(
2633                                self,
2634                                first_location.archetype_id,
2635                                bundle_id,
2636                                change_tick,
2637                            )
2638                        },
2639                        archetype_id: first_location.archetype_id,
2640                    };
2641                    // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2642                    unsafe {
2643                        cache.inserter.insert(
2644                            first_entity,
2645                            first_location,
2646                            first_bundle,
2647                            insert_mode,
2648                            caller,
2649                            RelationshipHookMode::Run,
2650                        )
2651                    };
2652                    break Some(cache);
2653                }
2654                invalid_entities.push(first_entity);
2655            } else {
2656                // We reached the end of the entities the caller provided and none were valid.
2657                break None;
2658            }
2659        };
2660
2661        if let Some(mut cache) = cache {
2662            for (entity, bundle) in batch_iter {
2663                if let Some(location) = cache.inserter.entities().get(entity) {
2664                    if location.archetype_id != cache.archetype_id {
2665                        cache = InserterArchetypeCache {
2666                            // SAFETY: we initialized this bundle_id in `register_info`
2667                            inserter: unsafe {
2668                                BundleInserter::new_with_id(
2669                                    self,
2670                                    location.archetype_id,
2671                                    bundle_id,
2672                                    change_tick,
2673                                )
2674                            },
2675                            archetype_id: location.archetype_id,
2676                        }
2677                    }
2678                    // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
2679                    unsafe {
2680                        cache.inserter.insert(
2681                            entity,
2682                            location,
2683                            bundle,
2684                            insert_mode,
2685                            caller,
2686                            RelationshipHookMode::Run,
2687                        )
2688                    };
2689                } else {
2690                    invalid_entities.push(entity);
2691                }
2692            }
2693        }
2694
2695        if invalid_entities.is_empty() {
2696            Ok(())
2697        } else {
2698            Err(TryInsertBatchError {
2699                bundle_type: core::any::type_name::<B>(),
2700                entities: invalid_entities,
2701            })
2702        }
2703    }
2704
2705    /// Temporarily removes the requested resource from this [`World`], runs custom user code,
2706    /// then re-adds the resource before returning.
2707    ///
2708    /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2709    /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2710    ///
2711    /// # Example
2712    /// ```
2713    /// use bevy_ecs::prelude::*;
2714    /// #[derive(Resource)]
2715    /// struct A(u32);
2716    /// #[derive(Component)]
2717    /// struct B(u32);
2718    /// let mut world = World::new();
2719    /// world.insert_resource(A(1));
2720    /// let entity = world.spawn(B(1)).id();
2721    ///
2722    /// world.resource_scope(|world, mut a: Mut<A>| {
2723    ///     let b = world.get_mut::<B>(entity).unwrap();
2724    ///     a.0 += b.0;
2725    /// });
2726    /// assert_eq!(world.get_resource::<A>().unwrap().0, 2);
2727    /// ```
2728    ///
2729    /// See also [`try_resource_scope`](Self::try_resource_scope).
2730    #[track_caller]
2731    pub fn resource_scope<R: Resource, U>(&mut self, f: impl FnOnce(&mut World, Mut<R>) -> U) -> U {
2732        self.try_resource_scope(f)
2733            .unwrap_or_else(|| panic!("resource does not exist: {}", core::any::type_name::<R>()))
2734    }
2735
2736    /// Temporarily removes the requested resource from this [`World`] if it exists, runs custom user code,
2737    /// then re-adds the resource before returning. Returns `None` if the resource does not exist in this [`World`].
2738    ///
2739    /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
2740    /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
2741    ///
2742    /// See also [`resource_scope`](Self::resource_scope).
2743    pub fn try_resource_scope<R: Resource, U>(
2744        &mut self,
2745        f: impl FnOnce(&mut World, Mut<R>) -> U,
2746    ) -> Option<U> {
2747        let last_change_tick = self.last_change_tick();
2748        let change_tick = self.change_tick();
2749
2750        let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
2751        let (ptr, mut ticks, mut caller) = self
2752            .storages
2753            .resources
2754            .get_mut(component_id)
2755            .and_then(ResourceData::remove)?;
2756        // Read the value onto the stack to avoid potential mut aliasing.
2757        // SAFETY: `ptr` was obtained from the TypeId of `R`.
2758        let mut value = unsafe { ptr.read::<R>() };
2759        let value_mut = Mut {
2760            value: &mut value,
2761            ticks: TicksMut {
2762                added: &mut ticks.added,
2763                changed: &mut ticks.changed,
2764                last_run: last_change_tick,
2765                this_run: change_tick,
2766            },
2767            changed_by: caller.as_mut(),
2768        };
2769        let result = f(self, value_mut);
2770        assert!(!self.contains_resource::<R>(),
2771            "Resource `{}` was inserted during a call to World::resource_scope.\n\
2772            This is not allowed as the original resource is reinserted to the world after the closure is invoked.",
2773            core::any::type_name::<R>());
2774
2775        OwningPtr::make(value, |ptr| {
2776            // SAFETY: pointer is of type R
2777            unsafe {
2778                self.storages.resources.get_mut(component_id).map(|info| {
2779                    info.insert_with_ticks(ptr, ticks, caller);
2780                })
2781            }
2782        })?;
2783
2784        Some(result)
2785    }
2786
2787    /// Sends an [`Event`].
2788    /// This method returns the [ID](`EventId`) of the sent `event`,
2789    /// or [`None`] if the `event` could not be sent.
2790    #[inline]
2791    pub fn send_event<E: Event>(&mut self, event: E) -> Option<EventId<E>> {
2792        self.send_event_batch(core::iter::once(event))?.next()
2793    }
2794
2795    /// Sends the default value of the [`Event`] of type `E`.
2796    /// This method returns the [ID](`EventId`) of the sent `event`,
2797    /// or [`None`] if the `event` could not be sent.
2798    #[inline]
2799    pub fn send_event_default<E: Event + Default>(&mut self) -> Option<EventId<E>> {
2800        self.send_event(E::default())
2801    }
2802
2803    /// Sends a batch of [`Event`]s from an iterator.
2804    /// This method returns the [IDs](`EventId`) of the sent `events`,
2805    /// or [`None`] if the `event` could not be sent.
2806    #[inline]
2807    pub fn send_event_batch<E: Event>(
2808        &mut self,
2809        events: impl IntoIterator<Item = E>,
2810    ) -> Option<SendBatchIds<E>> {
2811        let Some(mut events_resource) = self.get_resource_mut::<Events<E>>() else {
2812            log::error!(
2813                "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 ",
2814                core::any::type_name::<E>()
2815            );
2816            return None;
2817        };
2818        Some(events_resource.send_batch(events))
2819    }
2820
2821    /// Inserts a new resource with the given `value`. Will replace the value if it already existed.
2822    ///
2823    /// **You should prefer to use the typed API [`World::insert_resource`] where possible and only
2824    /// use this in cases where the actual types are not known at compile time.**
2825    ///
2826    /// # Safety
2827    /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
2828    #[inline]
2829    #[track_caller]
2830    pub unsafe fn insert_resource_by_id(
2831        &mut self,
2832        component_id: ComponentId,
2833        value: OwningPtr<'_>,
2834        caller: MaybeLocation,
2835    ) {
2836        let change_tick = self.change_tick();
2837
2838        let resource = self.initialize_resource_internal(component_id);
2839        // SAFETY: `value` is valid for `component_id`, ensured by caller
2840        unsafe {
2841            resource.insert(value, change_tick, caller);
2842        }
2843    }
2844
2845    /// Inserts a new `!Send` resource with the given `value`. Will replace the value if it already
2846    /// existed.
2847    ///
2848    /// **You should prefer to use the typed API [`World::insert_non_send_resource`] where possible and only
2849    /// use this in cases where the actual types are not known at compile time.**
2850    ///
2851    /// # Panics
2852    /// If a value is already present, this function will panic if not called from the same
2853    /// thread that the original value was inserted from.
2854    ///
2855    /// # Safety
2856    /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
2857    #[inline]
2858    #[track_caller]
2859    pub unsafe fn insert_non_send_by_id(
2860        &mut self,
2861        component_id: ComponentId,
2862        value: OwningPtr<'_>,
2863        caller: MaybeLocation,
2864    ) {
2865        let change_tick = self.change_tick();
2866
2867        let resource = self.initialize_non_send_internal(component_id);
2868        // SAFETY: `value` is valid for `component_id`, ensured by caller
2869        unsafe {
2870            resource.insert(value, change_tick, caller);
2871        }
2872    }
2873
2874    /// # Panics
2875    /// Panics if `component_id` is not registered as a `Send` component type in this `World`
2876    #[inline]
2877    pub(crate) fn initialize_resource_internal(
2878        &mut self,
2879        component_id: ComponentId,
2880    ) -> &mut ResourceData<true> {
2881        self.flush_components();
2882        let archetypes = &mut self.archetypes;
2883        self.storages
2884            .resources
2885            .initialize_with(component_id, &self.components, || {
2886                archetypes.new_archetype_component_id()
2887            })
2888    }
2889
2890    /// # Panics
2891    /// Panics if `component_id` is not registered in this world
2892    #[inline]
2893    pub(crate) fn initialize_non_send_internal(
2894        &mut self,
2895        component_id: ComponentId,
2896    ) -> &mut ResourceData<false> {
2897        self.flush_components();
2898        let archetypes = &mut self.archetypes;
2899        self.storages
2900            .non_send_resources
2901            .initialize_with(component_id, &self.components, || {
2902                archetypes.new_archetype_component_id()
2903            })
2904    }
2905
2906    /// Empties queued entities and adds them to the empty [`Archetype`](crate::archetype::Archetype).
2907    /// This should be called before doing operations that might operate on queued entities,
2908    /// such as inserting a [`Component`].
2909    pub(crate) fn flush_entities(&mut self) {
2910        let empty_archetype = self.archetypes.empty_mut();
2911        let table = &mut self.storages.tables[empty_archetype.table_id()];
2912        // PERF: consider pre-allocating space for flushed entities
2913        // SAFETY: entity is set to a valid location
2914        unsafe {
2915            self.entities.flush(|entity, location| {
2916                // SAFETY: no components are allocated by archetype.allocate() because the archetype
2917                // is empty
2918                *location = empty_archetype.allocate(entity, table.allocate(entity));
2919            });
2920        }
2921    }
2922
2923    /// Applies any commands in the world's internal [`CommandQueue`].
2924    /// This does not apply commands from any systems, only those stored in the world.
2925    ///
2926    /// # Panics
2927    /// This will panic if any of the queued commands are [`spawn`](Commands::spawn).
2928    /// If this is possible, you should instead use [`flush`](Self::flush).
2929    pub(crate) fn flush_commands(&mut self) {
2930        // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
2931        if !unsafe { self.command_queue.is_empty() } {
2932            // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
2933            unsafe {
2934                self.command_queue
2935                    .clone()
2936                    .apply_or_drop_queued(Some(self.into()));
2937            };
2938        }
2939    }
2940
2941    /// Applies any queued component registration.
2942    /// For spawning vanilla rust component types and resources, this is not strictly necessary.
2943    /// However, flushing components can make information available more quickly, and can have performance benefits.
2944    /// Additionally, for components and resources registered dynamically through a raw descriptor or similar,
2945    /// this is the only way to complete their registration.
2946    pub(crate) fn flush_components(&mut self) {
2947        self.components_registrator().apply_queued_registrations();
2948    }
2949
2950    /// Flushes queued entities and commands.
2951    ///
2952    /// Queued entities will be spawned, and then commands will be applied.
2953    #[inline]
2954    pub fn flush(&mut self) {
2955        self.flush_entities();
2956        self.flush_components();
2957        self.flush_commands();
2958    }
2959
2960    /// Increments the world's current change tick and returns the old value.
2961    ///
2962    /// If you need to call this method, but do not have `&mut` access to the world,
2963    /// consider using [`as_unsafe_world_cell_readonly`](Self::as_unsafe_world_cell_readonly)
2964    /// to obtain an [`UnsafeWorldCell`] and calling [`increment_change_tick`](UnsafeWorldCell::increment_change_tick) on that.
2965    /// Note that this *can* be done in safe code, despite the name of the type.
2966    #[inline]
2967    pub fn increment_change_tick(&mut self) -> Tick {
2968        let change_tick = self.change_tick.get_mut();
2969        let prev_tick = *change_tick;
2970        *change_tick = change_tick.wrapping_add(1);
2971        Tick::new(prev_tick)
2972    }
2973
2974    /// Reads the current change tick of this world.
2975    ///
2976    /// If you have exclusive (`&mut`) access to the world, consider using [`change_tick()`](Self::change_tick),
2977    /// which is more efficient since it does not require atomic synchronization.
2978    #[inline]
2979    pub fn read_change_tick(&self) -> Tick {
2980        let tick = self.change_tick.load(Ordering::Acquire);
2981        Tick::new(tick)
2982    }
2983
2984    /// Reads the current change tick of this world.
2985    ///
2986    /// This does the same thing as [`read_change_tick()`](Self::read_change_tick), only this method
2987    /// is more efficient since it does not require atomic synchronization.
2988    #[inline]
2989    pub fn change_tick(&mut self) -> Tick {
2990        let tick = *self.change_tick.get_mut();
2991        Tick::new(tick)
2992    }
2993
2994    /// When called from within an exclusive system (a [`System`] that takes `&mut World` as its first
2995    /// parameter), this method returns the [`Tick`] indicating the last time the exclusive system was run.
2996    ///
2997    /// Otherwise, this returns the `Tick` indicating the last time that [`World::clear_trackers`] was called.
2998    ///
2999    /// [`System`]: crate::system::System
3000    #[inline]
3001    pub fn last_change_tick(&self) -> Tick {
3002        self.last_change_tick
3003    }
3004
3005    /// Returns the id of the last ECS event that was fired.
3006    /// Used internally to ensure observers don't trigger multiple times for the same event.
3007    #[inline]
3008    pub(crate) fn last_trigger_id(&self) -> u32 {
3009        self.last_trigger_id
3010    }
3011
3012    /// Sets [`World::last_change_tick()`] to the specified value during a scope.
3013    /// When the scope terminates, it will return to its old value.
3014    ///
3015    /// This is useful if you need a region of code to be able to react to earlier changes made in the same system.
3016    ///
3017    /// # Examples
3018    ///
3019    /// ```
3020    /// # use bevy_ecs::prelude::*;
3021    /// // This function runs an update loop repeatedly, allowing each iteration of the loop
3022    /// // to react to changes made in the previous loop iteration.
3023    /// fn update_loop(
3024    ///     world: &mut World,
3025    ///     mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
3026    /// ) {
3027    ///     let mut last_change_tick = world.last_change_tick();
3028    ///
3029    ///     // Repeatedly run the update function until it requests a break.
3030    ///     loop {
3031    ///         let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
3032    ///             // Increment the change tick so we can detect changes from the previous update.
3033    ///             last_change_tick = world.change_tick();
3034    ///             world.increment_change_tick();
3035    ///
3036    ///             // Update once.
3037    ///             update_fn(world)
3038    ///         });
3039    ///
3040    ///         // End the loop when the closure returns `ControlFlow::Break`.
3041    ///         if control_flow.is_break() {
3042    ///             break;
3043    ///         }
3044    ///     }
3045    /// }
3046    /// #
3047    /// # #[derive(Resource)] struct Count(u32);
3048    /// # let mut world = World::new();
3049    /// # world.insert_resource(Count(0));
3050    /// # let saved_last_tick = world.last_change_tick();
3051    /// # let mut num_updates = 0;
3052    /// # update_loop(&mut world, |world| {
3053    /// #     let mut c = world.resource_mut::<Count>();
3054    /// #     match c.0 {
3055    /// #         0 => {
3056    /// #             assert_eq!(num_updates, 0);
3057    /// #             assert!(c.is_added());
3058    /// #             c.0 = 1;
3059    /// #         }
3060    /// #         1 => {
3061    /// #             assert_eq!(num_updates, 1);
3062    /// #             assert!(!c.is_added());
3063    /// #             assert!(c.is_changed());
3064    /// #             c.0 = 2;
3065    /// #         }
3066    /// #         2 if c.is_changed() => {
3067    /// #             assert_eq!(num_updates, 2);
3068    /// #             assert!(!c.is_added());
3069    /// #         }
3070    /// #         2 => {
3071    /// #             assert_eq!(num_updates, 3);
3072    /// #             assert!(!c.is_changed());
3073    /// #             world.remove_resource::<Count>();
3074    /// #             world.insert_resource(Count(3));
3075    /// #         }
3076    /// #         3 if c.is_changed() => {
3077    /// #             assert_eq!(num_updates, 4);
3078    /// #             assert!(c.is_added());
3079    /// #         }
3080    /// #         3 => {
3081    /// #             assert_eq!(num_updates, 5);
3082    /// #             assert!(!c.is_added());
3083    /// #             c.0 = 4;
3084    /// #             return std::ops::ControlFlow::Break(());
3085    /// #         }
3086    /// #         _ => unreachable!(),
3087    /// #     }
3088    /// #     num_updates += 1;
3089    /// #     std::ops::ControlFlow::Continue(())
3090    /// # });
3091    /// # assert_eq!(num_updates, 5);
3092    /// # assert_eq!(world.resource::<Count>().0, 4);
3093    /// # assert_eq!(world.last_change_tick(), saved_last_tick);
3094    /// ```
3095    pub fn last_change_tick_scope<T>(
3096        &mut self,
3097        last_change_tick: Tick,
3098        f: impl FnOnce(&mut World) -> T,
3099    ) -> T {
3100        struct LastTickGuard<'a> {
3101            world: &'a mut World,
3102            last_tick: Tick,
3103        }
3104
3105        // By setting the change tick in the drop impl, we ensure that
3106        // the change tick gets reset even if a panic occurs during the scope.
3107        impl Drop for LastTickGuard<'_> {
3108            fn drop(&mut self) {
3109                self.world.last_change_tick = self.last_tick;
3110            }
3111        }
3112
3113        let guard = LastTickGuard {
3114            last_tick: self.last_change_tick,
3115            world: self,
3116        };
3117
3118        guard.world.last_change_tick = last_change_tick;
3119
3120        f(guard.world)
3121    }
3122
3123    /// Iterates all component change ticks and clamps any older than [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
3124    /// This prevents overflow and thus prevents false positives.
3125    ///
3126    /// **Note:** Does nothing if the [`World`] counter has not been incremented at least [`CHECK_TICK_THRESHOLD`]
3127    /// times since the previous pass.
3128    // TODO: benchmark and optimize
3129    pub fn check_change_ticks(&mut self) {
3130        let change_tick = self.change_tick();
3131        if change_tick.relative_to(self.last_check_tick).get() < CHECK_TICK_THRESHOLD {
3132            return;
3133        }
3134
3135        let Storages {
3136            ref mut tables,
3137            ref mut sparse_sets,
3138            ref mut resources,
3139            ref mut non_send_resources,
3140        } = self.storages;
3141
3142        #[cfg(feature = "trace")]
3143        let _span = tracing::info_span!("check component ticks").entered();
3144        tables.check_change_ticks(change_tick);
3145        sparse_sets.check_change_ticks(change_tick);
3146        resources.check_change_ticks(change_tick);
3147        non_send_resources.check_change_ticks(change_tick);
3148
3149        if let Some(mut schedules) = self.get_resource_mut::<Schedules>() {
3150            schedules.check_change_ticks(change_tick);
3151        }
3152
3153        self.last_check_tick = change_tick;
3154    }
3155
3156    /// Runs both [`clear_entities`](Self::clear_entities) and [`clear_resources`](Self::clear_resources),
3157    /// invalidating all [`Entity`] and resource fetches such as [`Res`](crate::system::Res), [`ResMut`](crate::system::ResMut)
3158    pub fn clear_all(&mut self) {
3159        self.clear_entities();
3160        self.clear_resources();
3161    }
3162
3163    /// Despawns all entities in this [`World`].
3164    pub fn clear_entities(&mut self) {
3165        self.storages.tables.clear();
3166        self.storages.sparse_sets.clear_entities();
3167        self.archetypes.clear_entities();
3168        self.entities.clear();
3169    }
3170
3171    /// Clears all resources in this [`World`].
3172    ///
3173    /// **Note:** Any resource fetch to this [`World`] will fail unless they are re-initialized,
3174    /// including engine-internal resources that are only initialized on app/world construction.
3175    ///
3176    /// This can easily cause systems expecting certain resources to immediately start panicking.
3177    /// Use with caution.
3178    pub fn clear_resources(&mut self) {
3179        self.storages.resources.clear();
3180        self.storages.non_send_resources.clear();
3181    }
3182
3183    /// Registers all of the components in the given [`Bundle`] and returns both the component
3184    /// ids and the bundle id.
3185    ///
3186    /// This is largely equivalent to calling [`register_component`](Self::register_component) on each
3187    /// component in the bundle.
3188    #[inline]
3189    pub fn register_bundle<B: Bundle>(&mut self) -> &BundleInfo {
3190        // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too.
3191        let mut registrator =
3192            unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) };
3193        let id = self
3194            .bundles
3195            .register_info::<B>(&mut registrator, &mut self.storages);
3196        // SAFETY: We just initialized the bundle so its id should definitely be valid.
3197        unsafe { self.bundles.get(id).debug_checked_unwrap() }
3198    }
3199
3200    /// Registers the given [`ComponentId`]s as a dynamic bundle and returns both the required component ids and the bundle id.
3201    ///
3202    /// Note that the components need to be registered first, this function only creates a bundle combining them. Components
3203    /// can be registered with [`World::register_component`]/[`_with_descriptor`](World::register_component_with_descriptor).
3204    ///
3205    /// **You should prefer to use the typed API [`World::register_bundle`] where possible and only use this in cases where
3206    /// not all of the actual types are known at compile time.**
3207    ///
3208    /// # Panics
3209    /// This function will panic if any of the provided component ids do not belong to a component known to this [`World`].
3210    #[inline]
3211    pub fn register_dynamic_bundle(&mut self, component_ids: &[ComponentId]) -> &BundleInfo {
3212        let id =
3213            self.bundles
3214                .init_dynamic_info(&mut self.storages, &self.components, component_ids);
3215        // SAFETY: We just initialized the bundle so its id should definitely be valid.
3216        unsafe { self.bundles.get(id).debug_checked_unwrap() }
3217    }
3218}
3219
3220impl World {
3221    /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3222    /// The returned pointer must not be used to modify the resource, and must not be
3223    /// dereferenced after the immutable borrow of the [`World`] ends.
3224    ///
3225    /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
3226    /// use this in cases where the actual types are not known at compile time.**
3227    #[inline]
3228    pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3229        // SAFETY:
3230        // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3231        // - `&self` ensures there are no mutable borrows on world data
3232        unsafe {
3233            self.as_unsafe_world_cell_readonly()
3234                .get_resource_by_id(component_id)
3235        }
3236    }
3237
3238    /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
3239    /// The returned pointer may be used to modify the resource, as long as the mutable borrow
3240    /// of the [`World`] is still valid.
3241    ///
3242    /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
3243    /// use this in cases where the actual types are not known at compile time.**
3244    #[inline]
3245    pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3246        // SAFETY:
3247        // - `&mut self` ensures that all accessed data is unaliased
3248        // - `as_unsafe_world_cell` provides mutable permission to the whole world
3249        unsafe {
3250            self.as_unsafe_world_cell()
3251                .get_resource_mut_by_id(component_id)
3252        }
3253    }
3254
3255    /// Iterates over all resources in the world.
3256    ///
3257    /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents
3258    /// of each resource will require the use of unsafe code.
3259    ///
3260    /// # Examples
3261    ///
3262    /// ## Printing the size of all resources
3263    ///
3264    /// ```
3265    /// # use bevy_ecs::prelude::*;
3266    /// # #[derive(Resource)]
3267    /// # struct A(u32);
3268    /// # #[derive(Resource)]
3269    /// # struct B(u32);
3270    /// #
3271    /// # let mut world = World::new();
3272    /// # world.remove_resource::<bevy_ecs::entity_disabling::DefaultQueryFilters>();
3273    /// # world.insert_resource(A(1));
3274    /// # world.insert_resource(B(2));
3275    /// let mut total = 0;
3276    /// for (info, _) in world.iter_resources() {
3277    ///    println!("Resource: {}", info.name());
3278    ///    println!("Size: {} bytes", info.layout().size());
3279    ///    total += info.layout().size();
3280    /// }
3281    /// println!("Total size: {} bytes", total);
3282    /// # assert_eq!(total, size_of::<A>() + size_of::<B>());
3283    /// ```
3284    ///
3285    /// ## Dynamically running closures for resources matching specific `TypeId`s
3286    ///
3287    /// ```
3288    /// # use bevy_ecs::prelude::*;
3289    /// # use std::collections::HashMap;
3290    /// # use std::any::TypeId;
3291    /// # use bevy_ptr::Ptr;
3292    /// # #[derive(Resource)]
3293    /// # struct A(u32);
3294    /// # #[derive(Resource)]
3295    /// # struct B(u32);
3296    /// #
3297    /// # let mut world = World::new();
3298    /// # world.insert_resource(A(1));
3299    /// # world.insert_resource(B(2));
3300    /// #
3301    /// // In this example, `A` and `B` are resources. We deliberately do not use the
3302    /// // `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
3303    /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3304    ///
3305    /// // Create the hash map that will store the closures for each resource type
3306    /// let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();
3307    ///
3308    /// // Add closure for `A`
3309    /// closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
3310    ///     // SAFETY: We assert ptr is the same type of A with TypeId of A
3311    ///     let a = unsafe { &ptr.deref::<A>() };
3312    /// #   assert_eq!(a.0, 1);
3313    ///     // ... do something with `a` here
3314    /// }));
3315    ///
3316    /// // Add closure for `B`
3317    /// closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
3318    ///     // SAFETY: We assert ptr is the same type of B with TypeId of B
3319    ///     let b = unsafe { &ptr.deref::<B>() };
3320    /// #   assert_eq!(b.0, 2);
3321    ///     // ... do something with `b` here
3322    /// }));
3323    ///
3324    /// // Iterate all resources, in order to run the closures for each matching resource type
3325    /// for (info, ptr) in world.iter_resources() {
3326    ///     let Some(type_id) = info.type_id() else {
3327    ///        // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3328    ///        // dynamically inserted via a scripting language) in which case we can't match them.
3329    ///        continue;
3330    ///     };
3331    ///
3332    ///     let Some(closure) = closures.get(&type_id) else {
3333    ///        // No closure for this resource type, skip it.
3334    ///        continue;
3335    ///     };
3336    ///
3337    ///     // Run the closure for the resource
3338    ///     closure(&ptr);
3339    /// }
3340    /// ```
3341    #[inline]
3342    pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)> {
3343        self.storages
3344            .resources
3345            .iter()
3346            .filter_map(|(component_id, data)| {
3347                // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
3348                let component_info = unsafe {
3349                    self.components
3350                        .get_info(component_id)
3351                        .debug_checked_unwrap()
3352                };
3353                Some((component_info, data.get_data()?))
3354            })
3355    }
3356
3357    /// Mutably iterates over all resources in the world.
3358    ///
3359    /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading from or writing
3360    /// to the contents of each resource will require the use of unsafe code.
3361    ///
3362    /// # Example
3363    ///
3364    /// ```
3365    /// # use bevy_ecs::prelude::*;
3366    /// # use bevy_ecs::change_detection::MutUntyped;
3367    /// # use std::collections::HashMap;
3368    /// # use std::any::TypeId;
3369    /// # #[derive(Resource)]
3370    /// # struct A(u32);
3371    /// # #[derive(Resource)]
3372    /// # struct B(u32);
3373    /// #
3374    /// # let mut world = World::new();
3375    /// # world.insert_resource(A(1));
3376    /// # world.insert_resource(B(2));
3377    /// #
3378    /// // In this example, `A` and `B` are resources. We deliberately do not use the
3379    /// // `bevy_reflect` crate here to showcase the low-level `MutUntyped` usage. You should
3380    /// // probably use something like `ReflectFromPtr` in a real-world scenario.
3381    ///
3382    /// // Create the hash map that will store the mutator closures for each resource type
3383    /// let mut mutators: HashMap<TypeId, Box<dyn Fn(&mut MutUntyped<'_>)>> = HashMap::default();
3384    ///
3385    /// // Add mutator closure for `A`
3386    /// mutators.insert(TypeId::of::<A>(), Box::new(|mut_untyped| {
3387    ///     // Note: `MutUntyped::as_mut()` automatically marks the resource as changed
3388    ///     // for ECS change detection, and gives us a `PtrMut` we can use to mutate the resource.
3389    ///     // SAFETY: We assert ptr is the same type of A with TypeId of A
3390    ///     let a = unsafe { &mut mut_untyped.as_mut().deref_mut::<A>() };
3391    /// #   a.0 += 1;
3392    ///     // ... mutate `a` here
3393    /// }));
3394    ///
3395    /// // Add mutator closure for `B`
3396    /// mutators.insert(TypeId::of::<B>(), Box::new(|mut_untyped| {
3397    ///     // SAFETY: We assert ptr is the same type of B with TypeId of B
3398    ///     let b = unsafe { &mut mut_untyped.as_mut().deref_mut::<B>() };
3399    /// #   b.0 += 1;
3400    ///     // ... mutate `b` here
3401    /// }));
3402    ///
3403    /// // Iterate all resources, in order to run the mutator closures for each matching resource type
3404    /// for (info, mut mut_untyped) in world.iter_resources_mut() {
3405    ///     let Some(type_id) = info.type_id() else {
3406    ///        // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
3407    ///        // dynamically inserted via a scripting language) in which case we can't match them.
3408    ///        continue;
3409    ///     };
3410    ///
3411    ///     let Some(mutator) = mutators.get(&type_id) else {
3412    ///        // No mutator closure for this resource type, skip it.
3413    ///        continue;
3414    ///     };
3415    ///
3416    ///     // Run the mutator closure for the resource
3417    ///     mutator(&mut mut_untyped);
3418    /// }
3419    /// # assert_eq!(world.resource::<A>().0, 2);
3420    /// # assert_eq!(world.resource::<B>().0, 3);
3421    /// ```
3422    #[inline]
3423    pub fn iter_resources_mut(&mut self) -> impl Iterator<Item = (&ComponentInfo, MutUntyped<'_>)> {
3424        self.storages
3425            .resources
3426            .iter()
3427            .filter_map(|(component_id, data)| {
3428                // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
3429                let component_info = unsafe {
3430                    self.components
3431                        .get_info(component_id)
3432                        .debug_checked_unwrap()
3433                };
3434                let (ptr, ticks, caller) = data.get_with_ticks()?;
3435
3436                // SAFETY:
3437                // - We have exclusive access to the world, so no other code can be aliasing the `TickCells`
3438                // - We only hold one `TicksMut` at a time, and we let go of it before getting the next one
3439                let ticks = unsafe {
3440                    TicksMut::from_tick_cells(
3441                        ticks,
3442                        self.last_change_tick(),
3443                        self.read_change_tick(),
3444                    )
3445                };
3446
3447                let mut_untyped = MutUntyped {
3448                    // SAFETY:
3449                    // - We have exclusive access to the world, so no other code can be aliasing the `Ptr`
3450                    // - We iterate one resource at a time, and we let go of each `PtrMut` before getting the next one
3451                    value: unsafe { ptr.assert_unique() },
3452                    ticks,
3453                    // SAFETY:
3454                    // - We have exclusive access to the world, so no other code can be aliasing the `Ptr`
3455                    // - We iterate one resource at a time, and we let go of each `PtrMut` before getting the next one
3456                    changed_by: unsafe { caller.map(|caller| caller.deref_mut()) },
3457                };
3458
3459                Some((component_info, mut_untyped))
3460            })
3461    }
3462
3463    /// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
3464    /// The returned pointer must not be used to modify the resource, and must not be
3465    /// dereferenced after the immutable borrow of the [`World`] ends.
3466    ///
3467    /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
3468    /// use this in cases where the actual types are not known at compile time.**
3469    ///
3470    /// # Panics
3471    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3472    #[inline]
3473    pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
3474        // SAFETY:
3475        // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
3476        // - `&self` ensures there are no mutable borrows on world data
3477        unsafe {
3478            self.as_unsafe_world_cell_readonly()
3479                .get_non_send_resource_by_id(component_id)
3480        }
3481    }
3482
3483    /// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
3484    /// The returned pointer may be used to modify the resource, as long as the mutable borrow
3485    /// of the [`World`] is still valid.
3486    ///
3487    /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
3488    /// use this in cases where the actual types are not known at compile time.**
3489    ///
3490    /// # Panics
3491    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3492    #[inline]
3493    pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
3494        // SAFETY:
3495        // - `&mut self` ensures that all accessed data is unaliased
3496        // - `as_unsafe_world_cell` provides mutable permission to the whole world
3497        unsafe {
3498            self.as_unsafe_world_cell()
3499                .get_non_send_resource_mut_by_id(component_id)
3500        }
3501    }
3502
3503    /// Removes the resource of a given type, if it exists. Otherwise returns `None`.
3504    ///
3505    /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
3506    /// use this in cases where the actual types are not known at compile time.**
3507    pub fn remove_resource_by_id(&mut self, component_id: ComponentId) -> Option<()> {
3508        self.storages
3509            .resources
3510            .get_mut(component_id)?
3511            .remove_and_drop();
3512        Some(())
3513    }
3514
3515    /// Removes the resource of a given type, if it exists. Otherwise returns `None`.
3516    ///
3517    /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
3518    /// use this in cases where the actual types are not known at compile time.**
3519    ///
3520    /// # Panics
3521    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3522    pub fn remove_non_send_by_id(&mut self, component_id: ComponentId) -> Option<()> {
3523        self.storages
3524            .non_send_resources
3525            .get_mut(component_id)?
3526            .remove_and_drop();
3527        Some(())
3528    }
3529
3530    /// Retrieves an immutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3531    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3532    ///
3533    /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3534    /// use this in cases where the actual types are not known at compile time.**
3535    ///
3536    /// # Panics
3537    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
3538    #[inline]
3539    pub fn get_by_id(&self, entity: Entity, component_id: ComponentId) -> Option<Ptr<'_>> {
3540        self.get_entity(entity).ok()?.get_by_id(component_id).ok()
3541    }
3542
3543    /// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
3544    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
3545    ///
3546    /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
3547    /// use this in cases where the actual types are not known at compile time.**
3548    #[inline]
3549    pub fn get_mut_by_id(
3550        &mut self,
3551        entity: Entity,
3552        component_id: ComponentId,
3553    ) -> Option<MutUntyped<'_>> {
3554        self.get_entity_mut(entity)
3555            .ok()?
3556            .into_mut_by_id(component_id)
3557            .ok()
3558    }
3559}
3560
3561// Schedule-related methods
3562impl World {
3563    /// Adds the specified [`Schedule`] to the world. The schedule can later be run
3564    /// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
3565    /// accessing the [`Schedules`] resource.
3566    ///
3567    /// The `Schedules` resource will be initialized if it does not already exist.
3568    pub fn add_schedule(&mut self, schedule: Schedule) {
3569        let mut schedules = self.get_resource_or_init::<Schedules>();
3570        schedules.insert(schedule);
3571    }
3572
3573    /// Temporarily removes the schedule associated with `label` from the world,
3574    /// runs user code, and finally re-adds the schedule.
3575    /// This returns a [`TryRunScheduleError`] if there is no schedule
3576    /// associated with `label`.
3577    ///
3578    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3579    /// and system state is cached.
3580    ///
3581    /// For simple cases where you just need to call the schedule once,
3582    /// consider using [`World::try_run_schedule`] instead.
3583    /// For other use cases, see the example on [`World::schedule_scope`].
3584    pub fn try_schedule_scope<R>(
3585        &mut self,
3586        label: impl ScheduleLabel,
3587        f: impl FnOnce(&mut World, &mut Schedule) -> R,
3588    ) -> Result<R, TryRunScheduleError> {
3589        let label = label.intern();
3590        let Some(mut schedule) = self
3591            .get_resource_mut::<Schedules>()
3592            .and_then(|mut s| s.remove(label))
3593        else {
3594            return Err(TryRunScheduleError(label));
3595        };
3596
3597        let value = f(self, &mut schedule);
3598
3599        let old = self.resource_mut::<Schedules>().insert(schedule);
3600        if old.is_some() {
3601            warn!("Schedule `{label:?}` was inserted during a call to `World::schedule_scope`: its value has been overwritten");
3602        }
3603
3604        Ok(value)
3605    }
3606
3607    /// Temporarily removes the schedule associated with `label` from the world,
3608    /// runs user code, and finally re-adds the schedule.
3609    ///
3610    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3611    /// and system state is cached.
3612    ///
3613    /// # Examples
3614    ///
3615    /// ```
3616    /// # use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
3617    /// # #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)]
3618    /// # pub struct MySchedule;
3619    /// # #[derive(Resource)]
3620    /// # struct Counter(usize);
3621    /// #
3622    /// # let mut world = World::new();
3623    /// # world.insert_resource(Counter(0));
3624    /// # let mut schedule = Schedule::new(MySchedule);
3625    /// # schedule.add_systems(tick_counter);
3626    /// # world.init_resource::<Schedules>();
3627    /// # world.add_schedule(schedule);
3628    /// # fn tick_counter(mut counter: ResMut<Counter>) { counter.0 += 1; }
3629    /// // Run the schedule five times.
3630    /// world.schedule_scope(MySchedule, |world, schedule| {
3631    ///     for _ in 0..5 {
3632    ///         schedule.run(world);
3633    ///     }
3634    /// });
3635    /// # assert_eq!(world.resource::<Counter>().0, 5);
3636    /// ```
3637    ///
3638    /// For simple cases where you just need to call the schedule once,
3639    /// consider using [`World::run_schedule`] instead.
3640    ///
3641    /// # Panics
3642    ///
3643    /// If the requested schedule does not exist.
3644    pub fn schedule_scope<R>(
3645        &mut self,
3646        label: impl ScheduleLabel,
3647        f: impl FnOnce(&mut World, &mut Schedule) -> R,
3648    ) -> R {
3649        self.try_schedule_scope(label, f)
3650            .unwrap_or_else(|e| panic!("{e}"))
3651    }
3652
3653    /// Attempts to run the [`Schedule`] associated with the `label` a single time,
3654    /// and returns a [`TryRunScheduleError`] if the schedule does not exist.
3655    ///
3656    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3657    /// and system state is cached.
3658    ///
3659    /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3660    pub fn try_run_schedule(
3661        &mut self,
3662        label: impl ScheduleLabel,
3663    ) -> Result<(), TryRunScheduleError> {
3664        self.try_schedule_scope(label, |world, sched| sched.run(world))
3665    }
3666
3667    /// Runs the [`Schedule`] associated with the `label` a single time.
3668    ///
3669    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
3670    /// and system state is cached.
3671    ///
3672    /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
3673    ///
3674    /// # Panics
3675    ///
3676    /// If the requested schedule does not exist.
3677    pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
3678        self.schedule_scope(label, |world, sched| sched.run(world));
3679    }
3680
3681    /// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
3682    pub fn allow_ambiguous_component<T: Component>(&mut self) {
3683        let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3684        schedules.allow_ambiguous_component::<T>(self);
3685        self.insert_resource(schedules);
3686    }
3687
3688    /// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
3689    pub fn allow_ambiguous_resource<T: Resource>(&mut self) {
3690        let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
3691        schedules.allow_ambiguous_resource::<T>(self);
3692        self.insert_resource(schedules);
3693    }
3694}
3695
3696impl fmt::Debug for World {
3697    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3698        // SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
3699        // Accessing any data stored in the world would be unsound.
3700        f.debug_struct("World")
3701            .field("id", &self.id)
3702            .field("entity_count", &self.entities.len())
3703            .field("archetype_count", &self.archetypes.len())
3704            .field("component_count", &self.components.len())
3705            .field("resource_count", &self.storages.resources.len())
3706            .finish()
3707    }
3708}
3709
3710// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3711unsafe impl Send for World {}
3712// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
3713unsafe impl Sync for World {}
3714
3715/// Creates an instance of the type this trait is implemented for
3716/// using data from the supplied [`World`].
3717///
3718/// This can be helpful for complex initialization or context-aware defaults.
3719///
3720/// [`FromWorld`] is automatically implemented for any type implementing [`Default`]
3721/// and may also be derived for:
3722/// - any struct whose fields all implement `FromWorld`
3723/// - any enum where one variant has the attribute `#[from_world]`
3724///
3725/// ```rs
3726///
3727/// #[derive(Default)]
3728/// struct A;
3729///
3730/// #[derive(Default)]
3731/// struct B(Option<u32>)
3732///
3733/// struct C;
3734///
3735/// impl FromWorld for C {
3736///     fn from_world(_world: &mut World) -> Self {
3737///         Self
3738///     }
3739/// }
3740///
3741/// #[derive(FromWorld)]
3742/// struct D(A, B, C);
3743///
3744/// #[derive(FromWorld)]
3745/// enum E {
3746///     #[from_world]
3747///     F,
3748///     G
3749/// }
3750/// ```
3751pub trait FromWorld {
3752    /// Creates `Self` using data from the given [`World`].
3753    fn from_world(world: &mut World) -> Self;
3754}
3755
3756impl<T: Default> FromWorld for T {
3757    /// Creates `Self` using [`default()`](`Default::default`).
3758    fn from_world(_world: &mut World) -> Self {
3759        T::default()
3760    }
3761}
3762
3763#[cfg(test)]
3764#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
3765mod tests {
3766    use super::{FromWorld, World};
3767    use crate::{
3768        change_detection::{DetectChangesMut, MaybeLocation},
3769        component::{ComponentCloneBehavior, ComponentDescriptor, ComponentInfo, StorageType},
3770        entity::EntityHashSet,
3771        entity_disabling::{DefaultQueryFilters, Disabled},
3772        ptr::OwningPtr,
3773        resource::Resource,
3774        world::{error::EntityMutableFetchError, DeferredWorld},
3775    };
3776    use alloc::{
3777        borrow::ToOwned,
3778        string::{String, ToString},
3779        sync::Arc,
3780        vec,
3781        vec::Vec,
3782    };
3783    use bevy_ecs_macros::Component;
3784    use bevy_platform::collections::{HashMap, HashSet};
3785    use core::{
3786        any::TypeId,
3787        panic,
3788        sync::atomic::{AtomicBool, AtomicU32, Ordering},
3789    };
3790    use std::{println, sync::Mutex};
3791
3792    type ID = u8;
3793
3794    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3795    enum DropLogItem {
3796        Create(ID),
3797        Drop(ID),
3798    }
3799
3800    #[derive(Resource, Component)]
3801    struct MayPanicInDrop {
3802        drop_log: Arc<Mutex<Vec<DropLogItem>>>,
3803        expected_panic_flag: Arc<AtomicBool>,
3804        should_panic: bool,
3805        id: u8,
3806    }
3807
3808    impl MayPanicInDrop {
3809        fn new(
3810            drop_log: &Arc<Mutex<Vec<DropLogItem>>>,
3811            expected_panic_flag: &Arc<AtomicBool>,
3812            should_panic: bool,
3813            id: u8,
3814        ) -> Self {
3815            println!("creating component with id {id}");
3816            drop_log.lock().unwrap().push(DropLogItem::Create(id));
3817
3818            Self {
3819                drop_log: Arc::clone(drop_log),
3820                expected_panic_flag: Arc::clone(expected_panic_flag),
3821                should_panic,
3822                id,
3823            }
3824        }
3825    }
3826
3827    impl Drop for MayPanicInDrop {
3828        fn drop(&mut self) {
3829            println!("dropping component with id {}", self.id);
3830
3831            {
3832                let mut drop_log = self.drop_log.lock().unwrap();
3833                drop_log.push(DropLogItem::Drop(self.id));
3834                // Don't keep the mutex while panicking, or we'll poison it.
3835                drop(drop_log);
3836            }
3837
3838            if self.should_panic {
3839                self.expected_panic_flag.store(true, Ordering::SeqCst);
3840                panic!("testing what happens on panic inside drop");
3841            }
3842        }
3843    }
3844
3845    struct DropTestHelper {
3846        drop_log: Arc<Mutex<Vec<DropLogItem>>>,
3847        /// Set to `true` right before we intentionally panic, so that if we get
3848        /// a panic, we know if it was intended or not.
3849        expected_panic_flag: Arc<AtomicBool>,
3850    }
3851
3852    impl DropTestHelper {
3853        pub fn new() -> Self {
3854            Self {
3855                drop_log: Arc::new(Mutex::new(Vec::<DropLogItem>::new())),
3856                expected_panic_flag: Arc::new(AtomicBool::new(false)),
3857            }
3858        }
3859
3860        pub fn make_component(&self, should_panic: bool, id: ID) -> MayPanicInDrop {
3861            MayPanicInDrop::new(&self.drop_log, &self.expected_panic_flag, should_panic, id)
3862        }
3863
3864        pub fn finish(self, panic_res: std::thread::Result<()>) -> Vec<DropLogItem> {
3865            let drop_log = self.drop_log.lock().unwrap();
3866            let expected_panic_flag = self.expected_panic_flag.load(Ordering::SeqCst);
3867
3868            if !expected_panic_flag {
3869                match panic_res {
3870                    Ok(()) => panic!("Expected a panic but it didn't happen"),
3871                    Err(e) => std::panic::resume_unwind(e),
3872                }
3873            }
3874
3875            drop_log.to_owned()
3876        }
3877    }
3878
3879    #[test]
3880    fn panic_while_overwriting_component() {
3881        let helper = DropTestHelper::new();
3882
3883        let res = std::panic::catch_unwind(|| {
3884            let mut world = World::new();
3885            world
3886                .spawn_empty()
3887                .insert(helper.make_component(true, 0))
3888                .insert(helper.make_component(false, 1));
3889
3890            println!("Done inserting! Dropping world...");
3891        });
3892
3893        let drop_log = helper.finish(res);
3894
3895        assert_eq!(
3896            &*drop_log,
3897            [
3898                DropLogItem::Create(0),
3899                DropLogItem::Create(1),
3900                DropLogItem::Drop(0),
3901                DropLogItem::Drop(1),
3902            ]
3903        );
3904    }
3905
3906    #[derive(Resource)]
3907    struct TestResource(u32);
3908
3909    #[derive(Resource)]
3910    struct TestResource2(String);
3911
3912    #[derive(Resource)]
3913    struct TestResource3;
3914
3915    #[test]
3916    fn get_resource_by_id() {
3917        let mut world = World::new();
3918        world.insert_resource(TestResource(42));
3919        let component_id = world
3920            .components()
3921            .get_resource_id(TypeId::of::<TestResource>())
3922            .unwrap();
3923
3924        let resource = world.get_resource_by_id(component_id).unwrap();
3925        // SAFETY: `TestResource` is the correct resource type
3926        let resource = unsafe { resource.deref::<TestResource>() };
3927
3928        assert_eq!(resource.0, 42);
3929    }
3930
3931    #[test]
3932    fn get_resource_mut_by_id() {
3933        let mut world = World::new();
3934        world.insert_resource(TestResource(42));
3935        let component_id = world
3936            .components()
3937            .get_resource_id(TypeId::of::<TestResource>())
3938            .unwrap();
3939
3940        {
3941            let mut resource = world.get_resource_mut_by_id(component_id).unwrap();
3942            resource.set_changed();
3943            // SAFETY: `TestResource` is the correct resource type
3944            let resource = unsafe { resource.into_inner().deref_mut::<TestResource>() };
3945            resource.0 = 43;
3946        }
3947
3948        let resource = world.get_resource_by_id(component_id).unwrap();
3949        // SAFETY: `TestResource` is the correct resource type
3950        let resource = unsafe { resource.deref::<TestResource>() };
3951
3952        assert_eq!(resource.0, 43);
3953    }
3954
3955    #[test]
3956    fn iter_resources() {
3957        let mut world = World::new();
3958        // Remove DefaultQueryFilters so it doesn't show up in the iterator
3959        world.remove_resource::<DefaultQueryFilters>();
3960        world.insert_resource(TestResource(42));
3961        world.insert_resource(TestResource2("Hello, world!".to_string()));
3962        world.insert_resource(TestResource3);
3963        world.remove_resource::<TestResource3>();
3964
3965        let mut iter = world.iter_resources();
3966
3967        let (info, ptr) = iter.next().unwrap();
3968        assert_eq!(info.name(), core::any::type_name::<TestResource>());
3969        // SAFETY: We know that the resource is of type `TestResource`
3970        assert_eq!(unsafe { ptr.deref::<TestResource>().0 }, 42);
3971
3972        let (info, ptr) = iter.next().unwrap();
3973        assert_eq!(info.name(), core::any::type_name::<TestResource2>());
3974        assert_eq!(
3975            // SAFETY: We know that the resource is of type `TestResource2`
3976            unsafe { &ptr.deref::<TestResource2>().0 },
3977            &"Hello, world!".to_string()
3978        );
3979
3980        assert!(iter.next().is_none());
3981    }
3982
3983    #[test]
3984    fn iter_resources_mut() {
3985        let mut world = World::new();
3986        // Remove DefaultQueryFilters so it doesn't show up in the iterator
3987        world.remove_resource::<DefaultQueryFilters>();
3988        world.insert_resource(TestResource(42));
3989        world.insert_resource(TestResource2("Hello, world!".to_string()));
3990        world.insert_resource(TestResource3);
3991        world.remove_resource::<TestResource3>();
3992
3993        let mut iter = world.iter_resources_mut();
3994
3995        let (info, mut mut_untyped) = iter.next().unwrap();
3996        assert_eq!(info.name(), core::any::type_name::<TestResource>());
3997        // SAFETY: We know that the resource is of type `TestResource`
3998        unsafe {
3999            mut_untyped.as_mut().deref_mut::<TestResource>().0 = 43;
4000        };
4001
4002        let (info, mut mut_untyped) = iter.next().unwrap();
4003        assert_eq!(info.name(), core::any::type_name::<TestResource2>());
4004        // SAFETY: We know that the resource is of type `TestResource2`
4005        unsafe {
4006            mut_untyped.as_mut().deref_mut::<TestResource2>().0 = "Hello, world?".to_string();
4007        };
4008
4009        assert!(iter.next().is_none());
4010        drop(iter);
4011
4012        assert_eq!(world.resource::<TestResource>().0, 43);
4013        assert_eq!(
4014            world.resource::<TestResource2>().0,
4015            "Hello, world?".to_string()
4016        );
4017    }
4018
4019    #[test]
4020    fn dynamic_resource() {
4021        let mut world = World::new();
4022
4023        let descriptor = ComponentDescriptor::new_resource::<TestResource>();
4024
4025        let component_id = world.register_resource_with_descriptor(descriptor);
4026
4027        let value = 0;
4028        OwningPtr::make(value, |ptr| {
4029            // SAFETY: value is valid for the layout of `TestResource`
4030            unsafe {
4031                world.insert_resource_by_id(component_id, ptr, MaybeLocation::caller());
4032            }
4033        });
4034
4035        // SAFETY: We know that the resource is of type `TestResource`
4036        let resource = unsafe {
4037            world
4038                .get_resource_by_id(component_id)
4039                .unwrap()
4040                .deref::<TestResource>()
4041        };
4042        assert_eq!(resource.0, 0);
4043
4044        assert!(world.remove_resource_by_id(component_id).is_some());
4045    }
4046
4047    #[test]
4048    fn custom_resource_with_layout() {
4049        static DROP_COUNT: AtomicU32 = AtomicU32::new(0);
4050
4051        let mut world = World::new();
4052
4053        // SAFETY: the drop function is valid for the layout and the data will be safe to access from any thread
4054        let descriptor = unsafe {
4055            ComponentDescriptor::new_with_layout(
4056                "Custom Test Component".to_string(),
4057                StorageType::Table,
4058                core::alloc::Layout::new::<[u8; 8]>(),
4059                Some(|ptr| {
4060                    let data = ptr.read::<[u8; 8]>();
4061                    assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]);
4062                    DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4063                }),
4064                true,
4065                ComponentCloneBehavior::Default,
4066            )
4067        };
4068
4069        let component_id = world.register_resource_with_descriptor(descriptor);
4070
4071        let value: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
4072        OwningPtr::make(value, |ptr| {
4073            // SAFETY: value is valid for the component layout
4074            unsafe {
4075                world.insert_resource_by_id(component_id, ptr, MaybeLocation::caller());
4076            }
4077        });
4078
4079        // SAFETY: [u8; 8] is the correct type for the resource
4080        let data = unsafe {
4081            world
4082                .get_resource_by_id(component_id)
4083                .unwrap()
4084                .deref::<[u8; 8]>()
4085        };
4086        assert_eq!(*data, [0, 1, 2, 3, 4, 5, 6, 7]);
4087
4088        assert!(world.remove_resource_by_id(component_id).is_some());
4089
4090        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
4091    }
4092
4093    #[derive(Resource)]
4094    struct TestFromWorld(u32);
4095    impl FromWorld for TestFromWorld {
4096        fn from_world(world: &mut World) -> Self {
4097            let b = world.resource::<TestResource>();
4098            Self(b.0)
4099        }
4100    }
4101
4102    #[test]
4103    fn init_resource_does_not_overwrite() {
4104        let mut world = World::new();
4105        world.insert_resource(TestResource(0));
4106        world.init_resource::<TestFromWorld>();
4107        world.insert_resource(TestResource(1));
4108        world.init_resource::<TestFromWorld>();
4109
4110        let resource = world.resource::<TestFromWorld>();
4111
4112        assert_eq!(resource.0, 0);
4113    }
4114
4115    #[test]
4116    fn init_non_send_resource_does_not_overwrite() {
4117        let mut world = World::new();
4118        world.insert_resource(TestResource(0));
4119        world.init_non_send_resource::<TestFromWorld>();
4120        world.insert_resource(TestResource(1));
4121        world.init_non_send_resource::<TestFromWorld>();
4122
4123        let resource = world.non_send_resource::<TestFromWorld>();
4124
4125        assert_eq!(resource.0, 0);
4126    }
4127
4128    #[derive(Component)]
4129    struct Foo;
4130
4131    #[derive(Component)]
4132    struct Bar;
4133
4134    #[derive(Component)]
4135    struct Baz;
4136
4137    #[test]
4138    fn inspect_entity_components() {
4139        let mut world = World::new();
4140        let ent0 = world.spawn((Foo, Bar, Baz)).id();
4141        let ent1 = world.spawn((Foo, Bar)).id();
4142        let ent2 = world.spawn((Bar, Baz)).id();
4143        let ent3 = world.spawn((Foo, Baz)).id();
4144        let ent4 = world.spawn(Foo).id();
4145        let ent5 = world.spawn(Bar).id();
4146        let ent6 = world.spawn(Baz).id();
4147
4148        fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
4149            component_infos
4150                .into_iter()
4151                .map(ComponentInfo::type_id)
4152                .collect()
4153        }
4154
4155        let foo_id = TypeId::of::<Foo>();
4156        let bar_id = TypeId::of::<Bar>();
4157        let baz_id = TypeId::of::<Baz>();
4158        assert_eq!(
4159            to_type_ids(world.inspect_entity(ent0).unwrap().collect()),
4160            [Some(foo_id), Some(bar_id), Some(baz_id)]
4161                .into_iter()
4162                .collect::<HashSet<_>>()
4163        );
4164        assert_eq!(
4165            to_type_ids(world.inspect_entity(ent1).unwrap().collect()),
4166            [Some(foo_id), Some(bar_id)]
4167                .into_iter()
4168                .collect::<HashSet<_>>()
4169        );
4170        assert_eq!(
4171            to_type_ids(world.inspect_entity(ent2).unwrap().collect()),
4172            [Some(bar_id), Some(baz_id)]
4173                .into_iter()
4174                .collect::<HashSet<_>>()
4175        );
4176        assert_eq!(
4177            to_type_ids(world.inspect_entity(ent3).unwrap().collect()),
4178            [Some(foo_id), Some(baz_id)]
4179                .into_iter()
4180                .collect::<HashSet<_>>()
4181        );
4182        assert_eq!(
4183            to_type_ids(world.inspect_entity(ent4).unwrap().collect()),
4184            [Some(foo_id)].into_iter().collect::<HashSet<_>>()
4185        );
4186        assert_eq!(
4187            to_type_ids(world.inspect_entity(ent5).unwrap().collect()),
4188            [Some(bar_id)].into_iter().collect::<HashSet<_>>()
4189        );
4190        assert_eq!(
4191            to_type_ids(world.inspect_entity(ent6).unwrap().collect()),
4192            [Some(baz_id)].into_iter().collect::<HashSet<_>>()
4193        );
4194    }
4195
4196    #[test]
4197    fn iterate_entities() {
4198        let mut world = World::new();
4199        let mut entity_counters = <HashMap<_, _>>::default();
4200
4201        let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
4202            entity_counters.clear();
4203            for entity in world.iter_entities() {
4204                let counter = entity_counters.entry(entity.id()).or_insert(0);
4205                *counter += 1;
4206            }
4207        };
4208
4209        // Adding one entity and validating iteration
4210        let ent0 = world.spawn((Foo, Bar, Baz)).id();
4211
4212        iterate_and_count_entities(&world, &mut entity_counters);
4213        assert_eq!(entity_counters[&ent0], 1);
4214        assert_eq!(entity_counters.len(), 1);
4215
4216        // Spawning three more entities and then validating iteration
4217        let ent1 = world.spawn((Foo, Bar)).id();
4218        let ent2 = world.spawn((Bar, Baz)).id();
4219        let ent3 = world.spawn((Foo, Baz)).id();
4220
4221        iterate_and_count_entities(&world, &mut entity_counters);
4222
4223        assert_eq!(entity_counters[&ent0], 1);
4224        assert_eq!(entity_counters[&ent1], 1);
4225        assert_eq!(entity_counters[&ent2], 1);
4226        assert_eq!(entity_counters[&ent3], 1);
4227        assert_eq!(entity_counters.len(), 4);
4228
4229        // Despawning first entity and then validating the iteration
4230        assert!(world.despawn(ent0));
4231
4232        iterate_and_count_entities(&world, &mut entity_counters);
4233
4234        assert_eq!(entity_counters[&ent1], 1);
4235        assert_eq!(entity_counters[&ent2], 1);
4236        assert_eq!(entity_counters[&ent3], 1);
4237        assert_eq!(entity_counters.len(), 3);
4238
4239        // Spawning three more entities, despawning three and then validating the iteration
4240        let ent4 = world.spawn(Foo).id();
4241        let ent5 = world.spawn(Bar).id();
4242        let ent6 = world.spawn(Baz).id();
4243
4244        assert!(world.despawn(ent2));
4245        assert!(world.despawn(ent3));
4246        assert!(world.despawn(ent4));
4247
4248        iterate_and_count_entities(&world, &mut entity_counters);
4249
4250        assert_eq!(entity_counters[&ent1], 1);
4251        assert_eq!(entity_counters[&ent5], 1);
4252        assert_eq!(entity_counters[&ent6], 1);
4253        assert_eq!(entity_counters.len(), 3);
4254
4255        // Despawning remaining entities and then validating the iteration
4256        assert!(world.despawn(ent1));
4257        assert!(world.despawn(ent5));
4258        assert!(world.despawn(ent6));
4259
4260        iterate_and_count_entities(&world, &mut entity_counters);
4261
4262        assert_eq!(entity_counters.len(), 0);
4263    }
4264
4265    #[test]
4266    fn iterate_entities_mut() {
4267        #[derive(Component, PartialEq, Debug)]
4268        struct A(i32);
4269
4270        #[derive(Component, PartialEq, Debug)]
4271        struct B(i32);
4272
4273        let mut world = World::new();
4274
4275        let a1 = world.spawn(A(1)).id();
4276        let a2 = world.spawn(A(2)).id();
4277        let b1 = world.spawn(B(1)).id();
4278        let b2 = world.spawn(B(2)).id();
4279
4280        for mut entity in world.iter_entities_mut() {
4281            if let Some(mut a) = entity.get_mut::<A>() {
4282                a.0 -= 1;
4283            }
4284        }
4285        assert_eq!(world.entity(a1).get(), Some(&A(0)));
4286        assert_eq!(world.entity(a2).get(), Some(&A(1)));
4287        assert_eq!(world.entity(b1).get(), Some(&B(1)));
4288        assert_eq!(world.entity(b2).get(), Some(&B(2)));
4289
4290        for mut entity in world.iter_entities_mut() {
4291            if let Some(mut b) = entity.get_mut::<B>() {
4292                b.0 *= 2;
4293            }
4294        }
4295        assert_eq!(world.entity(a1).get(), Some(&A(0)));
4296        assert_eq!(world.entity(a2).get(), Some(&A(1)));
4297        assert_eq!(world.entity(b1).get(), Some(&B(2)));
4298        assert_eq!(world.entity(b2).get(), Some(&B(4)));
4299
4300        let mut entities = world.iter_entities_mut().collect::<Vec<_>>();
4301        entities.sort_by_key(|e| e.get::<A>().map(|a| a.0).or(e.get::<B>().map(|b| b.0)));
4302        let (a, b) = entities.split_at_mut(2);
4303        core::mem::swap(
4304            &mut a[1].get_mut::<A>().unwrap().0,
4305            &mut b[0].get_mut::<B>().unwrap().0,
4306        );
4307        assert_eq!(world.entity(a1).get(), Some(&A(0)));
4308        assert_eq!(world.entity(a2).get(), Some(&A(2)));
4309        assert_eq!(world.entity(b1).get(), Some(&B(1)));
4310        assert_eq!(world.entity(b2).get(), Some(&B(4)));
4311    }
4312
4313    #[test]
4314    fn spawn_empty_bundle() {
4315        let mut world = World::new();
4316        world.spawn(());
4317    }
4318
4319    #[test]
4320    fn get_entity() {
4321        let mut world = World::new();
4322
4323        let e1 = world.spawn_empty().id();
4324        let e2 = world.spawn_empty().id();
4325
4326        assert!(world.get_entity(e1).is_ok());
4327        assert!(world.get_entity([e1, e2]).is_ok());
4328        assert!(world
4329            .get_entity(&[e1, e2] /* this is an array not a slice */)
4330            .is_ok());
4331        assert!(world.get_entity(&vec![e1, e2][..]).is_ok());
4332        assert!(world
4333            .get_entity(&EntityHashSet::from_iter([e1, e2]))
4334            .is_ok());
4335
4336        world.entity_mut(e1).despawn();
4337
4338        assert_eq!(
4339            Err(e1),
4340            world.get_entity(e1).map(|_| {}).map_err(|e| e.entity)
4341        );
4342        assert_eq!(
4343            Err(e1),
4344            world.get_entity([e1, e2]).map(|_| {}).map_err(|e| e.entity)
4345        );
4346        assert_eq!(
4347            Err(e1),
4348            world
4349                .get_entity(&[e1, e2] /* this is an array not a slice */)
4350                .map(|_| {})
4351                .map_err(|e| e.entity)
4352        );
4353        assert_eq!(
4354            Err(e1),
4355            world
4356                .get_entity(&vec![e1, e2][..])
4357                .map(|_| {})
4358                .map_err(|e| e.entity)
4359        );
4360        assert_eq!(
4361            Err(e1),
4362            world
4363                .get_entity(&EntityHashSet::from_iter([e1, e2]))
4364                .map(|_| {})
4365                .map_err(|e| e.entity)
4366        );
4367    }
4368
4369    #[test]
4370    fn get_entity_mut() {
4371        let mut world = World::new();
4372
4373        let e1 = world.spawn_empty().id();
4374        let e2 = world.spawn_empty().id();
4375
4376        assert!(world.get_entity_mut(e1).is_ok());
4377        assert!(world.get_entity_mut([e1, e2]).is_ok());
4378        assert!(world
4379            .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4380            .is_ok());
4381        assert!(world.get_entity_mut(&vec![e1, e2][..]).is_ok());
4382        assert!(world
4383            .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4384            .is_ok());
4385
4386        assert_eq!(
4387            Err(EntityMutableFetchError::AliasedMutability(e1)),
4388            world.get_entity_mut([e1, e2, e1]).map(|_| {})
4389        );
4390        assert_eq!(
4391            Err(EntityMutableFetchError::AliasedMutability(e1)),
4392            world
4393                .get_entity_mut(&[e1, e2, e1] /* this is an array not a slice */)
4394                .map(|_| {})
4395        );
4396        assert_eq!(
4397            Err(EntityMutableFetchError::AliasedMutability(e1)),
4398            world.get_entity_mut(&vec![e1, e2, e1][..]).map(|_| {})
4399        );
4400        // Aliased mutability isn't allowed by HashSets
4401        assert!(world
4402            .get_entity_mut(&EntityHashSet::from_iter([e1, e2, e1]))
4403            .is_ok());
4404
4405        world.entity_mut(e1).despawn();
4406
4407        assert!(matches!(
4408            world.get_entity_mut(e1).map(|_| {}),
4409            Err(EntityMutableFetchError::EntityDoesNotExist(e)) if e.entity == e1
4410        ));
4411        assert!(matches!(
4412            world.get_entity_mut([e1, e2]).map(|_| {}),
4413            Err(EntityMutableFetchError::EntityDoesNotExist(e)) if e.entity == e1));
4414        assert!(matches!(
4415            world
4416                .get_entity_mut(&[e1, e2] /* this is an array not a slice */)
4417                .map(|_| {}),
4418            Err(EntityMutableFetchError::EntityDoesNotExist(e)) if e.entity == e1));
4419        assert!(matches!(
4420            world.get_entity_mut(&vec![e1, e2][..]).map(|_| {}),
4421            Err(EntityMutableFetchError::EntityDoesNotExist(e)) if e.entity == e1,
4422        ));
4423        assert!(matches!(
4424            world
4425                .get_entity_mut(&EntityHashSet::from_iter([e1, e2]))
4426                .map(|_| {}),
4427            Err(EntityMutableFetchError::EntityDoesNotExist(e)) if e.entity == e1));
4428    }
4429
4430    #[test]
4431    #[track_caller]
4432    fn entity_spawn_despawn_tracking() {
4433        use core::panic::Location;
4434
4435        let mut world = World::new();
4436        let entity = world.spawn_empty().id();
4437        assert_eq!(
4438            world.entities.entity_get_spawned_or_despawned_by(entity),
4439            MaybeLocation::new(Some(Location::caller()))
4440        );
4441        world.despawn(entity);
4442        assert_eq!(
4443            world.entities.entity_get_spawned_or_despawned_by(entity),
4444            MaybeLocation::new(Some(Location::caller()))
4445        );
4446        let new = world.spawn_empty().id();
4447        assert_eq!(entity.index(), new.index());
4448        assert_eq!(
4449            world.entities.entity_get_spawned_or_despawned_by(entity),
4450            MaybeLocation::new(None)
4451        );
4452        world.despawn(new);
4453        assert_eq!(
4454            world.entities.entity_get_spawned_or_despawned_by(entity),
4455            MaybeLocation::new(None)
4456        );
4457    }
4458
4459    #[test]
4460    fn new_world_has_disabling() {
4461        let mut world = World::new();
4462        world.spawn(Foo);
4463        world.spawn((Foo, Disabled));
4464        assert_eq!(1, world.query::<&Foo>().iter(&world).count());
4465
4466        // If we explicitly remove the resource, no entities should be filtered anymore
4467        world.remove_resource::<DefaultQueryFilters>();
4468        assert_eq!(2, world.query::<&Foo>().iter(&world).count());
4469    }
4470
4471    #[test]
4472    fn entities_and_commands() {
4473        #[derive(Component, PartialEq, Debug)]
4474        struct Foo(u32);
4475
4476        let mut world = World::new();
4477
4478        let eid = world.spawn(Foo(35)).id();
4479
4480        let (mut fetcher, mut commands) = world.entities_and_commands();
4481        let emut = fetcher.get_mut(eid).unwrap();
4482        commands.entity(eid).despawn();
4483        assert_eq!(emut.get::<Foo>().unwrap(), &Foo(35));
4484
4485        world.flush();
4486
4487        assert!(world.get_entity(eid).is_err());
4488    }
4489
4490    #[test]
4491    fn entities_and_commands_deferred() {
4492        #[derive(Component, PartialEq, Debug)]
4493        struct Foo(u32);
4494
4495        let mut world = World::new();
4496
4497        let eid = world.spawn(Foo(1)).id();
4498
4499        let mut dworld = DeferredWorld::from(&mut world);
4500
4501        let (mut fetcher, mut commands) = dworld.entities_and_commands();
4502        let emut = fetcher.get_mut(eid).unwrap();
4503        commands.entity(eid).despawn();
4504        assert_eq!(emut.get::<Foo>().unwrap(), &Foo(1));
4505
4506        world.flush();
4507
4508        assert!(world.get_entity(eid).is_err());
4509    }
4510}