Skip to main content

bevy_ecs/world/
mod.rs

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