Skip to main content

bevy_ecs/world/entity_access/
world_mut.rs

1use crate::{
2    archetype::Archetype,
3    bundle::{
4        Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode,
5    },
6    change_detection::{ComponentTicks, MaybeLocation, MutUntyped, Tick},
7    component::{Component, ComponentId, Components, Mutable, StorageType},
8    entity::{Entity, EntityCloner, EntityClonerBuilder, EntityLocation, OptIn, OptOut},
9    event::{EntityComponentsTrigger, EntityEvent},
10    lifecycle::{DespawnEvent, DiscardEvent, RemoveEvent, DESPAWN, DISCARD, REMOVE},
11    observer::IntoEntityObserver,
12    query::{
13        has_conflicts, DebugCheckedUnwrap, QueryAccessError, ReadOnlyQueryData,
14        ReleaseStateQueryData, SingleEntityQueryData,
15    },
16    relationship::RelationshipHookMode,
17    resource::{Resource, ResourceEntities},
18    storage::{SparseSets, Table},
19    system::EntityCommands,
20    template::{SceneEntityReferences, Template, TemplateContext},
21    world::{
22        error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, ComponentEntry,
23        DynamicComponentFetch, EntityMut, EntityRef, FilteredEntityMut, FilteredEntityRef, Mut,
24        OccupiedComponentEntry, Ref, VacantComponentEntry, World,
25    },
26};
27
28use alloc::vec::Vec;
29use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr};
30use core::{any::TypeId, marker::PhantomData, mem::MaybeUninit};
31
32/// A mutable reference to a particular [`Entity`], and the entire world.
33///
34/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
35/// which caches the [`EntityLocation`] to reduce duplicate lookups.
36///
37/// Since this type provides mutable access to the entire world, only one
38/// [`EntityWorldMut`] can exist at a time for a given world.
39///
40/// See also [`EntityMut`], which allows disjoint mutable access to multiple
41/// entities at once.  Unlike `EntityMut`, this type allows adding and
42/// removing components, and despawning the entity.
43///
44/// # Invariants and Risk
45///
46/// An [`EntityWorldMut`] may point to a despawned entity.
47/// You can check this via [`is_despawned`](Self::is_despawned).
48/// Using an [`EntityWorldMut`] of a despawned entity may panic in some contexts, so read method documentation carefully.
49///
50/// Unless you have strong reason to assume these invariants, you should generally avoid keeping an [`EntityWorldMut`] to an entity that is potentially not spawned.
51/// For example, when inserting a component, that component insert may trigger an observer that despawns the entity.
52/// So, when you don't have full knowledge of what commands may interact with this entity,
53/// do not further use this value without first checking [`is_despawned`](Self::is_despawned).
54pub struct EntityWorldMut<'w> {
55    world: &'w mut World,
56    entity: Entity,
57    location: Option<EntityLocation>,
58}
59
60impl<'w> EntityWorldMut<'w> {
61    #[track_caller]
62    #[inline(never)]
63    #[cold]
64    fn panic_despawned(&self) -> ! {
65        panic!(
66            "Entity {} {}",
67            self.entity,
68            self.world.entities().get_spawned(self.entity).unwrap_err()
69        );
70    }
71
72    #[inline(always)]
73    #[track_caller]
74    pub(crate) fn assert_not_despawned(&self) {
75        if self.location.is_none() {
76            self.panic_despawned()
77        }
78    }
79
80    #[inline(always)]
81    fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
82        let location = self.location();
83        let last_change_tick = self.world.last_change_tick;
84        let change_tick = self.world.read_change_tick();
85        UnsafeEntityCell::new(
86            self.world.as_unsafe_world_cell_readonly(),
87            self.entity,
88            location,
89            last_change_tick,
90            change_tick,
91        )
92    }
93
94    #[inline(always)]
95    fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
96        let location = self.location();
97        let last_change_tick = self.world.last_change_tick;
98        let change_tick = self.world.change_tick();
99        UnsafeEntityCell::new(
100            self.world.as_unsafe_world_cell(),
101            self.entity,
102            location,
103            last_change_tick,
104            change_tick,
105        )
106    }
107
108    #[inline(always)]
109    fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
110        let location = self.location();
111        let last_change_tick = self.world.last_change_tick;
112        let change_tick = self.world.change_tick();
113        UnsafeEntityCell::new(
114            self.world.as_unsafe_world_cell(),
115            self.entity,
116            location,
117            last_change_tick,
118            change_tick,
119        )
120    }
121
122    /// # Safety
123    ///
124    ///  The `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`.
125    ///  If the `entity` is not spawned for any reason (See [`EntityNotSpawnedError`](crate::entity::EntityNotSpawnedError)), the location should be `None`.
126    ///
127    ///  The above is trivially satisfied if `location` was sourced from `world.entities().get_spawned(entity).ok()`.
128    #[inline]
129    pub(crate) unsafe fn new(
130        world: &'w mut World,
131        entity: Entity,
132        location: Option<EntityLocation>,
133    ) -> Self {
134        debug_assert_eq!(world.entities().get_spawned(entity).ok(), location);
135
136        EntityWorldMut {
137            world,
138            entity,
139            location,
140        }
141    }
142
143    /// Consumes `self` and returns read-only access to all of the entity's
144    /// components, with the world `'w` lifetime.
145    pub fn into_readonly(self) -> EntityRef<'w> {
146        // SAFETY:
147        // - We have exclusive access to the entire world.
148        // - Consuming `self` ensures no mutable accesses are active.
149        unsafe { EntityRef::new(self.into_unsafe_entity_cell()) }
150    }
151
152    /// Gets read-only access to all of the entity's components.
153    #[inline]
154    pub fn as_readonly(&self) -> EntityRef<'_> {
155        // SAFETY:
156        // - We have exclusive access to the entire world.
157        // - `&self` ensures no mutable accesses are active.
158        unsafe { EntityRef::new(self.as_unsafe_entity_cell_readonly()) }
159    }
160
161    /// Consumes `self` and returns non-structural mutable access to all of the
162    /// entity's components, with the world `'w` lifetime.
163    pub fn into_mutable(self) -> EntityMut<'w> {
164        // SAFETY:
165        // - We have exclusive access to the entire world.
166        // - Consuming `self` ensures there are no other accesses.
167        unsafe { EntityMut::new(self.into_unsafe_entity_cell()) }
168    }
169
170    /// Gets non-structural mutable access to all of the entity's components.
171    #[inline]
172    pub fn as_mutable(&mut self) -> EntityMut<'_> {
173        // SAFETY:
174        // - We have exclusive access to the entire world.
175        // - `&mut self` ensures there are no other accesses.
176        unsafe { EntityMut::new(self.as_unsafe_entity_cell()) }
177    }
178
179    /// Returns the [ID](Entity) of the current entity.
180    #[inline]
181    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
182    pub fn id(&self) -> Entity {
183        self.entity
184    }
185
186    /// Gets metadata indicating the location where the current entity is stored.
187    #[inline]
188    pub fn try_location(&self) -> Option<EntityLocation> {
189        self.location
190    }
191
192    /// Returns if the entity is spawned or not.
193    #[inline]
194    pub fn is_spawned(&self) -> bool {
195        self.try_location().is_some()
196    }
197
198    /// Returns the archetype that the current entity belongs to.
199    #[inline]
200    pub fn try_archetype(&self) -> Option<&Archetype> {
201        self.try_location()
202            .map(|location| &self.world.archetypes[location.archetype_id])
203    }
204
205    /// Gets metadata indicating the location where the current entity is stored.
206    ///
207    /// # Panics
208    ///
209    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
210    #[inline]
211    pub fn location(&self) -> EntityLocation {
212        match self.try_location() {
213            Some(a) => a,
214            None => self.panic_despawned(),
215        }
216    }
217
218    /// Returns the archetype that the current entity belongs to.
219    ///
220    /// # Panics
221    ///
222    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
223    #[inline]
224    pub fn archetype(&self) -> &Archetype {
225        match self.try_archetype() {
226            Some(a) => a,
227            None => self.panic_despawned(),
228        }
229    }
230
231    /// Returns `true` if the current entity has a component of type `T`.
232    /// Otherwise, this returns `false`.
233    ///
234    /// ## Notes
235    ///
236    /// If you do not know the concrete type of a component, consider using
237    /// [`Self::contains_id`] or [`Self::contains_type_id`].
238    ///
239    /// # Panics
240    ///
241    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
242    #[inline]
243    pub fn contains<T: Component>(&self) -> bool {
244        self.contains_type_id(TypeId::of::<T>())
245    }
246
247    /// Returns `true` if the current entity has a component identified by `component_id`.
248    /// Otherwise, this returns false.
249    ///
250    /// ## Notes
251    ///
252    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
253    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
254    ///   [`Self::contains_type_id`].
255    ///
256    /// # Panics
257    ///
258    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
259    #[inline]
260    pub fn contains_id(&self, component_id: ComponentId) -> bool {
261        self.as_unsafe_entity_cell_readonly()
262            .contains_id(component_id)
263    }
264
265    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
266    /// Otherwise, this returns false.
267    ///
268    /// ## Notes
269    ///
270    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
271    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
272    ///
273    /// # Panics
274    ///
275    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
276    #[inline]
277    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
278        self.as_unsafe_entity_cell_readonly()
279            .contains_type_id(type_id)
280    }
281
282    /// Gets access to the component of type `T` for the current entity.
283    /// Returns `None` if the entity does not have a component of type `T`.
284    ///
285    /// # Panics
286    ///
287    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
288    #[inline]
289    pub fn get<T: Component>(&self) -> Option<&'_ T> {
290        self.as_readonly().get()
291    }
292
293    /// Returns read-only components for the current entity that match the query `Q`.
294    ///
295    /// # Panics
296    ///
297    /// If the entity does not have the components required by the query `Q` or if the entity
298    /// has been despawned while this `EntityWorldMut` is still alive.
299    #[inline]
300    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData + SingleEntityQueryData>(
301        &self,
302    ) -> Q::Item<'_, 'static> {
303        self.as_readonly().components::<Q>()
304    }
305
306    /// Returns read-only components for the current entity that match the query `Q`,
307    /// or `None` if the entity does not have the components required by the query `Q`.
308    ///
309    /// # Panics
310    ///
311    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
312    #[inline]
313    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData + SingleEntityQueryData>(
314        &self,
315    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
316        self.as_readonly().get_components::<Q>()
317    }
318
319    /// Returns components for the current entity that match the query `Q`,
320    /// or `None` if the entity does not have the components required by the query `Q`.
321    ///
322    /// # Example
323    ///
324    /// ```
325    /// # use bevy_ecs::prelude::*;
326    /// #
327    /// #[derive(Component)]
328    /// struct X(usize);
329    /// #[derive(Component)]
330    /// struct Y(usize);
331    ///
332    /// # let mut world = World::default();
333    /// let mut entity = world.spawn((X(0), Y(0)));
334    /// // Get mutable access to two components at once
335    /// // SAFETY: X and Y are different components
336    /// let (mut x, mut y) =
337    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
338    /// *x = X(1);
339    /// *y = Y(1);
340    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
341    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
342    /// ```
343    ///
344    /// # Safety
345    /// It is the caller's responsibility to ensure that
346    /// the `QueryData` does not provide aliasing mutable references to the same component.
347    ///
348    /// /// # See also
349    ///
350    /// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
351    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData + SingleEntityQueryData>(
352        &mut self,
353    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
354        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
355        unsafe { self.as_mutable().into_components_mut_unchecked::<Q>() }
356    }
357
358    /// Returns components for the current entity that match the query `Q`.
359    /// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
360    /// this will return a [`QueryAccessError`]
361    ///
362    /// # Example
363    ///
364    /// ```
365    /// # use bevy_ecs::prelude::*;
366    /// #
367    /// #[derive(Component)]
368    /// struct X(usize);
369    /// #[derive(Component)]
370    /// struct Y(usize);
371    ///
372    /// # let mut world = World::default();
373    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
374    /// // Get mutable access to two components at once
375    /// // SAFETY: X and Y are different components
376    /// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
377    /// ```
378    ///
379    /// Note that this does an O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
380    /// consideration you should use [`Self::get_components_mut_unchecked`] instead.
381    pub fn get_components_mut<Q: ReleaseStateQueryData + SingleEntityQueryData>(
382        &mut self,
383    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
384        self.as_mutable().into_components_mut::<Q>()
385    }
386
387    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
388    /// or `None` if the entity does not have the components required by the query `Q`.
389    ///
390    /// # Example
391    ///
392    /// ```
393    /// # use bevy_ecs::prelude::*;
394    /// #
395    /// #[derive(Component)]
396    /// struct X(usize);
397    /// #[derive(Component)]
398    /// struct Y(usize);
399    ///
400    /// # let mut world = World::default();
401    /// let mut entity = world.spawn((X(0), Y(0)));
402    /// // Get mutable access to two components at once
403    /// // SAFETY: X and Y are different components
404    /// let (mut x, mut y) =
405    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
406    /// *x = X(1);
407    /// *y = Y(1);
408    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
409    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
410    /// ```
411    ///
412    /// # Safety
413    /// It is the caller's responsibility to ensure that
414    /// the `QueryData` does not provide aliasing mutable references to the same component.
415    ///
416    /// # See also
417    ///
418    /// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
419    pub unsafe fn into_components_mut_unchecked<
420        Q: ReleaseStateQueryData + SingleEntityQueryData,
421    >(
422        self,
423    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
424        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
425        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
426    }
427
428    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
429    /// or `None` if the entity does not have the components required by the query `Q`.
430    ///
431    /// The checks for aliasing mutable references may be expensive.
432    /// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
433    /// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
434    ///
435    /// # Panics
436    ///
437    /// - If the `QueryData` provides aliasing mutable references to the same component.
438    /// - If the entity has been despawned while this `EntityWorldMut` is still alive.
439    ///
440    /// # Example
441    ///
442    /// ```
443    /// # use bevy_ecs::prelude::*;
444    /// #
445    /// #[derive(Component)]
446    /// struct X(usize);
447    /// #[derive(Component)]
448    /// struct Y(usize);
449    ///
450    /// # let mut world = World::default();
451    /// let mut entity = world.spawn((X(0), Y(0)));
452    /// // Get mutable access to two components at once
453    /// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
454    /// *x = X(1);
455    /// *y = Y(1);
456    /// ```
457    ///
458    /// ```should_panic
459    /// # use bevy_ecs::prelude::*;
460    /// #
461    /// # #[derive(Component)]
462    /// # struct X(usize);
463    /// #
464    /// # let mut world = World::default();
465    /// let mut entity = world.spawn((X(0)));
466    /// // This panics, as the `&mut X`s would alias:
467    /// entity.into_components_mut::<(&mut X, &mut X)>();
468    /// ```
469    pub fn into_components_mut<Q: ReleaseStateQueryData + SingleEntityQueryData>(
470        self,
471    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
472        has_conflicts::<Q>(self.world.components())?;
473        // SAFETY: we checked that there were not conflicting components above
474        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
475    }
476
477    /// Consumes `self` and gets access to the component of type `T` with
478    /// the world `'w` lifetime for the current entity.
479    /// Returns `None` if the entity does not have a component of type `T`.
480    ///
481    /// # Panics
482    ///
483    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
484    #[inline]
485    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
486        self.into_readonly().get()
487    }
488
489    /// Gets access to the component of type `T` for the current entity,
490    /// including change detection information as a [`Ref`].
491    ///
492    /// Returns `None` if the entity does not have a component of type `T`.
493    ///
494    /// # Panics
495    ///
496    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
497    #[inline]
498    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
499        self.as_readonly().get_ref()
500    }
501
502    /// Consumes `self` and gets access to the component of type `T`
503    /// with the world `'w` lifetime for the current entity,
504    /// including change detection information as a [`Ref`].
505    ///
506    /// Returns `None` if the entity does not have a component of type `T`.
507    ///
508    /// # Panics
509    ///
510    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
511    #[inline]
512    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
513        self.into_readonly().get_ref()
514    }
515
516    /// Gets mutable access to the component of type `T` for the current entity.
517    /// Returns `None` if the entity does not have a component of type `T`.
518    ///
519    /// # Panics
520    ///
521    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
522    #[inline]
523    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
524        self.as_mutable().into_mut()
525    }
526
527    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
528    /// provided closure on it, returning the result if `T` was available.
529    /// This will trigger the `Remove` and `Discard` component hooks without
530    /// causing an archetype move.
531    ///
532    /// This is most useful with immutable components, where removal and reinsertion
533    /// is the only way to modify a value.
534    ///
535    /// If you do not need to ensure the above hooks are triggered, and your component
536    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
537    ///
538    /// # Examples
539    ///
540    /// ```rust
541    /// # use bevy_ecs::prelude::*;
542    /// #
543    /// #[derive(Component, PartialEq, Eq, Debug)]
544    /// #[component(immutable)]
545    /// struct Foo(bool);
546    ///
547    /// # let mut world = World::default();
548    /// # world.register_component::<Foo>();
549    /// #
550    /// # let entity = world.spawn(Foo(false)).id();
551    /// #
552    /// # let mut entity = world.entity_mut(entity);
553    /// #
554    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
555    /// #
556    /// entity.modify_component(|foo: &mut Foo| {
557    ///     foo.0 = true;
558    /// });
559    /// #
560    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
561    /// ```
562    ///
563    /// # Panics
564    ///
565    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
566    #[inline]
567    pub fn modify_component<T: Component, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
568        self.assert_not_despawned();
569
570        let result = self
571            .world
572            .modify_component(self.entity, f)
573            .expect("entity access must be valid")?;
574
575        self.update_location();
576
577        Some(result)
578    }
579
580    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
581    /// provided closure on it, returning the result if `T` was available.
582    /// This will trigger the `Remove` and `Discard` component hooks without
583    /// causing an archetype move.
584    ///
585    /// This is most useful with immutable components, where removal and reinsertion
586    /// is the only way to modify a value.
587    ///
588    /// If you do not need to ensure the above hooks are triggered, and your component
589    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
590    ///
591    /// # Panics
592    ///
593    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
594    #[inline]
595    pub fn modify_component_by_id<R>(
596        &mut self,
597        component_id: ComponentId,
598        f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
599    ) -> Option<R> {
600        self.assert_not_despawned();
601
602        let result = self
603            .world
604            .modify_component_by_id(self.entity, component_id, f)
605            .expect("entity access must be valid")?;
606
607        self.update_location();
608
609        Some(result)
610    }
611
612    /// Gets mutable access to the component of type `T` for the current entity.
613    /// Returns `None` if the entity does not have a component of type `T`.
614    ///
615    /// # Safety
616    ///
617    /// - `T` must be a mutable component
618    #[inline]
619    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
620        let entity_mut = self.as_mutable();
621        // SAFETY: Same preconditions
622        unsafe { entity_mut.into_mut_assume_mutable() }
623    }
624
625    /// Consumes `self` and gets mutable access to the component of type `T`
626    /// with the world `'w` lifetime for the current entity.
627    /// Returns `None` if the entity does not have a component of type `T`.
628    ///
629    /// # Panics
630    ///
631    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
632    #[inline]
633    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
634        // SAFETY: consuming `self` implies exclusive access
635        unsafe { self.into_unsafe_entity_cell().get_mut() }
636    }
637
638    /// Consumes `self` and gets mutable access to the component of type `T`
639    /// with the world `'w` lifetime for the current entity.
640    /// Returns `None` if the entity does not have a component of type `T`.
641    ///
642    /// # Panics
643    ///
644    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
645    ///
646    /// # Safety
647    ///
648    /// - `T` must be a mutable component
649    #[inline]
650    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
651        // SAFETY: consuming `self` implies exclusive access
652        unsafe { self.into_unsafe_entity_cell().get_mut_assume_mutable() }
653    }
654
655    /// Gets a reference to the resource of the given type
656    ///
657    /// # Panics
658    ///
659    /// Panics if the resource does not exist.
660    /// Use [`get_resource`](EntityWorldMut::get_resource) instead if you want to handle this case.
661    #[inline]
662    #[track_caller]
663    pub fn resource<R: Resource>(&self) -> &R {
664        self.world.resource::<R>()
665    }
666
667    /// Gets a mutable reference to the resource of the given type
668    ///
669    /// # Panics
670    ///
671    /// Panics if the resource does not exist.
672    /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
673    ///
674    /// If you want to instead insert a value if the resource does not exist,
675    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
676    #[inline]
677    #[track_caller]
678    pub fn resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Mut<'_, R> {
679        self.world.resource_mut::<R>()
680    }
681
682    /// Gets a reference to the resource of the given type if it exists
683    #[inline]
684    pub fn get_resource<R: Resource>(&self) -> Option<&R> {
685        self.world.get_resource()
686    }
687
688    /// Gets a mutable reference to the resource of the given type if it exists
689    #[inline]
690    pub fn get_resource_mut<R: Resource<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, R>> {
691        self.world.get_resource_mut()
692    }
693
694    /// Temporarily removes the requested resource from the [`World`], runs custom user code,
695    /// then re-adds the resource before returning.
696    ///
697    /// # Panics
698    ///
699    /// Panics if the resource does not exist.
700    /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
701    ///
702    /// See [`World::resource_scope`] for further details.
703    #[track_caller]
704    pub fn resource_scope<R: Resource, U>(
705        &mut self,
706        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
707    ) -> U {
708        let id = self.id();
709        self.world_scope(|world| {
710            world.resource_scope(|world, res| {
711                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
712                // the outer `world_scope` will handle updating our location if it gets changed by the user code
713                let mut this = world.entity_mut(id);
714                f(&mut this, res)
715            })
716        })
717    }
718
719    /// Temporarily removes the requested resource from the [`World`] if it exists, runs custom user code,
720    /// then re-adds the resource before returning. Returns `None` if the resource does not exist in the [`World`].
721    ///
722    /// See [`World::try_resource_scope`] for further details.
723    pub fn try_resource_scope<R: Resource, U>(
724        &mut self,
725        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
726    ) -> Option<U> {
727        let id = self.id();
728        self.world_scope(|world| {
729            world.try_resource_scope(|world, res| {
730                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
731                // the outer `world_scope` will handle updating our location if it gets changed by the user code
732                let mut this = world.entity_mut(id);
733                f(&mut this, res)
734            })
735        })
736    }
737
738    /// Retrieves this world's [`ResourceEntities`].
739    #[inline]
740    #[track_caller]
741    pub fn resource_entities(&self) -> &ResourceEntities {
742        self.world.resource_entities()
743    }
744
745    /// Retrieves the [`Entity`] associated with the resource of type `R`, if it exists.
746    #[inline]
747    #[track_caller]
748    pub fn resource_entity<R: Resource>(&self) -> Option<Entity> {
749        self.world.resource_entity::<R>()
750    }
751
752    /// Retrieves the change ticks for the given component. This can be useful for implementing change
753    /// detection in custom runtimes.
754    ///
755    /// # Panics
756    ///
757    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
758    #[inline]
759    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
760        self.as_readonly().get_change_ticks::<T>()
761    }
762
763    /// Get the [`MaybeLocation`] from where the given [`Component`] was last changed from.
764    /// This contains information regarding the last place (in code) that changed this component and can be useful for debugging.
765    /// For more information, see [`Location`](https://doc.rust-lang.org/nightly/core/panic/struct.Location.html), and enable the `track_location` feature.
766    ///
767    /// # Panics
768    ///
769    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
770    #[inline]
771    pub fn get_changed_by<T: Component>(&self) -> Option<MaybeLocation> {
772        self.as_readonly().get_changed_by::<T>()
773    }
774
775    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
776    /// detection in custom runtimes.
777    ///
778    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
779    /// use this in cases where the actual component types are not known at
780    /// compile time.**
781    ///
782    /// # Panics
783    ///
784    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
785    #[inline]
786    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
787        self.as_readonly().get_change_ticks_by_id(component_id)
788    }
789
790    /// Returns untyped read-only reference(s) to component(s) for the
791    /// current entity, based on the given [`ComponentId`]s.
792    ///
793    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where
794    /// possible and only use this in cases where the actual component types
795    /// are not known at compile time.**
796    ///
797    /// Unlike [`EntityWorldMut::get`], this returns untyped reference(s) to
798    /// component(s), and it's the job of the caller to ensure the correct
799    /// type(s) are dereferenced (if necessary).
800    ///
801    /// # Errors
802    ///
803    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
804    /// not have a component.
805    ///
806    /// # Examples
807    ///
808    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
809    ///
810    /// # Panics
811    ///
812    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
813    #[inline]
814    pub fn get_by_id<F: DynamicComponentFetch>(
815        &self,
816        component_ids: F,
817    ) -> Result<F::Ref<'_>, EntityComponentError> {
818        self.as_readonly().get_by_id(component_ids)
819    }
820
821    /// Consumes `self` and returns untyped read-only reference(s) to
822    /// component(s) with lifetime `'w` for the current entity, based on the
823    /// given [`ComponentId`]s.
824    ///
825    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`]
826    /// where possible and only use this in cases where the actual component
827    /// types are not known at compile time.**
828    ///
829    /// Unlike [`EntityWorldMut::into_borrow`], this returns untyped reference(s) to
830    /// component(s), and it's the job of the caller to ensure the correct
831    /// type(s) are dereferenced (if necessary).
832    ///
833    /// # Errors
834    ///
835    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
836    /// not have a component.
837    ///
838    /// # Examples
839    ///
840    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
841    ///
842    /// # Panics
843    ///
844    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
845    #[inline]
846    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
847        self,
848        component_ids: F,
849    ) -> Result<F::Ref<'w>, EntityComponentError> {
850        self.into_readonly().get_by_id(component_ids)
851    }
852
853    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
854    /// the current entity, based on the given [`ComponentId`]s.
855    ///
856    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where
857    /// possible and only use this in cases where the actual component types
858    /// are not known at compile time.**
859    ///
860    /// Unlike [`EntityWorldMut::get_mut`], this returns untyped reference(s) to
861    /// component(s), and it's the job of the caller to ensure the correct
862    /// type(s) are dereferenced (if necessary).
863    ///
864    /// # Errors
865    ///
866    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
867    ///   not have a component.
868    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
869    ///   is requested multiple times.
870    ///
871    /// # Examples
872    ///
873    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
874    ///
875    /// # Panics
876    ///
877    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
878    #[inline]
879    pub fn get_mut_by_id<F: DynamicComponentFetch>(
880        &mut self,
881        component_ids: F,
882    ) -> Result<F::Mut<'_>, EntityComponentError> {
883        self.as_mutable().into_mut_by_id(component_ids)
884    }
885
886    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
887    /// the current entity, based on the given [`ComponentId`]s.
888    /// Assumes the given [`ComponentId`]s refer to mutable components.
889    ///
890    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut_assume_mutable`] where
891    /// possible and only use this in cases where the actual component types
892    /// are not known at compile time.**
893    ///
894    /// Unlike [`EntityWorldMut::get_mut_assume_mutable`], this returns untyped reference(s) to
895    /// component(s), and it's the job of the caller to ensure the correct
896    /// type(s) are dereferenced (if necessary).
897    ///
898    /// # Errors
899    ///
900    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
901    ///   not have a component.
902    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
903    ///   is requested multiple times.
904    ///
905    /// # Panics
906    ///
907    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
908    ///
909    /// # Safety
910    /// It is the callers responsibility to ensure that
911    /// - the provided [`ComponentId`]s must refer to mutable components.
912    #[inline]
913    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
914        &mut self,
915        component_ids: F,
916    ) -> Result<F::Mut<'_>, EntityComponentError> {
917        // SAFETY: Upheld by caller
918        unsafe {
919            self.as_mutable()
920                .into_mut_assume_mutable_by_id(component_ids)
921        }
922    }
923
924    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
925    /// to component(s) with lifetime `'w` for the current entity, based on the
926    /// given [`ComponentId`]s.
927    ///
928    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where
929    /// possible and only use this in cases where the actual component types
930    /// are not known at compile time.**
931    ///
932    /// Unlike [`EntityWorldMut::into_mut`], this returns untyped reference(s) to
933    /// component(s), and it's the job of the caller to ensure the correct
934    /// type(s) are dereferenced (if necessary).
935    ///
936    /// # Errors
937    ///
938    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
939    ///   not have a component.
940    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
941    ///   is requested multiple times.
942    ///
943    /// # Examples
944    ///
945    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
946    ///
947    /// # Panics
948    ///
949    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
950    #[inline]
951    pub fn into_mut_by_id<F: DynamicComponentFetch>(
952        self,
953        component_ids: F,
954    ) -> Result<F::Mut<'w>, EntityComponentError> {
955        self.into_mutable().into_mut_by_id(component_ids)
956    }
957
958    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
959    /// to component(s) with lifetime `'w` for the current entity, based on the
960    /// given [`ComponentId`]s.
961    /// Assumes the given [`ComponentId`]s refer to mutable components.
962    ///
963    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut_assume_mutable`] where
964    /// possible and only use this in cases where the actual component types
965    /// are not known at compile time.**
966    ///
967    /// Unlike [`EntityWorldMut::into_mut_assume_mutable`], this returns untyped reference(s) to
968    /// component(s), and it's the job of the caller to ensure the correct
969    /// type(s) are dereferenced (if necessary).
970    ///
971    /// # Errors
972    ///
973    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
974    ///   not have a component.
975    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
976    ///   is requested multiple times.
977    ///
978    /// # Panics
979    ///
980    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
981    ///
982    /// # Safety
983    /// It is the callers responsibility to ensure that
984    /// - the provided [`ComponentId`]s must refer to mutable components.
985    #[inline]
986    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
987        self,
988        component_ids: F,
989    ) -> Result<F::Mut<'w>, EntityComponentError> {
990        // SAFETY: Upheld by caller
991        unsafe {
992            self.into_mutable()
993                .into_mut_assume_mutable_by_id(component_ids)
994        }
995    }
996
997    /// Adds a [`Bundle`] of components to the entity.
998    ///
999    /// This will overwrite any previous value(s) of the same component type.
1000    ///
1001    /// # Panics
1002    ///
1003    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1004    #[track_caller]
1005    pub fn insert<T: Bundle>(&mut self, bundle: T) -> &mut Self {
1006        move_as_ptr!(bundle);
1007        self.insert_with_caller(
1008            bundle,
1009            InsertMode::Replace,
1010            MaybeLocation::caller(),
1011            RelationshipHookMode::Run,
1012        )
1013    }
1014
1015    /// Adds a [`Bundle`] of components to the entity.
1016    /// [`Relationship`](crate::relationship::Relationship) components in the bundle will follow the configuration
1017    /// in `relationship_hook_mode`.
1018    ///
1019    /// This will overwrite any previous value(s) of the same component type.
1020    ///
1021    /// # Warning
1022    ///
1023    /// This can easily break the integrity of relationships. This is intended to be used for cloning and spawning code internals,
1024    /// not most user-facing scenarios.
1025    ///
1026    /// # Panics
1027    ///
1028    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1029    #[track_caller]
1030    pub fn insert_with_relationship_hook_mode<T: Bundle>(
1031        &mut self,
1032        bundle: T,
1033        relationship_hook_mode: RelationshipHookMode,
1034    ) -> &mut Self {
1035        move_as_ptr!(bundle);
1036        self.insert_with_caller(
1037            bundle,
1038            InsertMode::Replace,
1039            MaybeLocation::caller(),
1040            relationship_hook_mode,
1041        )
1042    }
1043
1044    /// Adds a [`Bundle`] of components to the entity without overwriting.
1045    ///
1046    /// This will leave any previous value(s) of the same component type
1047    /// unchanged.
1048    ///
1049    /// # Panics
1050    ///
1051    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1052    #[track_caller]
1053    pub fn insert_if_new<T: Bundle>(&mut self, bundle: T) -> &mut Self {
1054        move_as_ptr!(bundle);
1055        self.insert_with_caller(
1056            bundle,
1057            InsertMode::Keep,
1058            MaybeLocation::caller(),
1059            RelationshipHookMode::Run,
1060        )
1061    }
1062
1063    /// Adds a [`Bundle`] of components to the entity.
1064    #[inline]
1065    pub(crate) fn insert_with_caller<T: Bundle>(
1066        &mut self,
1067        bundle: MovingPtr<'_, T>,
1068        mode: InsertMode,
1069        caller: MaybeLocation,
1070        relationship_hook_mode: RelationshipHookMode,
1071    ) -> &mut Self {
1072        let location = self.location();
1073        let change_tick = self.world.change_tick();
1074        // SAFETY:
1075        // - `location.archetype_id` is part of a valid `EntityLocation`.
1076        let mut bundle_inserter =
1077            unsafe { BundleInserter::new::<T>(self.world, location.archetype_id, change_tick) };
1078        // SAFETY:
1079        // - `location` matches current entity and thus must currently exist in the source
1080        //   archetype for this inserter and its location within the archetype.
1081        // - `T` matches the type used to create the `BundleInserter`.
1082        // - `apply_effect` is called exactly once after this function.
1083        // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
1084        //   and the caller ensures that the value is not accessed or dropped after this function
1085        //   returns.
1086        let (bundle, location) = bundle.partial_move(|bundle| unsafe {
1087            bundle_inserter.insert(
1088                self.entity,
1089                location,
1090                bundle,
1091                mode,
1092                caller,
1093                relationship_hook_mode,
1094            )
1095        });
1096        self.location = Some(location);
1097        self.world.flush();
1098        self.update_location();
1099        // SAFETY:
1100        // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
1101        // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
1102        unsafe { T::apply_effect(bundle, self) };
1103        self
1104    }
1105
1106    /// Inserts a dynamic [`Component`] into the entity.
1107    ///
1108    /// This will overwrite any previous value(s) of the same component type.
1109    ///
1110    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
1111    ///
1112    /// # Safety
1113    ///
1114    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
1115    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1116    ///
1117    /// # Panics
1118    ///
1119    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1120    #[track_caller]
1121    pub unsafe fn insert_by_id(
1122        &mut self,
1123        component_id: ComponentId,
1124        component: OwningPtr<'_>,
1125    ) -> &mut Self {
1126        // SAFETY: Upheld by caller
1127        unsafe {
1128            self.insert_by_id_with_caller(
1129                component_id,
1130                component,
1131                InsertMode::Replace,
1132                MaybeLocation::caller(),
1133                RelationshipHookMode::Run,
1134            )
1135        }
1136    }
1137
1138    /// # Safety
1139    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1140    #[inline]
1141    pub(crate) unsafe fn insert_by_id_with_caller(
1142        &mut self,
1143        component_id: ComponentId,
1144        component: OwningPtr<'_>,
1145        mode: InsertMode,
1146        caller: MaybeLocation,
1147        relationship_hook_insert_mode: RelationshipHookMode,
1148    ) -> &mut Self {
1149        let location = self.location();
1150        let change_tick = self.world.change_tick();
1151        let bundle_id = self.world.bundles.init_component_info(
1152            &mut self.world.storages,
1153            &self.world.components,
1154            component_id,
1155        );
1156        // SAFETY:
1157        // init done above via init_component_info
1158        let storage_type = unsafe { self.world.bundles.get_storage_unchecked(bundle_id) };
1159
1160        // SAFETY:
1161        // - bundle initialized above
1162        // - archetype id taken from existing entity
1163        let bundle_inserter = unsafe {
1164            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick)
1165        };
1166
1167        // SAFETY:
1168        // - only one component, with its component & storage type retrieved above
1169        // - entity & location both belong to self
1170        self.location = Some(unsafe {
1171            insert_dynamic_bundle(
1172                bundle_inserter,
1173                self.entity,
1174                location,
1175                Some(component).into_iter(),
1176                Some(storage_type).iter().cloned(),
1177                mode,
1178                caller,
1179                relationship_hook_insert_mode,
1180            )
1181        });
1182        self.world.flush();
1183        self.update_location();
1184        self
1185    }
1186
1187    /// Inserts a dynamic [`Bundle`] into the entity.
1188    ///
1189    /// This will overwrite any previous value(s) of the same component type.
1190    ///
1191    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
1192    /// If your [`Bundle`] only has one component, use the cached API [`EntityWorldMut::insert_by_id`].
1193    ///
1194    /// If possible, pass a sorted slice of `ComponentId` to maximize caching potential.
1195    ///
1196    /// # Safety
1197    /// - Each [`ComponentId`] must be from the same world as [`EntityWorldMut`]
1198    /// - Each [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1199    ///
1200    /// # Panics
1201    ///
1202    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1203    #[track_caller]
1204    pub unsafe fn insert_by_ids<'a, I: Iterator<Item = OwningPtr<'a>>>(
1205        &mut self,
1206        component_ids: &[ComponentId],
1207        iter_components: I,
1208    ) -> &mut Self {
1209        // SAFETY:
1210        // same preconditions
1211        unsafe {
1212            self.insert_by_ids_internal(component_ids, iter_components, RelationshipHookMode::Run)
1213        }
1214    }
1215
1216    /// # Safety
1217    /// see [`EntityWorldMut::insert_by_ids`]
1218    #[track_caller]
1219    pub(crate) unsafe fn insert_by_ids_internal<'a, I: Iterator<Item = OwningPtr<'a>>>(
1220        &mut self,
1221        component_ids: &[ComponentId],
1222        iter_components: I,
1223        relationship_hook_insert_mode: RelationshipHookMode,
1224    ) -> &mut Self {
1225        let location = self.location();
1226        let change_tick = self.world.change_tick();
1227        let bundle_id = self.world.bundles.init_dynamic_info(
1228            &mut self.world.storages,
1229            &self.world.components,
1230            component_ids,
1231        );
1232
1233        // SAFETY:
1234        // init done above via init_dynamic_info
1235        let mut storage_types =
1236            core::mem::take(unsafe { self.world.bundles.get_storages_unchecked(bundle_id) });
1237        // SAFETY:
1238        // - bundle initialized above
1239        // - archetype id taken from existing entity
1240        let bundle_inserter = unsafe {
1241            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick)
1242        };
1243
1244        // SAFETY:
1245        // - owning pointers are of the component's types per precondition
1246        // - storage types retrieved above
1247        // - entity & location both belong to self
1248        self.location = Some(unsafe {
1249            insert_dynamic_bundle(
1250                bundle_inserter,
1251                self.entity,
1252                location,
1253                iter_components,
1254                (*storage_types).iter().cloned(),
1255                InsertMode::Replace,
1256                MaybeLocation::caller(),
1257                relationship_hook_insert_mode,
1258            )
1259        });
1260        // SAFETY:
1261        // same as above
1262        *unsafe { self.world.bundles.get_storages_unchecked(bundle_id) } =
1263            core::mem::take(&mut storage_types);
1264        self.world.flush();
1265        self.update_location();
1266        self
1267    }
1268
1269    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
1270    ///
1271    /// **Note:** If the entity does not have every component in the bundle, this method will not
1272    /// remove any of them.
1273    ///
1274    /// # Panics
1275    ///
1276    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1277    #[must_use]
1278    #[track_caller]
1279    pub fn take<T: Bundle + BundleFromComponents>(&mut self) -> Option<T> {
1280        let location = self.location();
1281        let entity = self.entity;
1282        let change_tick = self.world.change_tick();
1283
1284        let mut remover =
1285            // SAFETY: The archetype id must be valid since this entity is in it.
1286            unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, change_tick, true) }?;
1287        // SAFETY:
1288        // - The passed location has the same archetype as the remover, since they came from the same location.
1289        // - `location` was obtained from a valid `Self`.
1290        let (new_location, result) = unsafe {
1291            remover.remove(
1292                entity,
1293                location,
1294                MaybeLocation::caller(),
1295                |sets, table, components, bundle_components| {
1296                    let mut bundle_components = bundle_components.iter().copied();
1297                    (
1298                        false,
1299                        T::from_components(&mut (sets, table), &mut |(sets, table)| {
1300                            let component_id = bundle_components.next().unwrap();
1301                            // SAFETY: the component existed to be removed, so its id must be valid.
1302                            let component_info = components.get_info_unchecked(component_id);
1303                            match component_info.storage_type() {
1304                                StorageType::Table => {
1305                                    table
1306                                        .as_mut()
1307                                        // SAFETY: The table must be valid if the component is in it.
1308                                        .debug_checked_unwrap()
1309                                        // SAFETY: The remover is cleaning this up.
1310                                        .take_component(component_id, location.table_row)
1311                                }
1312                                StorageType::SparseSet => sets
1313                                    .get_mut(component_id)
1314                                    .unwrap()
1315                                    .remove_and_forget(entity)
1316                                    .unwrap(),
1317                            }
1318                        }),
1319                    )
1320                },
1321            )
1322        };
1323        self.location = Some(new_location);
1324
1325        self.world.flush();
1326        self.update_location();
1327        Some(result)
1328    }
1329
1330    /// Removes any components in the [`Bundle`] from the entity.
1331    ///
1332    /// See [`EntityCommands::remove`](crate::system::EntityCommands::remove) for more details.
1333    ///
1334    /// # Panics
1335    ///
1336    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1337    #[track_caller]
1338    pub fn remove<T: Bundle>(&mut self) -> &mut Self {
1339        self.remove_with_caller::<T>(MaybeLocation::caller())
1340    }
1341
1342    #[inline]
1343    pub(crate) fn remove_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
1344        let location = self.location();
1345        let change_tick = self.world.change_tick();
1346
1347        let Some(mut remover) =
1348            // SAFETY: The archetype id must be valid since this entity is in it.
1349            (unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, change_tick, false) })
1350        else {
1351            return self;
1352        };
1353        // SAFETY:
1354        // - The remover archetype came from the passed location and the removal can not fail.
1355        // - `location` was obtained from a valid `Self`.
1356        let new_location = unsafe {
1357            remover.remove(
1358                self.entity,
1359                location,
1360                caller,
1361                BundleRemover::empty_pre_remove,
1362            )
1363        }
1364        .0;
1365
1366        self.location = Some(new_location);
1367        self.world.flush();
1368        self.update_location();
1369        self
1370    }
1371
1372    /// Removes all components in the [`Bundle`] and remove all required components for each component in the bundle
1373    ///
1374    /// # Panics
1375    ///
1376    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1377    #[track_caller]
1378    pub fn remove_with_requires<T: Bundle>(&mut self) -> &mut Self {
1379        self.remove_with_requires_with_caller::<T>(MaybeLocation::caller())
1380    }
1381
1382    pub(crate) fn remove_with_requires_with_caller<T: Bundle>(
1383        &mut self,
1384        caller: MaybeLocation,
1385    ) -> &mut Self {
1386        let location = self.location();
1387        let bundle_id = self.world.register_contributed_bundle_info::<T>();
1388        let change_tick = self.world.change_tick();
1389
1390        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1391        let Some(mut remover) = (unsafe {
1392            BundleRemover::new_with_id(
1393                self.world,
1394                location.archetype_id,
1395                bundle_id,
1396                change_tick,
1397                false,
1398            )
1399        }) else {
1400            return self;
1401        };
1402        // SAFETY:
1403        // - The remover archetype came from the passed location and the removal can not fail.
1404        // - `location` was obtained from a valid `Self`.
1405        let new_location = unsafe {
1406            remover.remove(
1407                self.entity,
1408                location,
1409                caller,
1410                BundleRemover::empty_pre_remove,
1411            )
1412        }
1413        .0;
1414
1415        self.location = Some(new_location);
1416        self.world.flush();
1417        self.update_location();
1418        self
1419    }
1420
1421    /// Removes any components except those in the [`Bundle`] (and its Required Components) from the entity.
1422    ///
1423    /// See [`EntityCommands::retain`](crate::system::EntityCommands::retain) for more details.
1424    ///
1425    /// # Panics
1426    ///
1427    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1428    #[track_caller]
1429    pub fn retain<T: Bundle>(&mut self) -> &mut Self {
1430        self.retain_with_caller::<T>(MaybeLocation::caller())
1431    }
1432
1433    #[inline]
1434    pub(crate) fn retain_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
1435        let old_location = self.location();
1436        let retained_bundle = self.world.register_bundle_info::<T>();
1437        let change_tick = self.world.change_tick();
1438        let archetypes = &mut self.world.archetypes;
1439
1440        // SAFETY: `retained_bundle` exists as we just registered it.
1441        let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) };
1442        let old_archetype = &mut archetypes[old_location.archetype_id];
1443
1444        // PERF: this could be stored in an Archetype Edge
1445        let to_remove = &old_archetype
1446            .iter_components()
1447            .filter(|c| !retained_bundle_info.contributed_components().contains(c))
1448            .collect::<Vec<_>>();
1449        let remove_bundle = self.world.bundles.init_dynamic_info(
1450            &mut self.world.storages,
1451            &self.world.components,
1452            to_remove,
1453        );
1454
1455        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1456        let Some(mut remover) = (unsafe {
1457            BundleRemover::new_with_id(
1458                self.world,
1459                old_location.archetype_id,
1460                remove_bundle,
1461                change_tick,
1462                false,
1463            )
1464        }) else {
1465            return self;
1466        };
1467        // SAFETY:
1468        // - The remover archetype came from the passed location and the removal can not fail.
1469        // - `old_location` was obtained from a valid `Self`.
1470        let new_location = unsafe {
1471            remover.remove(
1472                self.entity,
1473                old_location,
1474                caller,
1475                BundleRemover::empty_pre_remove,
1476            )
1477        }
1478        .0;
1479
1480        self.location = Some(new_location);
1481        self.world.flush();
1482        self.update_location();
1483        self
1484    }
1485
1486    /// Removes a dynamic [`Component`] from the entity if it exists.
1487    ///
1488    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
1489    ///
1490    /// # Panics
1491    ///
1492    /// Panics if the provided [`ComponentId`] does not exist in the [`World`] or if the
1493    /// entity has been despawned while this `EntityWorldMut` is still alive.
1494    #[track_caller]
1495    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1496        self.remove_by_id_with_caller(component_id, MaybeLocation::caller())
1497    }
1498
1499    #[inline]
1500    pub(crate) fn remove_by_id_with_caller(
1501        &mut self,
1502        component_id: ComponentId,
1503        caller: MaybeLocation,
1504    ) -> &mut Self {
1505        let location = self.location();
1506        let change_tick = self.world.change_tick();
1507        let components = &mut self.world.components;
1508
1509        let bundle_id = self.world.bundles.init_component_info(
1510            &mut self.world.storages,
1511            components,
1512            component_id,
1513        );
1514
1515        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1516        let Some(mut remover) = (unsafe {
1517            BundleRemover::new_with_id(
1518                self.world,
1519                location.archetype_id,
1520                bundle_id,
1521                change_tick,
1522                false,
1523            )
1524        }) else {
1525            return self;
1526        };
1527        // SAFETY:
1528        // - The remover archetype came from the passed location and the removal can not fail.
1529        // - `location` was obtained from a valid `Self`.
1530        let new_location = unsafe {
1531            remover.remove(
1532                self.entity,
1533                location,
1534                caller,
1535                BundleRemover::empty_pre_remove,
1536            )
1537        }
1538        .0;
1539
1540        self.location = Some(new_location);
1541        self.world.flush();
1542        self.update_location();
1543        self
1544    }
1545
1546    /// Removes a dynamic bundle from the entity if it exists.
1547    ///
1548    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
1549    ///
1550    /// # Panics
1551    ///
1552    /// Panics if any of the provided [`ComponentId`]s do not exist in the [`World`] or if the
1553    /// entity has been despawned while this `EntityWorldMut` is still alive.
1554    #[track_caller]
1555    pub fn remove_by_ids(&mut self, component_ids: &[ComponentId]) -> &mut Self {
1556        self.remove_by_ids_with_caller(
1557            component_ids,
1558            MaybeLocation::caller(),
1559            RelationshipHookMode::Run,
1560            BundleRemover::empty_pre_remove,
1561        )
1562    }
1563
1564    #[inline]
1565    pub(crate) fn remove_by_ids_with_caller<T: 'static>(
1566        &mut self,
1567        component_ids: &[ComponentId],
1568        caller: MaybeLocation,
1569        relationship_hook_mode: RelationshipHookMode,
1570        pre_remove: impl FnOnce(
1571            &mut SparseSets,
1572            Option<&mut Table>,
1573            &Components,
1574            &[ComponentId],
1575        ) -> (bool, T),
1576    ) -> &mut Self {
1577        let location = self.location();
1578        let change_tick = self.world.change_tick();
1579        let components = &mut self.world.components;
1580
1581        let bundle_id = self.world.bundles.init_dynamic_info(
1582            &mut self.world.storages,
1583            components,
1584            component_ids,
1585        );
1586
1587        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1588        let Some(mut remover) = (unsafe {
1589            BundleRemover::new_with_id(
1590                self.world,
1591                location.archetype_id,
1592                bundle_id,
1593                change_tick,
1594                false,
1595            )
1596        }) else {
1597            return self;
1598        };
1599        remover.relationship_hook_mode = relationship_hook_mode;
1600        // SAFETY:
1601        // - The remover archetype came from the passed location and the removal can not fail.
1602        // - `location` was obtained from a valid `Self`.
1603        let new_location = unsafe { remover.remove(self.entity, location, caller, pre_remove) }.0;
1604
1605        self.location = Some(new_location);
1606        self.world.flush();
1607        self.update_location();
1608        self
1609    }
1610
1611    /// Removes all components associated with the entity.
1612    ///
1613    /// # Panics
1614    ///
1615    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1616    #[track_caller]
1617    pub fn clear(&mut self) -> &mut Self {
1618        self.clear_with_caller(MaybeLocation::caller())
1619    }
1620
1621    #[inline]
1622    pub(crate) fn clear_with_caller(&mut self, caller: MaybeLocation) -> &mut Self {
1623        let location = self.location();
1624        let change_tick = self.world.change_tick();
1625
1626        // PERF: this should not be necessary
1627        let component_ids: Vec<ComponentId> = self.archetype().components().to_vec();
1628        let components = &mut self.world.components;
1629
1630        let bundle_id = self.world.bundles.init_dynamic_info(
1631            &mut self.world.storages,
1632            components,
1633            component_ids.as_slice(),
1634        );
1635
1636        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1637        let Some(mut remover) = (unsafe {
1638            BundleRemover::new_with_id(
1639                self.world,
1640                location.archetype_id,
1641                bundle_id,
1642                change_tick,
1643                false,
1644            )
1645        }) else {
1646            return self;
1647        };
1648        // SAFETY:
1649        // - The remover archetype came from the passed location and the removal can not fail.
1650        // - `location` was obtained from a valid `Self`.
1651        let new_location = unsafe {
1652            remover.remove(
1653                self.entity,
1654                location,
1655                caller,
1656                BundleRemover::empty_pre_remove,
1657            )
1658        }
1659        .0;
1660
1661        self.location = Some(new_location);
1662        self.world.flush();
1663        self.update_location();
1664        self
1665    }
1666
1667    /// Despawns the entity without freeing it to the allocator.
1668    /// This returns the new [`Entity`], which you must manage.
1669    /// Note that this still increases the generation to differentiate different spawns of the same row.
1670    ///
1671    /// Additionally, keep in mind the limitations documented in the type-level docs.
1672    /// Unless you have full knowledge of this [`EntityWorldMut`]'s lifetime,
1673    /// you may not assume that nothing else has taken responsibility of this [`Entity`].
1674    /// If you are not careful, this could cause a double free.
1675    ///
1676    /// This may be later [`spawn_at`](World::spawn_at).
1677    /// See [`World::despawn_no_free`] for details and usage examples.
1678    #[track_caller]
1679    pub fn despawn_no_free(mut self) -> Entity {
1680        self.despawn_no_free_with_caller(MaybeLocation::caller());
1681        self.entity
1682    }
1683
1684    /// Creates a new [`TemplateContext`] for this entity and passes it into the given `func`.
1685    pub fn template_context<T>(
1686        &mut self,
1687        func: impl FnOnce(&mut TemplateContext) -> crate::error::Result<T>,
1688    ) -> crate::error::Result<T> {
1689        let mut scene_entities = SceneEntityReferences::default();
1690        let mut context = TemplateContext::new(self, &mut scene_entities);
1691        func(&mut context)
1692    }
1693
1694    /// Builds the given template using a [`TemplateContext`] generated for this entity.
1695    pub fn build_template<T: Template>(&mut self, template: &T) -> crate::error::Result<T::Output> {
1696        self.template_context(|context| template.build_template(context))
1697    }
1698
1699    /// This despawns this entity if it is currently spawned, storing the new [`EntityGeneration`](crate::entity::EntityGeneration) in [`Self::entity`] but not freeing it.
1700    pub(crate) fn despawn_no_free_with_caller(&mut self, caller: MaybeLocation) {
1701        self.despawn_no_free_no_flush_with_caller(caller);
1702        self.world.flush();
1703    }
1704
1705    pub(crate) fn despawn_no_free_no_flush_with_caller(&mut self, caller: MaybeLocation) {
1706        // setup
1707        let Some(location) = self.location else {
1708            // If there is no location, we are already despawned
1709            return;
1710        };
1711        let archetype = &self.world.archetypes[location.archetype_id];
1712
1713        // SAFETY: Archetype cannot be mutably aliased by DeferredWorld
1714        let (archetype, mut deferred_world) = unsafe {
1715            let archetype: *const Archetype = archetype;
1716            let world = self.world.as_unsafe_world_cell();
1717            (&*archetype, world.into_deferred())
1718        };
1719
1720        // SAFETY: All components in the archetype exist in world
1721        unsafe {
1722            if archetype.has_despawn_observer() {
1723                // SAFETY: the DESPAWN event_key corresponds to the Despawn event's type
1724                deferred_world.trigger_raw(
1725                    DESPAWN,
1726                    &mut DespawnEvent {
1727                        entity: self.entity,
1728                    },
1729                    &mut EntityComponentsTrigger {
1730                        components: archetype.components(),
1731                        old_archetype: Some(archetype),
1732                        new_archetype: None,
1733                    },
1734                    caller,
1735                );
1736            }
1737            deferred_world.trigger_on_despawn(
1738                archetype,
1739                self.entity,
1740                archetype.iter_components(),
1741                caller,
1742            );
1743            if archetype.has_discard_observer() {
1744                // SAFETY: the DISCARD event_key corresponds to the Discard event's type
1745                deferred_world.trigger_raw(
1746                    DISCARD,
1747                    &mut DiscardEvent {
1748                        entity: self.entity,
1749                    },
1750                    &mut EntityComponentsTrigger {
1751                        components: archetype.components(),
1752                        old_archetype: Some(archetype),
1753                        new_archetype: None,
1754                    },
1755                    caller,
1756                );
1757            }
1758            deferred_world.trigger_on_discard(
1759                archetype,
1760                self.entity,
1761                archetype.iter_components(),
1762                caller,
1763                RelationshipHookMode::Run,
1764            );
1765            if archetype.has_remove_observer() {
1766                // SAFETY: the REMOVE event_key corresponds to the Remove event's type
1767                deferred_world.trigger_raw(
1768                    REMOVE,
1769                    &mut RemoveEvent {
1770                        entity: self.entity,
1771                    },
1772                    &mut EntityComponentsTrigger {
1773                        components: archetype.components(),
1774                        old_archetype: Some(archetype),
1775                        new_archetype: None,
1776                    },
1777                    caller,
1778                );
1779            }
1780            deferred_world.trigger_on_remove(
1781                archetype,
1782                self.entity,
1783                archetype.iter_components(),
1784                caller,
1785            );
1786        }
1787
1788        // do the despawn
1789        let change_tick = self.world.change_tick();
1790        for component_id in archetype.components() {
1791            self.world
1792                .removed_components
1793                .write(*component_id, self.entity);
1794        }
1795        // SAFETY: Since we had a location, and it was valid, this is safe.
1796        unsafe {
1797            let was_at = self
1798                .world
1799                .entities
1800                .update_existing_location(self.entity.index(), None);
1801            debug_assert_eq!(was_at, Some(location));
1802            self.world
1803                .entities
1804                .mark_spawned_or_despawned(self.entity.index(), caller, change_tick);
1805        }
1806
1807        let table_row;
1808        let moved_entity;
1809        {
1810            let archetype = &mut self.world.archetypes[location.archetype_id];
1811            let remove_result = archetype.swap_remove(location.archetype_row);
1812            if let Some(swapped_entity) = remove_result.swapped_entity {
1813                let swapped_location = self.world.entities.get_spawned(swapped_entity).unwrap();
1814                // SAFETY: swapped_entity is valid and the swapped entity's components are
1815                // moved to the new location immediately after.
1816                unsafe {
1817                    self.world.entities.update_existing_location(
1818                        swapped_entity.index(),
1819                        Some(EntityLocation {
1820                            archetype_id: swapped_location.archetype_id,
1821                            archetype_row: location.archetype_row,
1822                            table_id: swapped_location.table_id,
1823                            table_row: swapped_location.table_row,
1824                        }),
1825                    );
1826                }
1827            }
1828            table_row = remove_result.table_row;
1829
1830            for component_id in archetype.sparse_set_components() {
1831                // set must have existed for the component to be added.
1832                let sparse_set = self
1833                    .world
1834                    .storages
1835                    .sparse_sets
1836                    .get_mut(component_id)
1837                    .unwrap();
1838                sparse_set.remove(self.entity);
1839            }
1840            // SAFETY: table rows stored in archetypes always exist
1841            moved_entity = unsafe {
1842                self.world.storages.tables[archetype.table_id()].swap_remove_unchecked(table_row)
1843            };
1844        };
1845
1846        // Handle displaced entity
1847        if let Some(moved_entity) = moved_entity {
1848            let moved_location = self.world.entities.get_spawned(moved_entity).unwrap();
1849            // SAFETY: `moved_entity` is valid and the provided `EntityLocation` accurately reflects
1850            //         the current location of the entity and its component data.
1851            unsafe {
1852                self.world.entities.update_existing_location(
1853                    moved_entity.index(),
1854                    Some(EntityLocation {
1855                        archetype_id: moved_location.archetype_id,
1856                        archetype_row: moved_location.archetype_row,
1857                        table_id: moved_location.table_id,
1858                        table_row,
1859                    }),
1860                );
1861            }
1862            self.world.archetypes[moved_location.archetype_id]
1863                .set_entity_table_row(moved_location.archetype_row, table_row);
1864        }
1865
1866        // finish
1867        // SAFETY: We just despawned it.
1868        self.entity = unsafe { self.world.entities.mark_free(self.entity.index(), 1) };
1869    }
1870
1871    /// Despawns the current entity.
1872    ///
1873    /// See [`World::despawn`] for more details.
1874    ///
1875    /// # Note
1876    ///
1877    /// This will also despawn any [`Children`](crate::hierarchy::Children) entities, and any other [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1878    /// to despawn descendants. This results in "recursive despawn" behavior.
1879    #[track_caller]
1880    pub fn despawn(self) {
1881        self.despawn_with_caller(MaybeLocation::caller());
1882    }
1883
1884    pub(crate) fn despawn_with_caller(mut self, caller: MaybeLocation) {
1885        self.despawn_no_free_with_caller(caller);
1886        if let Ok(None) = self.world.entities.get(self.entity) {
1887            self.world.entity_allocator.free(self.entity);
1888        }
1889
1890        // Otherwise:
1891        // A command must have reconstructed it (had a location); don't free
1892        // A command must have already despawned it (err) or otherwise made the free unneeded (ex by spawning and despawning in commands); don't free
1893    }
1894
1895    /// Ensures any commands triggered by the actions of Self are applied, equivalent to [`World::flush`]
1896    pub fn flush(self) -> Entity {
1897        self.world.flush();
1898        self.entity
1899    }
1900
1901    /// Gets read-only access to the world that the current entity belongs to.
1902    #[inline]
1903    pub fn world(&self) -> &World {
1904        self.world
1905    }
1906
1907    /// Returns this entity's world.
1908    ///
1909    /// See [`EntityWorldMut::world_scope`] or [`EntityWorldMut::into_world_mut`] for a safe alternative.
1910    ///
1911    /// # Safety
1912    /// Caller must not modify the world in a way that changes the current entity's location
1913    /// If the caller _does_ do something that could change the location, `self.update_location()`
1914    /// must be called before using any other methods on this [`EntityWorldMut`].
1915    #[inline]
1916    pub unsafe fn world_mut(&mut self) -> &mut World {
1917        self.world
1918    }
1919
1920    /// Returns this entity's [`World`], consuming itself.
1921    #[inline]
1922    pub fn into_world_mut(self) -> &'w mut World {
1923        self.world
1924    }
1925
1926    /// Gives mutable access to this entity's [`World`] in a temporary scope.
1927    /// This is a safe alternative to using [`EntityWorldMut::world_mut`].
1928    ///
1929    /// # Examples
1930    ///
1931    /// ```
1932    /// # use bevy_ecs::prelude::*;
1933    /// #[derive(Resource, Default, Clone, Copy)]
1934    /// struct R(u32);
1935    ///
1936    /// # let mut world = World::new();
1937    /// # world.init_resource::<R>();
1938    /// # let mut entity = world.spawn_empty();
1939    /// // This closure gives us temporary access to the world.
1940    /// let new_r = entity.world_scope(|world: &mut World| {
1941    ///     // Mutate the world while we have access to it.
1942    ///     let mut r = world.resource_mut::<R>();
1943    ///     r.0 += 1;
1944    ///
1945    ///     // Return a value from the world before giving it back to the `EntityWorldMut`.
1946    ///     *r
1947    /// });
1948    /// # assert_eq!(new_r.0, 1);
1949    /// ```
1950    pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
1951        struct Guard<'w, 'a> {
1952            entity_mut: &'a mut EntityWorldMut<'w>,
1953        }
1954
1955        impl Drop for Guard<'_, '_> {
1956            #[inline]
1957            fn drop(&mut self) {
1958                self.entity_mut.update_location();
1959            }
1960        }
1961
1962        // When `guard` is dropped at the end of this scope,
1963        // it will update the cached `EntityLocation` for this instance.
1964        // This will run even in case the closure `f` unwinds.
1965        let guard = Guard { entity_mut: self };
1966        f(guard.entity_mut.world)
1967    }
1968
1969    /// Creates a new [`EntityCommands`] instance that writes commands
1970    /// Use [`EntityWorldMut::flush`] to apply all queued commands
1971    #[inline]
1972    pub fn entity_commands(&mut self) -> EntityCommands<'_> {
1973        let id = self.id();
1974        EntityCommands {
1975            entity: id,
1976            commands: self.world.commands(),
1977        }
1978    }
1979
1980    /// Updates the internal entity location to match the current location in the internal
1981    /// [`World`].
1982    ///
1983    /// This is *only* required when using the unsafe function [`EntityWorldMut::world_mut`],
1984    /// which enables the location to change.
1985    ///
1986    /// Note that if the entity is not spawned for any reason,
1987    /// this will have a location of `None`, leading some methods to panic.
1988    pub fn update_location(&mut self) {
1989        self.location = self.world.entities().get_spawned(self.entity).ok();
1990    }
1991
1992    /// Returns if the entity has been despawned.
1993    ///
1994    /// Normally it shouldn't be needed to explicitly check if the entity has been despawned
1995    /// between commands as this shouldn't happen. However, for some special cases where it
1996    /// is known that a hook or an observer might despawn the entity while a [`EntityWorldMut`]
1997    /// reference is still held, this method can be used to check if the entity is still alive
1998    /// to avoid panicking when calling further methods.
1999    #[inline]
2000    pub fn is_despawned(&self) -> bool {
2001        self.location.is_none()
2002    }
2003
2004    /// Gets an Entry into the world for this entity and component for in-place manipulation.
2005    ///
2006    /// The type parameter specifies which component to get.
2007    ///
2008    /// # Examples
2009    ///
2010    /// ```
2011    /// # use bevy_ecs::prelude::*;
2012    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
2013    /// struct Comp(u32);
2014    ///
2015    /// # let mut world = World::new();
2016    /// let mut entity = world.spawn_empty();
2017    /// entity.entry().or_insert_with(|| Comp(4));
2018    /// # let entity_id = entity.id();
2019    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
2020    ///
2021    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
2022    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
2023    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 5);
2024    /// ```
2025    ///
2026    /// # Panics
2027    ///
2028    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2029    pub fn entry<'a, T: Component>(&'a mut self) -> ComponentEntry<'w, 'a, T> {
2030        if self.contains::<T>() {
2031            ComponentEntry::Occupied(OccupiedComponentEntry {
2032                entity_world: self,
2033                _marker: PhantomData,
2034            })
2035        } else {
2036            ComponentEntry::Vacant(VacantComponentEntry {
2037                entity_world: self,
2038                _marker: PhantomData,
2039            })
2040        }
2041    }
2042
2043    /// Creates an [`Observer`](crate::observer::Observer) watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`]
2044    /// targets this entity.
2045    ///
2046    /// # Panics
2047    ///
2048    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2049    ///
2050    /// Panics if the given system is an exclusive system.
2051    #[track_caller]
2052    pub fn observe<M>(&mut self, observer: impl IntoEntityObserver<M>) -> &mut Self {
2053        self.observe_with_caller(observer, MaybeLocation::caller())
2054    }
2055
2056    pub(crate) fn observe_with_caller<M>(
2057        &mut self,
2058        observer: impl IntoEntityObserver<M>,
2059        caller: MaybeLocation,
2060    ) -> &mut Self {
2061        self.assert_not_despawned();
2062        let bundle = observer.into_observer_for_entity(self.entity);
2063        move_as_ptr!(bundle);
2064        self.world.spawn_with_caller(bundle, caller);
2065        self.world.flush();
2066        self.update_location();
2067        self
2068    }
2069
2070    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2071    /// configured through [`EntityClonerBuilder`].
2072    ///
2073    /// The other entity will receive all the components of the original that implement
2074    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2075    /// [denied](EntityClonerBuilder::deny) in the `config`.
2076    ///
2077    /// # Example
2078    ///
2079    /// ```
2080    /// # use bevy_ecs::prelude::*;
2081    /// # #[derive(Component, Clone, PartialEq, Debug)]
2082    /// # struct ComponentA;
2083    /// # #[derive(Component, Clone, PartialEq, Debug)]
2084    /// # struct ComponentB;
2085    /// # let mut world = World::new();
2086    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2087    /// # let target = world.spawn_empty().id();
2088    /// // Clone all components except ComponentA onto the target.
2089    /// world.entity_mut(entity).clone_with_opt_out(target, |builder| {
2090    ///     builder.deny::<ComponentA>();
2091    /// });
2092    /// # assert_eq!(world.get::<ComponentA>(target), None);
2093    /// # assert_eq!(world.get::<ComponentB>(target), Some(&ComponentB));
2094    /// ```
2095    ///
2096    /// See [`EntityClonerBuilder<OptOut>`] for more options.
2097    ///
2098    /// # Panics
2099    ///
2100    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2101    /// - If the target entity does not exist.
2102    pub fn clone_with_opt_out(
2103        &mut self,
2104        target: Entity,
2105        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2106    ) -> &mut Self {
2107        self.assert_not_despawned();
2108
2109        let mut builder = EntityCloner::build_opt_out(self.world);
2110        config(&mut builder);
2111        builder.clone_entity(self.entity, target);
2112
2113        self.world.flush();
2114        self.update_location();
2115        self
2116    }
2117
2118    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2119    /// configured through [`EntityClonerBuilder`].
2120    ///
2121    /// The other entity will receive only the components of the original that implement
2122    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2123    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2124    ///
2125    /// # Example
2126    ///
2127    /// ```
2128    /// # use bevy_ecs::prelude::*;
2129    /// # #[derive(Component, Clone, PartialEq, Debug)]
2130    /// # struct ComponentA;
2131    /// # #[derive(Component, Clone, PartialEq, Debug)]
2132    /// # struct ComponentB;
2133    /// # let mut world = World::new();
2134    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2135    /// # let target = world.spawn_empty().id();
2136    /// // Clone only ComponentA onto the target.
2137    /// world.entity_mut(entity).clone_with_opt_in(target, |builder| {
2138    ///     builder.allow::<ComponentA>();
2139    /// });
2140    /// # assert_eq!(world.get::<ComponentA>(target), Some(&ComponentA));
2141    /// # assert_eq!(world.get::<ComponentB>(target), None);
2142    /// ```
2143    ///
2144    /// See [`EntityClonerBuilder<OptIn>`] for more options.
2145    ///
2146    /// # Panics
2147    ///
2148    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2149    /// - If the target entity does not exist.
2150    pub fn clone_with_opt_in(
2151        &mut self,
2152        target: Entity,
2153        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2154    ) -> &mut Self {
2155        self.assert_not_despawned();
2156
2157        let mut builder = EntityCloner::build_opt_in(self.world);
2158        config(&mut builder);
2159        builder.clone_entity(self.entity, target);
2160
2161        self.world.flush();
2162        self.update_location();
2163        self
2164    }
2165
2166    /// Spawns a clone of this entity and returns the [`Entity`] of the clone.
2167    ///
2168    /// The clone will receive all the components of the original that implement
2169    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2170    ///
2171    /// To configure cloning behavior (such as only cloning certain components),
2172    /// use [`EntityWorldMut::clone_and_spawn_with_opt_out`]/
2173    /// [`opt_in`](`EntityWorldMut::clone_and_spawn_with_opt_in`).
2174    ///
2175    /// # Panics
2176    ///
2177    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2178    pub fn clone_and_spawn(&mut self) -> Entity {
2179        self.clone_and_spawn_with_opt_out(|_| {})
2180    }
2181
2182    /// Spawns a clone of this entity and allows configuring cloning behavior
2183    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2184    ///
2185    /// The clone will receive all the components of the original that implement
2186    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2187    /// [denied](EntityClonerBuilder::deny) in the `config`.
2188    ///
2189    /// # Example
2190    ///
2191    /// ```
2192    /// # use bevy_ecs::prelude::*;
2193    /// # let mut world = World::new();
2194    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2195    /// # #[derive(Component, Clone, PartialEq, Debug)]
2196    /// # struct ComponentA;
2197    /// # #[derive(Component, Clone, PartialEq, Debug)]
2198    /// # struct ComponentB;
2199    /// // Create a clone of an entity but without ComponentA.
2200    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_out(|builder| {
2201    ///     builder.deny::<ComponentA>();
2202    /// });
2203    /// # assert_eq!(world.get::<ComponentA>(entity_clone), None);
2204    /// # assert_eq!(world.get::<ComponentB>(entity_clone), Some(&ComponentB));
2205    /// ```
2206    ///
2207    /// See [`EntityClonerBuilder<OptOut>`] for more options.
2208    ///
2209    /// # Panics
2210    ///
2211    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2212    pub fn clone_and_spawn_with_opt_out(
2213        &mut self,
2214        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2215    ) -> Entity {
2216        self.assert_not_despawned();
2217        let entity_clone = self.world.spawn_empty().id();
2218
2219        let mut builder = EntityCloner::build_opt_out(self.world);
2220        config(&mut builder);
2221        builder.clone_entity(self.entity, entity_clone);
2222
2223        self.world.flush();
2224        self.update_location();
2225        entity_clone
2226    }
2227
2228    /// Spawns a clone of this entity and allows configuring cloning behavior
2229    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2230    ///
2231    /// The clone will receive only the components of the original that implement
2232    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2233    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2234    ///
2235    /// # Example
2236    ///
2237    /// ```
2238    /// # use bevy_ecs::prelude::*;
2239    /// # let mut world = World::new();
2240    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2241    /// # #[derive(Component, Clone, PartialEq, Debug)]
2242    /// # struct ComponentA;
2243    /// # #[derive(Component, Clone, PartialEq, Debug)]
2244    /// # struct ComponentB;
2245    /// // Create a clone of an entity but only with ComponentA.
2246    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_in(|builder| {
2247    ///     builder.allow::<ComponentA>();
2248    /// });
2249    /// # assert_eq!(world.get::<ComponentA>(entity_clone), Some(&ComponentA));
2250    /// # assert_eq!(world.get::<ComponentB>(entity_clone), None);
2251    /// ```
2252    ///
2253    /// See [`EntityClonerBuilder<OptIn>`] for more options.
2254    ///
2255    /// # Panics
2256    ///
2257    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2258    pub fn clone_and_spawn_with_opt_in(
2259        &mut self,
2260        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2261    ) -> Entity {
2262        self.assert_not_despawned();
2263        let entity_clone = self.world.spawn_empty().id();
2264
2265        let mut builder = EntityCloner::build_opt_in(self.world);
2266        config(&mut builder);
2267        builder.clone_entity(self.entity, entity_clone);
2268
2269        self.world.flush();
2270        self.update_location();
2271        entity_clone
2272    }
2273
2274    /// Clones the specified components of this entity and inserts them into another entity.
2275    ///
2276    /// Components can only be cloned if they implement
2277    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2278    ///
2279    /// # Panics
2280    ///
2281    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2282    /// - If the target entity does not exist.
2283    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2284        self.assert_not_despawned();
2285
2286        EntityCloner::build_opt_in(self.world)
2287            .allow::<B>()
2288            .clone_entity(self.entity, target);
2289
2290        self.world.flush();
2291        self.update_location();
2292        self
2293    }
2294
2295    /// Clones the specified components of this entity and inserts them into another entity,
2296    /// then removes the components from this entity.
2297    ///
2298    /// Components can only be cloned if they implement
2299    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2300    ///
2301    /// # Panics
2302    ///
2303    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2304    /// - If the target entity does not exist.
2305    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2306        self.assert_not_despawned();
2307
2308        EntityCloner::build_opt_in(self.world)
2309            .allow::<B>()
2310            .move_components(true)
2311            .clone_entity(self.entity, target);
2312
2313        self.world.flush();
2314        self.update_location();
2315        self
2316    }
2317
2318    /// Returns the source code location from which this entity has last been spawned.
2319    pub fn spawned_by(&self) -> MaybeLocation {
2320        self.world()
2321            .entities()
2322            .entity_get_spawned_or_despawned_by(self.entity)
2323            .map(|location| location.unwrap())
2324    }
2325
2326    /// Returns the [`Tick`] at which this entity has last been spawned.
2327    pub fn spawn_tick(&self) -> Tick {
2328        self.assert_not_despawned();
2329
2330        // SAFETY: entity being alive was asserted
2331        unsafe {
2332            self.world()
2333                .entities()
2334                .entity_get_spawned_or_despawned_unchecked(self.entity)
2335                .1
2336        }
2337    }
2338
2339    /// Reborrows this entity in a temporary scope.
2340    /// This is useful for executing a function that requires a `EntityWorldMut`
2341    /// but you do not want to move out the entity ownership.
2342    pub fn reborrow_scope<U>(&mut self, f: impl FnOnce(EntityWorldMut) -> U) -> U {
2343        let Self {
2344            entity, location, ..
2345        } = *self;
2346        self.world_scope(move |world| {
2347            f(EntityWorldMut {
2348                world,
2349                entity,
2350                location,
2351            })
2352        })
2353    }
2354
2355    /// Passes the current entity into the given function, and triggers the [`EntityEvent`] returned by that function.
2356    /// See [`EntityCommands::trigger`] for usage examples
2357    ///
2358    /// [`EntityCommands::trigger`]: crate::system::EntityCommands::trigger
2359    #[track_caller]
2360    pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
2361        &mut self,
2362        event_fn: impl FnOnce(Entity) -> E,
2363    ) -> &mut Self {
2364        let mut event = (event_fn)(self.entity);
2365        let caller = MaybeLocation::caller();
2366        self.world_scope(|world| {
2367            world.trigger_ref_with_caller(
2368                &mut event,
2369                &mut <E::Trigger<'_> as Default>::default(),
2370                caller,
2371            );
2372        });
2373        self
2374    }
2375}
2376
2377impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w> {
2378    #[inline]
2379    fn from(entity: EntityWorldMut<'w>) -> EntityRef<'w> {
2380        entity.into_readonly()
2381    }
2382}
2383
2384impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> {
2385    #[inline]
2386    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
2387        entity.as_readonly()
2388    }
2389}
2390
2391impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w> {
2392    #[inline]
2393    fn from(entity: EntityWorldMut<'w>) -> Self {
2394        entity.into_mutable()
2395    }
2396}
2397
2398impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a> {
2399    #[inline]
2400    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
2401        entity.as_mutable()
2402    }
2403}
2404
2405impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a, 'static> {
2406    #[inline]
2407    fn from(entity: EntityWorldMut<'a>) -> Self {
2408        entity.into_readonly().into_filtered()
2409    }
2410}
2411
2412impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static> {
2413    #[inline]
2414    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
2415        entity.as_readonly().into_filtered()
2416    }
2417}
2418
2419impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a, 'static> {
2420    #[inline]
2421    fn from(entity: EntityWorldMut<'a>) -> Self {
2422        entity.into_mutable().into_filtered()
2423    }
2424}
2425
2426impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static> {
2427    #[inline]
2428    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
2429        entity.as_mutable().into_filtered()
2430    }
2431}
2432
2433/// Inserts a dynamic [`Bundle`] into the entity.
2434///
2435/// # Safety
2436///
2437/// - [`OwningPtr`] and [`StorageType`] iterators must correspond to the
2438///   [`BundleInfo`](crate::bundle::BundleInfo) used to construct [`BundleInserter`]
2439/// - [`Entity`] must correspond to [`EntityLocation`]
2440unsafe fn insert_dynamic_bundle<
2441    'a,
2442    I: Iterator<Item = OwningPtr<'a>>,
2443    S: Iterator<Item = StorageType>,
2444>(
2445    mut bundle_inserter: BundleInserter<'_>,
2446    entity: Entity,
2447    location: EntityLocation,
2448    components: I,
2449    storage_types: S,
2450    mode: InsertMode,
2451    caller: MaybeLocation,
2452    relationship_hook_insert_mode: RelationshipHookMode,
2453) -> EntityLocation {
2454    struct DynamicInsertBundle<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> {
2455        components: I,
2456    }
2457
2458    impl<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> DynamicBundle
2459        for DynamicInsertBundle<'a, I>
2460    {
2461        type Effect = ();
2462        unsafe fn get_components(
2463            mut ptr: MovingPtr<'_, Self>,
2464            func: &mut impl FnMut(StorageType, OwningPtr<'_>),
2465        ) {
2466            (&mut ptr.components).for_each(|(t, ptr)| func(t, ptr));
2467        }
2468
2469        unsafe fn apply_effect(
2470            _ptr: MovingPtr<'_, MaybeUninit<Self>>,
2471            _entity: &mut EntityWorldMut,
2472        ) {
2473        }
2474    }
2475
2476    let bundle = DynamicInsertBundle {
2477        components: storage_types.zip(components),
2478    };
2479
2480    move_as_ptr!(bundle);
2481
2482    // SAFETY:
2483    // - `location` matches `entity`.  and thus must currently exist in the source
2484    //   archetype for this inserter and its location within the archetype.
2485    // - The caller must ensure that the iterators and storage types match up with the `BundleInserter`
2486    // - `DynamicInsertBundle::Effect: NoBundleEffect`
2487    // - `bundle` is not used or dropped after this point.
2488    unsafe {
2489        bundle_inserter.insert(
2490            entity,
2491            location,
2492            bundle,
2493            mode,
2494            caller,
2495            relationship_hook_insert_mode,
2496        )
2497    }
2498}