bevy_ecs/world/
entity_ref.rs

1use crate::{
2    archetype::{Archetype, ArchetypeId, Archetypes},
3    bundle::{Bundle, BundleId, BundleInfo, BundleInserter, DynamicBundle},
4    change_detection::MutUntyped,
5    component::{Component, ComponentId, ComponentTicks, Components, StorageType},
6    entity::{Entities, Entity, EntityLocation},
7    event::Event,
8    observer::{Observer, Observers},
9    query::Access,
10    removal_detection::RemovedComponentEvents,
11    storage::Storages,
12    system::IntoObserverSystem,
13    world::{DeferredWorld, Mut, World},
14};
15use bevy_ptr::{OwningPtr, Ptr};
16use std::{any::TypeId, marker::PhantomData};
17use thiserror::Error;
18
19use super::{unsafe_world_cell::UnsafeEntityCell, Ref, ON_REMOVE};
20
21/// A read-only reference to a particular [`Entity`] and all of its components.
22///
23/// # Examples
24///
25/// Read-only access disjoint with mutable access.
26///
27/// ```
28/// # use bevy_ecs::prelude::*;
29/// # #[derive(Component)] pub struct A;
30/// # #[derive(Component)] pub struct B;
31/// fn disjoint_system(
32///     query1: Query<&mut A>,
33///     query2: Query<EntityRef, Without<A>>,
34/// ) {
35///     // ...
36/// }
37/// # bevy_ecs::system::assert_is_system(disjoint_system);
38/// ```
39#[derive(Copy, Clone)]
40pub struct EntityRef<'w>(UnsafeEntityCell<'w>);
41
42impl<'w> EntityRef<'w> {
43    /// # Safety
44    /// - `cell` must have permission to read every component of the entity.
45    /// - No mutable accesses to any of the entity's components may exist
46    ///   at the same time as the returned [`EntityRef`].
47    #[inline]
48    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
49        Self(cell)
50    }
51
52    /// Returns the [ID](Entity) of the current entity.
53    #[inline]
54    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
55    pub fn id(&self) -> Entity {
56        self.0.id()
57    }
58
59    /// Gets metadata indicating the location where the current entity is stored.
60    #[inline]
61    pub fn location(&self) -> EntityLocation {
62        self.0.location()
63    }
64
65    /// Returns the archetype that the current entity belongs to.
66    #[inline]
67    pub fn archetype(&self) -> &Archetype {
68        self.0.archetype()
69    }
70
71    /// Returns `true` if the current entity has a component of type `T`.
72    /// Otherwise, this returns `false`.
73    ///
74    /// ## Notes
75    ///
76    /// If you do not know the concrete type of a component, consider using
77    /// [`Self::contains_id`] or [`Self::contains_type_id`].
78    #[inline]
79    pub fn contains<T: Component>(&self) -> bool {
80        self.contains_type_id(TypeId::of::<T>())
81    }
82
83    /// Returns `true` if the current entity has a component identified by `component_id`.
84    /// Otherwise, this returns false.
85    ///
86    /// ## Notes
87    ///
88    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
89    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
90    /// [`Self::contains_type_id`].
91    #[inline]
92    pub fn contains_id(&self, component_id: ComponentId) -> bool {
93        self.0.contains_id(component_id)
94    }
95
96    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
97    /// Otherwise, this returns false.
98    ///
99    /// ## Notes
100    ///
101    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
102    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
103    #[inline]
104    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
105        self.0.contains_type_id(type_id)
106    }
107
108    /// Gets access to the component of type `T` for the current entity.
109    /// Returns `None` if the entity does not have a component of type `T`.
110    #[inline]
111    pub fn get<T: Component>(&self) -> Option<&'w T> {
112        // SAFETY: We have read-only access to all components of this entity.
113        unsafe { self.0.get::<T>() }
114    }
115
116    /// Gets access to the component of type `T` for the current entity,
117    /// including change detection information as a [`Ref`].
118    ///
119    /// Returns `None` if the entity does not have a component of type `T`.
120    #[inline]
121    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
122        // SAFETY: We have read-only access to all components of this entity.
123        unsafe { self.0.get_ref::<T>() }
124    }
125
126    /// Retrieves the change ticks for the given component. This can be useful for implementing change
127    /// detection in custom runtimes.
128    #[inline]
129    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
130        // SAFETY: We have read-only access to all components of this entity.
131        unsafe { self.0.get_change_ticks::<T>() }
132    }
133
134    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
135    /// detection in custom runtimes.
136    ///
137    /// **You should prefer to use the typed API [`EntityRef::get_change_ticks`] where possible and only
138    /// use this in cases where the actual component types are not known at
139    /// compile time.**
140    #[inline]
141    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
142        // SAFETY: We have read-only access to all components of this entity.
143        unsafe { self.0.get_change_ticks_by_id(component_id) }
144    }
145
146    /// Gets the component of the given [`ComponentId`] from the entity.
147    ///
148    /// **You should prefer to use the typed API where possible and only
149    /// use this in cases where the actual component types are not known at
150    /// compile time.**
151    ///
152    /// Unlike [`EntityRef::get`], this returns a raw pointer to the component,
153    /// which is only valid while the `'w` borrow of the lifetime is active.
154    #[inline]
155    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
156        // SAFETY: We have read-only access to all components of this entity.
157        unsafe { self.0.get_by_id(component_id) }
158    }
159}
160
161impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w> {
162    fn from(entity_mut: EntityWorldMut<'w>) -> EntityRef<'w> {
163        // SAFETY:
164        // - `EntityWorldMut` guarantees exclusive access to the entire world.
165        unsafe { EntityRef::new(entity_mut.into_unsafe_entity_cell()) }
166    }
167}
168
169impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> {
170    fn from(value: &'a EntityWorldMut<'_>) -> Self {
171        // SAFETY:
172        // - `EntityWorldMut` guarantees exclusive access to the entire world.
173        // - `&value` ensures no mutable accesses are active.
174        unsafe { EntityRef::new(value.as_unsafe_entity_cell_readonly()) }
175    }
176}
177
178impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
179    fn from(value: EntityMut<'w>) -> Self {
180        // SAFETY:
181        // - `EntityMut` guarantees exclusive access to all of the entity's components.
182        unsafe { EntityRef::new(value.0) }
183    }
184}
185
186impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
187    fn from(value: &'a EntityMut<'_>) -> Self {
188        // SAFETY:
189        // - `EntityMut` guarantees exclusive access to all of the entity's components.
190        // - `&value` ensures there are no mutable accesses.
191        unsafe { EntityRef::new(value.0) }
192    }
193}
194
195impl<'a> TryFrom<FilteredEntityRef<'a>> for EntityRef<'a> {
196    type Error = TryFromFilteredError;
197
198    fn try_from(value: FilteredEntityRef<'a>) -> Result<Self, Self::Error> {
199        if !value.access.has_read_all() {
200            Err(TryFromFilteredError::MissingReadAllAccess)
201        } else {
202            // SAFETY: check above guarantees read-only access to all components of the entity.
203            Ok(unsafe { EntityRef::new(value.entity) })
204        }
205    }
206}
207
208impl<'a> TryFrom<&'a FilteredEntityRef<'_>> for EntityRef<'a> {
209    type Error = TryFromFilteredError;
210
211    fn try_from(value: &'a FilteredEntityRef<'_>) -> Result<Self, Self::Error> {
212        if !value.access.has_read_all() {
213            Err(TryFromFilteredError::MissingReadAllAccess)
214        } else {
215            // SAFETY: check above guarantees read-only access to all components of the entity.
216            Ok(unsafe { EntityRef::new(value.entity) })
217        }
218    }
219}
220
221impl<'a> TryFrom<FilteredEntityMut<'a>> for EntityRef<'a> {
222    type Error = TryFromFilteredError;
223
224    fn try_from(value: FilteredEntityMut<'a>) -> Result<Self, Self::Error> {
225        if !value.access.has_read_all() {
226            Err(TryFromFilteredError::MissingReadAllAccess)
227        } else {
228            // SAFETY: check above guarantees read-only access to all components of the entity.
229            Ok(unsafe { EntityRef::new(value.entity) })
230        }
231    }
232}
233
234impl<'a> TryFrom<&'a FilteredEntityMut<'_>> for EntityRef<'a> {
235    type Error = TryFromFilteredError;
236
237    fn try_from(value: &'a FilteredEntityMut<'_>) -> Result<Self, Self::Error> {
238        if !value.access.has_read_all() {
239            Err(TryFromFilteredError::MissingReadAllAccess)
240        } else {
241            // SAFETY: check above guarantees read-only access to all components of the entity.
242            Ok(unsafe { EntityRef::new(value.entity) })
243        }
244    }
245}
246
247/// Provides mutable access to a single entity and all of its components.
248///
249/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
250/// despawning the entity, and provides mutable access to the entire world.
251/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
252///
253/// # Examples
254///
255/// Disjoint mutable access.
256///
257/// ```
258/// # use bevy_ecs::prelude::*;
259/// # #[derive(Component)] pub struct A;
260/// fn disjoint_system(
261///     query1: Query<EntityMut, With<A>>,
262///     query2: Query<EntityMut, Without<A>>,
263/// ) {
264///     // ...
265/// }
266/// # bevy_ecs::system::assert_is_system(disjoint_system);
267/// ```
268pub struct EntityMut<'w>(UnsafeEntityCell<'w>);
269
270impl<'w> EntityMut<'w> {
271    /// # Safety
272    /// - `cell` must have permission to mutate every component of the entity.
273    /// - No accesses to any of the entity's components may exist
274    ///   at the same time as the returned [`EntityMut`].
275    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
276        Self(cell)
277    }
278
279    /// Returns a new instance with a shorter lifetime.
280    /// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
281    pub fn reborrow(&mut self) -> EntityMut<'_> {
282        // SAFETY: We have exclusive access to the entire entity and its components.
283        unsafe { Self::new(self.0) }
284    }
285
286    /// Gets read-only access to all of the entity's components.
287    pub fn as_readonly(&self) -> EntityRef<'_> {
288        EntityRef::from(self)
289    }
290
291    /// Returns the [ID](Entity) of the current entity.
292    #[inline]
293    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
294    pub fn id(&self) -> Entity {
295        self.0.id()
296    }
297
298    /// Gets metadata indicating the location where the current entity is stored.
299    #[inline]
300    pub fn location(&self) -> EntityLocation {
301        self.0.location()
302    }
303
304    /// Returns the archetype that the current entity belongs to.
305    #[inline]
306    pub fn archetype(&self) -> &Archetype {
307        self.0.archetype()
308    }
309
310    /// Returns `true` if the current entity has a component of type `T`.
311    /// Otherwise, this returns `false`.
312    ///
313    /// ## Notes
314    ///
315    /// If you do not know the concrete type of a component, consider using
316    /// [`Self::contains_id`] or [`Self::contains_type_id`].
317    #[inline]
318    pub fn contains<T: Component>(&self) -> bool {
319        self.contains_type_id(TypeId::of::<T>())
320    }
321
322    /// Returns `true` if the current entity has a component identified by `component_id`.
323    /// Otherwise, this returns false.
324    ///
325    /// ## Notes
326    ///
327    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
328    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
329    /// [`Self::contains_type_id`].
330    #[inline]
331    pub fn contains_id(&self, component_id: ComponentId) -> bool {
332        self.0.contains_id(component_id)
333    }
334
335    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
336    /// Otherwise, this returns false.
337    ///
338    /// ## Notes
339    ///
340    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
341    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
342    #[inline]
343    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
344        self.0.contains_type_id(type_id)
345    }
346
347    /// Gets access to the component of type `T` for the current entity.
348    /// Returns `None` if the entity does not have a component of type `T`.
349    #[inline]
350    pub fn get<T: Component>(&self) -> Option<&'_ T> {
351        self.as_readonly().get()
352    }
353
354    /// Consumes `self` and gets access to the component of type `T` with the
355    /// world `'w` lifetime for the current entity.
356    ///
357    /// Returns `None` if the entity does not have a component of type `T`.
358    #[inline]
359    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
360        // SAFETY: consuming `self` implies exclusive access
361        unsafe { self.0.get() }
362    }
363
364    /// Gets access to the component of type `T` for the current entity,
365    /// including change detection information as a [`Ref`].
366    ///
367    /// Returns `None` if the entity does not have a component of type `T`.
368    #[inline]
369    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
370        self.as_readonly().get_ref()
371    }
372
373    /// Consumes `self` and gets access to the component of type `T` with world
374    /// `'w` lifetime for the current entity, including change detection information
375    /// as a [`Ref<'w>`].
376    ///
377    /// Returns `None` if the entity does not have a component of type `T`.
378    #[inline]
379    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
380        // SAFETY: consuming `self` implies exclusive access
381        unsafe { self.0.get_ref() }
382    }
383
384    /// Gets mutable access to the component of type `T` for the current entity.
385    /// Returns `None` if the entity does not have a component of type `T`.
386    #[inline]
387    pub fn get_mut<T: Component>(&mut self) -> Option<Mut<'_, T>> {
388        // SAFETY: &mut self implies exclusive access for duration of returned value
389        unsafe { self.0.get_mut() }
390    }
391
392    /// Consumes self and gets mutable access to the component of type `T`
393    /// with the world `'w` lifetime for the current entity.
394    /// Returns `None` if the entity does not have a component of type `T`.
395    #[inline]
396    pub fn into_mut<T: Component>(self) -> Option<Mut<'w, T>> {
397        // SAFETY: consuming `self` implies exclusive access
398        unsafe { self.0.get_mut() }
399    }
400
401    /// Retrieves the change ticks for the given component. This can be useful for implementing change
402    /// detection in custom runtimes.
403    #[inline]
404    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
405        self.as_readonly().get_change_ticks::<T>()
406    }
407
408    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
409    /// detection in custom runtimes.
410    ///
411    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
412    /// use this in cases where the actual component types are not known at
413    /// compile time.**
414    #[inline]
415    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
416        self.as_readonly().get_change_ticks_by_id(component_id)
417    }
418
419    /// Gets the component of the given [`ComponentId`] from the entity.
420    ///
421    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where possible and only
422    /// use this in cases where the actual component types are not known at
423    /// compile time.**
424    ///
425    /// Unlike [`EntityMut::get`], this returns a raw pointer to the component,
426    /// which is only valid while the [`EntityMut`] is alive.
427    #[inline]
428    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
429        self.as_readonly().get_by_id(component_id)
430    }
431
432    /// Consumes `self` and gets the component of the given [`ComponentId`] with
433    /// world `'w` lifetime from the entity.
434    ///
435    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`] where possible and only
436    /// use this in cases where the actual component types are not known at
437    /// compile time.**
438    #[inline]
439    pub fn into_borrow_by_id(self, component_id: ComponentId) -> Option<Ptr<'w>> {
440        // SAFETY:
441        // consuming `self` ensures that no references exist to this entity's components.
442        unsafe { self.0.get_by_id(component_id) }
443    }
444
445    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
446    ///
447    /// **You should prefer to use the typed API [`EntityMut::get_mut`] where possible and only
448    /// use this in cases where the actual component types are not known at
449    /// compile time.**
450    ///
451    /// Unlike [`EntityMut::get_mut`], this returns a raw pointer to the component,
452    /// which is only valid while the [`EntityMut`] is alive.
453    #[inline]
454    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
455        // SAFETY:
456        // - `&mut self` ensures that no references exist to this entity's components.
457        // - `as_unsafe_world_cell` gives mutable permission for all components on this entity
458        unsafe { self.0.get_mut_by_id(component_id) }
459    }
460
461    /// Consumes `self` and gets a [`MutUntyped<'w>`] of the component of the given [`ComponentId`]
462    /// with world `'w` lifetime from the entity.
463    ///
464    /// **You should prefer to use the typed API [`EntityMut::into_mut`] where possible and only
465    /// use this in cases where the actual component types are not known at
466    /// compile time.**
467    #[inline]
468    pub fn into_mut_by_id(self, component_id: ComponentId) -> Option<MutUntyped<'w>> {
469        // SAFETY:
470        // consuming `self` ensures that no references exist to this entity's components.
471        unsafe { self.0.get_mut_by_id(component_id) }
472    }
473}
474
475impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
476    fn from(value: &'w mut EntityMut<'_>) -> Self {
477        value.reborrow()
478    }
479}
480
481impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w> {
482    fn from(value: EntityWorldMut<'w>) -> Self {
483        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
484        unsafe { EntityMut::new(value.into_unsafe_entity_cell()) }
485    }
486}
487
488impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a> {
489    fn from(value: &'a mut EntityWorldMut<'_>) -> Self {
490        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
491        unsafe { EntityMut::new(value.as_unsafe_entity_cell()) }
492    }
493}
494
495impl<'a> TryFrom<FilteredEntityMut<'a>> for EntityMut<'a> {
496    type Error = TryFromFilteredError;
497
498    fn try_from(value: FilteredEntityMut<'a>) -> Result<Self, Self::Error> {
499        if !value.access.has_read_all() {
500            Err(TryFromFilteredError::MissingReadAllAccess)
501        } else if !value.access.has_write_all() {
502            Err(TryFromFilteredError::MissingWriteAllAccess)
503        } else {
504            // SAFETY: check above guarantees exclusive access to all components of the entity.
505            Ok(unsafe { EntityMut::new(value.entity) })
506        }
507    }
508}
509
510impl<'a> TryFrom<&'a mut FilteredEntityMut<'_>> for EntityMut<'a> {
511    type Error = TryFromFilteredError;
512
513    fn try_from(value: &'a mut FilteredEntityMut<'_>) -> Result<Self, Self::Error> {
514        if !value.access.has_read_all() {
515            Err(TryFromFilteredError::MissingReadAllAccess)
516        } else if !value.access.has_write_all() {
517            Err(TryFromFilteredError::MissingWriteAllAccess)
518        } else {
519            // SAFETY: check above guarantees exclusive access to all components of the entity.
520            Ok(unsafe { EntityMut::new(value.entity) })
521        }
522    }
523}
524
525/// A mutable reference to a particular [`Entity`], and the entire world.
526/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
527/// which caches the [`EntityLocation`] to reduce duplicate lookups.
528///
529/// Since this type provides mutable access to the entire world, only one
530/// [`EntityWorldMut`] can exist at a time for a given world.
531///
532/// See also [`EntityMut`], which allows disjoint mutable access to multiple
533/// entities at once.  Unlike `EntityMut`, this type allows adding and
534/// removing components, and despawning the entity.
535pub struct EntityWorldMut<'w> {
536    world: &'w mut World,
537    entity: Entity,
538    location: EntityLocation,
539}
540
541impl<'w> EntityWorldMut<'w> {
542    fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
543        UnsafeEntityCell::new(
544            self.world.as_unsafe_world_cell_readonly(),
545            self.entity,
546            self.location,
547        )
548    }
549    fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
550        UnsafeEntityCell::new(
551            self.world.as_unsafe_world_cell(),
552            self.entity,
553            self.location,
554        )
555    }
556    fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
557        UnsafeEntityCell::new(
558            self.world.as_unsafe_world_cell(),
559            self.entity,
560            self.location,
561        )
562    }
563
564    /// # Safety
565    ///
566    ///  - `entity` must be valid for `world`: the generation should match that of the entity at the same index.
567    ///  - `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`
568    ///
569    ///  The above is trivially satisfied if `location` was sourced from `world.entities().get(entity)`.
570    #[inline]
571    pub(crate) unsafe fn new(
572        world: &'w mut World,
573        entity: Entity,
574        location: EntityLocation,
575    ) -> Self {
576        debug_assert!(world.entities().contains(entity));
577        debug_assert_eq!(world.entities().get(entity), Some(location));
578
579        EntityWorldMut {
580            world,
581            entity,
582            location,
583        }
584    }
585
586    /// Returns the [ID](Entity) of the current entity.
587    #[inline]
588    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
589    pub fn id(&self) -> Entity {
590        self.entity
591    }
592
593    /// Gets metadata indicating the location where the current entity is stored.
594    #[inline]
595    pub fn location(&self) -> EntityLocation {
596        self.location
597    }
598
599    /// Returns the archetype that the current entity belongs to.
600    #[inline]
601    pub fn archetype(&self) -> &Archetype {
602        &self.world.archetypes[self.location.archetype_id]
603    }
604
605    /// Returns `true` if the current entity has a component of type `T`.
606    /// Otherwise, this returns `false`.
607    ///
608    /// ## Notes
609    ///
610    /// If you do not know the concrete type of a component, consider using
611    /// [`Self::contains_id`] or [`Self::contains_type_id`].
612    #[inline]
613    pub fn contains<T: Component>(&self) -> bool {
614        self.contains_type_id(TypeId::of::<T>())
615    }
616
617    /// Returns `true` if the current entity has a component identified by `component_id`.
618    /// Otherwise, this returns false.
619    ///
620    /// ## Notes
621    ///
622    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
623    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
624    /// [`Self::contains_type_id`].
625    #[inline]
626    pub fn contains_id(&self, component_id: ComponentId) -> bool {
627        self.as_unsafe_entity_cell_readonly()
628            .contains_id(component_id)
629    }
630
631    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
632    /// Otherwise, this returns false.
633    ///
634    /// ## Notes
635    ///
636    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
637    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
638    #[inline]
639    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
640        self.as_unsafe_entity_cell_readonly()
641            .contains_type_id(type_id)
642    }
643
644    /// Gets access to the component of type `T` for the current entity.
645    /// Returns `None` if the entity does not have a component of type `T`.
646    #[inline]
647    pub fn get<T: Component>(&self) -> Option<&'_ T> {
648        EntityRef::from(self).get()
649    }
650
651    /// Consumes `self` and gets access to the component of type `T` with
652    /// the world `'w` lifetime for the current entity.
653    /// Returns `None` if the entity does not have a component of type `T`.
654    #[inline]
655    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
656        // SAFETY: consuming `self` implies exclusive access
657        unsafe { self.into_unsafe_entity_cell().get() }
658    }
659
660    /// Gets access to the component of type `T` for the current entity,
661    /// including change detection information as a [`Ref`].
662    ///
663    /// Returns `None` if the entity does not have a component of type `T`.
664    #[inline]
665    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
666        EntityRef::from(self).get_ref()
667    }
668
669    /// Consumes `self` and gets access to the component of type `T`
670    /// with the world `'w` lifetime for the current entity,
671    /// including change detection information as a [`Ref`].
672    ///
673    /// Returns `None` if the entity does not have a component of type `T`.
674    #[inline]
675    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
676        EntityRef::from(self).get_ref()
677    }
678
679    /// Gets mutable access to the component of type `T` for the current entity.
680    /// Returns `None` if the entity does not have a component of type `T`.
681    #[inline]
682    pub fn get_mut<T: Component>(&mut self) -> Option<Mut<'_, T>> {
683        // SAFETY: &mut self implies exclusive access for duration of returned value
684        unsafe { self.as_unsafe_entity_cell().get_mut() }
685    }
686
687    /// Consumes `self` and gets mutable access to the component of type `T`
688    /// with the world `'w` lifetime for the current entity.
689    /// Returns `None` if the entity does not have a component of type `T`.
690    #[inline]
691    pub fn into_mut<T: Component>(self) -> Option<Mut<'w, T>> {
692        // SAFETY: consuming `self` implies exclusive access
693        unsafe { self.into_unsafe_entity_cell().get_mut() }
694    }
695
696    /// Retrieves the change ticks for the given component. This can be useful for implementing change
697    /// detection in custom runtimes.
698    #[inline]
699    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
700        EntityRef::from(self).get_change_ticks::<T>()
701    }
702
703    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
704    /// detection in custom runtimes.
705    ///
706    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
707    /// use this in cases where the actual component types are not known at
708    /// compile time.**
709    #[inline]
710    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
711        EntityRef::from(self).get_change_ticks_by_id(component_id)
712    }
713
714    /// Gets the component of the given [`ComponentId`] from the entity.
715    ///
716    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where possible and only
717    /// use this in cases where the actual component types are not known at
718    /// compile time.**
719    ///
720    /// Unlike [`EntityWorldMut::get`], this returns a raw pointer to the component,
721    /// which is only valid while the [`EntityWorldMut`] is alive.
722    #[inline]
723    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
724        EntityRef::from(self).get_by_id(component_id)
725    }
726
727    /// Consumes `self` and gets the component of the given [`ComponentId`] with
728    /// with world `'w` lifetime from the entity.
729    ///
730    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`] where
731    /// possible and only use this in cases where the actual component types are not
732    /// known at compile time.**
733    #[inline]
734    pub fn into_borrow_by_id(self, component_id: ComponentId) -> Option<Ptr<'w>> {
735        // SAFETY: consuming `self` implies exclusive access
736        unsafe { self.into_unsafe_entity_cell().get_by_id(component_id) }
737    }
738
739    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
740    ///
741    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where possible and only
742    /// use this in cases where the actual component types are not known at
743    /// compile time.**
744    ///
745    /// Unlike [`EntityWorldMut::get_mut`], this returns a raw pointer to the component,
746    /// which is only valid while the [`EntityWorldMut`] is alive.
747    #[inline]
748    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
749        // SAFETY:
750        // - `&mut self` ensures that no references exist to this entity's components.
751        // - `as_unsafe_world_cell` gives mutable permission for all components on this entity
752        unsafe { self.as_unsafe_entity_cell().get_mut_by_id(component_id) }
753    }
754
755    /// Consumes `self` and gets a [`MutUntyped<'w>`] of the component with the world `'w` lifetime
756    /// of the given [`ComponentId`] from the entity.
757    ///
758    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where possible and only
759    /// use this in cases where the actual component types are not known at
760    /// compile time.**
761    #[inline]
762    pub fn into_mut_by_id(self, component_id: ComponentId) -> Option<MutUntyped<'w>> {
763        // SAFETY:
764        // consuming `self` ensures that no references exist to this entity's components.
765        unsafe { self.into_unsafe_entity_cell().get_mut_by_id(component_id) }
766    }
767
768    /// Adds a [`Bundle`] of components to the entity.
769    ///
770    /// This will overwrite any previous value(s) of the same component type.
771    pub fn insert<T: Bundle>(&mut self, bundle: T) -> &mut Self {
772        let change_tick = self.world.change_tick();
773        let mut bundle_inserter =
774            BundleInserter::new::<T>(self.world, self.location.archetype_id, change_tick);
775        // SAFETY: location matches current entity. `T` matches `bundle_info`
776        self.location = unsafe { bundle_inserter.insert(self.entity, self.location, bundle) };
777        self
778    }
779
780    /// Inserts a dynamic [`Component`] into the entity.
781    ///
782    /// This will overwrite any previous value(s) of the same component type.
783    ///
784    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
785    ///
786    /// # Safety
787    ///
788    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
789    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
790    pub unsafe fn insert_by_id(
791        &mut self,
792        component_id: ComponentId,
793        component: OwningPtr<'_>,
794    ) -> &mut Self {
795        let change_tick = self.world.change_tick();
796        let bundle_id = self
797            .world
798            .bundles
799            .init_component_info(&self.world.components, component_id);
800        let storage_type = self.world.bundles.get_storage_unchecked(bundle_id);
801
802        let bundle_inserter = BundleInserter::new_with_id(
803            self.world,
804            self.location.archetype_id,
805            bundle_id,
806            change_tick,
807        );
808
809        self.location = insert_dynamic_bundle(
810            bundle_inserter,
811            self.entity,
812            self.location,
813            Some(component).into_iter(),
814            Some(storage_type).iter().cloned(),
815        );
816        self
817    }
818
819    /// Inserts a dynamic [`Bundle`] into the entity.
820    ///
821    /// This will overwrite any previous value(s) of the same component type.
822    ///
823    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
824    /// If your [`Bundle`] only has one component, use the cached API [`EntityWorldMut::insert_by_id`].
825    ///
826    /// If possible, pass a sorted slice of `ComponentId` to maximize caching potential.
827    ///
828    /// # Safety
829    /// - Each [`ComponentId`] must be from the same world as [`EntityWorldMut`]
830    /// - Each [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
831    pub unsafe fn insert_by_ids<'a, I: Iterator<Item = OwningPtr<'a>>>(
832        &mut self,
833        component_ids: &[ComponentId],
834        iter_components: I,
835    ) -> &mut Self {
836        let change_tick = self.world.change_tick();
837        let bundle_id = self
838            .world
839            .bundles
840            .init_dynamic_info(&self.world.components, component_ids);
841        let mut storage_types =
842            std::mem::take(self.world.bundles.get_storages_unchecked(bundle_id));
843        let bundle_inserter = BundleInserter::new_with_id(
844            self.world,
845            self.location.archetype_id,
846            bundle_id,
847            change_tick,
848        );
849
850        self.location = insert_dynamic_bundle(
851            bundle_inserter,
852            self.entity,
853            self.location,
854            iter_components,
855            (*storage_types).iter().cloned(),
856        );
857        *self.world.bundles.get_storages_unchecked(bundle_id) = std::mem::take(&mut storage_types);
858        self
859    }
860
861    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
862    ///
863    /// **Note:** If the entity does not have every component in the bundle, this method will not
864    /// remove any of them.
865    // TODO: BundleRemover?
866    #[must_use]
867    pub fn take<T: Bundle>(&mut self) -> Option<T> {
868        let world = &mut self.world;
869        let storages = &mut world.storages;
870        let components = &mut world.components;
871        let bundle_id = world.bundles.init_info::<T>(components, storages);
872        // SAFETY: We just ensured this bundle exists
873        let bundle_info = unsafe { world.bundles.get_unchecked(bundle_id) };
874        let old_location = self.location;
875        // SAFETY: `archetype_id` exists because it is referenced in the old `EntityLocation` which is valid,
876        // components exist in `bundle_info` because `Bundles::init_info` initializes a `BundleInfo` containing all components of the bundle type `T`
877        let new_archetype_id = unsafe {
878            remove_bundle_from_archetype(
879                &mut world.archetypes,
880                storages,
881                components,
882                &world.observers,
883                old_location.archetype_id,
884                bundle_info,
885                false,
886            )?
887        };
888
889        if new_archetype_id == old_location.archetype_id {
890            return None;
891        }
892
893        let entity = self.entity;
894        // SAFETY: Archetypes and Bundles cannot be mutably aliased through DeferredWorld
895        let (old_archetype, bundle_info, mut deferred_world) = unsafe {
896            let bundle_info: *const BundleInfo = bundle_info;
897            let world = world.as_unsafe_world_cell();
898            (
899                &world.archetypes()[old_location.archetype_id],
900                &*bundle_info,
901                world.into_deferred(),
902            )
903        };
904
905        // SAFETY: all bundle components exist in World
906        unsafe {
907            trigger_on_remove_hooks_and_observers(
908                &mut deferred_world,
909                old_archetype,
910                entity,
911                bundle_info,
912            );
913        }
914
915        let archetypes = &mut world.archetypes;
916        let storages = &mut world.storages;
917        let components = &mut world.components;
918        let entities = &mut world.entities;
919        let removed_components = &mut world.removed_components;
920
921        let entity = self.entity;
922        let mut bundle_components = bundle_info.iter_components();
923        // SAFETY: bundle components are iterated in order, which guarantees that the component type
924        // matches
925        let result = unsafe {
926            T::from_components(storages, &mut |storages| {
927                let component_id = bundle_components.next().unwrap();
928                // SAFETY:
929                // - entity location is valid
930                // - table row is removed below, without dropping the contents
931                // - `components` comes from the same world as `storages`
932                take_component(
933                    storages,
934                    components,
935                    removed_components,
936                    component_id,
937                    entity,
938                    old_location,
939                )
940            })
941        };
942
943        #[allow(clippy::undocumented_unsafe_blocks)] // TODO: document why this is safe
944        unsafe {
945            Self::move_entity_from_remove::<false>(
946                entity,
947                &mut self.location,
948                old_location.archetype_id,
949                old_location,
950                entities,
951                archetypes,
952                storages,
953                new_archetype_id,
954            );
955        }
956        Some(result)
957    }
958
959    /// # Safety
960    ///
961    /// `new_archetype_id` must have the same or a subset of the components
962    /// in `old_archetype_id`. Probably more safety stuff too, audit a call to
963    /// this fn as if the code here was written inline
964    ///
965    /// when DROP is true removed components will be dropped otherwise they will be forgotten
966    ///
967    // We use a const generic here so that we are less reliant on
968    // inlining for rustc to optimize out the `match DROP`
969    #[allow(clippy::too_many_arguments)]
970    unsafe fn move_entity_from_remove<const DROP: bool>(
971        entity: Entity,
972        self_location: &mut EntityLocation,
973        old_archetype_id: ArchetypeId,
974        old_location: EntityLocation,
975        entities: &mut Entities,
976        archetypes: &mut Archetypes,
977        storages: &mut Storages,
978        new_archetype_id: ArchetypeId,
979    ) {
980        let old_archetype = &mut archetypes[old_archetype_id];
981        let remove_result = old_archetype.swap_remove(old_location.archetype_row);
982        // if an entity was moved into this entity's archetype row, update its archetype row
983        if let Some(swapped_entity) = remove_result.swapped_entity {
984            let swapped_location = entities.get(swapped_entity).unwrap();
985
986            entities.set(
987                swapped_entity.index(),
988                EntityLocation {
989                    archetype_id: swapped_location.archetype_id,
990                    archetype_row: old_location.archetype_row,
991                    table_id: swapped_location.table_id,
992                    table_row: swapped_location.table_row,
993                },
994            );
995        }
996        let old_table_row = remove_result.table_row;
997        let old_table_id = old_archetype.table_id();
998        let new_archetype = &mut archetypes[new_archetype_id];
999
1000        let new_location = if old_table_id == new_archetype.table_id() {
1001            new_archetype.allocate(entity, old_table_row)
1002        } else {
1003            let (old_table, new_table) = storages
1004                .tables
1005                .get_2_mut(old_table_id, new_archetype.table_id());
1006
1007            let move_result = if DROP {
1008                // SAFETY: old_table_row exists
1009                unsafe { old_table.move_to_and_drop_missing_unchecked(old_table_row, new_table) }
1010            } else {
1011                // SAFETY: old_table_row exists
1012                unsafe { old_table.move_to_and_forget_missing_unchecked(old_table_row, new_table) }
1013            };
1014
1015            // SAFETY: move_result.new_row is a valid position in new_archetype's table
1016            let new_location = unsafe { new_archetype.allocate(entity, move_result.new_row) };
1017
1018            // if an entity was moved into this entity's table row, update its table row
1019            if let Some(swapped_entity) = move_result.swapped_entity {
1020                let swapped_location = entities.get(swapped_entity).unwrap();
1021
1022                entities.set(
1023                    swapped_entity.index(),
1024                    EntityLocation {
1025                        archetype_id: swapped_location.archetype_id,
1026                        archetype_row: swapped_location.archetype_row,
1027                        table_id: swapped_location.table_id,
1028                        table_row: old_location.table_row,
1029                    },
1030                );
1031                archetypes[swapped_location.archetype_id]
1032                    .set_entity_table_row(swapped_location.archetype_row, old_table_row);
1033            }
1034
1035            new_location
1036        };
1037
1038        *self_location = new_location;
1039        // SAFETY: The entity is valid and has been moved to the new location already.
1040        unsafe {
1041            entities.set(entity.index(), new_location);
1042        }
1043    }
1044
1045    /// Remove the components of `bundle` from `entity`.
1046    ///
1047    /// SAFETY:
1048    /// - A `BundleInfo` with the corresponding `BundleId` must have been initialized.
1049    #[allow(clippy::too_many_arguments)]
1050    unsafe fn remove_bundle(&mut self, bundle: BundleId) -> EntityLocation {
1051        let entity = self.entity;
1052        let world = &mut self.world;
1053        let location = self.location;
1054        // SAFETY: the caller guarantees that the BundleInfo for this id has been initialized.
1055        let bundle_info = world.bundles.get_unchecked(bundle);
1056
1057        // SAFETY: `archetype_id` exists because it is referenced in `location` which is valid
1058        // and components in `bundle_info` must exist due to this function's safety invariants.
1059        let new_archetype_id = remove_bundle_from_archetype(
1060            &mut world.archetypes,
1061            &mut world.storages,
1062            &world.components,
1063            &world.observers,
1064            location.archetype_id,
1065            bundle_info,
1066            // components from the bundle that are not present on the entity are ignored
1067            true,
1068        )
1069        .expect("intersections should always return a result");
1070
1071        if new_archetype_id == location.archetype_id {
1072            return location;
1073        }
1074
1075        // SAFETY: Archetypes and Bundles cannot be mutably aliased through DeferredWorld
1076        let (old_archetype, bundle_info, mut deferred_world) = unsafe {
1077            let bundle_info: *const BundleInfo = bundle_info;
1078            let world = world.as_unsafe_world_cell();
1079            (
1080                &world.archetypes()[location.archetype_id],
1081                &*bundle_info,
1082                world.into_deferred(),
1083            )
1084        };
1085
1086        // SAFETY: all bundle components exist in World
1087        unsafe {
1088            trigger_on_remove_hooks_and_observers(
1089                &mut deferred_world,
1090                old_archetype,
1091                entity,
1092                bundle_info,
1093            );
1094        }
1095
1096        let old_archetype = &world.archetypes[location.archetype_id];
1097        for component_id in bundle_info.iter_components() {
1098            if old_archetype.contains(component_id) {
1099                world.removed_components.send(component_id, entity);
1100
1101                // Make sure to drop components stored in sparse sets.
1102                // Dense components are dropped later in `move_to_and_drop_missing_unchecked`.
1103                if let Some(StorageType::SparseSet) = old_archetype.get_storage_type(component_id) {
1104                    world
1105                        .storages
1106                        .sparse_sets
1107                        .get_mut(component_id)
1108                        .unwrap()
1109                        .remove(entity);
1110                }
1111            }
1112        }
1113
1114        // SAFETY: `new_archetype_id` is a subset of the components in `old_location.archetype_id`
1115        // because it is created by removing a bundle from these components.
1116        let mut new_location = location;
1117        Self::move_entity_from_remove::<true>(
1118            entity,
1119            &mut new_location,
1120            location.archetype_id,
1121            location,
1122            &mut world.entities,
1123            &mut world.archetypes,
1124            &mut world.storages,
1125            new_archetype_id,
1126        );
1127
1128        new_location
1129    }
1130
1131    /// Removes any components in the [`Bundle`] from the entity.
1132    ///
1133    /// See [`EntityCommands::remove`](crate::system::EntityCommands::remove) for more details.
1134    // TODO: BundleRemover?
1135    pub fn remove<T: Bundle>(&mut self) -> &mut Self {
1136        let storages = &mut self.world.storages;
1137        let components = &mut self.world.components;
1138        let bundle_info = self.world.bundles.init_info::<T>(components, storages);
1139
1140        // SAFETY: the `BundleInfo` is initialized above
1141        self.location = unsafe { self.remove_bundle(bundle_info) };
1142
1143        self
1144    }
1145
1146    /// Removes any components except those in the [`Bundle`] from the entity.
1147    ///
1148    /// See [`EntityCommands::retain`](crate::system::EntityCommands::retain) for more details.
1149    pub fn retain<T: Bundle>(&mut self) -> &mut Self {
1150        let archetypes = &mut self.world.archetypes;
1151        let storages = &mut self.world.storages;
1152        let components = &mut self.world.components;
1153
1154        let retained_bundle = self.world.bundles.init_info::<T>(components, storages);
1155        // SAFETY: `retained_bundle` exists as we just initialized it.
1156        let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) };
1157        let old_location = self.location;
1158        let old_archetype = &mut archetypes[old_location.archetype_id];
1159
1160        let to_remove = &old_archetype
1161            .components()
1162            .filter(|c| !retained_bundle_info.components().contains(c))
1163            .collect::<Vec<_>>();
1164        let remove_bundle = self.world.bundles.init_dynamic_info(components, to_remove);
1165
1166        // SAFETY: the `BundleInfo` for the components to remove is initialized above
1167        self.location = unsafe { self.remove_bundle(remove_bundle) };
1168        self
1169    }
1170
1171    /// Removes a dynamic [`Component`] from the entity if it exists.
1172    ///
1173    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
1174    ///
1175    /// # Panics
1176    ///
1177    /// Panics if the provided [`ComponentId`] does not exist in the [`World`].
1178    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1179        let components = &mut self.world.components;
1180
1181        let bundle_id = self
1182            .world
1183            .bundles
1184            .init_component_info(components, component_id);
1185
1186        // SAFETY: the `BundleInfo` for this `component_id` is initialized above
1187        self.location = unsafe { self.remove_bundle(bundle_id) };
1188
1189        self
1190    }
1191
1192    /// Removes all components associated with the entity.
1193    pub fn clear(&mut self) -> &mut Self {
1194        let component_ids: Vec<ComponentId> = self.archetype().components().collect();
1195        let components = &mut self.world.components;
1196
1197        let bundle_id = self
1198            .world
1199            .bundles
1200            .init_dynamic_info(components, component_ids.as_slice());
1201
1202        // SAFETY: the `BundleInfo` for this `component_id` is initialized above
1203        self.location = unsafe { self.remove_bundle(bundle_id) };
1204
1205        self
1206    }
1207
1208    /// Despawns the current entity.
1209    ///
1210    /// See [`World::despawn`] for more details.
1211    pub fn despawn(self) {
1212        let world = self.world;
1213        world.flush_entities();
1214        let archetype = &world.archetypes[self.location.archetype_id];
1215
1216        // SAFETY: Archetype cannot be mutably aliased by DeferredWorld
1217        let (archetype, mut deferred_world) = unsafe {
1218            let archetype: *const Archetype = archetype;
1219            let world = world.as_unsafe_world_cell();
1220            (&*archetype, world.into_deferred())
1221        };
1222
1223        // SAFETY: All components in the archetype exist in world
1224        unsafe {
1225            deferred_world.trigger_on_remove(archetype, self.entity, archetype.components());
1226            if archetype.has_remove_observer() {
1227                deferred_world.trigger_observers(ON_REMOVE, self.entity, archetype.components());
1228            }
1229        }
1230
1231        for component_id in archetype.components() {
1232            world.removed_components.send(component_id, self.entity);
1233        }
1234
1235        let location = world
1236            .entities
1237            .free(self.entity)
1238            .expect("entity should exist at this point.");
1239        let table_row;
1240        let moved_entity;
1241
1242        {
1243            let archetype = &mut world.archetypes[self.location.archetype_id];
1244            let remove_result = archetype.swap_remove(location.archetype_row);
1245            if let Some(swapped_entity) = remove_result.swapped_entity {
1246                let swapped_location = world.entities.get(swapped_entity).unwrap();
1247                // SAFETY: swapped_entity is valid and the swapped entity's components are
1248                // moved to the new location immediately after.
1249                unsafe {
1250                    world.entities.set(
1251                        swapped_entity.index(),
1252                        EntityLocation {
1253                            archetype_id: swapped_location.archetype_id,
1254                            archetype_row: location.archetype_row,
1255                            table_id: swapped_location.table_id,
1256                            table_row: swapped_location.table_row,
1257                        },
1258                    );
1259                }
1260            }
1261            table_row = remove_result.table_row;
1262
1263            for component_id in archetype.sparse_set_components() {
1264                let sparse_set = world.storages.sparse_sets.get_mut(component_id).unwrap();
1265                sparse_set.remove(self.entity);
1266            }
1267            // SAFETY: table rows stored in archetypes always exist
1268            moved_entity = unsafe {
1269                world.storages.tables[archetype.table_id()].swap_remove_unchecked(table_row)
1270            };
1271        };
1272
1273        if let Some(moved_entity) = moved_entity {
1274            let moved_location = world.entities.get(moved_entity).unwrap();
1275            // SAFETY: `moved_entity` is valid and the provided `EntityLocation` accurately reflects
1276            //         the current location of the entity and its component data.
1277            unsafe {
1278                world.entities.set(
1279                    moved_entity.index(),
1280                    EntityLocation {
1281                        archetype_id: moved_location.archetype_id,
1282                        archetype_row: moved_location.archetype_row,
1283                        table_id: moved_location.table_id,
1284                        table_row,
1285                    },
1286                );
1287            }
1288            world.archetypes[moved_location.archetype_id]
1289                .set_entity_table_row(moved_location.archetype_row, table_row);
1290        }
1291        world.flush();
1292    }
1293
1294    /// Ensures any commands triggered by the actions of Self are applied, equivalent to [`World::flush`]
1295    pub fn flush(self) -> Entity {
1296        self.world.flush();
1297        self.entity
1298    }
1299
1300    /// Gets read-only access to the world that the current entity belongs to.
1301    #[inline]
1302    pub fn world(&self) -> &World {
1303        self.world
1304    }
1305
1306    /// Returns this entity's world.
1307    ///
1308    /// See [`EntityWorldMut::world_scope`] or [`EntityWorldMut::into_world_mut`] for a safe alternative.
1309    ///
1310    /// # Safety
1311    /// Caller must not modify the world in a way that changes the current entity's location
1312    /// If the caller _does_ do something that could change the location, `self.update_location()`
1313    /// must be called before using any other methods on this [`EntityWorldMut`].
1314    #[inline]
1315    pub unsafe fn world_mut(&mut self) -> &mut World {
1316        self.world
1317    }
1318
1319    /// Returns this entity's [`World`], consuming itself.
1320    #[inline]
1321    pub fn into_world_mut(self) -> &'w mut World {
1322        self.world
1323    }
1324
1325    /// Gives mutable access to this entity's [`World`] in a temporary scope.
1326    /// This is a safe alternative to using [`EntityWorldMut::world_mut`].
1327    ///
1328    /// # Examples
1329    ///
1330    /// ```
1331    /// # use bevy_ecs::prelude::*;
1332    /// #[derive(Resource, Default, Clone, Copy)]
1333    /// struct R(u32);
1334    ///
1335    /// # let mut world = World::new();
1336    /// # world.init_resource::<R>();
1337    /// # let mut entity = world.spawn_empty();
1338    /// // This closure gives us temporary access to the world.
1339    /// let new_r = entity.world_scope(|world: &mut World| {
1340    ///     // Mutate the world while we have access to it.
1341    ///     let mut r = world.resource_mut::<R>();
1342    ///     r.0 += 1;
1343    ///
1344    ///     // Return a value from the world before giving it back to the `EntityWorldMut`.
1345    ///     *r
1346    /// });
1347    /// # assert_eq!(new_r.0, 1);
1348    /// ```
1349    pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
1350        struct Guard<'w, 'a> {
1351            entity_mut: &'a mut EntityWorldMut<'w>,
1352        }
1353
1354        impl Drop for Guard<'_, '_> {
1355            #[inline]
1356            fn drop(&mut self) {
1357                self.entity_mut.update_location();
1358            }
1359        }
1360
1361        // When `guard` is dropped at the end of this scope,
1362        // it will update the cached `EntityLocation` for this instance.
1363        // This will run even in case the closure `f` unwinds.
1364        let guard = Guard { entity_mut: self };
1365        f(guard.entity_mut.world)
1366    }
1367
1368    /// Updates the internal entity location to match the current location in the internal
1369    /// [`World`].
1370    ///
1371    /// This is *only* required when using the unsafe function [`EntityWorldMut::world_mut`],
1372    /// which enables the location to change.
1373    pub fn update_location(&mut self) {
1374        self.location = self.world.entities().get(self.entity).unwrap();
1375    }
1376
1377    /// Gets an Entry into the world for this entity and component for in-place manipulation.
1378    ///
1379    /// The type parameter specifies which component to get.
1380    ///
1381    /// # Examples
1382    ///
1383    /// ```
1384    /// # use bevy_ecs::prelude::*;
1385    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1386    /// struct Comp(u32);
1387    ///
1388    /// # let mut world = World::new();
1389    /// let mut entity = world.spawn_empty();
1390    /// entity.entry().or_insert_with(|| Comp(4));
1391    /// # let entity_id = entity.id();
1392    /// assert_eq!(world.query::<&Comp>().single(&world).0, 4);
1393    ///
1394    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
1395    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
1396    /// assert_eq!(world.query::<&Comp>().single(&world).0, 5);
1397    ///
1398    /// ```
1399    pub fn entry<'a, T: Component>(&'a mut self) -> Entry<'w, 'a, T> {
1400        if self.contains::<T>() {
1401            Entry::Occupied(OccupiedEntry {
1402                entity_world: self,
1403                _marker: PhantomData,
1404            })
1405        } else {
1406            Entry::Vacant(VacantEntry {
1407                entity_world: self,
1408                _marker: PhantomData,
1409            })
1410        }
1411    }
1412
1413    /// Creates an [`Observer`](crate::observer::Observer) listening for events of type `E` targeting this entity.
1414    /// In order to trigger the callback the entity must also match the query when the event is fired.
1415    pub fn observe<E: Event, B: Bundle, M>(
1416        &mut self,
1417        observer: impl IntoObserverSystem<E, B, M>,
1418    ) -> &mut Self {
1419        self.world
1420            .spawn(Observer::new(observer).with_entity(self.entity));
1421        self
1422    }
1423}
1424
1425/// SAFETY: all components in the archetype must exist in world
1426unsafe fn trigger_on_remove_hooks_and_observers(
1427    deferred_world: &mut DeferredWorld,
1428    archetype: &Archetype,
1429    entity: Entity,
1430    bundle_info: &BundleInfo,
1431) {
1432    deferred_world.trigger_on_remove(archetype, entity, bundle_info.iter_components());
1433    if archetype.has_remove_observer() {
1434        deferred_world.trigger_observers(ON_REMOVE, entity, bundle_info.iter_components());
1435    }
1436}
1437
1438/// A view into a single entity and component in a world, which may either be vacant or occupied.
1439///
1440/// This `enum` can only be constructed from the [`entry`] method on [`EntityWorldMut`].
1441///
1442/// [`entry`]: EntityWorldMut::entry
1443pub enum Entry<'w, 'a, T: Component> {
1444    /// An occupied entry.
1445    Occupied(OccupiedEntry<'w, 'a, T>),
1446    /// A vacant entry.
1447    Vacant(VacantEntry<'w, 'a, T>),
1448}
1449
1450impl<'w, 'a, T: Component> Entry<'w, 'a, T> {
1451    /// Provides in-place mutable access to an occupied entry.
1452    ///
1453    /// # Examples
1454    ///
1455    /// ```
1456    /// # use bevy_ecs::prelude::*;
1457    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1458    /// struct Comp(u32);
1459    ///
1460    /// # let mut world = World::new();
1461    /// let mut entity = world.spawn(Comp(0));
1462    ///
1463    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
1464    /// assert_eq!(world.query::<&Comp>().single(&world).0, 1);
1465    /// ```
1466    #[inline]
1467    pub fn and_modify<F: FnOnce(Mut<'_, T>)>(self, f: F) -> Self {
1468        match self {
1469            Entry::Occupied(mut entry) => {
1470                f(entry.get_mut());
1471                Entry::Occupied(entry)
1472            }
1473            Entry::Vacant(entry) => Entry::Vacant(entry),
1474        }
1475    }
1476
1477    /// Replaces the component of the entry, and returns an [`OccupiedEntry`].
1478    ///
1479    /// # Examples
1480    ///
1481    /// ```
1482    /// # use bevy_ecs::prelude::*;
1483    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1484    /// struct Comp(u32);
1485    ///
1486    /// # let mut world = World::new();
1487    /// let mut entity = world.spawn_empty();
1488    ///
1489    /// let entry = entity.entry().insert_entry(Comp(4));
1490    /// assert_eq!(entry.get(), &Comp(4));
1491    ///
1492    /// let entry = entity.entry().insert_entry(Comp(2));
1493    /// assert_eq!(entry.get(), &Comp(2));
1494    /// ```
1495    #[inline]
1496    pub fn insert_entry(self, component: T) -> OccupiedEntry<'w, 'a, T> {
1497        match self {
1498            Entry::Occupied(mut entry) => {
1499                entry.insert(component);
1500                entry
1501            }
1502            Entry::Vacant(entry) => entry.insert_entry(component),
1503        }
1504    }
1505
1506    /// Ensures the entry has this component by inserting the given default if empty, and
1507    /// returns a mutable reference to this component in the entry.
1508    ///
1509    /// # Examples
1510    ///
1511    /// ```
1512    /// # use bevy_ecs::prelude::*;
1513    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1514    /// struct Comp(u32);
1515    ///
1516    /// # let mut world = World::new();
1517    /// let mut entity = world.spawn_empty();
1518    ///
1519    /// entity.entry().or_insert(Comp(4));
1520    /// # let entity_id = entity.id();
1521    /// assert_eq!(world.query::<&Comp>().single(&world).0, 4);
1522    ///
1523    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
1524    /// entity.entry().or_insert(Comp(15)).0 *= 2;
1525    /// assert_eq!(world.query::<&Comp>().single(&world).0, 8);
1526    /// ```
1527    #[inline]
1528    pub fn or_insert(self, default: T) -> Mut<'a, T> {
1529        match self {
1530            Entry::Occupied(entry) => entry.into_mut(),
1531            Entry::Vacant(entry) => entry.insert(default),
1532        }
1533    }
1534
1535    /// Ensures the entry has this component by inserting the result of the default function if
1536    /// empty, and returns a mutable reference to this component in the entry.
1537    ///
1538    /// # Examples
1539    ///
1540    /// ```
1541    /// # use bevy_ecs::prelude::*;
1542    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1543    /// struct Comp(u32);
1544    ///
1545    /// # let mut world = World::new();
1546    /// let mut entity = world.spawn_empty();
1547    ///
1548    /// entity.entry().or_insert_with(|| Comp(4));
1549    /// assert_eq!(world.query::<&Comp>().single(&world).0, 4);
1550    /// ```
1551    #[inline]
1552    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> Mut<'a, T> {
1553        match self {
1554            Entry::Occupied(entry) => entry.into_mut(),
1555            Entry::Vacant(entry) => entry.insert(default()),
1556        }
1557    }
1558}
1559
1560impl<'w, 'a, T: Component + Default> Entry<'w, 'a, T> {
1561    /// Ensures the entry has this component by inserting the default value if empty, and
1562    /// returns a mutable reference to this component in the entry.
1563    ///
1564    /// # Examples
1565    ///
1566    /// ```
1567    /// # use bevy_ecs::prelude::*;
1568    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1569    /// struct Comp(u32);
1570    ///
1571    /// # let mut world = World::new();
1572    /// let mut entity = world.spawn_empty();
1573    ///
1574    /// entity.entry::<Comp>().or_default();
1575    /// assert_eq!(world.query::<&Comp>().single(&world).0, 0);
1576    /// ```
1577    #[inline]
1578    pub fn or_default(self) -> Mut<'a, T> {
1579        match self {
1580            Entry::Occupied(entry) => entry.into_mut(),
1581            Entry::Vacant(entry) => entry.insert(Default::default()),
1582        }
1583    }
1584}
1585
1586/// A view into an occupied entry in a [`EntityWorldMut`]. It is part of the [`Entry`] enum.
1587///
1588/// The contained entity must have the component type parameter if we have this struct.
1589pub struct OccupiedEntry<'w, 'a, T: Component> {
1590    entity_world: &'a mut EntityWorldMut<'w>,
1591    _marker: PhantomData<T>,
1592}
1593
1594impl<'w, 'a, T: Component> OccupiedEntry<'w, 'a, T> {
1595    /// Gets a reference to the component in the entry.
1596    ///
1597    /// # Examples
1598    ///
1599    /// ```
1600    /// # use bevy_ecs::{prelude::*, world::Entry};
1601    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1602    /// struct Comp(u32);
1603    ///
1604    /// # let mut world = World::new();
1605    /// let mut entity = world.spawn(Comp(5));
1606    ///
1607    /// if let Entry::Occupied(o) = entity.entry::<Comp>() {
1608    ///     assert_eq!(o.get().0, 5);
1609    /// }
1610    /// ```
1611    #[inline]
1612    pub fn get(&self) -> &T {
1613        // This shouldn't panic because if we have an OccupiedEntry the component must exist.
1614        self.entity_world.get::<T>().unwrap()
1615    }
1616
1617    /// Gets a mutable reference to the component in the entry.
1618    ///
1619    /// If you need a reference to the `OccupiedEntry` which may outlive the destruction of
1620    /// the `Entry` value, see [`into_mut`].
1621    ///
1622    /// [`into_mut`]: Self::into_mut
1623    ///
1624    /// # Examples
1625    ///
1626    /// ```
1627    /// # use bevy_ecs::{prelude::*, world::Entry};
1628    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1629    /// struct Comp(u32);
1630    ///
1631    /// # let mut world = World::new();
1632    /// let mut entity = world.spawn(Comp(5));
1633    ///
1634    /// if let Entry::Occupied(mut o) = entity.entry::<Comp>() {
1635    ///     o.get_mut().0 += 10;
1636    ///     assert_eq!(o.get().0, 15);
1637    ///
1638    ///     // We can use the same Entry multiple times.
1639    ///     o.get_mut().0 += 2
1640    /// }
1641    ///
1642    /// assert_eq!(world.query::<&Comp>().single(&world).0, 17);
1643    /// ```
1644    #[inline]
1645    pub fn get_mut(&mut self) -> Mut<'_, T> {
1646        // This shouldn't panic because if we have an OccupiedEntry the component must exist.
1647        self.entity_world.get_mut::<T>().unwrap()
1648    }
1649
1650    /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry with
1651    /// a lifetime bound to the `EntityWorldMut`.
1652    ///
1653    /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
1654    ///
1655    /// [`get_mut`]: Self::get_mut
1656    ///
1657    /// # Examples
1658    ///
1659    /// ```
1660    /// # use bevy_ecs::{prelude::*, world::Entry};
1661    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1662    /// struct Comp(u32);
1663    ///
1664    /// # let mut world = World::new();
1665    /// let mut entity = world.spawn(Comp(5));
1666    ///
1667    /// if let Entry::Occupied(o) = entity.entry::<Comp>() {
1668    ///     o.into_mut().0 += 10;
1669    /// }
1670    ///
1671    /// assert_eq!(world.query::<&Comp>().single(&world).0, 15);
1672    /// ```
1673    #[inline]
1674    pub fn into_mut(self) -> Mut<'a, T> {
1675        // This shouldn't panic because if we have an OccupiedEntry the component must exist.
1676        self.entity_world.get_mut().unwrap()
1677    }
1678
1679    /// Replaces the component of the entry.
1680    ///
1681    /// # Examples
1682    ///
1683    /// ```
1684    /// # use bevy_ecs::{prelude::*, world::Entry};
1685    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1686    /// struct Comp(u32);
1687    ///
1688    /// # let mut world = World::new();
1689    /// let mut entity = world.spawn(Comp(5));
1690    ///
1691    /// if let Entry::Occupied(mut o) = entity.entry::<Comp>() {
1692    ///     o.insert(Comp(10));
1693    /// }
1694    ///
1695    /// assert_eq!(world.query::<&Comp>().single(&world).0, 10);
1696    /// ```
1697    #[inline]
1698    pub fn insert(&mut self, component: T) {
1699        self.entity_world.insert(component);
1700    }
1701
1702    /// Removes the component from the entry and returns it.
1703    ///
1704    /// # Examples
1705    ///
1706    /// ```
1707    /// # use bevy_ecs::{prelude::*, world::Entry};
1708    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1709    /// struct Comp(u32);
1710    ///
1711    /// # let mut world = World::new();
1712    /// let mut entity = world.spawn(Comp(5));
1713    ///
1714    /// if let Entry::Occupied(o) = entity.entry::<Comp>() {
1715    ///     assert_eq!(o.take(), Comp(5));
1716    /// }
1717    ///
1718    /// assert_eq!(world.query::<&Comp>().iter(&world).len(), 0);
1719    /// ```
1720    #[inline]
1721    pub fn take(self) -> T {
1722        // This shouldn't panic because if we have an OccupiedEntry the component must exist.
1723        self.entity_world.take().unwrap()
1724    }
1725}
1726
1727/// A view into a vacant entry in a [`EntityWorldMut`]. It is part of the [`Entry`] enum.
1728pub struct VacantEntry<'w, 'a, T: Component> {
1729    entity_world: &'a mut EntityWorldMut<'w>,
1730    _marker: PhantomData<T>,
1731}
1732
1733impl<'w, 'a, T: Component> VacantEntry<'w, 'a, T> {
1734    /// Inserts the component into the `VacantEntry` and returns a mutable reference to it.
1735    ///
1736    /// # Examples
1737    ///
1738    /// ```
1739    /// # use bevy_ecs::{prelude::*, world::Entry};
1740    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1741    /// struct Comp(u32);
1742    ///
1743    /// # let mut world = World::new();
1744    /// let mut entity = world.spawn_empty();
1745    ///
1746    /// if let Entry::Vacant(v) = entity.entry::<Comp>() {
1747    ///     v.insert(Comp(10));
1748    /// }
1749    ///
1750    /// assert_eq!(world.query::<&Comp>().single(&world).0, 10);
1751    /// ```
1752    #[inline]
1753    pub fn insert(self, component: T) -> Mut<'a, T> {
1754        self.entity_world.insert(component);
1755        // This shouldn't panic because we just added this component
1756        self.entity_world.get_mut::<T>().unwrap()
1757    }
1758
1759    /// Inserts the component into the `VacantEntry` and returns an `OccupiedEntry`.
1760    ///
1761    /// # Examples
1762    ///
1763    /// ```
1764    /// # use bevy_ecs::{prelude::*, world::Entry};
1765    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1766    /// struct Comp(u32);
1767    ///
1768    /// # let mut world = World::new();
1769    /// let mut entity = world.spawn_empty();
1770    ///
1771    /// if let Entry::Vacant(v) = entity.entry::<Comp>() {
1772    ///     v.insert_entry(Comp(10));
1773    /// }
1774    ///
1775    /// assert_eq!(world.query::<&Comp>().single(&world).0, 10);
1776    /// ```
1777    #[inline]
1778    pub fn insert_entry(self, component: T) -> OccupiedEntry<'w, 'a, T> {
1779        self.entity_world.insert(component);
1780        OccupiedEntry {
1781            entity_world: self.entity_world,
1782            _marker: PhantomData,
1783        }
1784    }
1785}
1786
1787/// Provides read-only access to a single entity and some of its components defined by the contained [`Access`].
1788#[derive(Clone)]
1789pub struct FilteredEntityRef<'w> {
1790    entity: UnsafeEntityCell<'w>,
1791    access: Access<ComponentId>,
1792}
1793
1794impl<'w> FilteredEntityRef<'w> {
1795    /// # Safety
1796    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
1797    /// - If `access` takes read access to a component no mutable reference to that
1798    /// component can exist at the same time as the returned [`FilteredEntityMut`]
1799    /// - If `access` takes any access for a component `entity` must have that component.
1800    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: Access<ComponentId>) -> Self {
1801        Self { entity, access }
1802    }
1803
1804    /// Returns the [ID](Entity) of the current entity.
1805    #[inline]
1806    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
1807    pub fn id(&self) -> Entity {
1808        self.entity.id()
1809    }
1810
1811    /// Gets metadata indicating the location where the current entity is stored.
1812    #[inline]
1813    pub fn location(&self) -> EntityLocation {
1814        self.entity.location()
1815    }
1816
1817    /// Returns the archetype that the current entity belongs to.
1818    #[inline]
1819    pub fn archetype(&self) -> &Archetype {
1820        self.entity.archetype()
1821    }
1822
1823    /// Returns an iterator over the component ids that are accessed by self.
1824    #[inline]
1825    pub fn components(&self) -> impl Iterator<Item = ComponentId> + '_ {
1826        self.access.reads_and_writes()
1827    }
1828
1829    /// Returns a reference to the underlying [`Access`].
1830    #[inline]
1831    pub fn access(&self) -> &Access<ComponentId> {
1832        &self.access
1833    }
1834
1835    /// Returns `true` if the current entity has a component of type `T`.
1836    /// Otherwise, this returns `false`.
1837    ///
1838    /// ## Notes
1839    ///
1840    /// If you do not know the concrete type of a component, consider using
1841    /// [`Self::contains_id`] or [`Self::contains_type_id`].
1842    #[inline]
1843    pub fn contains<T: Component>(&self) -> bool {
1844        self.contains_type_id(TypeId::of::<T>())
1845    }
1846
1847    /// Returns `true` if the current entity has a component identified by `component_id`.
1848    /// Otherwise, this returns false.
1849    ///
1850    /// ## Notes
1851    ///
1852    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1853    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
1854    /// [`Self::contains_type_id`].
1855    #[inline]
1856    pub fn contains_id(&self, component_id: ComponentId) -> bool {
1857        self.entity.contains_id(component_id)
1858    }
1859
1860    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
1861    /// Otherwise, this returns false.
1862    ///
1863    /// ## Notes
1864    ///
1865    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1866    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
1867    #[inline]
1868    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
1869        self.entity.contains_type_id(type_id)
1870    }
1871
1872    /// Gets access to the component of type `T` for the current entity.
1873    /// Returns `None` if the entity does not have a component of type `T`.
1874    #[inline]
1875    pub fn get<T: Component>(&self) -> Option<&'w T> {
1876        let id = self.entity.world().components().get_id(TypeId::of::<T>())?;
1877        self.access
1878            .has_read(id)
1879            // SAFETY: We have read access
1880            .then(|| unsafe { self.entity.get() })
1881            .flatten()
1882    }
1883
1884    /// Gets access to the component of type `T` for the current entity,
1885    /// including change detection information as a [`Ref`].
1886    ///
1887    /// Returns `None` if the entity does not have a component of type `T`.
1888    #[inline]
1889    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
1890        let id = self.entity.world().components().get_id(TypeId::of::<T>())?;
1891        self.access
1892            .has_read(id)
1893            // SAFETY: We have read access
1894            .then(|| unsafe { self.entity.get_ref() })
1895            .flatten()
1896    }
1897
1898    /// Retrieves the change ticks for the given component. This can be useful for implementing change
1899    /// detection in custom runtimes.
1900    #[inline]
1901    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
1902        let id = self.entity.world().components().get_id(TypeId::of::<T>())?;
1903        self.access
1904            .has_read(id)
1905            // SAFETY: We have read access
1906            .then(|| unsafe { self.entity.get_change_ticks::<T>() })
1907            .flatten()
1908    }
1909
1910    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
1911    /// detection in custom runtimes.
1912    ///
1913    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
1914    /// use this in cases where the actual component types are not known at
1915    /// compile time.**
1916    #[inline]
1917    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
1918        self.access
1919            .has_read(component_id)
1920            // SAFETY: We have read access
1921            .then(|| unsafe { self.entity.get_change_ticks_by_id(component_id) })
1922            .flatten()
1923    }
1924
1925    /// Gets the component of the given [`ComponentId`] from the entity.
1926    ///
1927    /// **You should prefer to use the typed API [`Self::get`] where possible and only
1928    /// use this in cases where the actual component types are not known at
1929    /// compile time.**
1930    ///
1931    /// Unlike [`FilteredEntityRef::get`], this returns a raw pointer to the component,
1932    /// which is only valid while the [`FilteredEntityRef`] is alive.
1933    #[inline]
1934    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
1935        self.access
1936            .has_read(component_id)
1937            // SAFETY: We have read access
1938            .then(|| unsafe { self.entity.get_by_id(component_id) })
1939            .flatten()
1940    }
1941}
1942
1943impl<'w> From<FilteredEntityMut<'w>> for FilteredEntityRef<'w> {
1944    fn from(entity_mut: FilteredEntityMut<'w>) -> Self {
1945        // SAFETY:
1946        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1947        unsafe { FilteredEntityRef::new(entity_mut.entity, entity_mut.access) }
1948    }
1949}
1950
1951impl<'a> From<&'a FilteredEntityMut<'_>> for FilteredEntityRef<'a> {
1952    fn from(entity_mut: &'a FilteredEntityMut<'_>) -> Self {
1953        // SAFETY:
1954        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1955        unsafe { FilteredEntityRef::new(entity_mut.entity, entity_mut.access.clone()) }
1956    }
1957}
1958
1959impl<'a> From<EntityRef<'a>> for FilteredEntityRef<'a> {
1960    fn from(entity: EntityRef<'a>) -> Self {
1961        // SAFETY:
1962        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1963        unsafe {
1964            let mut access = Access::default();
1965            access.read_all();
1966            FilteredEntityRef::new(entity.0, access)
1967        }
1968    }
1969}
1970
1971impl<'a> From<&'a EntityRef<'_>> for FilteredEntityRef<'a> {
1972    fn from(entity: &'a EntityRef<'_>) -> Self {
1973        // SAFETY:
1974        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1975        unsafe {
1976            let mut access = Access::default();
1977            access.read_all();
1978            FilteredEntityRef::new(entity.0, access)
1979        }
1980    }
1981}
1982
1983impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a> {
1984    fn from(entity: EntityMut<'a>) -> Self {
1985        // SAFETY:
1986        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1987        unsafe {
1988            let mut access = Access::default();
1989            access.read_all();
1990            FilteredEntityRef::new(entity.0, access)
1991        }
1992    }
1993}
1994
1995impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a> {
1996    fn from(entity: &'a EntityMut<'_>) -> Self {
1997        // SAFETY:
1998        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
1999        unsafe {
2000            let mut access = Access::default();
2001            access.read_all();
2002            FilteredEntityRef::new(entity.0, access)
2003        }
2004    }
2005}
2006
2007impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a> {
2008    fn from(entity: EntityWorldMut<'a>) -> Self {
2009        // SAFETY:
2010        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2011        unsafe {
2012            let mut access = Access::default();
2013            access.read_all();
2014            FilteredEntityRef::new(entity.into_unsafe_entity_cell(), access)
2015        }
2016    }
2017}
2018
2019impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a> {
2020    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
2021        // SAFETY:
2022        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2023        unsafe {
2024            let mut access = Access::default();
2025            access.read_all();
2026            FilteredEntityRef::new(entity.as_unsafe_entity_cell_readonly(), access)
2027        }
2028    }
2029}
2030
2031/// Provides mutable access to a single entity and some of its components defined by the contained [`Access`].
2032pub struct FilteredEntityMut<'w> {
2033    entity: UnsafeEntityCell<'w>,
2034    access: Access<ComponentId>,
2035}
2036
2037impl<'w> FilteredEntityMut<'w> {
2038    /// # Safety
2039    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
2040    /// - If `access` takes read access to a component no mutable reference to that
2041    /// component can exist at the same time as the returned [`FilteredEntityMut`]
2042    /// - If `access` takes write access to a component, no reference to that component
2043    /// may exist at the same time as the returned [`FilteredEntityMut`]
2044    /// - If `access` takes any access for a component `entity` must have that component.
2045    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: Access<ComponentId>) -> Self {
2046        Self { entity, access }
2047    }
2048
2049    /// Returns a new instance with a shorter lifetime.
2050    /// This is useful if you have `&mut FilteredEntityMut`, but you need `FilteredEntityMut`.
2051    pub fn reborrow(&mut self) -> FilteredEntityMut<'_> {
2052        // SAFETY: We have exclusive access to the entire entity and its components.
2053        unsafe { Self::new(self.entity, self.access.clone()) }
2054    }
2055
2056    /// Gets read-only access to all of the entity's components.
2057    pub fn as_readonly(&self) -> FilteredEntityRef<'_> {
2058        FilteredEntityRef::from(self)
2059    }
2060
2061    /// Returns the [ID](Entity) of the current entity.
2062    #[inline]
2063    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
2064    pub fn id(&self) -> Entity {
2065        self.entity.id()
2066    }
2067
2068    /// Gets metadata indicating the location where the current entity is stored.
2069    #[inline]
2070    pub fn location(&self) -> EntityLocation {
2071        self.entity.location()
2072    }
2073
2074    /// Returns the archetype that the current entity belongs to.
2075    #[inline]
2076    pub fn archetype(&self) -> &Archetype {
2077        self.entity.archetype()
2078    }
2079
2080    /// Returns an iterator over the component ids that are accessed by self.
2081    #[inline]
2082    pub fn components(&self) -> impl Iterator<Item = ComponentId> + '_ {
2083        self.access.reads_and_writes()
2084    }
2085
2086    /// Returns a reference to the underlying [`Access`].
2087    #[inline]
2088    pub fn access(&self) -> &Access<ComponentId> {
2089        &self.access
2090    }
2091
2092    /// Returns `true` if the current entity has a component of type `T`.
2093    /// Otherwise, this returns `false`.
2094    ///
2095    /// ## Notes
2096    ///
2097    /// If you do not know the concrete type of a component, consider using
2098    /// [`Self::contains_id`] or [`Self::contains_type_id`].
2099    #[inline]
2100    pub fn contains<T: Component>(&self) -> bool {
2101        self.contains_type_id(TypeId::of::<T>())
2102    }
2103
2104    /// Returns `true` if the current entity has a component identified by `component_id`.
2105    /// Otherwise, this returns false.
2106    ///
2107    /// ## Notes
2108    ///
2109    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
2110    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
2111    /// [`Self::contains_type_id`].
2112    #[inline]
2113    pub fn contains_id(&self, component_id: ComponentId) -> bool {
2114        self.entity.contains_id(component_id)
2115    }
2116
2117    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
2118    /// Otherwise, this returns false.
2119    ///
2120    /// ## Notes
2121    ///
2122    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
2123    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
2124    #[inline]
2125    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
2126        self.entity.contains_type_id(type_id)
2127    }
2128
2129    /// Gets access to the component of type `T` for the current entity.
2130    /// Returns `None` if the entity does not have a component of type `T`.
2131    #[inline]
2132    pub fn get<T: Component>(&self) -> Option<&'_ T> {
2133        self.as_readonly().get()
2134    }
2135
2136    /// Gets access to the component of type `T` for the current entity,
2137    /// including change detection information as a [`Ref`].
2138    ///
2139    /// Returns `None` if the entity does not have a component of type `T`.
2140    #[inline]
2141    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
2142        self.as_readonly().get_ref()
2143    }
2144
2145    /// Gets mutable access to the component of type `T` for the current entity.
2146    /// Returns `None` if the entity does not have a component of type `T`.
2147    #[inline]
2148    pub fn get_mut<T: Component>(&mut self) -> Option<Mut<'_, T>> {
2149        let id = self.entity.world().components().get_id(TypeId::of::<T>())?;
2150        self.access
2151            .has_write(id)
2152            // SAFETY: We have write access
2153            .then(|| unsafe { self.entity.get_mut() })
2154            .flatten()
2155    }
2156
2157    /// Consumes self and gets mutable access to the component of type `T`
2158    /// with the world `'w` lifetime for the current entity.
2159    /// Returns `None` if the entity does not have a component of type `T`.
2160    #[inline]
2161    pub fn into_mut<T: Component>(self) -> Option<Mut<'w, T>> {
2162        let id = self.entity.world().components().get_id(TypeId::of::<T>())?;
2163        self.access
2164            .has_write(id)
2165            // SAFETY: We have write access
2166            .then(|| unsafe { self.entity.get_mut() })
2167            .flatten()
2168    }
2169
2170    /// Retrieves the change ticks for the given component. This can be useful for implementing change
2171    /// detection in custom runtimes.
2172    #[inline]
2173    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
2174        self.as_readonly().get_change_ticks::<T>()
2175    }
2176
2177    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
2178    /// detection in custom runtimes.
2179    ///
2180    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
2181    /// use this in cases where the actual component types are not known at
2182    /// compile time.**
2183    #[inline]
2184    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
2185        self.as_readonly().get_change_ticks_by_id(component_id)
2186    }
2187
2188    /// Gets the component of the given [`ComponentId`] from the entity.
2189    ///
2190    /// **You should prefer to use the typed API [`Self::get`] where possible and only
2191    /// use this in cases where the actual component types are not known at
2192    /// compile time.**
2193    ///
2194    /// Unlike [`FilteredEntityMut::get`], this returns a raw pointer to the component,
2195    /// which is only valid while the [`FilteredEntityMut`] is alive.
2196    #[inline]
2197    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
2198        self.as_readonly().get_by_id(component_id)
2199    }
2200
2201    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
2202    ///
2203    /// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
2204    /// use this in cases where the actual component types are not known at
2205    /// compile time.**
2206    ///
2207    /// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component,
2208    /// which is only valid while the [`FilteredEntityMut`] is alive.
2209    #[inline]
2210    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
2211        self.access
2212            .has_write(component_id)
2213            // SAFETY: We have write access
2214            .then(|| unsafe { self.entity.get_mut_by_id(component_id) })
2215            .flatten()
2216    }
2217}
2218
2219impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a> {
2220    fn from(entity: EntityMut<'a>) -> Self {
2221        // SAFETY:
2222        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
2223        unsafe {
2224            let mut access = Access::default();
2225            access.read_all();
2226            access.write_all();
2227            FilteredEntityMut::new(entity.0, access)
2228        }
2229    }
2230}
2231
2232impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a> {
2233    fn from(entity: &'a mut EntityMut<'_>) -> Self {
2234        // SAFETY:
2235        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
2236        unsafe {
2237            let mut access = Access::default();
2238            access.read_all();
2239            access.write_all();
2240            FilteredEntityMut::new(entity.0, access)
2241        }
2242    }
2243}
2244
2245impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a> {
2246    fn from(entity: EntityWorldMut<'a>) -> Self {
2247        // SAFETY:
2248        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2249        unsafe {
2250            let mut access = Access::default();
2251            access.read_all();
2252            access.write_all();
2253            FilteredEntityMut::new(entity.into_unsafe_entity_cell(), access)
2254        }
2255    }
2256}
2257
2258impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a> {
2259    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
2260        // SAFETY:
2261        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2262        unsafe {
2263            let mut access = Access::default();
2264            access.read_all();
2265            access.write_all();
2266            FilteredEntityMut::new(entity.as_unsafe_entity_cell(), access)
2267        }
2268    }
2269}
2270
2271#[derive(Error, Debug)]
2272pub enum TryFromFilteredError {
2273    #[error("Conversion failed, filtered entity ref does not have read access to all components")]
2274    MissingReadAllAccess,
2275
2276    #[error("Conversion failed, filtered entity ref does not have write access to all components")]
2277    MissingWriteAllAccess,
2278}
2279
2280/// Inserts a dynamic [`Bundle`] into the entity.
2281///
2282/// # Safety
2283///
2284/// - [`OwningPtr`] and [`StorageType`] iterators must correspond to the
2285/// [`BundleInfo`] used to construct [`BundleInserter`]
2286/// - [`Entity`] must correspond to [`EntityLocation`]
2287unsafe fn insert_dynamic_bundle<
2288    'a,
2289    I: Iterator<Item = OwningPtr<'a>>,
2290    S: Iterator<Item = StorageType>,
2291>(
2292    mut bundle_inserter: BundleInserter<'_>,
2293    entity: Entity,
2294    location: EntityLocation,
2295    components: I,
2296    storage_types: S,
2297) -> EntityLocation {
2298    struct DynamicInsertBundle<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> {
2299        components: I,
2300    }
2301
2302    impl<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> DynamicBundle
2303        for DynamicInsertBundle<'a, I>
2304    {
2305        fn get_components(self, func: &mut impl FnMut(StorageType, OwningPtr<'_>)) {
2306            self.components.for_each(|(t, ptr)| func(t, ptr));
2307        }
2308    }
2309
2310    let bundle = DynamicInsertBundle {
2311        components: storage_types.zip(components),
2312    };
2313
2314    // SAFETY: location matches current entity.
2315    unsafe { bundle_inserter.insert(entity, location, bundle) }
2316}
2317
2318/// Removes a bundle from the given archetype and returns the resulting archetype (or None if the
2319/// removal was invalid). in the event that adding the given bundle does not result in an Archetype
2320/// change. Results are cached in the Archetype Graph to avoid redundant work.
2321/// if `intersection` is false, attempting to remove a bundle with components _not_ contained in the
2322/// current archetype will fail, returning None. if `intersection` is true, components in the bundle
2323/// but not in the current archetype will be ignored
2324///
2325/// # Safety
2326/// `archetype_id` must exist and components in `bundle_info` must exist
2327unsafe fn remove_bundle_from_archetype(
2328    archetypes: &mut Archetypes,
2329    storages: &mut Storages,
2330    components: &Components,
2331    observers: &Observers,
2332    archetype_id: ArchetypeId,
2333    bundle_info: &BundleInfo,
2334    intersection: bool,
2335) -> Option<ArchetypeId> {
2336    // check the archetype graph to see if the Bundle has been removed from this archetype in the
2337    // past
2338    let remove_bundle_result = {
2339        let edges = archetypes[archetype_id].edges();
2340        if intersection {
2341            edges.get_remove_bundle(bundle_info.id())
2342        } else {
2343            edges.get_take_bundle(bundle_info.id())
2344        }
2345    };
2346    let result = if let Some(result) = remove_bundle_result {
2347        // this Bundle removal result is cached. just return that!
2348        result
2349    } else {
2350        let mut next_table_components;
2351        let mut next_sparse_set_components;
2352        let next_table_id;
2353        {
2354            let current_archetype = &mut archetypes[archetype_id];
2355            let mut removed_table_components = Vec::new();
2356            let mut removed_sparse_set_components = Vec::new();
2357            for component_id in bundle_info.components().iter().cloned() {
2358                if current_archetype.contains(component_id) {
2359                    // SAFETY: bundle components were already initialized by bundles.get_info
2360                    let component_info = unsafe { components.get_info_unchecked(component_id) };
2361                    match component_info.storage_type() {
2362                        StorageType::Table => removed_table_components.push(component_id),
2363                        StorageType::SparseSet => removed_sparse_set_components.push(component_id),
2364                    }
2365                } else if !intersection {
2366                    // a component in the bundle was not present in the entity's archetype, so this
2367                    // removal is invalid cache the result in the archetype
2368                    // graph
2369                    current_archetype
2370                        .edges_mut()
2371                        .insert_take_bundle(bundle_info.id(), None);
2372                    return None;
2373                }
2374            }
2375
2376            // sort removed components so we can do an efficient "sorted remove". archetype
2377            // components are already sorted
2378            removed_table_components.sort();
2379            removed_sparse_set_components.sort();
2380            next_table_components = current_archetype.table_components().collect();
2381            next_sparse_set_components = current_archetype.sparse_set_components().collect();
2382            sorted_remove(&mut next_table_components, &removed_table_components);
2383            sorted_remove(
2384                &mut next_sparse_set_components,
2385                &removed_sparse_set_components,
2386            );
2387
2388            next_table_id = if removed_table_components.is_empty() {
2389                current_archetype.table_id()
2390            } else {
2391                // SAFETY: all components in next_table_components exist
2392                unsafe {
2393                    storages
2394                        .tables
2395                        .get_id_or_insert(&next_table_components, components)
2396                }
2397            };
2398        }
2399
2400        let new_archetype_id = archetypes.get_id_or_insert(
2401            components,
2402            observers,
2403            next_table_id,
2404            next_table_components,
2405            next_sparse_set_components,
2406        );
2407        Some(new_archetype_id)
2408    };
2409    let current_archetype = &mut archetypes[archetype_id];
2410    // cache the result in an edge
2411    if intersection {
2412        current_archetype
2413            .edges_mut()
2414            .insert_remove_bundle(bundle_info.id(), result);
2415    } else {
2416        current_archetype
2417            .edges_mut()
2418            .insert_take_bundle(bundle_info.id(), result);
2419    }
2420    result
2421}
2422
2423fn sorted_remove<T: Eq + Ord + Copy>(source: &mut Vec<T>, remove: &[T]) {
2424    let mut remove_index = 0;
2425    source.retain(|value| {
2426        while remove_index < remove.len() && *value > remove[remove_index] {
2427            remove_index += 1;
2428        }
2429
2430        if remove_index < remove.len() {
2431            *value != remove[remove_index]
2432        } else {
2433            true
2434        }
2435    });
2436}
2437
2438/// Moves component data out of storage.
2439///
2440/// This function leaves the underlying memory unchanged, but the component behind
2441/// returned pointer is semantically owned by the caller and will not be dropped in its original location.
2442/// Caller is responsible to drop component data behind returned pointer.
2443///
2444/// # Safety
2445/// - `location.table_row` must be in bounds of column of component id `component_id`
2446/// - `component_id` must be valid
2447/// - `components` must come from the same world as `self`
2448/// - The relevant table row **must be removed** by the caller once all components are taken, without dropping the value
2449#[inline]
2450pub(crate) unsafe fn take_component<'a>(
2451    storages: &'a mut Storages,
2452    components: &Components,
2453    removed_components: &mut RemovedComponentEvents,
2454    component_id: ComponentId,
2455    entity: Entity,
2456    location: EntityLocation,
2457) -> OwningPtr<'a> {
2458    // SAFETY: caller promises component_id to be valid
2459    let component_info = unsafe { components.get_info_unchecked(component_id) };
2460    removed_components.send(component_id, entity);
2461    match component_info.storage_type() {
2462        StorageType::Table => {
2463            let table = &mut storages.tables[location.table_id];
2464            let components = table.get_column_mut(component_id).unwrap();
2465            // SAFETY:
2466            // - archetypes only store valid table_rows
2467            // - index is in bounds as promised by caller
2468            // - promote is safe because the caller promises to remove the table row without dropping it immediately afterwards
2469            unsafe {
2470                components
2471                    .get_data_unchecked_mut(location.table_row)
2472                    .promote()
2473            }
2474        }
2475        StorageType::SparseSet => storages
2476            .sparse_sets
2477            .get_mut(component_id)
2478            .unwrap()
2479            .remove_and_forget(entity)
2480            .unwrap(),
2481    }
2482}
2483
2484#[cfg(test)]
2485mod tests {
2486    use bevy_ptr::OwningPtr;
2487    use std::panic::AssertUnwindSafe;
2488
2489    use crate::world::{FilteredEntityMut, FilteredEntityRef};
2490    use crate::{self as bevy_ecs, component::ComponentId, prelude::*, system::assert_is_system};
2491
2492    #[test]
2493    fn sorted_remove() {
2494        let mut a = vec![1, 2, 3, 4, 5, 6, 7];
2495        let b = vec![1, 2, 3, 5, 7];
2496        super::sorted_remove(&mut a, &b);
2497
2498        assert_eq!(a, vec![4, 6]);
2499
2500        let mut a = vec![1];
2501        let b = vec![1];
2502        super::sorted_remove(&mut a, &b);
2503
2504        assert_eq!(a, vec![]);
2505
2506        let mut a = vec![1];
2507        let b = vec![2];
2508        super::sorted_remove(&mut a, &b);
2509
2510        assert_eq!(a, vec![1]);
2511    }
2512
2513    #[derive(Component, Clone, Copy, Debug, PartialEq)]
2514    struct TestComponent(u32);
2515
2516    #[derive(Component, Clone, Copy, Debug, PartialEq)]
2517    #[component(storage = "SparseSet")]
2518    struct TestComponent2(u32);
2519
2520    #[test]
2521    fn entity_ref_get_by_id() {
2522        let mut world = World::new();
2523        let entity = world.spawn(TestComponent(42)).id();
2524        let component_id = world
2525            .components()
2526            .get_id(std::any::TypeId::of::<TestComponent>())
2527            .unwrap();
2528
2529        let entity = world.entity(entity);
2530        let test_component = entity.get_by_id(component_id).unwrap();
2531        // SAFETY: points to a valid `TestComponent`
2532        let test_component = unsafe { test_component.deref::<TestComponent>() };
2533
2534        assert_eq!(test_component.0, 42);
2535    }
2536
2537    #[test]
2538    fn entity_mut_get_by_id() {
2539        let mut world = World::new();
2540        let entity = world.spawn(TestComponent(42)).id();
2541        let component_id = world
2542            .components()
2543            .get_id(std::any::TypeId::of::<TestComponent>())
2544            .unwrap();
2545
2546        let mut entity_mut = world.entity_mut(entity);
2547        let mut test_component = entity_mut.get_mut_by_id(component_id).unwrap();
2548        {
2549            test_component.set_changed();
2550            let test_component =
2551                // SAFETY: `test_component` has unique access of the `EntityWorldMut` and is not used afterwards
2552                unsafe { test_component.into_inner().deref_mut::<TestComponent>() };
2553            test_component.0 = 43;
2554        }
2555
2556        let entity = world.entity(entity);
2557        let test_component = entity.get_by_id(component_id).unwrap();
2558        // SAFETY: `TestComponent` is the correct component type
2559        let test_component = unsafe { test_component.deref::<TestComponent>() };
2560
2561        assert_eq!(test_component.0, 43);
2562    }
2563
2564    #[test]
2565    fn entity_ref_get_by_id_invalid_component_id() {
2566        let invalid_component_id = ComponentId::new(usize::MAX);
2567
2568        let mut world = World::new();
2569        let entity = world.spawn_empty().id();
2570        let entity = world.entity(entity);
2571        assert!(entity.get_by_id(invalid_component_id).is_none());
2572    }
2573
2574    #[test]
2575    fn entity_mut_get_by_id_invalid_component_id() {
2576        let invalid_component_id = ComponentId::new(usize::MAX);
2577
2578        let mut world = World::new();
2579        let mut entity = world.spawn_empty();
2580        assert!(entity.get_by_id(invalid_component_id).is_none());
2581        assert!(entity.get_mut_by_id(invalid_component_id).is_none());
2582    }
2583
2584    // regression test for https://github.com/bevyengine/bevy/pull/7387
2585    #[test]
2586    fn entity_mut_world_scope_panic() {
2587        let mut world = World::new();
2588
2589        let mut entity = world.spawn_empty();
2590        let old_location = entity.location();
2591        let id = entity.id();
2592        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
2593            entity.world_scope(|w| {
2594                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
2595                // This will get updated at the end of the scope.
2596                w.entity_mut(id).insert(TestComponent(0));
2597
2598                // Ensure that the entity location still gets updated even in case of a panic.
2599                panic!("this should get caught by the outer scope")
2600            });
2601        }));
2602        assert!(res.is_err());
2603
2604        // Ensure that the location has been properly updated.
2605        assert_ne!(entity.location(), old_location);
2606    }
2607
2608    // regression test for https://github.com/bevyengine/bevy/pull/7805
2609    #[test]
2610    fn removing_sparse_updates_archetype_row() {
2611        #[derive(Component, PartialEq, Debug)]
2612        struct Dense(u8);
2613
2614        #[derive(Component)]
2615        #[component(storage = "SparseSet")]
2616        struct Sparse;
2617
2618        let mut world = World::new();
2619        let e1 = world.spawn((Dense(0), Sparse)).id();
2620        let e2 = world.spawn((Dense(1), Sparse)).id();
2621
2622        world.entity_mut(e1).remove::<Sparse>();
2623        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
2624    }
2625
2626    // regression test for https://github.com/bevyengine/bevy/pull/7805
2627    #[test]
2628    fn removing_dense_updates_table_row() {
2629        #[derive(Component, PartialEq, Debug)]
2630        struct Dense(u8);
2631
2632        #[derive(Component)]
2633        #[component(storage = "SparseSet")]
2634        struct Sparse;
2635
2636        let mut world = World::new();
2637        let e1 = world.spawn((Dense(0), Sparse)).id();
2638        let e2 = world.spawn((Dense(1), Sparse)).id();
2639
2640        world.entity_mut(e1).remove::<Dense>();
2641        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
2642    }
2643
2644    // Test that calling retain with `()` removes all components.
2645    #[test]
2646    fn retain_nothing() {
2647        #[derive(Component)]
2648        struct Marker<const N: usize>;
2649
2650        let mut world = World::new();
2651        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
2652
2653        world.entity_mut(ent).retain::<()>();
2654        assert_eq!(world.entity(ent).archetype().components().next(), None);
2655    }
2656
2657    // Test removing some components with `retain`, including components not on the entity.
2658    #[test]
2659    fn retain_some_components() {
2660        #[derive(Component)]
2661        struct Marker<const N: usize>;
2662
2663        let mut world = World::new();
2664        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
2665
2666        world.entity_mut(ent).retain::<(Marker<2>, Marker<4>)>();
2667        // Check that marker 2 was retained.
2668        assert!(world.entity(ent).get::<Marker<2>>().is_some());
2669        // Check that only marker 2 was retained.
2670        assert_eq!(
2671            world
2672                .entity(ent)
2673                .archetype()
2674                .components()
2675                .collect::<Vec<_>>()
2676                .len(),
2677            1
2678        );
2679    }
2680
2681    // regression test for https://github.com/bevyengine/bevy/pull/7805
2682    #[test]
2683    fn inserting_sparse_updates_archetype_row() {
2684        #[derive(Component, PartialEq, Debug)]
2685        struct Dense(u8);
2686
2687        #[derive(Component)]
2688        #[component(storage = "SparseSet")]
2689        struct Sparse;
2690
2691        let mut world = World::new();
2692        let e1 = world.spawn(Dense(0)).id();
2693        let e2 = world.spawn(Dense(1)).id();
2694
2695        world.entity_mut(e1).insert(Sparse);
2696        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
2697    }
2698
2699    // regression test for https://github.com/bevyengine/bevy/pull/7805
2700    #[test]
2701    fn inserting_dense_updates_archetype_row() {
2702        #[derive(Component, PartialEq, Debug)]
2703        struct Dense(u8);
2704
2705        #[derive(Component)]
2706        struct Dense2;
2707
2708        #[derive(Component)]
2709        #[component(storage = "SparseSet")]
2710        struct Sparse;
2711
2712        let mut world = World::new();
2713        let e1 = world.spawn(Dense(0)).id();
2714        let e2 = world.spawn(Dense(1)).id();
2715
2716        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
2717
2718        // archetype with [e2, e1]
2719        // table with [e1, e2]
2720
2721        world.entity_mut(e2).insert(Dense2);
2722
2723        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
2724    }
2725
2726    #[test]
2727    fn inserting_dense_updates_table_row() {
2728        #[derive(Component, PartialEq, Debug)]
2729        struct Dense(u8);
2730
2731        #[derive(Component)]
2732        struct Dense2;
2733
2734        #[derive(Component)]
2735        #[component(storage = "SparseSet")]
2736        struct Sparse;
2737
2738        let mut world = World::new();
2739        let e1 = world.spawn(Dense(0)).id();
2740        let e2 = world.spawn(Dense(1)).id();
2741
2742        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
2743
2744        // archetype with [e2, e1]
2745        // table with [e1, e2]
2746
2747        world.entity_mut(e1).insert(Dense2);
2748
2749        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
2750    }
2751
2752    // regression test for https://github.com/bevyengine/bevy/pull/7805
2753    #[test]
2754    fn despawning_entity_updates_archetype_row() {
2755        #[derive(Component, PartialEq, Debug)]
2756        struct Dense(u8);
2757
2758        #[derive(Component)]
2759        #[component(storage = "SparseSet")]
2760        struct Sparse;
2761
2762        let mut world = World::new();
2763        let e1 = world.spawn(Dense(0)).id();
2764        let e2 = world.spawn(Dense(1)).id();
2765
2766        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
2767
2768        // archetype with [e2, e1]
2769        // table with [e1, e2]
2770
2771        world.entity_mut(e2).despawn();
2772
2773        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
2774    }
2775
2776    // regression test for https://github.com/bevyengine/bevy/pull/7805
2777    #[test]
2778    fn despawning_entity_updates_table_row() {
2779        #[derive(Component, PartialEq, Debug)]
2780        struct Dense(u8);
2781
2782        #[derive(Component)]
2783        #[component(storage = "SparseSet")]
2784        struct Sparse;
2785
2786        let mut world = World::new();
2787        let e1 = world.spawn(Dense(0)).id();
2788        let e2 = world.spawn(Dense(1)).id();
2789
2790        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
2791
2792        // archetype with [e2, e1]
2793        // table with [e1, e2]
2794
2795        world.entity_mut(e1).despawn();
2796
2797        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
2798    }
2799
2800    #[test]
2801    fn entity_mut_insert_by_id() {
2802        let mut world = World::new();
2803        let test_component_id = world.init_component::<TestComponent>();
2804
2805        let mut entity = world.spawn_empty();
2806        OwningPtr::make(TestComponent(42), |ptr| {
2807            // SAFETY: `ptr` matches the component id
2808            unsafe { entity.insert_by_id(test_component_id, ptr) };
2809        });
2810
2811        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
2812
2813        assert_eq!(components, vec![&TestComponent(42)]);
2814
2815        // Compare with `insert_bundle_by_id`
2816
2817        let mut entity = world.spawn_empty();
2818        OwningPtr::make(TestComponent(84), |ptr| {
2819            // SAFETY: `ptr` matches the component id
2820            unsafe { entity.insert_by_ids(&[test_component_id], vec![ptr].into_iter()) };
2821        });
2822
2823        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
2824
2825        assert_eq!(components, vec![&TestComponent(42), &TestComponent(84)]);
2826    }
2827
2828    #[test]
2829    fn entity_mut_insert_bundle_by_id() {
2830        let mut world = World::new();
2831        let test_component_id = world.init_component::<TestComponent>();
2832        let test_component_2_id = world.init_component::<TestComponent2>();
2833
2834        let component_ids = [test_component_id, test_component_2_id];
2835        let test_component_value = TestComponent(42);
2836        let test_component_2_value = TestComponent2(84);
2837
2838        let mut entity = world.spawn_empty();
2839        OwningPtr::make(test_component_value, |ptr1| {
2840            OwningPtr::make(test_component_2_value, |ptr2| {
2841                // SAFETY: `ptr1` and `ptr2` match the component ids
2842                unsafe { entity.insert_by_ids(&component_ids, vec![ptr1, ptr2].into_iter()) };
2843            });
2844        });
2845
2846        let dynamic_components: Vec<_> = world
2847            .query::<(&TestComponent, &TestComponent2)>()
2848            .iter(&world)
2849            .collect();
2850
2851        assert_eq!(
2852            dynamic_components,
2853            vec![(&TestComponent(42), &TestComponent2(84))]
2854        );
2855
2856        // Compare with `World` generated using static type equivalents
2857        let mut static_world = World::new();
2858
2859        static_world.spawn((test_component_value, test_component_2_value));
2860        let static_components: Vec<_> = static_world
2861            .query::<(&TestComponent, &TestComponent2)>()
2862            .iter(&static_world)
2863            .collect();
2864
2865        assert_eq!(dynamic_components, static_components);
2866    }
2867
2868    #[test]
2869    fn entity_mut_remove_by_id() {
2870        let mut world = World::new();
2871        let test_component_id = world.init_component::<TestComponent>();
2872
2873        let mut entity = world.spawn(TestComponent(42));
2874        entity.remove_by_id(test_component_id);
2875
2876        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
2877
2878        assert_eq!(components, vec![] as Vec<&TestComponent>);
2879
2880        // remove non-existent component does not panic
2881        world.spawn_empty().remove_by_id(test_component_id);
2882    }
2883
2884    #[derive(Component)]
2885    struct A;
2886
2887    #[derive(Resource)]
2888    struct R;
2889
2890    #[test]
2891    fn disjoint_access() {
2892        fn disjoint_readonly(_: Query<EntityMut, With<A>>, _: Query<EntityRef, Without<A>>) {}
2893
2894        fn disjoint_mutable(_: Query<EntityMut, With<A>>, _: Query<EntityMut, Without<A>>) {}
2895
2896        assert_is_system(disjoint_readonly);
2897        assert_is_system(disjoint_mutable);
2898    }
2899
2900    #[test]
2901    fn ref_compatible() {
2902        fn borrow_system(_: Query<(EntityRef, &A)>, _: Query<&A>) {}
2903
2904        assert_is_system(borrow_system);
2905    }
2906
2907    #[test]
2908    fn ref_compatible_with_resource() {
2909        fn borrow_system(_: Query<EntityRef>, _: Res<R>) {}
2910
2911        assert_is_system(borrow_system);
2912    }
2913
2914    #[test]
2915    #[ignore] // This should pass, but it currently fails due to limitations in our access model.
2916    fn ref_compatible_with_resource_mut() {
2917        fn borrow_system(_: Query<EntityRef>, _: ResMut<R>) {}
2918
2919        assert_is_system(borrow_system);
2920    }
2921
2922    #[test]
2923    #[should_panic]
2924    fn ref_incompatible_with_mutable_component() {
2925        fn incompatible_system(_: Query<(EntityRef, &mut A)>) {}
2926
2927        assert_is_system(incompatible_system);
2928    }
2929
2930    #[test]
2931    #[should_panic]
2932    fn ref_incompatible_with_mutable_query() {
2933        fn incompatible_system(_: Query<EntityRef>, _: Query<&mut A>) {}
2934
2935        assert_is_system(incompatible_system);
2936    }
2937
2938    #[test]
2939    fn mut_compatible_with_entity() {
2940        fn borrow_mut_system(_: Query<(Entity, EntityMut)>) {}
2941
2942        assert_is_system(borrow_mut_system);
2943    }
2944
2945    #[test]
2946    #[ignore] // This should pass, but it currently fails due to limitations in our access model.
2947    fn mut_compatible_with_resource() {
2948        fn borrow_mut_system(_: Res<R>, _: Query<EntityMut>) {}
2949
2950        assert_is_system(borrow_mut_system);
2951    }
2952
2953    #[test]
2954    #[ignore] // This should pass, but it currently fails due to limitations in our access model.
2955    fn mut_compatible_with_resource_mut() {
2956        fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut>) {}
2957
2958        assert_is_system(borrow_mut_system);
2959    }
2960
2961    #[test]
2962    #[should_panic]
2963    fn mut_incompatible_with_read_only_component() {
2964        fn incompatible_system(_: Query<(EntityMut, &A)>) {}
2965
2966        assert_is_system(incompatible_system);
2967    }
2968
2969    #[test]
2970    #[should_panic]
2971    fn mut_incompatible_with_mutable_component() {
2972        fn incompatible_system(_: Query<(EntityMut, &mut A)>) {}
2973
2974        assert_is_system(incompatible_system);
2975    }
2976
2977    #[test]
2978    #[should_panic]
2979    fn mut_incompatible_with_read_only_query() {
2980        fn incompatible_system(_: Query<EntityMut>, _: Query<&A>) {}
2981
2982        assert_is_system(incompatible_system);
2983    }
2984
2985    #[test]
2986    #[should_panic]
2987    fn mut_incompatible_with_mutable_query() {
2988        fn incompatible_system(_: Query<EntityMut>, _: Query<&mut A>) {}
2989
2990        assert_is_system(incompatible_system);
2991    }
2992
2993    #[test]
2994    fn filtered_entity_ref_normal() {
2995        let mut world = World::new();
2996        let a_id = world.init_component::<A>();
2997
2998        let e: FilteredEntityRef = world.spawn(A).into();
2999
3000        assert!(e.get::<A>().is_some());
3001        assert!(e.get_ref::<A>().is_some());
3002        assert!(e.get_change_ticks::<A>().is_some());
3003        assert!(e.get_by_id(a_id).is_some());
3004        assert!(e.get_change_ticks_by_id(a_id).is_some());
3005    }
3006
3007    #[test]
3008    fn filtered_entity_ref_missing() {
3009        let mut world = World::new();
3010        let a_id = world.init_component::<A>();
3011
3012        let e: FilteredEntityRef = world.spawn(()).into();
3013
3014        assert!(e.get::<A>().is_none());
3015        assert!(e.get_ref::<A>().is_none());
3016        assert!(e.get_change_ticks::<A>().is_none());
3017        assert!(e.get_by_id(a_id).is_none());
3018        assert!(e.get_change_ticks_by_id(a_id).is_none());
3019    }
3020
3021    #[test]
3022    fn filtered_entity_mut_normal() {
3023        let mut world = World::new();
3024        let a_id = world.init_component::<A>();
3025
3026        let mut e: FilteredEntityMut = world.spawn(A).into();
3027
3028        assert!(e.get::<A>().is_some());
3029        assert!(e.get_ref::<A>().is_some());
3030        assert!(e.get_mut::<A>().is_some());
3031        assert!(e.get_change_ticks::<A>().is_some());
3032        assert!(e.get_by_id(a_id).is_some());
3033        assert!(e.get_mut_by_id(a_id).is_some());
3034        assert!(e.get_change_ticks_by_id(a_id).is_some());
3035    }
3036
3037    #[test]
3038    fn filtered_entity_mut_missing() {
3039        let mut world = World::new();
3040        let a_id = world.init_component::<A>();
3041
3042        let mut e: FilteredEntityMut = world.spawn(()).into();
3043
3044        assert!(e.get::<A>().is_none());
3045        assert!(e.get_ref::<A>().is_none());
3046        assert!(e.get_mut::<A>().is_none());
3047        assert!(e.get_change_ticks::<A>().is_none());
3048        assert!(e.get_by_id(a_id).is_none());
3049        assert!(e.get_mut_by_id(a_id).is_none());
3050        assert!(e.get_change_ticks_by_id(a_id).is_none());
3051    }
3052}