bevy_ecs/world/
mod.rs

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