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_ref;
7pub mod error;
8mod identifier;
9mod spawn_batch;
10pub mod unsafe_world_cell;
11
12pub use crate::{
13    change_detection::{Mut, Ref, CHECK_TICK_THRESHOLD},
14    world::command_queue::CommandQueue,
15};
16pub use component_constants::*;
17pub use deferred_world::DeferredWorld;
18pub use entity_ref::{
19    EntityMut, EntityRef, EntityWorldMut, Entry, FilteredEntityMut, FilteredEntityRef,
20    OccupiedEntry, VacantEntry,
21};
22pub use identifier::WorldId;
23pub use spawn_batch::*;
24
25use crate::{
26    archetype::{ArchetypeComponentId, ArchetypeId, ArchetypeRow, Archetypes},
27    bundle::{Bundle, BundleInfo, BundleInserter, BundleSpawner, Bundles},
28    change_detection::{MutUntyped, TicksMut},
29    component::{
30        Component, ComponentDescriptor, ComponentHooks, ComponentId, ComponentInfo, ComponentTicks,
31        Components, Tick,
32    },
33    entity::{AllocAtWithoutReplacement, Entities, Entity, EntityHashSet, EntityLocation},
34    event::{Event, EventId, Events, SendBatchIds},
35    observer::Observers,
36    query::{DebugCheckedUnwrap, QueryData, QueryEntityError, QueryFilter, QueryState},
37    removal_detection::RemovedComponentEvents,
38    schedule::{Schedule, ScheduleLabel, Schedules},
39    storage::{ResourceData, Storages},
40    system::{Commands, Res, Resource},
41    world::command_queue::RawCommandQueue,
42    world::error::TryRunScheduleError,
43};
44use bevy_ptr::{OwningPtr, Ptr};
45use bevy_utils::tracing::warn;
46use std::{
47    any::TypeId,
48    fmt,
49    mem::MaybeUninit,
50    sync::atomic::{AtomicU32, Ordering},
51};
52use unsafe_world_cell::{UnsafeEntityCell, UnsafeWorldCell};
53
54/// A [`World`] mutation.
55///
56/// Should be used with [`Commands::add`].
57///
58/// # Usage
59///
60/// ```
61/// # use bevy_ecs::prelude::*;
62/// # use bevy_ecs::world::Command;
63/// // Our world resource
64/// #[derive(Resource, Default)]
65/// struct Counter(u64);
66///
67/// // Our custom command
68/// struct AddToCounter(u64);
69///
70/// impl Command for AddToCounter {
71///     fn apply(self, world: &mut World) {
72///         let mut counter = world.get_resource_or_insert_with(Counter::default);
73///         counter.0 += self.0;
74///     }
75/// }
76///
77/// fn some_system(mut commands: Commands) {
78///     commands.add(AddToCounter(42));
79/// }
80/// ```
81pub trait Command: Send + 'static {
82    /// Applies this command, causing it to mutate the provided `world`.
83    ///
84    /// This method is used to define what a command "does" when it is ultimately applied.
85    /// Because this method takes `self`, you can store data or settings on the type that implements this trait.
86    /// This data is set by the system or other source of the command, and then ultimately read in this method.
87    fn apply(self, world: &mut World);
88}
89
90/// Stores and exposes operations on [entities](Entity), [components](Component), resources,
91/// and their associated metadata.
92///
93/// Each [`Entity`] has a set of components. Each component can have up to one instance of each
94/// component type. Entity components can be created, updated, removed, and queried using a given
95/// [`World`].
96///
97/// For complex access patterns involving [`SystemParam`](crate::system::SystemParam),
98/// consider using [`SystemState`](crate::system::SystemState).
99///
100/// To mutate different parts of the world simultaneously,
101/// use [`World::resource_scope`] or [`SystemState`](crate::system::SystemState).
102///
103/// ## Resources
104///
105/// Worlds can also store [`Resource`]s,
106/// which are unique instances of a given type that don't belong to a specific Entity.
107/// There are also *non send resources*, which can only be accessed on the main thread.
108/// See [`Resource`] for usage.
109pub struct World {
110    id: WorldId,
111    pub(crate) entities: Entities,
112    pub(crate) components: Components,
113    pub(crate) archetypes: Archetypes,
114    pub(crate) storages: Storages,
115    pub(crate) bundles: Bundles,
116    pub(crate) observers: Observers,
117    pub(crate) removed_components: RemovedComponentEvents,
118    pub(crate) change_tick: AtomicU32,
119    pub(crate) last_change_tick: Tick,
120    pub(crate) last_check_tick: Tick,
121    pub(crate) last_trigger_id: u32,
122    pub(crate) command_queue: RawCommandQueue,
123}
124
125impl Default for World {
126    fn default() -> Self {
127        let mut world = Self {
128            id: WorldId::new().expect("More `bevy` `World`s have been created than is supported"),
129            entities: Entities::new(),
130            components: Default::default(),
131            archetypes: Archetypes::new(),
132            storages: Default::default(),
133            bundles: Default::default(),
134            observers: Observers::default(),
135            removed_components: Default::default(),
136            // Default value is `1`, and `last_change_tick`s default to `0`, such that changes
137            // are detected on first system runs and for direct world queries.
138            change_tick: AtomicU32::new(1),
139            last_change_tick: Tick::new(0),
140            last_check_tick: Tick::new(0),
141            last_trigger_id: 0,
142            command_queue: RawCommandQueue::new(),
143        };
144        world.bootstrap();
145        world
146    }
147}
148
149impl Drop for World {
150    fn drop(&mut self) {
151        // SAFETY: Not passing a pointer so the argument is always valid
152        unsafe { self.command_queue.apply_or_drop_queued(None) };
153        // SAFETY: Pointers in internal command queue are only invalidated here
154        drop(unsafe { Box::from_raw(self.command_queue.bytes.as_ptr()) });
155        // SAFETY: Pointers in internal command queue are only invalidated here
156        drop(unsafe { Box::from_raw(self.command_queue.cursor.as_ptr()) });
157    }
158}
159
160impl World {
161    /// This performs initialization that _must_ happen for every [`World`] immediately upon creation (such as claiming specific component ids).
162    /// This _must_ be run as part of constructing a [`World`], before it is returned to the caller.
163    #[inline]
164    fn bootstrap(&mut self) {
165        assert_eq!(ON_ADD, self.init_component::<OnAdd>());
166        assert_eq!(ON_INSERT, self.init_component::<OnInsert>());
167        assert_eq!(ON_REMOVE, self.init_component::<OnRemove>());
168    }
169    /// Creates a new empty [`World`].
170    ///
171    /// # Panics
172    ///
173    /// If [`usize::MAX`] [`World`]s have been created.
174    /// This guarantee allows System Parameters to safely uniquely identify a [`World`],
175    /// since its [`WorldId`] is unique
176    #[inline]
177    pub fn new() -> World {
178        World::default()
179    }
180
181    /// Retrieves this [`World`]'s unique ID
182    #[inline]
183    pub fn id(&self) -> WorldId {
184        self.id
185    }
186
187    /// Creates a new [`UnsafeWorldCell`] view with complete read+write access.
188    #[inline]
189    pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> {
190        UnsafeWorldCell::new_mutable(self)
191    }
192
193    /// Creates a new [`UnsafeWorldCell`] view with only read access to everything.
194    #[inline]
195    pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_> {
196        UnsafeWorldCell::new_readonly(self)
197    }
198
199    /// Retrieves this world's [`Entities`] collection.
200    #[inline]
201    pub fn entities(&self) -> &Entities {
202        &self.entities
203    }
204
205    /// Retrieves this world's [`Entities`] collection mutably.
206    ///
207    /// # Safety
208    /// Mutable reference must not be used to put the [`Entities`] data
209    /// in an invalid state for this [`World`]
210    #[inline]
211    pub unsafe fn entities_mut(&mut self) -> &mut Entities {
212        &mut self.entities
213    }
214
215    /// Retrieves this world's [`Archetypes`] collection.
216    #[inline]
217    pub fn archetypes(&self) -> &Archetypes {
218        &self.archetypes
219    }
220
221    /// Retrieves this world's [`Components`] collection.
222    #[inline]
223    pub fn components(&self) -> &Components {
224        &self.components
225    }
226
227    /// Retrieves this world's [`Storages`] collection.
228    #[inline]
229    pub fn storages(&self) -> &Storages {
230        &self.storages
231    }
232
233    /// Retrieves this world's [`Bundles`] collection.
234    #[inline]
235    pub fn bundles(&self) -> &Bundles {
236        &self.bundles
237    }
238
239    /// Retrieves this world's [`RemovedComponentEvents`] collection
240    #[inline]
241    pub fn removed_components(&self) -> &RemovedComponentEvents {
242        &self.removed_components
243    }
244
245    /// Creates a new [`Commands`] instance that writes to the world's command queue
246    /// Use [`World::flush`] to apply all queued commands
247    #[inline]
248    pub fn commands(&mut self) -> Commands {
249        // SAFETY: command_queue is stored on world and always valid while the world exists
250        unsafe { Commands::new_raw_from_entities(self.command_queue.clone(), &self.entities) }
251    }
252
253    /// Initializes a new [`Component`] type and returns the [`ComponentId`] created for it.
254    pub fn init_component<T: Component>(&mut self) -> ComponentId {
255        self.components.init_component::<T>(&mut self.storages)
256    }
257
258    /// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] type.
259    ///
260    /// Will panic if `T` exists in any archetypes.
261    pub fn register_component_hooks<T: Component>(&mut self) -> &mut ComponentHooks {
262        let index = self.init_component::<T>();
263        assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if {} may already be in use", std::any::type_name::<T>());
264        // SAFETY: We just created this component
265        unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() }
266    }
267
268    /// Returns a mutable reference to the [`ComponentHooks`] for a [`Component`] with the given id if it exists.
269    ///
270    /// Will panic if `id` exists in any archetypes.
271    pub fn register_component_hooks_by_id(
272        &mut self,
273        id: ComponentId,
274    ) -> Option<&mut ComponentHooks> {
275        assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(id)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if the component with id {:?} may already be in use", id);
276        self.components.get_hooks_mut(id)
277    }
278
279    /// Initializes a new [`Component`] type and returns the [`ComponentId`] created for it.
280    ///
281    /// This method differs from [`World::init_component`] in that it uses a [`ComponentDescriptor`]
282    /// to initialize the new component type instead of statically available type information. This
283    /// enables the dynamic initialization of new component definitions at runtime for advanced use cases.
284    ///
285    /// While the option to initialize a component from a descriptor is useful in type-erased
286    /// contexts, the standard `World::init_component` function should always be used instead
287    /// when type information is available at compile time.
288    pub fn init_component_with_descriptor(
289        &mut self,
290        descriptor: ComponentDescriptor,
291    ) -> ComponentId {
292        self.components
293            .init_component_with_descriptor(&mut self.storages, descriptor)
294    }
295
296    /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
297    ///
298    /// The returned `ComponentId` is specific to the `World` instance
299    /// it was retrieved from and should not be used with another `World` instance.
300    ///
301    /// Returns [`None`] if the `Component` type has not yet been initialized within
302    /// the `World` using [`World::init_component`].
303    ///
304    /// ```
305    /// use bevy_ecs::prelude::*;
306    ///
307    /// let mut world = World::new();
308    ///
309    /// #[derive(Component)]
310    /// struct ComponentA;
311    ///
312    /// let component_a_id = world.init_component::<ComponentA>();
313    ///
314    /// assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())
315    /// ```
316    ///
317    /// # See also
318    ///
319    /// * [`Components::component_id()`]
320    /// * [`Components::get_id()`]
321    #[inline]
322    pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
323        self.components.component_id::<T>()
324    }
325
326    /// Retrieves an [`EntityRef`] that exposes read-only operations for the given `entity`.
327    /// This will panic if the `entity` does not exist. Use [`World::get_entity`] if you want
328    /// to check for entity existence instead of implicitly panic-ing.
329    ///
330    /// ```
331    /// use bevy_ecs::{component::Component, world::World};
332    ///
333    /// #[derive(Component)]
334    /// struct Position {
335    ///   x: f32,
336    ///   y: f32,
337    /// }
338    ///
339    /// let mut world = World::new();
340    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
341    /// let position = world.entity(entity).get::<Position>().unwrap();
342    /// assert_eq!(position.x, 0.0);
343    /// ```
344    #[inline]
345    #[track_caller]
346    pub fn entity(&self, entity: Entity) -> EntityRef {
347        #[inline(never)]
348        #[cold]
349        #[track_caller]
350        fn panic_no_entity(entity: Entity) -> ! {
351            panic!("Entity {entity:?} does not exist");
352        }
353
354        match self.get_entity(entity) {
355            Some(entity) => entity,
356            None => panic_no_entity(entity),
357        }
358    }
359
360    /// Retrieves an [`EntityWorldMut`] that exposes read and write operations for the given `entity`.
361    /// This will panic if the `entity` does not exist. Use [`World::get_entity_mut`] if you want
362    /// to check for entity existence instead of implicitly panic-ing.
363    ///
364    /// ```
365    /// use bevy_ecs::{component::Component, world::World};
366    ///
367    /// #[derive(Component)]
368    /// struct Position {
369    ///   x: f32,
370    ///   y: f32,
371    /// }
372    ///
373    /// let mut world = World::new();
374    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
375    /// let mut entity_mut = world.entity_mut(entity);
376    /// let mut position = entity_mut.get_mut::<Position>().unwrap();
377    /// position.x = 1.0;
378    /// ```
379    #[inline]
380    #[track_caller]
381    pub fn entity_mut(&mut self, entity: Entity) -> EntityWorldMut {
382        #[inline(never)]
383        #[cold]
384        #[track_caller]
385        fn panic_no_entity(entity: Entity) -> ! {
386            panic!("Entity {entity:?} does not exist");
387        }
388
389        match self.get_entity_mut(entity) {
390            Some(entity) => entity,
391            None => panic_no_entity(entity),
392        }
393    }
394
395    /// Gets an [`EntityRef`] for multiple entities at once.
396    ///
397    /// # Panics
398    ///
399    /// If any entity does not exist in the world.
400    ///
401    /// # Examples
402    ///
403    /// ```
404    /// # use bevy_ecs::prelude::*;
405    /// # let mut world = World::new();
406    /// # let id1 = world.spawn_empty().id();
407    /// # let id2 = world.spawn_empty().id();
408    /// // Getting multiple entities.
409    /// let [entity1, entity2] = world.many_entities([id1, id2]);
410    /// ```
411    ///
412    /// ```should_panic
413    /// # use bevy_ecs::prelude::*;
414    /// # let mut world = World::new();
415    /// # let id1 = world.spawn_empty().id();
416    /// # let id2 = world.spawn_empty().id();
417    /// // Trying to get a despawned entity will fail.
418    /// world.despawn(id2);
419    /// world.many_entities([id1, id2]);
420    /// ```
421    pub fn many_entities<const N: usize>(&mut self, entities: [Entity; N]) -> [EntityRef<'_>; N] {
422        #[inline(never)]
423        #[cold]
424        #[track_caller]
425        fn panic_no_entity(entity: Entity) -> ! {
426            panic!("Entity {entity:?} does not exist");
427        }
428
429        match self.get_many_entities(entities) {
430            Ok(refs) => refs,
431            Err(entity) => panic_no_entity(entity),
432        }
433    }
434
435    /// Gets mutable access to multiple entities at once.
436    ///
437    /// # Panics
438    ///
439    /// If any entities do not exist in the world,
440    /// or if the same entity is specified multiple times.
441    ///
442    /// # Examples
443    ///
444    /// Disjoint mutable access.
445    ///
446    /// ```
447    /// # use bevy_ecs::prelude::*;
448    /// # let mut world = World::new();
449    /// # let id1 = world.spawn_empty().id();
450    /// # let id2 = world.spawn_empty().id();
451    /// // Disjoint mutable access.
452    /// let [entity1, entity2] = world.many_entities_mut([id1, id2]);
453    /// ```
454    ///
455    /// Trying to access the same entity multiple times will fail.
456    ///
457    /// ```should_panic
458    /// # use bevy_ecs::prelude::*;
459    /// # let mut world = World::new();
460    /// # let id = world.spawn_empty().id();
461    /// world.many_entities_mut([id, id]);
462    /// ```
463    pub fn many_entities_mut<const N: usize>(
464        &mut self,
465        entities: [Entity; N],
466    ) -> [EntityMut<'_>; N] {
467        #[inline(never)]
468        #[cold]
469        #[track_caller]
470        fn panic_on_err(e: QueryEntityError) -> ! {
471            panic!("{e}");
472        }
473
474        match self.get_many_entities_mut(entities) {
475            Ok(borrows) => borrows,
476            Err(e) => panic_on_err(e),
477        }
478    }
479
480    /// Returns the components of an [`Entity`] through [`ComponentInfo`].
481    #[inline]
482    pub fn inspect_entity(&self, entity: Entity) -> Vec<&ComponentInfo> {
483        let entity_location = self
484            .entities()
485            .get(entity)
486            .unwrap_or_else(|| panic!("Entity {entity:?} does not exist"));
487
488        let archetype = self
489            .archetypes()
490            .get(entity_location.archetype_id)
491            .unwrap_or_else(|| {
492                panic!(
493                    "Archetype {:?} does not exist",
494                    entity_location.archetype_id
495                )
496            });
497
498        archetype
499            .components()
500            .filter_map(|id| self.components().get_info(id))
501            .collect()
502    }
503
504    /// Returns an [`EntityWorldMut`] for the given `entity` (if it exists) or spawns one if it doesn't exist.
505    /// This will return [`None`] if the `entity` exists with a different generation.
506    ///
507    /// # Note
508    /// Spawning a specific `entity` value is rarely the right choice. Most apps should favor [`World::spawn`].
509    /// This method should generally only be used for sharing entities across apps, and only when they have a
510    /// scheme worked out to share an ID space (which doesn't happen by default).
511    #[inline]
512    pub fn get_or_spawn(&mut self, entity: Entity) -> Option<EntityWorldMut> {
513        self.flush();
514        match self.entities.alloc_at_without_replacement(entity) {
515            AllocAtWithoutReplacement::Exists(location) => {
516                // SAFETY: `entity` exists and `location` is that entity's location
517                Some(unsafe { EntityWorldMut::new(self, entity, location) })
518            }
519            AllocAtWithoutReplacement::DidNotExist => {
520                // SAFETY: entity was just allocated
521                Some(unsafe { self.spawn_at_empty_internal(entity) })
522            }
523            AllocAtWithoutReplacement::ExistsWithWrongGeneration => None,
524        }
525    }
526
527    /// Retrieves an [`EntityRef`] that exposes read-only operations for the given `entity`.
528    /// Returns [`None`] if the `entity` does not exist.
529    /// Instead of unwrapping the value returned from this function, prefer [`World::entity`].
530    ///
531    /// ```
532    /// use bevy_ecs::{component::Component, world::World};
533    ///
534    /// #[derive(Component)]
535    /// struct Position {
536    ///   x: f32,
537    ///   y: f32,
538    /// }
539    ///
540    /// let mut world = World::new();
541    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
542    /// let entity_ref = world.get_entity(entity).unwrap();
543    /// let position = entity_ref.get::<Position>().unwrap();
544    /// assert_eq!(position.x, 0.0);
545    /// ```
546    #[inline]
547    pub fn get_entity(&self, entity: Entity) -> Option<EntityRef> {
548        let location = self.entities.get(entity)?;
549        // SAFETY: if the Entity is invalid, the function returns early.
550        // Additionally, Entities::get(entity) returns the correct EntityLocation if the entity exists.
551        let entity_cell =
552            UnsafeEntityCell::new(self.as_unsafe_world_cell_readonly(), entity, location);
553        // SAFETY: The UnsafeEntityCell has read access to the entire world.
554        let entity_ref = unsafe { EntityRef::new(entity_cell) };
555        Some(entity_ref)
556    }
557
558    /// Gets an [`EntityRef`] for multiple entities at once.
559    ///
560    /// # Errors
561    ///
562    /// If any entity does not exist in the world.
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// # use bevy_ecs::prelude::*;
568    /// # let mut world = World::new();
569    /// # let id1 = world.spawn_empty().id();
570    /// # let id2 = world.spawn_empty().id();
571    /// // Getting multiple entities.
572    /// let [entity1, entity2] = world.get_many_entities([id1, id2]).unwrap();
573    ///
574    /// // Trying to get a despawned entity will fail.
575    /// world.despawn(id2);
576    /// assert!(world.get_many_entities([id1, id2]).is_err());
577    /// ```
578    pub fn get_many_entities<const N: usize>(
579        &self,
580        entities: [Entity; N],
581    ) -> Result<[EntityRef<'_>; N], Entity> {
582        let mut refs = [MaybeUninit::uninit(); N];
583        for (r, id) in std::iter::zip(&mut refs, entities) {
584            *r = MaybeUninit::new(self.get_entity(id).ok_or(id)?);
585        }
586
587        // SAFETY: Each item was initialized in the above loop.
588        let refs = refs.map(|r| unsafe { MaybeUninit::assume_init(r) });
589
590        Ok(refs)
591    }
592
593    /// Gets an [`EntityRef`] for multiple entities at once, whose number is determined at runtime.
594    ///
595    /// # Errors
596    ///
597    /// If any entity does not exist in the world.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// # use bevy_ecs::prelude::*;
603    /// # let mut world = World::new();
604    /// # let id1 = world.spawn_empty().id();
605    /// # let id2 = world.spawn_empty().id();
606    /// // Getting multiple entities.
607    /// let entities = world.get_many_entities_dynamic(&[id1, id2]).unwrap();
608    /// let entity1 = entities.get(0).unwrap();
609    /// let entity2 = entities.get(1).unwrap();
610    ///
611    /// // Trying to get a despawned entity will fail.
612    /// world.despawn(id2);
613    /// assert!(world.get_many_entities_dynamic(&[id1, id2]).is_err());
614    /// ```
615    pub fn get_many_entities_dynamic<'w>(
616        &'w self,
617        entities: &[Entity],
618    ) -> Result<Vec<EntityRef<'w>>, Entity> {
619        let mut borrows = Vec::with_capacity(entities.len());
620        for &id in entities {
621            borrows.push(self.get_entity(id).ok_or(id)?);
622        }
623
624        Ok(borrows)
625    }
626
627    /// Returns an [`Entity`] iterator of current entities.
628    ///
629    /// This is useful in contexts where you only have read-only access to the [`World`].
630    #[inline]
631    pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>> + '_ {
632        self.archetypes.iter().flat_map(|archetype| {
633            archetype
634                .entities()
635                .iter()
636                .enumerate()
637                .map(|(archetype_row, archetype_entity)| {
638                    let entity = archetype_entity.id();
639                    let location = EntityLocation {
640                        archetype_id: archetype.id(),
641                        archetype_row: ArchetypeRow::new(archetype_row),
642                        table_id: archetype.table_id(),
643                        table_row: archetype_entity.table_row(),
644                    };
645
646                    // SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
647                    let cell = UnsafeEntityCell::new(
648                        self.as_unsafe_world_cell_readonly(),
649                        entity,
650                        location,
651                    );
652                    // SAFETY: `&self` gives read access to the entire world.
653                    unsafe { EntityRef::new(cell) }
654                })
655        })
656    }
657
658    /// Returns a mutable iterator over all entities in the `World`.
659    pub fn iter_entities_mut(&mut self) -> impl Iterator<Item = EntityMut<'_>> + '_ {
660        let world_cell = self.as_unsafe_world_cell();
661        world_cell.archetypes().iter().flat_map(move |archetype| {
662            archetype
663                .entities()
664                .iter()
665                .enumerate()
666                .map(move |(archetype_row, archetype_entity)| {
667                    let entity = archetype_entity.id();
668                    let location = EntityLocation {
669                        archetype_id: archetype.id(),
670                        archetype_row: ArchetypeRow::new(archetype_row),
671                        table_id: archetype.table_id(),
672                        table_row: archetype_entity.table_row(),
673                    };
674
675                    // SAFETY: entity exists and location accurately specifies the archetype where the entity is stored.
676                    let cell = UnsafeEntityCell::new(world_cell, entity, location);
677                    // SAFETY: We have exclusive access to the entire world. We only create one borrow for each entity,
678                    // so none will conflict with one another.
679                    unsafe { EntityMut::new(cell) }
680                })
681        })
682    }
683
684    /// Retrieves an [`EntityWorldMut`] that exposes read and write operations for the given `entity`.
685    /// Returns [`None`] if the `entity` does not exist.
686    /// Instead of unwrapping the value returned from this function, prefer [`World::entity_mut`].
687    ///
688    /// ```
689    /// use bevy_ecs::{component::Component, world::World};
690    ///
691    /// #[derive(Component)]
692    /// struct Position {
693    ///   x: f32,
694    ///   y: f32,
695    /// }
696    ///
697    /// let mut world = World::new();
698    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
699    /// let mut entity_mut = world.get_entity_mut(entity).unwrap();
700    /// let mut position = entity_mut.get_mut::<Position>().unwrap();
701    /// position.x = 1.0;
702    /// ```
703    #[inline]
704    pub fn get_entity_mut(&mut self, entity: Entity) -> Option<EntityWorldMut> {
705        let location = self.entities.get(entity)?;
706        // SAFETY: `entity` exists and `location` is that entity's location
707        Some(unsafe { EntityWorldMut::new(self, entity, location) })
708    }
709
710    /// Verify that no duplicate entities are present in the given slice.
711    /// Does NOT check if the entities actually exist in the world.
712    ///
713    /// # Errors
714    ///
715    /// If any entities are duplicated.
716    fn verify_unique_entities(entities: &[Entity]) -> Result<(), QueryEntityError> {
717        for i in 0..entities.len() {
718            for j in 0..i {
719                if entities[i] == entities[j] {
720                    return Err(QueryEntityError::AliasedMutability(entities[i]));
721                }
722            }
723        }
724        Ok(())
725    }
726
727    /// Gets mutable access to multiple entities.
728    ///
729    /// # Errors
730    ///
731    /// If any entities do not exist in the world,
732    /// or if the same entity is specified multiple times.
733    ///
734    /// # Examples
735    ///
736    /// ```
737    /// # use bevy_ecs::prelude::*;
738    /// # let mut world = World::new();
739    /// # let id1 = world.spawn_empty().id();
740    /// # let id2 = world.spawn_empty().id();
741    /// // Disjoint mutable access.
742    /// let [entity1, entity2] = world.get_many_entities_mut([id1, id2]).unwrap();
743    ///
744    /// // Trying to access the same entity multiple times will fail.
745    /// assert!(world.get_many_entities_mut([id1, id1]).is_err());
746    /// ```
747    pub fn get_many_entities_mut<const N: usize>(
748        &mut self,
749        entities: [Entity; N],
750    ) -> Result<[EntityMut<'_>; N], QueryEntityError> {
751        Self::verify_unique_entities(&entities)?;
752
753        // SAFETY: Each entity is unique.
754        unsafe { self.get_entities_mut_unchecked(entities) }
755    }
756
757    /// # Safety
758    /// `entities` must contain no duplicate [`Entity`] IDs.
759    unsafe fn get_entities_mut_unchecked<const N: usize>(
760        &mut self,
761        entities: [Entity; N],
762    ) -> Result<[EntityMut<'_>; N], QueryEntityError> {
763        let world_cell = self.as_unsafe_world_cell();
764
765        let mut cells = [MaybeUninit::uninit(); N];
766        for (cell, id) in std::iter::zip(&mut cells, entities) {
767            *cell = MaybeUninit::new(
768                world_cell
769                    .get_entity(id)
770                    .ok_or(QueryEntityError::NoSuchEntity(id))?,
771            );
772        }
773        // SAFETY: Each item was initialized in the loop above.
774        let cells = cells.map(|c| unsafe { MaybeUninit::assume_init(c) });
775
776        // SAFETY:
777        // - `world_cell` has exclusive access to the entire world.
778        // - The caller ensures that each entity is unique, so none
779        //   of the borrows will conflict with one another.
780        let borrows = cells.map(|c| unsafe { EntityMut::new(c) });
781
782        Ok(borrows)
783    }
784
785    /// Gets mutable access to multiple entities, whose number is determined at runtime.
786    ///
787    /// # Errors
788    ///
789    /// If any entities do not exist in the world,
790    /// or if the same entity is specified multiple times.
791    ///
792    /// # Examples
793    ///
794    /// ```
795    /// # use bevy_ecs::prelude::*;
796    /// # let mut world = World::new();
797    /// # let id1 = world.spawn_empty().id();
798    /// # let id2 = world.spawn_empty().id();
799    /// // Disjoint mutable access.
800    /// let mut entities = world.get_many_entities_dynamic_mut(&[id1, id2]).unwrap();
801    /// let entity1 = entities.get_mut(0).unwrap();
802    ///
803    /// // Trying to access the same entity multiple times will fail.
804    /// assert!(world.get_many_entities_dynamic_mut(&[id1, id1]).is_err());
805    /// ```
806    pub fn get_many_entities_dynamic_mut<'w>(
807        &'w mut self,
808        entities: &[Entity],
809    ) -> Result<Vec<EntityMut<'w>>, QueryEntityError> {
810        Self::verify_unique_entities(entities)?;
811
812        // SAFETY: Each entity is unique.
813        unsafe { self.get_entities_dynamic_mut_unchecked(entities.iter().copied()) }
814    }
815
816    /// Gets mutable access to multiple entities, contained in a [`HashSet`].
817    /// The uniqueness of items in a [`HashSet`] allows us to avoid checking for duplicates.
818    ///
819    /// # Errors
820    ///
821    /// If any entities do not exist in the world.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// # use bevy_ecs::prelude::*;
827    /// # use bevy_ecs::entity::EntityHash;
828    /// # use bevy_ecs::entity::EntityHashSet;
829    /// # use bevy_utils::hashbrown::HashSet;
830    /// # use bevy_utils::hashbrown::hash_map::DefaultHashBuilder;
831    /// # let mut world = World::new();
832    /// # let id1 = world.spawn_empty().id();
833    /// # let id2 = world.spawn_empty().id();
834    /// let s = EntityHash::default();
835    /// let mut set = EntityHashSet::with_hasher(s);
836    /// set.insert(id1);
837    /// set.insert(id2);
838    ///
839    /// // Disjoint mutable access.
840    /// let mut entities = world.get_many_entities_from_set_mut(&set).unwrap();
841    /// let entity1 = entities.get_mut(0).unwrap();
842    /// ```
843    pub fn get_many_entities_from_set_mut<'w>(
844        &'w mut self,
845        entities: &EntityHashSet,
846    ) -> Result<Vec<EntityMut<'w>>, QueryEntityError> {
847        // SAFETY: Each entity is unique.
848        unsafe { self.get_entities_dynamic_mut_unchecked(entities.iter().copied()) }
849    }
850
851    /// # Safety
852    /// `entities` must produce no duplicate [`Entity`] IDs.
853    unsafe fn get_entities_dynamic_mut_unchecked(
854        &mut self,
855        entities: impl ExactSizeIterator<Item = Entity>,
856    ) -> Result<Vec<EntityMut<'_>>, QueryEntityError> {
857        let world_cell = self.as_unsafe_world_cell();
858
859        let mut cells = Vec::with_capacity(entities.len());
860        for id in entities {
861            cells.push(
862                world_cell
863                    .get_entity(id)
864                    .ok_or(QueryEntityError::NoSuchEntity(id))?,
865            );
866        }
867
868        let borrows = cells
869            .into_iter()
870            // SAFETY:
871            // - `world_cell` has exclusive access to the entire world.
872            // - The caller ensures that each entity is unique, so none
873            //   of the borrows will conflict with one another.
874            .map(|c| unsafe { EntityMut::new(c) })
875            .collect();
876
877        Ok(borrows)
878    }
879
880    /// Spawns a new [`Entity`] and returns a corresponding [`EntityWorldMut`], which can be used
881    /// to add components to the entity or retrieve its id.
882    ///
883    /// ```
884    /// use bevy_ecs::{component::Component, world::World};
885    ///
886    /// #[derive(Component)]
887    /// struct Position {
888    ///   x: f32,
889    ///   y: f32,
890    /// }
891    /// #[derive(Component)]
892    /// struct Label(&'static str);
893    /// #[derive(Component)]
894    /// struct Num(u32);
895    ///
896    /// let mut world = World::new();
897    /// let entity = world.spawn_empty()
898    ///     .insert(Position { x: 0.0, y: 0.0 }) // add a single component
899    ///     .insert((Num(1), Label("hello"))) // add a bundle of components
900    ///     .id();
901    ///
902    /// let position = world.entity(entity).get::<Position>().unwrap();
903    /// assert_eq!(position.x, 0.0);
904    /// ```
905    pub fn spawn_empty(&mut self) -> EntityWorldMut {
906        self.flush();
907        let entity = self.entities.alloc();
908        // SAFETY: entity was just allocated
909        unsafe { self.spawn_at_empty_internal(entity) }
910    }
911
912    /// Spawns a new [`Entity`] with a given [`Bundle`] of [components](`Component`) and returns
913    /// a corresponding [`EntityWorldMut`], which can be used to add components to the entity or
914    /// retrieve its id.
915    ///
916    /// ```
917    /// use bevy_ecs::{bundle::Bundle, component::Component, world::World};
918    ///
919    /// #[derive(Component)]
920    /// struct Position {
921    ///   x: f32,
922    ///   y: f32,
923    /// }
924    ///
925    /// #[derive(Component)]
926    /// struct Velocity {
927    ///     x: f32,
928    ///     y: f32,
929    /// };
930    ///
931    /// #[derive(Component)]
932    /// struct Name(&'static str);
933    ///
934    /// #[derive(Bundle)]
935    /// struct PhysicsBundle {
936    ///     position: Position,
937    ///     velocity: Velocity,
938    /// }
939    ///
940    /// let mut world = World::new();
941    ///
942    /// // `spawn` can accept a single component:
943    /// world.spawn(Position { x: 0.0, y: 0.0 });
944
945    /// // It can also accept a tuple of components:
946    /// world.spawn((
947    ///     Position { x: 0.0, y: 0.0 },
948    ///     Velocity { x: 1.0, y: 1.0 },
949    /// ));
950
951    /// // Or it can accept a pre-defined Bundle of components:
952    /// world.spawn(PhysicsBundle {
953    ///     position: Position { x: 2.0, y: 2.0 },
954    ///     velocity: Velocity { x: 0.0, y: 4.0 },
955    /// });
956    ///
957    /// let entity = world
958    ///     // Tuples can also mix Bundles and Components
959    ///     .spawn((
960    ///         PhysicsBundle {
961    ///             position: Position { x: 2.0, y: 2.0 },
962    ///             velocity: Velocity { x: 0.0, y: 4.0 },
963    ///         },
964    ///         Name("Elaina Proctor"),
965    ///     ))
966    ///     // Calling id() will return the unique identifier for the spawned entity
967    ///     .id();
968    /// let position = world.entity(entity).get::<Position>().unwrap();
969    /// assert_eq!(position.x, 2.0);
970    /// ```
971    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityWorldMut {
972        self.flush();
973        let change_tick = self.change_tick();
974        let entity = self.entities.alloc();
975        let entity_location = {
976            let mut bundle_spawner = BundleSpawner::new::<B>(self, change_tick);
977            // SAFETY: bundle's type matches `bundle_info`, entity is allocated but non-existent
978            unsafe { bundle_spawner.spawn_non_existent(entity, bundle) }
979        };
980
981        // SAFETY: entity and location are valid, as they were just created above
982        unsafe { EntityWorldMut::new(self, entity, entity_location) }
983    }
984
985    /// # Safety
986    /// must be called on an entity that was just allocated
987    unsafe fn spawn_at_empty_internal(&mut self, entity: Entity) -> EntityWorldMut {
988        let archetype = self.archetypes.empty_mut();
989        // PERF: consider avoiding allocating entities in the empty archetype unless needed
990        let table_row = self.storages.tables[archetype.table_id()].allocate(entity);
991        // SAFETY: no components are allocated by archetype.allocate() because the archetype is
992        // empty
993        let location = unsafe { archetype.allocate(entity, table_row) };
994        // SAFETY: entity index was just allocated
995        unsafe {
996            self.entities.set(entity.index(), location);
997        }
998        EntityWorldMut::new(self, entity, location)
999    }
1000
1001    /// Spawns a batch of entities with the same component [`Bundle`] type. Takes a given
1002    /// [`Bundle`] iterator and returns a corresponding [`Entity`] iterator.
1003    /// This is more efficient than spawning entities and adding components to them individually,
1004    /// but it is limited to spawning entities with the same [`Bundle`] type, whereas spawning
1005    /// individually is more flexible.
1006    ///
1007    /// ```
1008    /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1009    ///
1010    /// #[derive(Component)]
1011    /// struct Str(&'static str);
1012    /// #[derive(Component)]
1013    /// struct Num(u32);
1014    ///
1015    /// let mut world = World::new();
1016    /// let entities = world.spawn_batch(vec![
1017    ///   (Str("a"), Num(0)), // the first entity
1018    ///   (Str("b"), Num(1)), // the second entity
1019    /// ]).collect::<Vec<Entity>>();
1020    ///
1021    /// assert_eq!(entities.len(), 2);
1022    /// ```
1023    pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
1024    where
1025        I: IntoIterator,
1026        I::Item: Bundle,
1027    {
1028        SpawnBatchIter::new(self, iter.into_iter())
1029    }
1030
1031    /// Retrieves a reference to the given `entity`'s [`Component`] of the given type.
1032    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1033    /// ```
1034    /// use bevy_ecs::{component::Component, world::World};
1035    ///
1036    /// #[derive(Component)]
1037    /// struct Position {
1038    ///   x: f32,
1039    ///   y: f32,
1040    /// }
1041    ///
1042    /// let mut world = World::new();
1043    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1044    /// let position = world.get::<Position>(entity).unwrap();
1045    /// assert_eq!(position.x, 0.0);
1046    /// ```
1047    #[inline]
1048    pub fn get<T: Component>(&self, entity: Entity) -> Option<&T> {
1049        self.get_entity(entity)?.get()
1050    }
1051
1052    /// Retrieves a mutable reference to the given `entity`'s [`Component`] of the given type.
1053    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
1054    /// ```
1055    /// use bevy_ecs::{component::Component, world::World};
1056    ///
1057    /// #[derive(Component)]
1058    /// struct Position {
1059    ///   x: f32,
1060    ///   y: f32,
1061    /// }
1062    ///
1063    /// let mut world = World::new();
1064    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1065    /// let mut position = world.get_mut::<Position>(entity).unwrap();
1066    /// position.x = 1.0;
1067    /// ```
1068    #[inline]
1069    pub fn get_mut<T: Component>(&mut self, entity: Entity) -> Option<Mut<T>> {
1070        // SAFETY:
1071        // - `as_unsafe_world_cell` is the only thing that is borrowing world
1072        // - `as_unsafe_world_cell` provides mutable permission to everything
1073        // - `&mut self` ensures no other borrows on world data
1074        unsafe { self.as_unsafe_world_cell().get_entity(entity)?.get_mut() }
1075    }
1076
1077    /// Despawns the given `entity`, if it exists. This will also remove all of the entity's
1078    /// [`Component`]s. Returns `true` if the `entity` is successfully despawned and `false` if
1079    /// the `entity` does not exist.
1080    ///
1081    /// # Note
1082    ///
1083    /// This won't clean up external references to the entity (such as parent-child relationships
1084    /// if you're using `bevy_hierarchy`), which may leave the world in an invalid state.
1085    ///
1086    /// ```
1087    /// use bevy_ecs::{component::Component, world::World};
1088    ///
1089    /// #[derive(Component)]
1090    /// struct Position {
1091    ///   x: f32,
1092    ///   y: f32,
1093    /// }
1094    ///
1095    /// let mut world = World::new();
1096    /// let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
1097    /// assert!(world.despawn(entity));
1098    /// assert!(world.get_entity(entity).is_none());
1099    /// assert!(world.get::<Position>(entity).is_none());
1100    /// ```
1101    #[inline]
1102    pub fn despawn(&mut self, entity: Entity) -> bool {
1103        self.flush();
1104        if let Some(entity) = self.get_entity_mut(entity) {
1105            entity.despawn();
1106            true
1107        } else {
1108            warn!("error[B0003]: Could not despawn entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/#b0003", entity);
1109            false
1110        }
1111    }
1112
1113    /// Clears the internal component tracker state.
1114    ///
1115    /// The world maintains some internal state about changed and removed components. This state
1116    /// is used by [`RemovedComponents`] to provide access to the entities that had a specific type
1117    /// of component removed since last tick.
1118    ///
1119    /// The state is also used for change detection when accessing components and resources outside
1120    /// of a system, for example via [`World::get_mut()`] or [`World::get_resource_mut()`].
1121    ///
1122    /// By clearing this internal state, the world "forgets" about those changes, allowing a new round
1123    /// of detection to be recorded.
1124    ///
1125    /// When using `bevy_ecs` as part of the full Bevy engine, this method is called automatically
1126    /// by `bevy_app::App::update` and `bevy_app::SubApp::update`, so you don't need to call it manually.
1127    /// When using `bevy_ecs` as a separate standalone crate however, you do need to call this manually.
1128    ///
1129    /// ```
1130    /// # use bevy_ecs::prelude::*;
1131    /// # #[derive(Component, Default)]
1132    /// # struct Transform;
1133    /// // a whole new world
1134    /// let mut world = World::new();
1135    ///
1136    /// // you changed it
1137    /// let entity = world.spawn(Transform::default()).id();
1138    ///
1139    /// // change is detected
1140    /// let transform = world.get_mut::<Transform>(entity).unwrap();
1141    /// assert!(transform.is_changed());
1142    ///
1143    /// // update the last change tick
1144    /// world.clear_trackers();
1145    ///
1146    /// // change is no longer detected
1147    /// let transform = world.get_mut::<Transform>(entity).unwrap();
1148    /// assert!(!transform.is_changed());
1149    /// ```
1150    ///
1151    /// [`RemovedComponents`]: crate::removal_detection::RemovedComponents
1152    pub fn clear_trackers(&mut self) {
1153        self.removed_components.update();
1154        self.last_change_tick = self.increment_change_tick();
1155    }
1156
1157    /// Returns [`QueryState`] for the given [`QueryData`], which is used to efficiently
1158    /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1159    /// ```
1160    /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1161    ///
1162    /// #[derive(Component, Debug, PartialEq)]
1163    /// struct Position {
1164    ///   x: f32,
1165    ///   y: f32,
1166    /// }
1167    ///
1168    /// #[derive(Component)]
1169    /// struct Velocity {
1170    ///   x: f32,
1171    ///   y: f32,
1172    /// }
1173    ///
1174    /// let mut world = World::new();
1175    /// let entities = world.spawn_batch(vec![
1176    ///     (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
1177    ///     (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
1178    /// ]).collect::<Vec<Entity>>();
1179    ///
1180    /// let mut query = world.query::<(&mut Position, &Velocity)>();
1181    /// for (mut position, velocity) in query.iter_mut(&mut world) {
1182    ///    position.x += velocity.x;
1183    ///    position.y += velocity.y;
1184    /// }
1185    ///
1186    /// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
1187    /// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
1188    /// ```
1189    ///
1190    /// To iterate over entities in a deterministic order,
1191    /// sort the results of the query using the desired component as a key.
1192    /// Note that this requires fetching the whole result set from the query
1193    /// and allocation of a [`Vec`] to store it.
1194    ///
1195    /// ```
1196    /// use bevy_ecs::{component::Component, entity::Entity, world::World};
1197    ///
1198    /// #[derive(Component, PartialEq, Eq, PartialOrd, Ord, Debug)]
1199    /// struct Order(i32);
1200    /// #[derive(Component, PartialEq, Debug)]
1201    /// struct Label(&'static str);
1202    ///
1203    /// let mut world = World::new();
1204    /// let a = world.spawn((Order(2), Label("second"))).id();
1205    /// let b = world.spawn((Order(3), Label("third"))).id();
1206    /// let c = world.spawn((Order(1), Label("first"))).id();
1207    /// let mut entities = world.query::<(Entity, &Order, &Label)>()
1208    ///     .iter(&world)
1209    ///     .collect::<Vec<_>>();
1210    /// // Sort the query results by their `Order` component before comparing
1211    /// // to expected results. Query iteration order should not be relied on.
1212    /// entities.sort_by_key(|e| e.1);
1213    /// assert_eq!(entities, vec![
1214    ///     (c, &Order(1), &Label("first")),
1215    ///     (a, &Order(2), &Label("second")),
1216    ///     (b, &Order(3), &Label("third")),
1217    /// ]);
1218    /// ```
1219    #[inline]
1220    pub fn query<D: QueryData>(&mut self) -> QueryState<D, ()> {
1221        self.query_filtered::<D, ()>()
1222    }
1223
1224    /// Returns [`QueryState`] for the given filtered [`QueryData`], which is used to efficiently
1225    /// run queries on the [`World`] by storing and reusing the [`QueryState`].
1226    /// ```
1227    /// use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
1228    ///
1229    /// #[derive(Component)]
1230    /// struct A;
1231    /// #[derive(Component)]
1232    /// struct B;
1233    ///
1234    /// let mut world = World::new();
1235    /// let e1 = world.spawn(A).id();
1236    /// let e2 = world.spawn((A, B)).id();
1237    ///
1238    /// let mut query = world.query_filtered::<Entity, With<B>>();
1239    /// let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
1240    ///
1241    /// assert_eq!(matching_entities, vec![e2]);
1242    /// ```
1243    #[inline]
1244    pub fn query_filtered<D: QueryData, F: QueryFilter>(&mut self) -> QueryState<D, F> {
1245        QueryState::new(self)
1246    }
1247
1248    /// Returns an iterator of entities that had components of type `T` removed
1249    /// since the last call to [`World::clear_trackers`].
1250    pub fn removed<T: Component>(&self) -> impl Iterator<Item = Entity> + '_ {
1251        self.components
1252            .get_id(TypeId::of::<T>())
1253            .map(|component_id| self.removed_with_id(component_id))
1254            .into_iter()
1255            .flatten()
1256    }
1257
1258    /// Returns an iterator of entities that had components with the given `component_id` removed
1259    /// since the last call to [`World::clear_trackers`].
1260    pub fn removed_with_id(&self, component_id: ComponentId) -> impl Iterator<Item = Entity> + '_ {
1261        self.removed_components
1262            .get(component_id)
1263            .map(|removed| removed.iter_current_update_events().cloned())
1264            .into_iter()
1265            .flatten()
1266            .map(|e| e.into())
1267    }
1268
1269    /// Initializes a new resource and returns the [`ComponentId`] created for it.
1270    ///
1271    /// If the resource already exists, nothing happens.
1272    ///
1273    /// The value given by the [`FromWorld::from_world`] method will be used.
1274    /// Note that any resource with the [`Default`] trait automatically implements [`FromWorld`],
1275    /// and those default values will be here instead.
1276    #[inline]
1277    pub fn init_resource<R: Resource + FromWorld>(&mut self) -> ComponentId {
1278        let component_id = self.components.init_resource::<R>();
1279        if self
1280            .storages
1281            .resources
1282            .get(component_id)
1283            .map_or(true, |data| !data.is_present())
1284        {
1285            let value = R::from_world(self);
1286            OwningPtr::make(value, |ptr| {
1287                // SAFETY: component_id was just initialized and corresponds to resource of type R.
1288                unsafe {
1289                    self.insert_resource_by_id(component_id, ptr);
1290                }
1291            });
1292        }
1293        component_id
1294    }
1295
1296    /// Inserts a new resource with the given `value`.
1297    ///
1298    /// Resources are "unique" data of a given type.
1299    /// If you insert a resource of a type that already exists,
1300    /// you will overwrite any existing data.
1301    #[inline]
1302    pub fn insert_resource<R: Resource>(&mut self, value: R) {
1303        let component_id = self.components.init_resource::<R>();
1304        OwningPtr::make(value, |ptr| {
1305            // SAFETY: component_id was just initialized and corresponds to resource of type R.
1306            unsafe {
1307                self.insert_resource_by_id(component_id, ptr);
1308            }
1309        });
1310    }
1311
1312    /// Initializes a new non-send resource and returns the [`ComponentId`] created for it.
1313    ///
1314    /// If the resource already exists, nothing happens.
1315    ///
1316    /// The value given by the [`FromWorld::from_world`] method will be used.
1317    /// Note that any resource with the `Default` trait automatically implements `FromWorld`,
1318    /// and those default values will be here instead.
1319    ///
1320    /// # Panics
1321    ///
1322    /// Panics if called from a thread other than the main thread.
1323    #[inline]
1324    pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> ComponentId {
1325        let component_id = self.components.init_non_send::<R>();
1326        if self
1327            .storages
1328            .non_send_resources
1329            .get(component_id)
1330            .map_or(true, |data| !data.is_present())
1331        {
1332            let value = R::from_world(self);
1333            OwningPtr::make(value, |ptr| {
1334                // SAFETY: component_id was just initialized and corresponds to resource of type R.
1335                unsafe {
1336                    self.insert_non_send_by_id(component_id, ptr);
1337                }
1338            });
1339        }
1340        component_id
1341    }
1342
1343    /// Inserts a new non-send resource with the given `value`.
1344    ///
1345    /// `NonSend` resources cannot be sent across threads,
1346    /// and do not need the `Send + Sync` bounds.
1347    /// Systems with `NonSend` resources are always scheduled on the main thread.
1348    ///
1349    /// # Panics
1350    /// If a value is already present, this function will panic if called
1351    /// from a different thread than where the original value was inserted from.
1352    #[inline]
1353    pub fn insert_non_send_resource<R: 'static>(&mut self, value: R) {
1354        let component_id = self.components.init_non_send::<R>();
1355        OwningPtr::make(value, |ptr| {
1356            // SAFETY: component_id was just initialized and corresponds to resource of type R.
1357            unsafe {
1358                self.insert_non_send_by_id(component_id, ptr);
1359            }
1360        });
1361    }
1362
1363    /// Removes the resource of a given type and returns it, if it exists. Otherwise returns `None`.
1364    #[inline]
1365    pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
1366        let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
1367        let (ptr, _) = self.storages.resources.get_mut(component_id)?.remove()?;
1368        // SAFETY: `component_id` was gotten via looking up the `R` type
1369        unsafe { Some(ptr.read::<R>()) }
1370    }
1371
1372    /// Removes a `!Send` resource from the world and returns it, if present.
1373    ///
1374    /// `NonSend` resources cannot be sent across threads,
1375    /// and do not need the `Send + Sync` bounds.
1376    /// Systems with `NonSend` resources are always scheduled on the main thread.
1377    ///
1378    /// Returns `None` if a value was not previously present.
1379    ///
1380    /// # Panics
1381    /// If a value is present, this function will panic if called from a different
1382    /// thread than where the value was inserted from.
1383    #[inline]
1384    pub fn remove_non_send_resource<R: 'static>(&mut self) -> Option<R> {
1385        let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
1386        let (ptr, _) = self
1387            .storages
1388            .non_send_resources
1389            .get_mut(component_id)?
1390            .remove()?;
1391        // SAFETY: `component_id` was gotten via looking up the `R` type
1392        unsafe { Some(ptr.read::<R>()) }
1393    }
1394
1395    /// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
1396    #[inline]
1397    pub fn contains_resource<R: Resource>(&self) -> bool {
1398        self.components
1399            .get_resource_id(TypeId::of::<R>())
1400            .and_then(|component_id| self.storages.resources.get(component_id))
1401            .map(|info| info.is_present())
1402            .unwrap_or(false)
1403    }
1404
1405    /// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
1406    #[inline]
1407    pub fn contains_non_send<R: 'static>(&self) -> bool {
1408        self.components
1409            .get_resource_id(TypeId::of::<R>())
1410            .and_then(|component_id| self.storages.non_send_resources.get(component_id))
1411            .map(|info| info.is_present())
1412            .unwrap_or(false)
1413    }
1414
1415    /// Returns `true` if a resource of type `R` exists and was added since the world's
1416    /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
1417    ///
1418    /// This means that:
1419    /// - When called from an exclusive system, this will check for additions since the system last ran.
1420    /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
1421    ///   was called.
1422    pub fn is_resource_added<R: Resource>(&self) -> bool {
1423        self.components
1424            .get_resource_id(TypeId::of::<R>())
1425            .map(|component_id| self.is_resource_added_by_id(component_id))
1426            .unwrap_or(false)
1427    }
1428
1429    /// Returns `true` if a resource with id `component_id` exists and was added since the world's
1430    /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
1431    ///
1432    /// This means that:
1433    /// - When called from an exclusive system, this will check for additions since the system last ran.
1434    /// - When called elsewhere, this will check for additions since the last time that [`World::clear_trackers`]
1435    ///   was called.
1436    pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool {
1437        self.storages
1438            .resources
1439            .get(component_id)
1440            .and_then(|resource| {
1441                resource
1442                    .get_ticks()
1443                    .map(|ticks| ticks.is_added(self.last_change_tick(), self.read_change_tick()))
1444            })
1445            .unwrap_or(false)
1446    }
1447
1448    /// Returns `true` if a resource of type `R` exists and was modified since the world's
1449    /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
1450    ///
1451    /// This means that:
1452    /// - When called from an exclusive system, this will check for changes since the system last ran.
1453    /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
1454    ///   was called.
1455    pub fn is_resource_changed<R: Resource>(&self) -> bool {
1456        self.components
1457            .get_resource_id(TypeId::of::<R>())
1458            .map(|component_id| self.is_resource_changed_by_id(component_id))
1459            .unwrap_or(false)
1460    }
1461
1462    /// Returns `true` if a resource with id `component_id` exists and was modified since the world's
1463    /// [`last_change_tick`](World::last_change_tick()). Otherwise, this returns `false`.
1464    ///
1465    /// This means that:
1466    /// - When called from an exclusive system, this will check for changes since the system last ran.
1467    /// - When called elsewhere, this will check for changes since the last time that [`World::clear_trackers`]
1468    ///   was called.
1469    pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool {
1470        self.storages
1471            .resources
1472            .get(component_id)
1473            .and_then(|resource| {
1474                resource
1475                    .get_ticks()
1476                    .map(|ticks| ticks.is_changed(self.last_change_tick(), self.read_change_tick()))
1477            })
1478            .unwrap_or(false)
1479    }
1480
1481    /// Retrieves the change ticks for the given resource.
1482    pub fn get_resource_change_ticks<R: Resource>(&self) -> Option<ComponentTicks> {
1483        self.components
1484            .get_resource_id(TypeId::of::<R>())
1485            .and_then(|component_id| self.get_resource_change_ticks_by_id(component_id))
1486    }
1487
1488    /// Retrieves the change ticks for the given [`ComponentId`].
1489    ///
1490    /// **You should prefer to use the typed API [`World::get_resource_change_ticks`] where possible.**
1491    pub fn get_resource_change_ticks_by_id(
1492        &self,
1493        component_id: ComponentId,
1494    ) -> Option<ComponentTicks> {
1495        self.storages
1496            .resources
1497            .get(component_id)
1498            .and_then(|resource| resource.get_ticks())
1499    }
1500
1501    /// Gets a reference to the resource of the given type
1502    ///
1503    /// # Panics
1504    ///
1505    /// Panics if the resource does not exist.
1506    /// Use [`get_resource`](World::get_resource) instead if you want to handle this case.
1507    ///
1508    /// If you want to instead insert a value if the resource does not exist,
1509    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
1510    #[inline]
1511    #[track_caller]
1512    pub fn resource<R: Resource>(&self) -> &R {
1513        match self.get_resource() {
1514            Some(x) => x,
1515            None => panic!(
1516                "Requested resource {} does not exist in the `World`.
1517                Did you forget to add it using `app.insert_resource` / `app.init_resource`?
1518                Resources are also implicitly added via `app.add_event`,
1519                and can be added by plugins.",
1520                std::any::type_name::<R>()
1521            ),
1522        }
1523    }
1524
1525    /// Gets a reference to the resource of the given type
1526    ///
1527    /// # Panics
1528    ///
1529    /// Panics if the resource does not exist.
1530    /// Use [`get_resource_ref`](World::get_resource_ref) instead if you want to handle this case.
1531    ///
1532    /// If you want to instead insert a value if the resource does not exist,
1533    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
1534    #[inline]
1535    #[track_caller]
1536    pub fn resource_ref<R: Resource>(&self) -> Res<R> {
1537        match self.get_resource_ref() {
1538            Some(x) => x,
1539            None => panic!(
1540                "Requested resource {} does not exist in the `World`.
1541                Did you forget to add it using `app.insert_resource` / `app.init_resource`?
1542                Resources are also implicitly added via `app.add_event`,
1543                and can be added by plugins.",
1544                std::any::type_name::<R>()
1545            ),
1546        }
1547    }
1548
1549    /// Gets a mutable reference to the resource of the given type
1550    ///
1551    /// # Panics
1552    ///
1553    /// Panics if the resource does not exist.
1554    /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
1555    ///
1556    /// If you want to instead insert a value if the resource does not exist,
1557    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
1558    #[inline]
1559    #[track_caller]
1560    pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
1561        match self.get_resource_mut() {
1562            Some(x) => x,
1563            None => panic!(
1564                "Requested resource {} does not exist in the `World`.
1565                Did you forget to add it using `app.insert_resource` / `app.init_resource`?
1566                Resources are also implicitly added via `app.add_event`,
1567                and can be added by plugins.",
1568                std::any::type_name::<R>()
1569            ),
1570        }
1571    }
1572
1573    /// Gets a reference to the resource of the given type if it exists
1574    #[inline]
1575    pub fn get_resource<R: Resource>(&self) -> Option<&R> {
1576        // SAFETY:
1577        // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
1578        // - `&self` ensures nothing in world is borrowed mutably
1579        unsafe { self.as_unsafe_world_cell_readonly().get_resource() }
1580    }
1581
1582    /// Gets a reference including change detection to the resource of the given type if it exists.
1583    #[inline]
1584    pub fn get_resource_ref<R: Resource>(&self) -> Option<Res<R>> {
1585        // SAFETY:
1586        // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably
1587        // - `&self` ensures nothing in world is borrowed mutably
1588        unsafe { self.as_unsafe_world_cell_readonly().get_resource_ref() }
1589    }
1590
1591    /// Gets a mutable reference to the resource of the given type if it exists
1592    #[inline]
1593    pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
1594        // SAFETY:
1595        // - `as_unsafe_world_cell` gives permission to access everything mutably
1596        // - `&mut self` ensures nothing in world is borrowed
1597        unsafe { self.as_unsafe_world_cell().get_resource_mut() }
1598    }
1599
1600    /// Gets a mutable reference to the resource of type `T` if it exists,
1601    /// otherwise inserts the resource using the result of calling `func`.
1602    #[inline]
1603    pub fn get_resource_or_insert_with<R: Resource>(
1604        &mut self,
1605        func: impl FnOnce() -> R,
1606    ) -> Mut<'_, R> {
1607        let change_tick = self.change_tick();
1608        let last_change_tick = self.last_change_tick();
1609
1610        let component_id = self.components.init_resource::<R>();
1611        let data = self.initialize_resource_internal(component_id);
1612        if !data.is_present() {
1613            OwningPtr::make(func(), |ptr| {
1614                // SAFETY: component_id was just initialized and corresponds to resource of type R.
1615                unsafe {
1616                    data.insert(ptr, change_tick);
1617                }
1618            });
1619        }
1620
1621        // SAFETY: The resource must be present, as we would have inserted it if it was empty.
1622        let data = unsafe {
1623            data.get_mut(last_change_tick, change_tick)
1624                .debug_checked_unwrap()
1625        };
1626        // SAFETY: The underlying type of the resource is `R`.
1627        unsafe { data.with_type::<R>() }
1628    }
1629
1630    /// Gets an immutable reference to the non-send resource of the given type, if it exists.
1631    ///
1632    /// # Panics
1633    ///
1634    /// Panics if the resource does not exist.
1635    /// Use [`get_non_send_resource`](World::get_non_send_resource) instead if you want to handle this case.
1636    ///
1637    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
1638    #[inline]
1639    #[track_caller]
1640    pub fn non_send_resource<R: 'static>(&self) -> &R {
1641        match self.get_non_send_resource() {
1642            Some(x) => x,
1643            None => panic!(
1644                "Requested non-send resource {} does not exist in the `World`.
1645                Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`?
1646                Non-send resources can also be added by plugins.",
1647                std::any::type_name::<R>()
1648            ),
1649        }
1650    }
1651
1652    /// Gets a mutable reference to the non-send resource of the given type, if it exists.
1653    ///
1654    /// # Panics
1655    ///
1656    /// Panics if the resource does not exist.
1657    /// Use [`get_non_send_resource_mut`](World::get_non_send_resource_mut) instead if you want to handle this case.
1658    ///
1659    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
1660    #[inline]
1661    #[track_caller]
1662    pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
1663        match self.get_non_send_resource_mut() {
1664            Some(x) => x,
1665            None => panic!(
1666                "Requested non-send resource {} does not exist in the `World`.
1667                Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`?
1668                Non-send resources can also be added by plugins.",
1669                std::any::type_name::<R>()
1670            ),
1671        }
1672    }
1673
1674    /// Gets a reference to the non-send resource of the given type, if it exists.
1675    /// Otherwise returns `None`.
1676    ///
1677    /// # Panics
1678    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
1679    #[inline]
1680    pub fn get_non_send_resource<R: 'static>(&self) -> Option<&R> {
1681        // SAFETY:
1682        // - `as_unsafe_world_cell_readonly` gives permission to access the entire world immutably
1683        // - `&self` ensures that there are no mutable borrows of world data
1684        unsafe { self.as_unsafe_world_cell_readonly().get_non_send_resource() }
1685    }
1686
1687    /// Gets a mutable reference to the non-send resource of the given type, if it exists.
1688    /// Otherwise returns `None`.
1689    ///
1690    /// # Panics
1691    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
1692    #[inline]
1693    pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
1694        // SAFETY:
1695        // - `as_unsafe_world_cell` gives permission to access the entire world mutably
1696        // - `&mut self` ensures that there are no borrows of world data
1697        unsafe { self.as_unsafe_world_cell().get_non_send_resource_mut() }
1698    }
1699
1700    // Shorthand helper function for getting the [`ArchetypeComponentId`] for a resource.
1701    #[inline]
1702    pub(crate) fn get_resource_archetype_component_id(
1703        &self,
1704        component_id: ComponentId,
1705    ) -> Option<ArchetypeComponentId> {
1706        let resource = self.storages.resources.get(component_id)?;
1707        Some(resource.id())
1708    }
1709
1710    // Shorthand helper function for getting the [`ArchetypeComponentId`] for a resource.
1711    #[inline]
1712    pub(crate) fn get_non_send_archetype_component_id(
1713        &self,
1714        component_id: ComponentId,
1715    ) -> Option<ArchetypeComponentId> {
1716        let resource = self.storages.non_send_resources.get(component_id)?;
1717        Some(resource.id())
1718    }
1719
1720    /// For a given batch of ([`Entity`], [`Bundle`]) pairs, either spawns each [`Entity`] with the given
1721    /// bundle (if the entity does not exist), or inserts the [`Bundle`] (if the entity already exists).
1722    /// This is faster than doing equivalent operations one-by-one.
1723    /// Returns `Ok` if all entities were successfully inserted into or spawned. Otherwise it returns an `Err`
1724    /// with a list of entities that could not be spawned or inserted into. A "spawn or insert" operation can
1725    /// only fail if an [`Entity`] is passed in with an "invalid generation" that conflicts with an existing [`Entity`].
1726    ///
1727    /// # Note
1728    /// Spawning a specific `entity` value is rarely the right choice. Most apps should use [`World::spawn_batch`].
1729    /// This method should generally only be used for sharing entities across apps, and only when they have a scheme
1730    /// worked out to share an ID space (which doesn't happen by default).
1731    ///
1732    /// ```
1733    /// use bevy_ecs::{entity::Entity, world::World, component::Component};
1734    /// #[derive(Component)]
1735    /// struct A(&'static str);
1736    /// #[derive(Component, PartialEq, Debug)]
1737    /// struct B(f32);
1738    ///
1739    /// let mut world = World::new();
1740    /// let e0 = world.spawn_empty().id();
1741    /// let e1 = world.spawn_empty().id();
1742    /// world.insert_or_spawn_batch(vec![
1743    ///   (e0, (A("a"), B(0.0))), // the first entity
1744    ///   (e1, (A("b"), B(1.0))), // the second entity
1745    /// ]);
1746    ///
1747    /// assert_eq!(world.get::<B>(e0), Some(&B(0.0)));
1748    /// ```
1749    pub fn insert_or_spawn_batch<I, B>(&mut self, iter: I) -> Result<(), Vec<Entity>>
1750    where
1751        I: IntoIterator,
1752        I::IntoIter: Iterator<Item = (Entity, B)>,
1753        B: Bundle,
1754    {
1755        self.flush();
1756
1757        let change_tick = self.change_tick();
1758
1759        let bundle_id = self
1760            .bundles
1761            .init_info::<B>(&mut self.components, &mut self.storages);
1762        enum SpawnOrInsert<'w> {
1763            Spawn(BundleSpawner<'w>),
1764            Insert(BundleInserter<'w>, ArchetypeId),
1765        }
1766
1767        impl<'w> SpawnOrInsert<'w> {
1768            fn entities(&mut self) -> &mut Entities {
1769                match self {
1770                    SpawnOrInsert::Spawn(spawner) => spawner.entities(),
1771                    SpawnOrInsert::Insert(inserter, _) => inserter.entities(),
1772                }
1773            }
1774        }
1775        // SAFETY: we initialized this bundle_id in `init_info`
1776        let mut spawn_or_insert = SpawnOrInsert::Spawn(unsafe {
1777            BundleSpawner::new_with_id(self, bundle_id, change_tick)
1778        });
1779
1780        let mut invalid_entities = Vec::new();
1781        for (entity, bundle) in iter {
1782            match spawn_or_insert
1783                .entities()
1784                .alloc_at_without_replacement(entity)
1785            {
1786                AllocAtWithoutReplacement::Exists(location) => {
1787                    match spawn_or_insert {
1788                        SpawnOrInsert::Insert(ref mut inserter, archetype)
1789                            if location.archetype_id == archetype =>
1790                        {
1791                            // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
1792                            unsafe { inserter.insert(entity, location, bundle) };
1793                        }
1794                        _ => {
1795                            // SAFETY: we initialized this bundle_id in `init_info`
1796                            let mut inserter = unsafe {
1797                                BundleInserter::new_with_id(
1798                                    self,
1799                                    location.archetype_id,
1800                                    bundle_id,
1801                                    change_tick,
1802                                )
1803                            };
1804                            // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
1805                            unsafe { inserter.insert(entity, location, bundle) };
1806                            spawn_or_insert =
1807                                SpawnOrInsert::Insert(inserter, location.archetype_id);
1808                        }
1809                    };
1810                }
1811                AllocAtWithoutReplacement::DidNotExist => {
1812                    if let SpawnOrInsert::Spawn(ref mut spawner) = spawn_or_insert {
1813                        // SAFETY: `entity` is allocated (but non existent), bundle matches inserter
1814                        unsafe { spawner.spawn_non_existent(entity, bundle) };
1815                    } else {
1816                        // SAFETY: we initialized this bundle_id in `init_info`
1817                        let mut spawner =
1818                            unsafe { BundleSpawner::new_with_id(self, bundle_id, change_tick) };
1819                        // SAFETY: `entity` is valid, `location` matches entity, bundle matches inserter
1820                        unsafe { spawner.spawn_non_existent(entity, bundle) };
1821                        spawn_or_insert = SpawnOrInsert::Spawn(spawner);
1822                    }
1823                }
1824                AllocAtWithoutReplacement::ExistsWithWrongGeneration => {
1825                    invalid_entities.push(entity);
1826                }
1827            }
1828        }
1829
1830        if invalid_entities.is_empty() {
1831            Ok(())
1832        } else {
1833            Err(invalid_entities)
1834        }
1835    }
1836
1837    /// Temporarily removes the requested resource from this [`World`], runs custom user code,
1838    /// then re-adds the resource before returning.
1839    ///
1840    /// This enables safe simultaneous mutable access to both a resource and the rest of the [`World`].
1841    /// For more complex access patterns, consider using [`SystemState`](crate::system::SystemState).
1842    ///
1843    /// # Example
1844    /// ```
1845    /// use bevy_ecs::prelude::*;
1846    /// #[derive(Resource)]
1847    /// struct A(u32);
1848    /// #[derive(Component)]
1849    /// struct B(u32);
1850    /// let mut world = World::new();
1851    /// world.insert_resource(A(1));
1852    /// let entity = world.spawn(B(1)).id();
1853    ///
1854    /// world.resource_scope(|world, mut a: Mut<A>| {
1855    ///     let b = world.get_mut::<B>(entity).unwrap();
1856    ///     a.0 += b.0;
1857    /// });
1858    /// assert_eq!(world.get_resource::<A>().unwrap().0, 2);
1859    /// ```
1860    pub fn resource_scope<R: Resource, U>(&mut self, f: impl FnOnce(&mut World, Mut<R>) -> U) -> U {
1861        let last_change_tick = self.last_change_tick();
1862        let change_tick = self.change_tick();
1863
1864        let component_id = self
1865            .components
1866            .get_resource_id(TypeId::of::<R>())
1867            .unwrap_or_else(|| panic!("resource does not exist: {}", std::any::type_name::<R>()));
1868        let (ptr, mut ticks) = self
1869            .storages
1870            .resources
1871            .get_mut(component_id)
1872            .and_then(|info| info.remove())
1873            .unwrap_or_else(|| panic!("resource does not exist: {}", std::any::type_name::<R>()));
1874        // Read the value onto the stack to avoid potential mut aliasing.
1875        // SAFETY: `ptr` was obtained from the TypeId of `R`.
1876        let mut value = unsafe { ptr.read::<R>() };
1877        let value_mut = Mut {
1878            value: &mut value,
1879            ticks: TicksMut {
1880                added: &mut ticks.added,
1881                changed: &mut ticks.changed,
1882                last_run: last_change_tick,
1883                this_run: change_tick,
1884            },
1885        };
1886        let result = f(self, value_mut);
1887        assert!(!self.contains_resource::<R>(),
1888            "Resource `{}` was inserted during a call to World::resource_scope.\n\
1889            This is not allowed as the original resource is reinserted to the world after the closure is invoked.",
1890            std::any::type_name::<R>());
1891
1892        OwningPtr::make(value, |ptr| {
1893            // SAFETY: pointer is of type R
1894            unsafe {
1895                self.storages
1896                    .resources
1897                    .get_mut(component_id)
1898                    .map(|info| info.insert_with_ticks(ptr, ticks))
1899                    .unwrap_or_else(|| {
1900                        panic!(
1901                            "No resource of type {} exists in the World.",
1902                            std::any::type_name::<R>()
1903                        )
1904                    });
1905            }
1906        });
1907
1908        result
1909    }
1910
1911    /// Sends an [`Event`].
1912    /// This method returns the [ID](`EventId`) of the sent `event`,
1913    /// or [`None`] if the `event` could not be sent.
1914    #[inline]
1915    pub fn send_event<E: Event>(&mut self, event: E) -> Option<EventId<E>> {
1916        self.send_event_batch(std::iter::once(event))?.next()
1917    }
1918
1919    /// Sends the default value of the [`Event`] of type `E`.
1920    /// This method returns the [ID](`EventId`) of the sent `event`,
1921    /// or [`None`] if the `event` could not be sent.
1922    #[inline]
1923    pub fn send_event_default<E: Event + Default>(&mut self) -> Option<EventId<E>> {
1924        self.send_event(E::default())
1925    }
1926
1927    /// Sends a batch of [`Event`]s from an iterator.
1928    /// This method returns the [IDs](`EventId`) of the sent `events`,
1929    /// or [`None`] if the `event` could not be sent.
1930    #[inline]
1931    pub fn send_event_batch<E: Event>(
1932        &mut self,
1933        events: impl IntoIterator<Item = E>,
1934    ) -> Option<SendBatchIds<E>> {
1935        let Some(mut events_resource) = self.get_resource_mut::<Events<E>>() else {
1936            bevy_utils::tracing::error!(
1937                "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 ",
1938                std::any::type_name::<E>()
1939            );
1940            return None;
1941        };
1942        Some(events_resource.send_batch(events))
1943    }
1944
1945    /// Inserts a new resource with the given `value`. Will replace the value if it already existed.
1946    ///
1947    /// **You should prefer to use the typed API [`World::insert_resource`] where possible and only
1948    /// use this in cases where the actual types are not known at compile time.**
1949    ///
1950    /// # Safety
1951    /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
1952    #[inline]
1953    pub unsafe fn insert_resource_by_id(
1954        &mut self,
1955        component_id: ComponentId,
1956        value: OwningPtr<'_>,
1957    ) {
1958        let change_tick = self.change_tick();
1959
1960        let resource = self.initialize_resource_internal(component_id);
1961        // SAFETY: `value` is valid for `component_id`, ensured by caller
1962        unsafe {
1963            resource.insert(value, change_tick);
1964        }
1965    }
1966
1967    /// Inserts a new `!Send` resource with the given `value`. Will replace the value if it already
1968    /// existed.
1969    ///
1970    /// **You should prefer to use the typed API [`World::insert_non_send_resource`] where possible and only
1971    /// use this in cases where the actual types are not known at compile time.**
1972    ///
1973    /// # Panics
1974    /// If a value is already present, this function will panic if not called from the same
1975    /// thread that the original value was inserted from.
1976    ///
1977    /// # Safety
1978    /// The value referenced by `value` must be valid for the given [`ComponentId`] of this world.
1979    #[inline]
1980    pub unsafe fn insert_non_send_by_id(
1981        &mut self,
1982        component_id: ComponentId,
1983        value: OwningPtr<'_>,
1984    ) {
1985        let change_tick = self.change_tick();
1986
1987        let resource = self.initialize_non_send_internal(component_id);
1988        // SAFETY: `value` is valid for `component_id`, ensured by caller
1989        unsafe {
1990            resource.insert(value, change_tick);
1991        }
1992    }
1993
1994    /// # Panics
1995    /// Panics if `component_id` is not registered as a `Send` component type in this `World`
1996    #[inline]
1997    pub(crate) fn initialize_resource_internal(
1998        &mut self,
1999        component_id: ComponentId,
2000    ) -> &mut ResourceData<true> {
2001        let archetypes = &mut self.archetypes;
2002        self.storages
2003            .resources
2004            .initialize_with(component_id, &self.components, || {
2005                archetypes.new_archetype_component_id()
2006            })
2007    }
2008
2009    /// # Panics
2010    /// Panics if `component_id` is not registered in this world
2011    #[inline]
2012    pub(crate) fn initialize_non_send_internal(
2013        &mut self,
2014        component_id: ComponentId,
2015    ) -> &mut ResourceData<false> {
2016        let archetypes = &mut self.archetypes;
2017        self.storages
2018            .non_send_resources
2019            .initialize_with(component_id, &self.components, || {
2020                archetypes.new_archetype_component_id()
2021            })
2022    }
2023
2024    /// Empties queued entities and adds them to the empty [`Archetype`](crate::archetype::Archetype).
2025    /// This should be called before doing operations that might operate on queued entities,
2026    /// such as inserting a [`Component`].
2027    pub(crate) fn flush_entities(&mut self) {
2028        let empty_archetype = self.archetypes.empty_mut();
2029        let table = &mut self.storages.tables[empty_archetype.table_id()];
2030        // PERF: consider pre-allocating space for flushed entities
2031        // SAFETY: entity is set to a valid location
2032        unsafe {
2033            self.entities.flush(|entity, location| {
2034                // SAFETY: no components are allocated by archetype.allocate() because the archetype
2035                // is empty
2036                *location = empty_archetype.allocate(entity, table.allocate(entity));
2037            });
2038        }
2039    }
2040
2041    /// Calls both [`World::flush_entities`] and [`World::flush_commands`].
2042    #[inline]
2043    pub fn flush(&mut self) {
2044        self.flush_entities();
2045        self.flush_commands();
2046    }
2047
2048    /// Applies any commands in the world's internal [`CommandQueue`].
2049    /// This does not apply commands from any systems, only those stored in the world.
2050    pub fn flush_commands(&mut self) {
2051        // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
2052        if !unsafe { self.command_queue.is_empty() } {
2053            // SAFETY: `self.command_queue` is only de-allocated in `World`'s `Drop`
2054            unsafe {
2055                self.command_queue
2056                    .clone()
2057                    .apply_or_drop_queued(Some(self.into()));
2058            };
2059        }
2060    }
2061
2062    /// Increments the world's current change tick and returns the old value.
2063    #[inline]
2064    pub fn increment_change_tick(&self) -> Tick {
2065        let prev_tick = self.change_tick.fetch_add(1, Ordering::AcqRel);
2066        Tick::new(prev_tick)
2067    }
2068
2069    /// Reads the current change tick of this world.
2070    ///
2071    /// If you have exclusive (`&mut`) access to the world, consider using [`change_tick()`](Self::change_tick),
2072    /// which is more efficient since it does not require atomic synchronization.
2073    #[inline]
2074    pub fn read_change_tick(&self) -> Tick {
2075        let tick = self.change_tick.load(Ordering::Acquire);
2076        Tick::new(tick)
2077    }
2078
2079    /// Reads the current change tick of this world.
2080    ///
2081    /// This does the same thing as [`read_change_tick()`](Self::read_change_tick), only this method
2082    /// is more efficient since it does not require atomic synchronization.
2083    #[inline]
2084    pub fn change_tick(&mut self) -> Tick {
2085        let tick = *self.change_tick.get_mut();
2086        Tick::new(tick)
2087    }
2088
2089    /// When called from within an exclusive system (a [`System`] that takes `&mut World` as its first
2090    /// parameter), this method returns the [`Tick`] indicating the last time the exclusive system was run.
2091    ///
2092    /// Otherwise, this returns the `Tick` indicating the last time that [`World::clear_trackers`] was called.
2093    ///
2094    /// [`System`]: crate::system::System
2095    #[inline]
2096    pub fn last_change_tick(&self) -> Tick {
2097        self.last_change_tick
2098    }
2099
2100    /// Returns the id of the last ECS event that was fired.
2101    /// Used internally to ensure observers don't trigger multiple times for the same event.
2102    #[inline]
2103    pub(crate) fn last_trigger_id(&self) -> u32 {
2104        self.last_trigger_id
2105    }
2106
2107    /// Sets [`World::last_change_tick()`] to the specified value during a scope.
2108    /// When the scope terminates, it will return to its old value.
2109    ///
2110    /// This is useful if you need a region of code to be able to react to earlier changes made in the same system.
2111    ///
2112    /// # Examples
2113    ///
2114    /// ```
2115    /// # use bevy_ecs::prelude::*;
2116    /// // This function runs an update loop repeatedly, allowing each iteration of the loop
2117    /// // to react to changes made in the previous loop iteration.
2118    /// fn update_loop(
2119    ///     world: &mut World,
2120    ///     mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
2121    /// ) {
2122    ///     let mut last_change_tick = world.last_change_tick();
2123    ///
2124    ///     // Repeatedly run the update function until it requests a break.
2125    ///     loop {
2126    ///         let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
2127    ///             // Increment the change tick so we can detect changes from the previous update.
2128    ///             last_change_tick = world.change_tick();
2129    ///             world.increment_change_tick();
2130    ///
2131    ///             // Update once.
2132    ///             update_fn(world)
2133    ///         });
2134    ///
2135    ///         // End the loop when the closure returns `ControlFlow::Break`.
2136    ///         if control_flow.is_break() {
2137    ///             break;
2138    ///         }
2139    ///     }
2140    /// }
2141    /// #
2142    /// # #[derive(Resource)] struct Count(u32);
2143    /// # let mut world = World::new();
2144    /// # world.insert_resource(Count(0));
2145    /// # let saved_last_tick = world.last_change_tick();
2146    /// # let mut num_updates = 0;
2147    /// # update_loop(&mut world, |world| {
2148    /// #     let mut c = world.resource_mut::<Count>();
2149    /// #     match c.0 {
2150    /// #         0 => {
2151    /// #             assert_eq!(num_updates, 0);
2152    /// #             assert!(c.is_added());
2153    /// #             c.0 = 1;
2154    /// #         }
2155    /// #         1 => {
2156    /// #             assert_eq!(num_updates, 1);
2157    /// #             assert!(!c.is_added());
2158    /// #             assert!(c.is_changed());
2159    /// #             c.0 = 2;
2160    /// #         }
2161    /// #         2 if c.is_changed() => {
2162    /// #             assert_eq!(num_updates, 2);
2163    /// #             assert!(!c.is_added());
2164    /// #         }
2165    /// #         2 => {
2166    /// #             assert_eq!(num_updates, 3);
2167    /// #             assert!(!c.is_changed());
2168    /// #             world.remove_resource::<Count>();
2169    /// #             world.insert_resource(Count(3));
2170    /// #         }
2171    /// #         3 if c.is_changed() => {
2172    /// #             assert_eq!(num_updates, 4);
2173    /// #             assert!(c.is_added());
2174    /// #         }
2175    /// #         3 => {
2176    /// #             assert_eq!(num_updates, 5);
2177    /// #             assert!(!c.is_added());
2178    /// #             c.0 = 4;
2179    /// #             return std::ops::ControlFlow::Break(());
2180    /// #         }
2181    /// #         _ => unreachable!(),
2182    /// #     }
2183    /// #     num_updates += 1;
2184    /// #     std::ops::ControlFlow::Continue(())
2185    /// # });
2186    /// # assert_eq!(num_updates, 5);
2187    /// # assert_eq!(world.resource::<Count>().0, 4);
2188    /// # assert_eq!(world.last_change_tick(), saved_last_tick);
2189    /// ```
2190    pub fn last_change_tick_scope<T>(
2191        &mut self,
2192        last_change_tick: Tick,
2193        f: impl FnOnce(&mut World) -> T,
2194    ) -> T {
2195        struct LastTickGuard<'a> {
2196            world: &'a mut World,
2197            last_tick: Tick,
2198        }
2199
2200        // By setting the change tick in the drop impl, we ensure that
2201        // the change tick gets reset even if a panic occurs during the scope.
2202        impl std::ops::Drop for LastTickGuard<'_> {
2203            fn drop(&mut self) {
2204                self.world.last_change_tick = self.last_tick;
2205            }
2206        }
2207
2208        let guard = LastTickGuard {
2209            last_tick: self.last_change_tick,
2210            world: self,
2211        };
2212
2213        guard.world.last_change_tick = last_change_tick;
2214
2215        f(guard.world)
2216    }
2217
2218    /// Iterates all component change ticks and clamps any older than [`MAX_CHANGE_AGE`](crate::change_detection::MAX_CHANGE_AGE).
2219    /// This prevents overflow and thus prevents false positives.
2220    ///
2221    /// **Note:** Does nothing if the [`World`] counter has not been incremented at least [`CHECK_TICK_THRESHOLD`]
2222    /// times since the previous pass.
2223    // TODO: benchmark and optimize
2224    pub fn check_change_ticks(&mut self) {
2225        let change_tick = self.change_tick();
2226        if change_tick.relative_to(self.last_check_tick).get() < CHECK_TICK_THRESHOLD {
2227            return;
2228        }
2229
2230        let Storages {
2231            ref mut tables,
2232            ref mut sparse_sets,
2233            ref mut resources,
2234            ref mut non_send_resources,
2235        } = self.storages;
2236
2237        #[cfg(feature = "trace")]
2238        let _span = bevy_utils::tracing::info_span!("check component ticks").entered();
2239        tables.check_change_ticks(change_tick);
2240        sparse_sets.check_change_ticks(change_tick);
2241        resources.check_change_ticks(change_tick);
2242        non_send_resources.check_change_ticks(change_tick);
2243
2244        if let Some(mut schedules) = self.get_resource_mut::<Schedules>() {
2245            schedules.check_change_ticks(change_tick);
2246        }
2247
2248        self.last_check_tick = change_tick;
2249    }
2250
2251    /// Runs both [`clear_entities`](Self::clear_entities) and [`clear_resources`](Self::clear_resources),
2252    /// invalidating all [`Entity`] and resource fetches such as [`Res`], [`ResMut`](crate::system::ResMut)
2253    pub fn clear_all(&mut self) {
2254        self.clear_entities();
2255        self.clear_resources();
2256    }
2257
2258    /// Despawns all entities in this [`World`].
2259    pub fn clear_entities(&mut self) {
2260        self.storages.tables.clear();
2261        self.storages.sparse_sets.clear_entities();
2262        self.archetypes.clear_entities();
2263        self.entities.clear();
2264    }
2265
2266    /// Clears all resources in this [`World`].
2267    ///
2268    /// **Note:** Any resource fetch to this [`World`] will fail unless they are re-initialized,
2269    /// including engine-internal resources that are only initialized on app/world construction.
2270    ///
2271    /// This can easily cause systems expecting certain resources to immediately start panicking.
2272    /// Use with caution.
2273    pub fn clear_resources(&mut self) {
2274        self.storages.resources.clear();
2275        self.storages.non_send_resources.clear();
2276    }
2277
2278    /// Initializes all of the components in the given [`Bundle`] and returns both the component
2279    /// ids and the bundle id.
2280    ///
2281    /// This is largely equivalent to calling [`init_component`](Self::init_component) on each
2282    /// component in the bundle.
2283    #[inline]
2284    pub fn init_bundle<B: Bundle>(&mut self) -> &BundleInfo {
2285        let id = self
2286            .bundles
2287            .init_info::<B>(&mut self.components, &mut self.storages);
2288        // SAFETY: We just initialised the bundle so its id should definitely be valid.
2289        unsafe { self.bundles.get(id).debug_checked_unwrap() }
2290    }
2291}
2292
2293impl World {
2294    /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
2295    /// The returned pointer must not be used to modify the resource, and must not be
2296    /// dereferenced after the immutable borrow of the [`World`] ends.
2297    ///
2298    /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
2299    /// use this in cases where the actual types are not known at compile time.**
2300    #[inline]
2301    pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
2302        // SAFETY:
2303        // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
2304        // - `&self` ensures there are no mutable borrows on world data
2305        unsafe {
2306            self.as_unsafe_world_cell_readonly()
2307                .get_resource_by_id(component_id)
2308        }
2309    }
2310
2311    /// Gets a pointer to the resource with the id [`ComponentId`] if it exists.
2312    /// The returned pointer may be used to modify the resource, as long as the mutable borrow
2313    /// of the [`World`] is still valid.
2314    ///
2315    /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
2316    /// use this in cases where the actual types are not known at compile time.**
2317    #[inline]
2318    pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
2319        // SAFETY:
2320        // - `&mut self` ensures that all accessed data is unaliased
2321        // - `as_unsafe_world_cell` provides mutable permission to the whole world
2322        unsafe {
2323            self.as_unsafe_world_cell()
2324                .get_resource_mut_by_id(component_id)
2325        }
2326    }
2327
2328    /// Iterates over all resources in the world.
2329    ///
2330    /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents
2331    /// of each resource will require the use of unsafe code.
2332    ///
2333    /// # Examples
2334    ///
2335    /// ## Printing the size of all resources
2336    ///
2337    /// ```
2338    /// # use bevy_ecs::prelude::*;
2339    /// # #[derive(Resource)]
2340    /// # struct A(u32);
2341    /// # #[derive(Resource)]
2342    /// # struct B(u32);
2343    /// #
2344    /// # let mut world = World::new();
2345    /// # world.insert_resource(A(1));
2346    /// # world.insert_resource(B(2));
2347    /// let mut total = 0;
2348    /// for (info, _) in world.iter_resources() {
2349    ///    println!("Resource: {}", info.name());
2350    ///    println!("Size: {} bytes", info.layout().size());
2351    ///    total += info.layout().size();
2352    /// }
2353    /// println!("Total size: {} bytes", total);
2354    /// # assert_eq!(total, std::mem::size_of::<A>() + std::mem::size_of::<B>());
2355    /// ```
2356    ///
2357    /// ## Dynamically running closures for resources matching specific `TypeId`s
2358    ///
2359    /// ```
2360    /// # use bevy_ecs::prelude::*;
2361    /// # use std::collections::HashMap;
2362    /// # use std::any::TypeId;
2363    /// # use bevy_ptr::Ptr;
2364    /// # #[derive(Resource)]
2365    /// # struct A(u32);
2366    /// # #[derive(Resource)]
2367    /// # struct B(u32);
2368    /// #
2369    /// # let mut world = World::new();
2370    /// # world.insert_resource(A(1));
2371    /// # world.insert_resource(B(2));
2372    /// #
2373    /// // In this example, `A` and `B` are resources. We deliberately do not use the
2374    /// // `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
2375    /// // probably use something like `ReflectFromPtr` in a real-world scenario.
2376    ///
2377    /// // Create the hash map that will store the closures for each resource type
2378    /// let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::new();
2379    ///
2380    /// // Add closure for `A`
2381    /// closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
2382    ///     // SAFETY: We assert ptr is the same type of A with TypeId of A
2383    ///     let a = unsafe { &ptr.deref::<A>() };
2384    /// #   assert_eq!(a.0, 1);
2385    ///     // ... do something with `a` here
2386    /// }));
2387    ///
2388    /// // Add closure for `B`
2389    /// closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
2390    ///     // SAFETY: We assert ptr is the same type of B with TypeId of B
2391    ///     let b = unsafe { &ptr.deref::<B>() };
2392    /// #   assert_eq!(b.0, 2);
2393    ///     // ... do something with `b` here
2394    /// }));
2395    ///
2396    /// // Iterate all resources, in order to run the closures for each matching resource type
2397    /// for (info, ptr) in world.iter_resources() {
2398    ///     let Some(type_id) = info.type_id() else {
2399    ///        // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
2400    ///        // dynamically inserted via a scripting language) in which case we can't match them.
2401    ///        continue;
2402    ///     };
2403    ///
2404    ///     let Some(closure) = closures.get(&type_id) else {
2405    ///        // No closure for this resource type, skip it.
2406    ///        continue;
2407    ///     };
2408    ///
2409    ///     // Run the closure for the resource
2410    ///     closure(&ptr);
2411    /// }
2412    /// ```
2413    #[inline]
2414    pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)> {
2415        self.storages
2416            .resources
2417            .iter()
2418            .filter_map(|(component_id, data)| {
2419                // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
2420                let component_info = unsafe {
2421                    self.components
2422                        .get_info(component_id)
2423                        .debug_checked_unwrap()
2424                };
2425                Some((component_info, data.get_data()?))
2426            })
2427    }
2428
2429    /// Mutably iterates over all resources in the world.
2430    ///
2431    /// The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading from or writing
2432    /// to the contents of each resource will require the use of unsafe code.
2433    ///
2434    /// # Example
2435    ///
2436    /// ```
2437    /// # use bevy_ecs::prelude::*;
2438    /// # use bevy_ecs::change_detection::MutUntyped;
2439    /// # use std::collections::HashMap;
2440    /// # use std::any::TypeId;
2441    /// # #[derive(Resource)]
2442    /// # struct A(u32);
2443    /// # #[derive(Resource)]
2444    /// # struct B(u32);
2445    /// #
2446    /// # let mut world = World::new();
2447    /// # world.insert_resource(A(1));
2448    /// # world.insert_resource(B(2));
2449    /// #
2450    /// // In this example, `A` and `B` are resources. We deliberately do not use the
2451    /// // `bevy_reflect` crate here to showcase the low-level `MutUntyped` usage. You should
2452    /// // probably use something like `ReflectFromPtr` in a real-world scenario.
2453    ///
2454    /// // Create the hash map that will store the mutator closures for each resource type
2455    /// let mut mutators: HashMap<TypeId, Box<dyn Fn(&mut MutUntyped<'_>)>> = HashMap::new();
2456    ///
2457    /// // Add mutator closure for `A`
2458    /// mutators.insert(TypeId::of::<A>(), Box::new(|mut_untyped| {
2459    ///     // Note: `MutUntyped::as_mut()` automatically marks the resource as changed
2460    ///     // for ECS change detection, and gives us a `PtrMut` we can use to mutate the resource.
2461    ///     // SAFETY: We assert ptr is the same type of A with TypeId of A
2462    ///     let a = unsafe { &mut mut_untyped.as_mut().deref_mut::<A>() };
2463    /// #   a.0 += 1;
2464    ///     // ... mutate `a` here
2465    /// }));
2466    ///
2467    /// // Add mutator closure for `B`
2468    /// mutators.insert(TypeId::of::<B>(), Box::new(|mut_untyped| {
2469    ///     // SAFETY: We assert ptr is the same type of B with TypeId of B
2470    ///     let b = unsafe { &mut mut_untyped.as_mut().deref_mut::<B>() };
2471    /// #   b.0 += 1;
2472    ///     // ... mutate `b` here
2473    /// }));
2474    ///
2475    /// // Iterate all resources, in order to run the mutator closures for each matching resource type
2476    /// for (info, mut mut_untyped) in world.iter_resources_mut() {
2477    ///     let Some(type_id) = info.type_id() else {
2478    ///        // It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
2479    ///        // dynamically inserted via a scripting language) in which case we can't match them.
2480    ///        continue;
2481    ///     };
2482    ///
2483    ///     let Some(mutator) = mutators.get(&type_id) else {
2484    ///        // No mutator closure for this resource type, skip it.
2485    ///        continue;
2486    ///     };
2487    ///
2488    ///     // Run the mutator closure for the resource
2489    ///     mutator(&mut mut_untyped);
2490    /// }
2491    /// # assert_eq!(world.resource::<A>().0, 2);
2492    /// # assert_eq!(world.resource::<B>().0, 3);
2493    /// ```
2494    #[inline]
2495    pub fn iter_resources_mut(&mut self) -> impl Iterator<Item = (&ComponentInfo, MutUntyped<'_>)> {
2496        self.storages
2497            .resources
2498            .iter()
2499            .filter_map(|(component_id, data)| {
2500                // SAFETY: If a resource has been initialized, a corresponding ComponentInfo must exist with its ID.
2501                let component_info = unsafe {
2502                    self.components
2503                        .get_info(component_id)
2504                        .debug_checked_unwrap()
2505                };
2506                let (ptr, ticks) = data.get_with_ticks()?;
2507
2508                // SAFETY:
2509                // - We have exclusive access to the world, so no other code can be aliasing the `TickCells`
2510                // - We only hold one `TicksMut` at a time, and we let go of it before getting the next one
2511                let ticks = unsafe {
2512                    TicksMut::from_tick_cells(
2513                        ticks,
2514                        self.last_change_tick(),
2515                        self.read_change_tick(),
2516                    )
2517                };
2518
2519                let mut_untyped = MutUntyped {
2520                    // SAFETY:
2521                    // - We have exclusive access to the world, so no other code can be aliasing the `Ptr`
2522                    // - We iterate one resource at a time, and we let go of each `PtrMut` before getting the next one
2523                    value: unsafe { ptr.assert_unique() },
2524                    ticks,
2525                };
2526
2527                Some((component_info, mut_untyped))
2528            })
2529    }
2530
2531    /// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
2532    /// The returned pointer must not be used to modify the resource, and must not be
2533    /// dereferenced after the immutable borrow of the [`World`] ends.
2534    ///
2535    /// **You should prefer to use the typed API [`World::get_resource`] where possible and only
2536    /// use this in cases where the actual types are not known at compile time.**
2537    ///
2538    /// # Panics
2539    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2540    #[inline]
2541    pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
2542        // SAFETY:
2543        // - `as_unsafe_world_cell_readonly` gives permission to access the whole world immutably
2544        // - `&self` ensures there are no mutable borrows on world data
2545        unsafe {
2546            self.as_unsafe_world_cell_readonly()
2547                .get_non_send_resource_by_id(component_id)
2548        }
2549    }
2550
2551    /// Gets a `!Send` resource to the resource with the id [`ComponentId`] if it exists.
2552    /// The returned pointer may be used to modify the resource, as long as the mutable borrow
2553    /// of the [`World`] is still valid.
2554    ///
2555    /// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
2556    /// use this in cases where the actual types are not known at compile time.**
2557    ///
2558    /// # Panics
2559    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2560    #[inline]
2561    pub fn get_non_send_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
2562        // SAFETY:
2563        // - `&mut self` ensures that all accessed data is unaliased
2564        // - `as_unsafe_world_cell` provides mutable permission to the whole world
2565        unsafe {
2566            self.as_unsafe_world_cell()
2567                .get_non_send_resource_mut_by_id(component_id)
2568        }
2569    }
2570
2571    /// Removes the resource of a given type, if it exists. Otherwise returns `None`.
2572    ///
2573    /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
2574    /// use this in cases where the actual types are not known at compile time.**
2575    pub fn remove_resource_by_id(&mut self, component_id: ComponentId) -> Option<()> {
2576        self.storages
2577            .resources
2578            .get_mut(component_id)?
2579            .remove_and_drop();
2580        Some(())
2581    }
2582
2583    /// Removes the resource of a given type, if it exists. Otherwise returns `None`.
2584    ///
2585    /// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
2586    /// use this in cases where the actual types are not known at compile time.**
2587    ///
2588    /// # Panics
2589    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2590    pub fn remove_non_send_by_id(&mut self, component_id: ComponentId) -> Option<()> {
2591        self.storages
2592            .non_send_resources
2593            .get_mut(component_id)?
2594            .remove_and_drop();
2595        Some(())
2596    }
2597
2598    /// Retrieves an immutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
2599    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
2600    ///
2601    /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
2602    /// use this in cases where the actual types are not known at compile time.**
2603    ///
2604    /// # Panics
2605    /// This function will panic if it isn't called from the same thread that the resource was inserted from.
2606    #[inline]
2607    pub fn get_by_id(&self, entity: Entity, component_id: ComponentId) -> Option<Ptr<'_>> {
2608        // SAFETY:
2609        // - `&self` ensures that all accessed data is not mutably aliased
2610        // - `as_unsafe_world_cell_readonly` provides shared/readonly permission to the whole world
2611        unsafe {
2612            self.as_unsafe_world_cell_readonly()
2613                .get_entity(entity)?
2614                .get_by_id(component_id)
2615        }
2616    }
2617
2618    /// Retrieves a mutable untyped reference to the given `entity`'s [`Component`] of the given [`ComponentId`].
2619    /// Returns `None` if the `entity` does not have a [`Component`] of the given type.
2620    ///
2621    /// **You should prefer to use the typed API [`World::get_mut`] where possible and only
2622    /// use this in cases where the actual types are not known at compile time.**
2623    #[inline]
2624    pub fn get_mut_by_id(
2625        &mut self,
2626        entity: Entity,
2627        component_id: ComponentId,
2628    ) -> Option<MutUntyped<'_>> {
2629        // SAFETY:
2630        // - `&mut self` ensures that all accessed data is unaliased
2631        // - `as_unsafe_world_cell` provides mutable permission to the whole world
2632        unsafe {
2633            self.as_unsafe_world_cell()
2634                .get_entity(entity)?
2635                .get_mut_by_id(component_id)
2636        }
2637    }
2638}
2639
2640// Schedule-related methods
2641impl World {
2642    /// Adds the specified [`Schedule`] to the world. The schedule can later be run
2643    /// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
2644    /// accessing the [`Schedules`] resource.
2645    ///
2646    /// The `Schedules` resource will be initialized if it does not already exist.
2647    pub fn add_schedule(&mut self, schedule: Schedule) {
2648        let mut schedules = self.get_resource_or_insert_with(Schedules::default);
2649        schedules.insert(schedule);
2650    }
2651
2652    /// Temporarily removes the schedule associated with `label` from the world,
2653    /// runs user code, and finally re-adds the schedule.
2654    /// This returns a [`TryRunScheduleError`] if there is no schedule
2655    /// associated with `label`.
2656    ///
2657    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
2658    /// and system state is cached.
2659    ///
2660    /// For simple cases where you just need to call the schedule once,
2661    /// consider using [`World::try_run_schedule`] instead.
2662    /// For other use cases, see the example on [`World::schedule_scope`].
2663    pub fn try_schedule_scope<R>(
2664        &mut self,
2665        label: impl ScheduleLabel,
2666        f: impl FnOnce(&mut World, &mut Schedule) -> R,
2667    ) -> Result<R, TryRunScheduleError> {
2668        let label = label.intern();
2669        let Some(mut schedule) = self
2670            .get_resource_mut::<Schedules>()
2671            .and_then(|mut s| s.remove(label))
2672        else {
2673            return Err(TryRunScheduleError(label));
2674        };
2675
2676        let value = f(self, &mut schedule);
2677
2678        let old = self.resource_mut::<Schedules>().insert(schedule);
2679        if old.is_some() {
2680            warn!("Schedule `{label:?}` was inserted during a call to `World::schedule_scope`: its value has been overwritten");
2681        }
2682
2683        Ok(value)
2684    }
2685
2686    /// Temporarily removes the schedule associated with `label` from the world,
2687    /// runs user code, and finally re-adds the schedule.
2688    ///
2689    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
2690    /// and system state is cached.
2691    ///
2692    /// # Examples
2693    ///
2694    /// ```
2695    /// # use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
2696    /// # #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)]
2697    /// # pub struct MySchedule;
2698    /// # #[derive(Resource)]
2699    /// # struct Counter(usize);
2700    /// #
2701    /// # let mut world = World::new();
2702    /// # world.insert_resource(Counter(0));
2703    /// # let mut schedule = Schedule::new(MySchedule);
2704    /// # schedule.add_systems(tick_counter);
2705    /// # world.init_resource::<Schedules>();
2706    /// # world.add_schedule(schedule);
2707    /// # fn tick_counter(mut counter: ResMut<Counter>) { counter.0 += 1; }
2708    /// // Run the schedule five times.
2709    /// world.schedule_scope(MySchedule, |world, schedule| {
2710    ///     for _ in 0..5 {
2711    ///         schedule.run(world);
2712    ///     }
2713    /// });
2714    /// # assert_eq!(world.resource::<Counter>().0, 5);
2715    /// ```
2716    ///
2717    /// For simple cases where you just need to call the schedule once,
2718    /// consider using [`World::run_schedule`] instead.
2719    ///
2720    /// # Panics
2721    ///
2722    /// If the requested schedule does not exist.
2723    pub fn schedule_scope<R>(
2724        &mut self,
2725        label: impl ScheduleLabel,
2726        f: impl FnOnce(&mut World, &mut Schedule) -> R,
2727    ) -> R {
2728        self.try_schedule_scope(label, f)
2729            .unwrap_or_else(|e| panic!("{e}"))
2730    }
2731
2732    /// Attempts to run the [`Schedule`] associated with the `label` a single time,
2733    /// and returns a [`TryRunScheduleError`] if the schedule does not exist.
2734    ///
2735    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
2736    /// and system state is cached.
2737    ///
2738    /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
2739    pub fn try_run_schedule(
2740        &mut self,
2741        label: impl ScheduleLabel,
2742    ) -> Result<(), TryRunScheduleError> {
2743        self.try_schedule_scope(label, |world, sched| sched.run(world))
2744    }
2745
2746    /// Runs the [`Schedule`] associated with the `label` a single time.
2747    ///
2748    /// The [`Schedule`] is fetched from the [`Schedules`] resource of the world by its label,
2749    /// and system state is cached.
2750    ///
2751    /// For simple testing use cases, call [`Schedule::run(&mut world)`](Schedule::run) instead.
2752    ///
2753    /// # Panics
2754    ///
2755    /// If the requested schedule does not exist.
2756    pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
2757        self.schedule_scope(label, |world, sched| sched.run(world));
2758    }
2759
2760    /// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`.
2761    pub fn allow_ambiguous_component<T: Component>(&mut self) {
2762        let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
2763        schedules.allow_ambiguous_component::<T>(self);
2764        self.insert_resource(schedules);
2765    }
2766
2767    /// Ignore system order ambiguities caused by conflicts on [`Resource`]s of type `T`.
2768    pub fn allow_ambiguous_resource<T: Resource>(&mut self) {
2769        let mut schedules = self.remove_resource::<Schedules>().unwrap_or_default();
2770        schedules.allow_ambiguous_resource::<T>(self);
2771        self.insert_resource(schedules);
2772    }
2773}
2774
2775impl fmt::Debug for World {
2776    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2777        // SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
2778        // Accessing any data stored in the world would be unsound.
2779        f.debug_struct("World")
2780            .field("id", &self.id)
2781            .field("entity_count", &self.entities.len())
2782            .field("archetype_count", &self.archetypes.len())
2783            .field("component_count", &self.components.len())
2784            .field("resource_count", &self.storages.resources.len())
2785            .finish()
2786    }
2787}
2788
2789// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
2790unsafe impl Send for World {}
2791// SAFETY: all methods on the world ensure that non-send resources are only accessible on the main thread
2792unsafe impl Sync for World {}
2793
2794/// Creates an instance of the type this trait is implemented for
2795/// using data from the supplied [`World`].
2796///
2797/// This can be helpful for complex initialization or context-aware defaults.
2798pub trait FromWorld {
2799    /// Creates `Self` using data from the given [`World`].
2800    fn from_world(world: &mut World) -> Self;
2801}
2802
2803impl<T: Default> FromWorld for T {
2804    fn from_world(_world: &mut World) -> Self {
2805        T::default()
2806    }
2807}
2808
2809#[cfg(test)]
2810mod tests {
2811    use super::{FromWorld, World};
2812    use crate::{
2813        change_detection::DetectChangesMut,
2814        component::{ComponentDescriptor, ComponentInfo, StorageType},
2815        ptr::OwningPtr,
2816        system::Resource,
2817    };
2818    use bevy_ecs_macros::Component;
2819    use bevy_utils::{HashMap, HashSet};
2820    use std::{
2821        any::TypeId,
2822        panic,
2823        sync::{
2824            atomic::{AtomicBool, AtomicU32, Ordering},
2825            Arc, Mutex,
2826        },
2827    };
2828
2829    // For bevy_ecs_macros
2830    use crate as bevy_ecs;
2831
2832    type ID = u8;
2833
2834    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2835    enum DropLogItem {
2836        Create(ID),
2837        Drop(ID),
2838    }
2839
2840    #[derive(Resource, Component)]
2841    struct MayPanicInDrop {
2842        drop_log: Arc<Mutex<Vec<DropLogItem>>>,
2843        expected_panic_flag: Arc<AtomicBool>,
2844        should_panic: bool,
2845        id: u8,
2846    }
2847
2848    impl MayPanicInDrop {
2849        fn new(
2850            drop_log: &Arc<Mutex<Vec<DropLogItem>>>,
2851            expected_panic_flag: &Arc<AtomicBool>,
2852            should_panic: bool,
2853            id: u8,
2854        ) -> Self {
2855            println!("creating component with id {id}");
2856            drop_log.lock().unwrap().push(DropLogItem::Create(id));
2857
2858            Self {
2859                drop_log: Arc::clone(drop_log),
2860                expected_panic_flag: Arc::clone(expected_panic_flag),
2861                should_panic,
2862                id,
2863            }
2864        }
2865    }
2866
2867    impl Drop for MayPanicInDrop {
2868        fn drop(&mut self) {
2869            println!("dropping component with id {}", self.id);
2870
2871            {
2872                let mut drop_log = self.drop_log.lock().unwrap();
2873                drop_log.push(DropLogItem::Drop(self.id));
2874                // Don't keep the mutex while panicking, or we'll poison it.
2875                drop(drop_log);
2876            }
2877
2878            if self.should_panic {
2879                self.expected_panic_flag.store(true, Ordering::SeqCst);
2880                panic!("testing what happens on panic inside drop");
2881            }
2882        }
2883    }
2884
2885    struct DropTestHelper {
2886        drop_log: Arc<Mutex<Vec<DropLogItem>>>,
2887        /// Set to `true` right before we intentionally panic, so that if we get
2888        /// a panic, we know if it was intended or not.
2889        expected_panic_flag: Arc<AtomicBool>,
2890    }
2891
2892    impl DropTestHelper {
2893        pub fn new() -> Self {
2894            Self {
2895                drop_log: Arc::new(Mutex::new(Vec::<DropLogItem>::new())),
2896                expected_panic_flag: Arc::new(AtomicBool::new(false)),
2897            }
2898        }
2899
2900        pub fn make_component(&self, should_panic: bool, id: ID) -> MayPanicInDrop {
2901            MayPanicInDrop::new(&self.drop_log, &self.expected_panic_flag, should_panic, id)
2902        }
2903
2904        pub fn finish(self, panic_res: std::thread::Result<()>) -> Vec<DropLogItem> {
2905            let drop_log = self.drop_log.lock().unwrap();
2906            let expected_panic_flag = self.expected_panic_flag.load(Ordering::SeqCst);
2907
2908            if !expected_panic_flag {
2909                match panic_res {
2910                    Ok(()) => panic!("Expected a panic but it didn't happen"),
2911                    Err(e) => panic::resume_unwind(e),
2912                }
2913            }
2914
2915            drop_log.to_owned()
2916        }
2917    }
2918
2919    #[test]
2920    fn panic_while_overwriting_component() {
2921        let helper = DropTestHelper::new();
2922
2923        let res = panic::catch_unwind(|| {
2924            let mut world = World::new();
2925            world
2926                .spawn_empty()
2927                .insert(helper.make_component(true, 0))
2928                .insert(helper.make_component(false, 1));
2929
2930            println!("Done inserting! Dropping world...");
2931        });
2932
2933        let drop_log = helper.finish(res);
2934
2935        assert_eq!(
2936            &*drop_log,
2937            [
2938                DropLogItem::Create(0),
2939                DropLogItem::Create(1),
2940                DropLogItem::Drop(0),
2941                DropLogItem::Drop(1),
2942            ]
2943        );
2944    }
2945
2946    #[derive(Resource)]
2947    struct TestResource(u32);
2948
2949    #[derive(Resource)]
2950    struct TestResource2(String);
2951
2952    #[derive(Resource)]
2953    struct TestResource3;
2954
2955    #[test]
2956    fn get_resource_by_id() {
2957        let mut world = World::new();
2958        world.insert_resource(TestResource(42));
2959        let component_id = world
2960            .components()
2961            .get_resource_id(TypeId::of::<TestResource>())
2962            .unwrap();
2963
2964        let resource = world.get_resource_by_id(component_id).unwrap();
2965        // SAFETY: `TestResource` is the correct resource type
2966        let resource = unsafe { resource.deref::<TestResource>() };
2967
2968        assert_eq!(resource.0, 42);
2969    }
2970
2971    #[test]
2972    fn get_resource_mut_by_id() {
2973        let mut world = World::new();
2974        world.insert_resource(TestResource(42));
2975        let component_id = world
2976            .components()
2977            .get_resource_id(TypeId::of::<TestResource>())
2978            .unwrap();
2979
2980        {
2981            let mut resource = world.get_resource_mut_by_id(component_id).unwrap();
2982            resource.set_changed();
2983            // SAFETY: `TestResource` is the correct resource type
2984            let resource = unsafe { resource.into_inner().deref_mut::<TestResource>() };
2985            resource.0 = 43;
2986        }
2987
2988        let resource = world.get_resource_by_id(component_id).unwrap();
2989        // SAFETY: `TestResource` is the correct resource type
2990        let resource = unsafe { resource.deref::<TestResource>() };
2991
2992        assert_eq!(resource.0, 43);
2993    }
2994
2995    #[test]
2996    fn iter_resources() {
2997        let mut world = World::new();
2998        world.insert_resource(TestResource(42));
2999        world.insert_resource(TestResource2("Hello, world!".to_string()));
3000        world.insert_resource(TestResource3);
3001        world.remove_resource::<TestResource3>();
3002
3003        let mut iter = world.iter_resources();
3004
3005        let (info, ptr) = iter.next().unwrap();
3006        assert_eq!(info.name(), std::any::type_name::<TestResource>());
3007        // SAFETY: We know that the resource is of type `TestResource`
3008        assert_eq!(unsafe { ptr.deref::<TestResource>().0 }, 42);
3009
3010        let (info, ptr) = iter.next().unwrap();
3011        assert_eq!(info.name(), std::any::type_name::<TestResource2>());
3012        assert_eq!(
3013            // SAFETY: We know that the resource is of type `TestResource2`
3014            unsafe { &ptr.deref::<TestResource2>().0 },
3015            &"Hello, world!".to_string()
3016        );
3017
3018        assert!(iter.next().is_none());
3019    }
3020
3021    #[test]
3022    fn iter_resources_mut() {
3023        let mut world = World::new();
3024        world.insert_resource(TestResource(42));
3025        world.insert_resource(TestResource2("Hello, world!".to_string()));
3026        world.insert_resource(TestResource3);
3027        world.remove_resource::<TestResource3>();
3028
3029        let mut iter = world.iter_resources_mut();
3030
3031        let (info, mut mut_untyped) = iter.next().unwrap();
3032        assert_eq!(info.name(), std::any::type_name::<TestResource>());
3033        // SAFETY: We know that the resource is of type `TestResource`
3034        unsafe {
3035            mut_untyped.as_mut().deref_mut::<TestResource>().0 = 43;
3036        };
3037
3038        let (info, mut mut_untyped) = iter.next().unwrap();
3039        assert_eq!(info.name(), std::any::type_name::<TestResource2>());
3040        // SAFETY: We know that the resource is of type `TestResource2`
3041        unsafe {
3042            mut_untyped.as_mut().deref_mut::<TestResource2>().0 = "Hello, world?".to_string();
3043        };
3044
3045        assert!(iter.next().is_none());
3046        std::mem::drop(iter);
3047
3048        assert_eq!(world.resource::<TestResource>().0, 43);
3049        assert_eq!(
3050            world.resource::<TestResource2>().0,
3051            "Hello, world?".to_string()
3052        );
3053    }
3054
3055    #[test]
3056    fn custom_resource_with_layout() {
3057        static DROP_COUNT: AtomicU32 = AtomicU32::new(0);
3058
3059        let mut world = World::new();
3060
3061        // SAFETY: the drop function is valid for the layout and the data will be safe to access from any thread
3062        let descriptor = unsafe {
3063            ComponentDescriptor::new_with_layout(
3064                "Custom Test Component".to_string(),
3065                StorageType::Table,
3066                std::alloc::Layout::new::<[u8; 8]>(),
3067                Some(|ptr| {
3068                    let data = ptr.read::<[u8; 8]>();
3069                    assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]);
3070                    DROP_COUNT.fetch_add(1, Ordering::SeqCst);
3071                }),
3072            )
3073        };
3074
3075        let component_id = world.init_component_with_descriptor(descriptor);
3076
3077        let value: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
3078        OwningPtr::make(value, |ptr| {
3079            // SAFETY: value is valid for the component layout
3080            unsafe {
3081                world.insert_resource_by_id(component_id, ptr);
3082            }
3083        });
3084
3085        // SAFETY: [u8; 8] is the correct type for the resource
3086        let data = unsafe {
3087            world
3088                .get_resource_by_id(component_id)
3089                .unwrap()
3090                .deref::<[u8; 8]>()
3091        };
3092        assert_eq!(*data, [0, 1, 2, 3, 4, 5, 6, 7]);
3093
3094        assert!(world.remove_resource_by_id(component_id).is_some());
3095
3096        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
3097    }
3098
3099    #[derive(Resource)]
3100    struct TestFromWorld(u32);
3101    impl FromWorld for TestFromWorld {
3102        fn from_world(world: &mut World) -> Self {
3103            let b = world.resource::<TestResource>();
3104            Self(b.0)
3105        }
3106    }
3107
3108    #[test]
3109    fn init_resource_does_not_overwrite() {
3110        let mut world = World::new();
3111        world.insert_resource(TestResource(0));
3112        world.init_resource::<TestFromWorld>();
3113        world.insert_resource(TestResource(1));
3114        world.init_resource::<TestFromWorld>();
3115
3116        let resource = world.resource::<TestFromWorld>();
3117
3118        assert_eq!(resource.0, 0);
3119    }
3120
3121    #[test]
3122    fn init_non_send_resource_does_not_overwrite() {
3123        let mut world = World::new();
3124        world.insert_resource(TestResource(0));
3125        world.init_non_send_resource::<TestFromWorld>();
3126        world.insert_resource(TestResource(1));
3127        world.init_non_send_resource::<TestFromWorld>();
3128
3129        let resource = world.non_send_resource::<TestFromWorld>();
3130
3131        assert_eq!(resource.0, 0);
3132    }
3133
3134    #[derive(Component)]
3135    struct Foo;
3136
3137    #[derive(Component)]
3138    struct Bar;
3139
3140    #[derive(Component)]
3141    struct Baz;
3142
3143    #[test]
3144    fn inspect_entity_components() {
3145        let mut world = World::new();
3146        let ent0 = world.spawn((Foo, Bar, Baz)).id();
3147        let ent1 = world.spawn((Foo, Bar)).id();
3148        let ent2 = world.spawn((Bar, Baz)).id();
3149        let ent3 = world.spawn((Foo, Baz)).id();
3150        let ent4 = world.spawn(Foo).id();
3151        let ent5 = world.spawn(Bar).id();
3152        let ent6 = world.spawn(Baz).id();
3153
3154        fn to_type_ids(component_infos: Vec<&ComponentInfo>) -> HashSet<Option<TypeId>> {
3155            component_infos
3156                .into_iter()
3157                .map(|component_info| component_info.type_id())
3158                .collect()
3159        }
3160
3161        let foo_id = TypeId::of::<Foo>();
3162        let bar_id = TypeId::of::<Bar>();
3163        let baz_id = TypeId::of::<Baz>();
3164        assert_eq!(
3165            to_type_ids(world.inspect_entity(ent0)),
3166            [Some(foo_id), Some(bar_id), Some(baz_id)].into()
3167        );
3168        assert_eq!(
3169            to_type_ids(world.inspect_entity(ent1)),
3170            [Some(foo_id), Some(bar_id)].into()
3171        );
3172        assert_eq!(
3173            to_type_ids(world.inspect_entity(ent2)),
3174            [Some(bar_id), Some(baz_id)].into()
3175        );
3176        assert_eq!(
3177            to_type_ids(world.inspect_entity(ent3)),
3178            [Some(foo_id), Some(baz_id)].into()
3179        );
3180        assert_eq!(
3181            to_type_ids(world.inspect_entity(ent4)),
3182            [Some(foo_id)].into()
3183        );
3184        assert_eq!(
3185            to_type_ids(world.inspect_entity(ent5)),
3186            [Some(bar_id)].into()
3187        );
3188        assert_eq!(
3189            to_type_ids(world.inspect_entity(ent6)),
3190            [Some(baz_id)].into()
3191        );
3192    }
3193
3194    #[test]
3195    fn iterate_entities() {
3196        let mut world = World::new();
3197        let mut entity_counters = HashMap::new();
3198
3199        let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
3200            entity_counters.clear();
3201            for entity in world.iter_entities() {
3202                let counter = entity_counters.entry(entity.id()).or_insert(0);
3203                *counter += 1;
3204            }
3205        };
3206
3207        // Adding one entity and validating iteration
3208        let ent0 = world.spawn((Foo, Bar, Baz)).id();
3209
3210        iterate_and_count_entities(&world, &mut entity_counters);
3211        assert_eq!(entity_counters[&ent0], 1);
3212        assert_eq!(entity_counters.len(), 1);
3213
3214        // Spawning three more entities and then validating iteration
3215        let ent1 = world.spawn((Foo, Bar)).id();
3216        let ent2 = world.spawn((Bar, Baz)).id();
3217        let ent3 = world.spawn((Foo, Baz)).id();
3218
3219        iterate_and_count_entities(&world, &mut entity_counters);
3220
3221        assert_eq!(entity_counters[&ent0], 1);
3222        assert_eq!(entity_counters[&ent1], 1);
3223        assert_eq!(entity_counters[&ent2], 1);
3224        assert_eq!(entity_counters[&ent3], 1);
3225        assert_eq!(entity_counters.len(), 4);
3226
3227        // Despawning first entity and then validating the iteration
3228        assert!(world.despawn(ent0));
3229
3230        iterate_and_count_entities(&world, &mut entity_counters);
3231
3232        assert_eq!(entity_counters[&ent1], 1);
3233        assert_eq!(entity_counters[&ent2], 1);
3234        assert_eq!(entity_counters[&ent3], 1);
3235        assert_eq!(entity_counters.len(), 3);
3236
3237        // Spawning three more entities, despawning three and then validating the iteration
3238        let ent4 = world.spawn(Foo).id();
3239        let ent5 = world.spawn(Bar).id();
3240        let ent6 = world.spawn(Baz).id();
3241
3242        assert!(world.despawn(ent2));
3243        assert!(world.despawn(ent3));
3244        assert!(world.despawn(ent4));
3245
3246        iterate_and_count_entities(&world, &mut entity_counters);
3247
3248        assert_eq!(entity_counters[&ent1], 1);
3249        assert_eq!(entity_counters[&ent5], 1);
3250        assert_eq!(entity_counters[&ent6], 1);
3251        assert_eq!(entity_counters.len(), 3);
3252
3253        // Despawning remaining entities and then validating the iteration
3254        assert!(world.despawn(ent1));
3255        assert!(world.despawn(ent5));
3256        assert!(world.despawn(ent6));
3257
3258        iterate_and_count_entities(&world, &mut entity_counters);
3259
3260        assert_eq!(entity_counters.len(), 0);
3261    }
3262
3263    #[test]
3264    fn iterate_entities_mut() {
3265        #[derive(Component, PartialEq, Debug)]
3266        struct A(i32);
3267
3268        #[derive(Component, PartialEq, Debug)]
3269        struct B(i32);
3270
3271        let mut world = World::new();
3272
3273        let a1 = world.spawn(A(1)).id();
3274        let a2 = world.spawn(A(2)).id();
3275        let b1 = world.spawn(B(1)).id();
3276        let b2 = world.spawn(B(2)).id();
3277
3278        for mut entity in world.iter_entities_mut() {
3279            if let Some(mut a) = entity.get_mut::<A>() {
3280                a.0 -= 1;
3281            }
3282        }
3283        assert_eq!(world.entity(a1).get(), Some(&A(0)));
3284        assert_eq!(world.entity(a2).get(), Some(&A(1)));
3285        assert_eq!(world.entity(b1).get(), Some(&B(1)));
3286        assert_eq!(world.entity(b2).get(), Some(&B(2)));
3287
3288        for mut entity in world.iter_entities_mut() {
3289            if let Some(mut b) = entity.get_mut::<B>() {
3290                b.0 *= 2;
3291            }
3292        }
3293        assert_eq!(world.entity(a1).get(), Some(&A(0)));
3294        assert_eq!(world.entity(a2).get(), Some(&A(1)));
3295        assert_eq!(world.entity(b1).get(), Some(&B(2)));
3296        assert_eq!(world.entity(b2).get(), Some(&B(4)));
3297
3298        let mut entities = world.iter_entities_mut().collect::<Vec<_>>();
3299        entities.sort_by_key(|e| e.get::<A>().map(|a| a.0).or(e.get::<B>().map(|b| b.0)));
3300        let (a, b) = entities.split_at_mut(2);
3301        std::mem::swap(
3302            &mut a[1].get_mut::<A>().unwrap().0,
3303            &mut b[0].get_mut::<B>().unwrap().0,
3304        );
3305        assert_eq!(world.entity(a1).get(), Some(&A(0)));
3306        assert_eq!(world.entity(a2).get(), Some(&A(2)));
3307        assert_eq!(world.entity(b1).get(), Some(&B(1)));
3308        assert_eq!(world.entity(b2).get(), Some(&B(4)));
3309    }
3310
3311    #[test]
3312    fn spawn_empty_bundle() {
3313        let mut world = World::new();
3314        world.spawn(());
3315    }
3316
3317    #[test]
3318    fn test_verify_unique_entities() {
3319        let mut world = World::new();
3320        let entity1 = world.spawn(()).id();
3321        let entity2 = world.spawn(()).id();
3322        let entity3 = world.spawn(()).id();
3323        let entity4 = world.spawn(()).id();
3324        let entity5 = world.spawn(()).id();
3325
3326        assert!(
3327            World::verify_unique_entities(&[entity1, entity2, entity3, entity4, entity5]).is_ok()
3328        );
3329        assert!(World::verify_unique_entities(&[entity1, entity1, entity2, entity5]).is_err());
3330        assert!(World::verify_unique_entities(&[
3331            entity1, entity2, entity3, entity4, entity5, entity1
3332        ])
3333        .is_err());
3334    }
3335}