bevy_ecs/world/
entity_ref.rs

1use crate::{
2    archetype::Archetype,
3    bundle::{
4        Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode,
5    },
6    change_detection::{MaybeLocation, MutUntyped},
7    component::{Component, ComponentId, ComponentTicks, Components, Mutable, StorageType, Tick},
8    entity::{
9        ContainsEntity, Entity, EntityCloner, EntityClonerBuilder, EntityEquivalent,
10        EntityIdLocation, EntityLocation, OptIn, OptOut,
11    },
12    event::{EntityComponentsTrigger, EntityEvent},
13    lifecycle::{Despawn, Remove, Replace, DESPAWN, REMOVE, REPLACE},
14    observer::Observer,
15    query::{Access, DebugCheckedUnwrap, ReadOnlyQueryData, ReleaseStateQueryData},
16    relationship::RelationshipHookMode,
17    resource::Resource,
18    storage::{SparseSets, Table},
19    system::IntoObserverSystem,
20    world::{error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, Mut, Ref, World},
21};
22use alloc::vec::Vec;
23use bevy_platform::collections::{HashMap, HashSet};
24use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr, Ptr};
25use core::{
26    any::TypeId,
27    cmp::Ordering,
28    hash::{Hash, Hasher},
29    marker::PhantomData,
30    mem::MaybeUninit,
31};
32use thiserror::Error;
33
34/// A read-only reference to a particular [`Entity`] and all of its components.
35///
36/// # Examples
37///
38/// Read-only access disjoint with mutable access.
39///
40/// ```
41/// # use bevy_ecs::prelude::*;
42/// # #[derive(Component)] pub struct A;
43/// # #[derive(Component)] pub struct B;
44/// fn disjoint_system(
45///     query1: Query<&mut A>,
46///     query2: Query<EntityRef, Without<A>>,
47/// ) {
48///     // ...
49/// }
50/// # bevy_ecs::system::assert_is_system(disjoint_system);
51/// ```
52#[derive(Copy, Clone)]
53pub struct EntityRef<'w> {
54    cell: UnsafeEntityCell<'w>,
55}
56
57impl<'w> EntityRef<'w> {
58    /// # Safety
59    /// - `cell` must have permission to read every component of the entity.
60    /// - No mutable accesses to any of the entity's components may exist
61    ///   at the same time as the returned [`EntityRef`].
62    #[inline]
63    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
64        Self { cell }
65    }
66
67    /// Returns the [ID](Entity) of the current entity.
68    #[inline]
69    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
70    pub fn id(&self) -> Entity {
71        self.cell.id()
72    }
73
74    /// Gets metadata indicating the location where the current entity is stored.
75    #[inline]
76    pub fn location(&self) -> EntityLocation {
77        self.cell.location()
78    }
79
80    /// Returns the archetype that the current entity belongs to.
81    #[inline]
82    pub fn archetype(&self) -> &Archetype {
83        self.cell.archetype()
84    }
85
86    /// Returns `true` if the current entity has a component of type `T`.
87    /// Otherwise, this returns `false`.
88    ///
89    /// ## Notes
90    ///
91    /// If you do not know the concrete type of a component, consider using
92    /// [`Self::contains_id`] or [`Self::contains_type_id`].
93    #[inline]
94    pub fn contains<T: Component>(&self) -> bool {
95        self.contains_type_id(TypeId::of::<T>())
96    }
97
98    /// Returns `true` if the current entity has a component identified by `component_id`.
99    /// Otherwise, this returns false.
100    ///
101    /// ## Notes
102    ///
103    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
104    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
105    ///   [`Self::contains_type_id`].
106    #[inline]
107    pub fn contains_id(&self, component_id: ComponentId) -> bool {
108        self.cell.contains_id(component_id)
109    }
110
111    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
112    /// Otherwise, this returns false.
113    ///
114    /// ## Notes
115    ///
116    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
117    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
118    #[inline]
119    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
120        self.cell.contains_type_id(type_id)
121    }
122
123    /// Gets access to the component of type `T` for the current entity.
124    /// Returns `None` if the entity does not have a component of type `T`.
125    #[inline]
126    pub fn get<T: Component>(&self) -> Option<&'w T> {
127        // SAFETY: We have read-only access to all components of this entity.
128        unsafe { self.cell.get::<T>() }
129    }
130
131    /// Gets access to the component of type `T` for the current entity,
132    /// including change detection information as a [`Ref`].
133    ///
134    /// Returns `None` if the entity does not have a component of type `T`.
135    #[inline]
136    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
137        // SAFETY: We have read-only access to all components of this entity.
138        unsafe { self.cell.get_ref::<T>() }
139    }
140
141    /// Retrieves the change ticks for the given component. This can be useful for implementing change
142    /// detection in custom runtimes.
143    #[inline]
144    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
145        // SAFETY: We have read-only access to all components of this entity.
146        unsafe { self.cell.get_change_ticks::<T>() }
147    }
148
149    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
150    /// detection in custom runtimes.
151    ///
152    /// **You should prefer to use the typed API [`EntityRef::get_change_ticks`] where possible and only
153    /// use this in cases where the actual component types are not known at
154    /// compile time.**
155    #[inline]
156    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
157        // SAFETY: We have read-only access to all components of this entity.
158        unsafe { self.cell.get_change_ticks_by_id(component_id) }
159    }
160
161    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
162    /// current entity, based on the given [`ComponentId`]s.
163    ///
164    /// **You should prefer to use the typed API [`EntityRef::get`] where
165    /// possible and only use this in cases where the actual component types
166    /// are not known at compile time.**
167    ///
168    /// Unlike [`EntityRef::get`], this returns untyped reference(s) to
169    /// component(s), and it's the job of the caller to ensure the correct
170    /// type(s) are dereferenced (if necessary).
171    ///
172    /// # Errors
173    ///
174    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
175    /// not have a component.
176    ///
177    /// # Examples
178    ///
179    /// ## Single [`ComponentId`]
180    ///
181    /// ```
182    /// # use bevy_ecs::prelude::*;
183    /// #
184    /// # #[derive(Component, PartialEq, Debug)]
185    /// # pub struct Foo(i32);
186    /// # let mut world = World::new();
187    /// let entity = world.spawn(Foo(42)).id();
188    ///
189    /// // Grab the component ID for `Foo` in whatever way you like.
190    /// let component_id = world.register_component::<Foo>();
191    ///
192    /// // Then, get the component by ID.
193    /// let ptr = world.entity(entity).get_by_id(component_id);
194    /// # assert_eq!(unsafe { ptr.unwrap().deref::<Foo>() }, &Foo(42));
195    /// ```
196    ///
197    /// ## Array of [`ComponentId`]s
198    ///
199    /// ```
200    /// # use bevy_ecs::prelude::*;
201    /// #
202    /// # #[derive(Component, PartialEq, Debug)]
203    /// # pub struct X(i32);
204    /// # #[derive(Component, PartialEq, Debug)]
205    /// # pub struct Y(i32);
206    /// # let mut world = World::new();
207    /// let entity = world.spawn((X(42), Y(10))).id();
208    ///
209    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
210    /// let x_id = world.register_component::<X>();
211    /// let y_id = world.register_component::<Y>();
212    ///
213    /// // Then, get the components by ID. You'll receive a same-sized array.
214    /// let Ok([x_ptr, y_ptr]) = world.entity(entity).get_by_id([x_id, y_id]) else {
215    ///     // Up to you to handle if a component is missing from the entity.
216    /// #   unreachable!();
217    /// };
218    /// # assert_eq!((unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() }), (&X(42), &Y(10)));
219    /// ```
220    ///
221    /// ## Slice of [`ComponentId`]s
222    ///
223    /// ```
224    /// # use bevy_ecs::{prelude::*, component::ComponentId};
225    /// #
226    /// # #[derive(Component, PartialEq, Debug)]
227    /// # pub struct X(i32);
228    /// # #[derive(Component, PartialEq, Debug)]
229    /// # pub struct Y(i32);
230    /// # let mut world = World::new();
231    /// let entity = world.spawn((X(42), Y(10))).id();
232    ///
233    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
234    /// let x_id = world.register_component::<X>();
235    /// let y_id = world.register_component::<Y>();
236    ///
237    /// // Then, get the components by ID. You'll receive a vec of ptrs.
238    /// let ptrs = world.entity(entity).get_by_id(&[x_id, y_id] as &[ComponentId]);
239    /// # let ptrs = ptrs.unwrap();
240    /// # assert_eq!((unsafe { ptrs[0].deref::<X>() }, unsafe { ptrs[1].deref::<Y>() }), (&X(42), &Y(10)));
241    /// ```
242    ///
243    /// ## [`HashSet`] of [`ComponentId`]s
244    ///
245    /// ```
246    /// # use bevy_platform::collections::HashSet;
247    /// # use bevy_ecs::{prelude::*, component::ComponentId};
248    /// #
249    /// # #[derive(Component, PartialEq, Debug)]
250    /// # pub struct X(i32);
251    /// # #[derive(Component, PartialEq, Debug)]
252    /// # pub struct Y(i32);
253    /// # let mut world = World::new();
254    /// let entity = world.spawn((X(42), Y(10))).id();
255    ///
256    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
257    /// let x_id = world.register_component::<X>();
258    /// let y_id = world.register_component::<Y>();
259    ///
260    /// // Then, get the components by ID. You'll receive a vec of ptrs.
261    /// let ptrs = world.entity(entity).get_by_id(&HashSet::from_iter([x_id, y_id]));
262    /// # let ptrs = ptrs.unwrap();
263    /// # assert_eq!((unsafe { ptrs[&x_id].deref::<X>() }, unsafe { ptrs[&y_id].deref::<Y>() }), (&X(42), &Y(10)));
264    /// ```
265    #[inline]
266    pub fn get_by_id<F: DynamicComponentFetch>(
267        &self,
268        component_ids: F,
269    ) -> Result<F::Ref<'w>, EntityComponentError> {
270        // SAFETY: We have read-only access to all components of this entity.
271        unsafe { component_ids.fetch_ref(self.cell) }
272    }
273
274    /// Returns read-only components for the current entity that match the query `Q`.
275    ///
276    /// # Panics
277    ///
278    /// If the entity does not have the components required by the query `Q`.
279    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'w, 'static> {
280        self.get_components::<Q>()
281            .expect("Query does not match the current entity")
282    }
283
284    /// Returns read-only components for the current entity that match the query `Q`,
285    /// or `None` if the entity does not have the components required by the query `Q`.
286    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
287        &self,
288    ) -> Option<Q::Item<'w, 'static>> {
289        // SAFETY:
290        // - We have read-only access to all components of this entity.
291        // - The query is read-only, and read-only references cannot have conflicts.
292        unsafe { self.cell.get_components::<Q>() }
293    }
294
295    /// Returns the source code location from which this entity has been spawned.
296    pub fn spawned_by(&self) -> MaybeLocation {
297        self.cell.spawned_by()
298    }
299
300    /// Returns the [`Tick`] at which this entity has been spawned.
301    pub fn spawn_tick(&self) -> Tick {
302        self.cell.spawn_tick()
303    }
304}
305
306impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w> {
307    fn from(entity: EntityWorldMut<'w>) -> EntityRef<'w> {
308        // SAFETY:
309        // - `EntityWorldMut` guarantees exclusive access to the entire world.
310        unsafe { EntityRef::new(entity.into_unsafe_entity_cell()) }
311    }
312}
313
314impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> {
315    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
316        // SAFETY:
317        // - `EntityWorldMut` guarantees exclusive access to the entire world.
318        // - `&entity` ensures no mutable accesses are active.
319        unsafe { EntityRef::new(entity.as_unsafe_entity_cell_readonly()) }
320    }
321}
322
323impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
324    fn from(entity: EntityMut<'w>) -> Self {
325        // SAFETY:
326        // - `EntityMut` guarantees exclusive access to all of the entity's components.
327        unsafe { EntityRef::new(entity.cell) }
328    }
329}
330
331impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
332    fn from(entity: &'a EntityMut<'_>) -> Self {
333        // SAFETY:
334        // - `EntityMut` guarantees exclusive access to all of the entity's components.
335        // - `&entity` ensures there are no mutable accesses.
336        unsafe { EntityRef::new(entity.cell) }
337    }
338}
339
340impl<'a> TryFrom<FilteredEntityRef<'a, '_>> for EntityRef<'a> {
341    type Error = TryFromFilteredError;
342
343    fn try_from(entity: FilteredEntityRef<'a, '_>) -> Result<Self, Self::Error> {
344        if !entity.access.has_read_all() {
345            Err(TryFromFilteredError::MissingReadAllAccess)
346        } else {
347            // SAFETY: check above guarantees read-only access to all components of the entity.
348            Ok(unsafe { EntityRef::new(entity.entity) })
349        }
350    }
351}
352
353impl<'a> TryFrom<&'a FilteredEntityRef<'_, '_>> for EntityRef<'a> {
354    type Error = TryFromFilteredError;
355
356    fn try_from(entity: &'a FilteredEntityRef<'_, '_>) -> Result<Self, Self::Error> {
357        if !entity.access.has_read_all() {
358            Err(TryFromFilteredError::MissingReadAllAccess)
359        } else {
360            // SAFETY: check above guarantees read-only access to all components of the entity.
361            Ok(unsafe { EntityRef::new(entity.entity) })
362        }
363    }
364}
365
366impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityRef<'a> {
367    type Error = TryFromFilteredError;
368
369    fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
370        if !entity.access.has_read_all() {
371            Err(TryFromFilteredError::MissingReadAllAccess)
372        } else {
373            // SAFETY: check above guarantees read-only access to all components of the entity.
374            Ok(unsafe { EntityRef::new(entity.entity) })
375        }
376    }
377}
378
379impl<'a> TryFrom<&'a FilteredEntityMut<'_, '_>> for EntityRef<'a> {
380    type Error = TryFromFilteredError;
381
382    fn try_from(entity: &'a FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
383        if !entity.access.has_read_all() {
384            Err(TryFromFilteredError::MissingReadAllAccess)
385        } else {
386            // SAFETY: check above guarantees read-only access to all components of the entity.
387            Ok(unsafe { EntityRef::new(entity.entity) })
388        }
389    }
390}
391
392impl PartialEq for EntityRef<'_> {
393    fn eq(&self, other: &Self) -> bool {
394        self.entity() == other.entity()
395    }
396}
397
398impl Eq for EntityRef<'_> {}
399
400impl PartialOrd for EntityRef<'_> {
401    /// [`EntityRef`]'s comparison trait implementations match the underlying [`Entity`],
402    /// and cannot discern between different worlds.
403    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
404        Some(self.cmp(other))
405    }
406}
407
408impl Ord for EntityRef<'_> {
409    fn cmp(&self, other: &Self) -> Ordering {
410        self.entity().cmp(&other.entity())
411    }
412}
413
414impl Hash for EntityRef<'_> {
415    fn hash<H: Hasher>(&self, state: &mut H) {
416        self.entity().hash(state);
417    }
418}
419
420impl ContainsEntity for EntityRef<'_> {
421    fn entity(&self) -> Entity {
422        self.id()
423    }
424}
425
426// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
427unsafe impl EntityEquivalent for EntityRef<'_> {}
428
429/// Provides mutable access to a single entity and all of its components.
430///
431/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
432/// despawning the entity, and provides mutable access to the entire world.
433/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
434///
435/// # Examples
436///
437/// Disjoint mutable access.
438///
439/// ```
440/// # use bevy_ecs::prelude::*;
441/// # #[derive(Component)] pub struct A;
442/// fn disjoint_system(
443///     query1: Query<EntityMut, With<A>>,
444///     query2: Query<EntityMut, Without<A>>,
445/// ) {
446///     // ...
447/// }
448/// # bevy_ecs::system::assert_is_system(disjoint_system);
449/// ```
450pub struct EntityMut<'w> {
451    cell: UnsafeEntityCell<'w>,
452}
453
454impl<'w> EntityMut<'w> {
455    /// # Safety
456    /// - `cell` must have permission to mutate every component of the entity.
457    /// - No accesses to any of the entity's components may exist
458    ///   at the same time as the returned [`EntityMut`].
459    #[inline]
460    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
461        Self { cell }
462    }
463
464    /// Returns a new instance with a shorter lifetime.
465    /// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
466    pub fn reborrow(&mut self) -> EntityMut<'_> {
467        // SAFETY: We have exclusive access to the entire entity and its components.
468        unsafe { Self::new(self.cell) }
469    }
470
471    /// Consumes `self` and returns read-only access to all of the entity's
472    /// components, with the world `'w` lifetime.
473    pub fn into_readonly(self) -> EntityRef<'w> {
474        EntityRef::from(self)
475    }
476
477    /// Gets read-only access to all of the entity's components.
478    pub fn as_readonly(&self) -> EntityRef<'_> {
479        EntityRef::from(self)
480    }
481
482    /// Returns the [ID](Entity) of the current entity.
483    #[inline]
484    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
485    pub fn id(&self) -> Entity {
486        self.cell.id()
487    }
488
489    /// Gets metadata indicating the location where the current entity is stored.
490    #[inline]
491    pub fn location(&self) -> EntityLocation {
492        self.cell.location()
493    }
494
495    /// Returns the archetype that the current entity belongs to.
496    #[inline]
497    pub fn archetype(&self) -> &Archetype {
498        self.cell.archetype()
499    }
500
501    /// Returns `true` if the current entity has a component of type `T`.
502    /// Otherwise, this returns `false`.
503    ///
504    /// ## Notes
505    ///
506    /// If you do not know the concrete type of a component, consider using
507    /// [`Self::contains_id`] or [`Self::contains_type_id`].
508    #[inline]
509    pub fn contains<T: Component>(&self) -> bool {
510        self.contains_type_id(TypeId::of::<T>())
511    }
512
513    /// Returns `true` if the current entity has a component identified by `component_id`.
514    /// Otherwise, this returns false.
515    ///
516    /// ## Notes
517    ///
518    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
519    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
520    ///   [`Self::contains_type_id`].
521    #[inline]
522    pub fn contains_id(&self, component_id: ComponentId) -> bool {
523        self.cell.contains_id(component_id)
524    }
525
526    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
527    /// Otherwise, this returns false.
528    ///
529    /// ## Notes
530    ///
531    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
532    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
533    #[inline]
534    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
535        self.cell.contains_type_id(type_id)
536    }
537
538    /// Gets access to the component of type `T` for the current entity.
539    /// Returns `None` if the entity does not have a component of type `T`.
540    #[inline]
541    pub fn get<T: Component>(&self) -> Option<&'_ T> {
542        self.as_readonly().get()
543    }
544
545    /// Returns read-only components for the current entity that match the query `Q`.
546    ///
547    /// # Panics
548    ///
549    /// If the entity does not have the components required by the query `Q`.
550    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
551        self.as_readonly().components::<Q>()
552    }
553
554    /// Returns read-only components for the current entity that match the query `Q`,
555    /// or `None` if the entity does not have the components required by the query `Q`.
556    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
557        &self,
558    ) -> Option<Q::Item<'_, 'static>> {
559        self.as_readonly().get_components::<Q>()
560    }
561
562    /// Returns components for the current entity that match the query `Q`,
563    /// or `None` if the entity does not have the components required by the query `Q`.
564    ///
565    /// # Example
566    ///
567    /// ```
568    /// # use bevy_ecs::prelude::*;
569    /// #
570    /// #[derive(Component)]
571    /// struct X(usize);
572    /// #[derive(Component)]
573    /// struct Y(usize);
574    ///
575    /// # let mut world = World::default();
576    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
577    /// // Get mutable access to two components at once
578    /// // SAFETY: X and Y are different components
579    /// let (mut x, mut y) =
580    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
581    /// *x = X(1);
582    /// *y = Y(1);
583    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
584    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
585    /// ```
586    ///
587    /// # Safety
588    /// It is the caller's responsibility to ensure that
589    /// the `QueryData` does not provide aliasing mutable references to the same component.
590    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
591        &mut self,
592    ) -> Option<Q::Item<'_, 'static>> {
593        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
594        unsafe { self.reborrow().into_components_mut_unchecked::<Q>() }
595    }
596
597    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
598    /// or `None` if the entity does not have the components required by the query `Q`.
599    ///
600    /// # Example
601    ///
602    /// ```
603    /// # use bevy_ecs::prelude::*;
604    /// #
605    /// #[derive(Component)]
606    /// struct X(usize);
607    /// #[derive(Component)]
608    /// struct Y(usize);
609    ///
610    /// # let mut world = World::default();
611    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
612    /// // Get mutable access to two components at once
613    /// // SAFETY: X and Y are different components
614    /// let (mut x, mut y) =
615    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
616    /// *x = X(1);
617    /// *y = Y(1);
618    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
619    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
620    /// ```
621    ///
622    /// # Safety
623    /// It is the caller's responsibility to ensure that
624    /// the `QueryData` does not provide aliasing mutable references to the same component.
625    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
626        self,
627    ) -> Option<Q::Item<'w, 'static>> {
628        // SAFETY:
629        // - We have mutable access to all components of this entity.
630        // - Caller asserts the `QueryData` does not provide aliasing mutable references to the same component
631        unsafe { self.cell.get_components::<Q>() }
632    }
633
634    /// Consumes `self` and gets access to the component of type `T` with the
635    /// world `'w` lifetime for the current entity.
636    ///
637    /// Returns `None` if the entity does not have a component of type `T`.
638    #[inline]
639    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
640        self.into_readonly().get()
641    }
642
643    /// Gets access to the component of type `T` for the current entity,
644    /// including change detection information as a [`Ref`].
645    ///
646    /// Returns `None` if the entity does not have a component of type `T`.
647    #[inline]
648    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
649        self.as_readonly().get_ref()
650    }
651
652    /// Consumes `self` and gets access to the component of type `T` with world
653    /// `'w` lifetime for the current entity, including change detection information
654    /// as a [`Ref<'w>`].
655    ///
656    /// Returns `None` if the entity does not have a component of type `T`.
657    #[inline]
658    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
659        self.into_readonly().get_ref()
660    }
661
662    /// Gets mutable access to the component of type `T` for the current entity.
663    /// Returns `None` if the entity does not have a component of type `T`.
664    #[inline]
665    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
666        // SAFETY: &mut self implies exclusive access for duration of returned value
667        unsafe { self.cell.get_mut() }
668    }
669
670    /// Gets mutable access to the component of type `T` for the current entity.
671    /// Returns `None` if the entity does not have a component of type `T`.
672    ///
673    /// # Safety
674    ///
675    /// - `T` must be a mutable component
676    #[inline]
677    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
678        // SAFETY:
679        // - &mut self implies exclusive access for duration of returned value
680        // - Caller ensures `T` is a mutable component
681        unsafe { self.cell.get_mut_assume_mutable() }
682    }
683
684    /// Consumes self and gets mutable access to the component of type `T`
685    /// with the world `'w` lifetime for the current entity.
686    /// Returns `None` if the entity does not have a component of type `T`.
687    #[inline]
688    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
689        // SAFETY: consuming `self` implies exclusive access
690        unsafe { self.cell.get_mut() }
691    }
692
693    /// Gets mutable access to the component of type `T` for the current entity.
694    /// Returns `None` if the entity does not have a component of type `T`.
695    ///
696    /// # Safety
697    ///
698    /// - `T` must be a mutable component
699    #[inline]
700    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
701        // SAFETY:
702        // - Consuming `self` implies exclusive access
703        // - Caller ensures `T` is a mutable component
704        unsafe { self.cell.get_mut_assume_mutable() }
705    }
706
707    /// Retrieves the change ticks for the given component. This can be useful for implementing change
708    /// detection in custom runtimes.
709    #[inline]
710    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
711        self.as_readonly().get_change_ticks::<T>()
712    }
713
714    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
715    /// detection in custom runtimes.
716    ///
717    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
718    /// use this in cases where the actual component types are not known at
719    /// compile time.**
720    #[inline]
721    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
722        self.as_readonly().get_change_ticks_by_id(component_id)
723    }
724
725    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
726    /// current entity, based on the given [`ComponentId`]s.
727    ///
728    /// **You should prefer to use the typed API [`EntityMut::get`] where
729    /// possible and only use this in cases where the actual component types
730    /// are not known at compile time.**
731    ///
732    /// Unlike [`EntityMut::get`], this returns untyped reference(s) to
733    /// component(s), and it's the job of the caller to ensure the correct
734    /// type(s) are dereferenced (if necessary).
735    ///
736    /// # Errors
737    ///
738    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
739    /// not have a component.
740    ///
741    /// # Examples
742    ///
743    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
744    #[inline]
745    pub fn get_by_id<F: DynamicComponentFetch>(
746        &self,
747        component_ids: F,
748    ) -> Result<F::Ref<'_>, EntityComponentError> {
749        self.as_readonly().get_by_id(component_ids)
750    }
751
752    /// Consumes `self` and returns [untyped read-only reference(s)](Ptr) to
753    /// component(s) with lifetime `'w` for the current entity, based on the
754    /// given [`ComponentId`]s.
755    ///
756    /// **You should prefer to use the typed API [`EntityMut::into_borrow`]
757    /// where possible and only use this in cases where the actual component
758    /// types are not known at compile time.**
759    ///
760    /// Unlike [`EntityMut::into_borrow`], this returns untyped reference(s) to
761    /// component(s), and it's the job of the caller to ensure the correct
762    /// type(s) are dereferenced (if necessary).
763    ///
764    /// # Errors
765    ///
766    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
767    /// not have a component.
768    ///
769    /// # Examples
770    ///
771    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
772    #[inline]
773    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
774        self,
775        component_ids: F,
776    ) -> Result<F::Ref<'w>, EntityComponentError> {
777        self.into_readonly().get_by_id(component_ids)
778    }
779
780    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
781    /// the current entity, based on the given [`ComponentId`]s.
782    ///
783    /// **You should prefer to use the typed API [`EntityMut::get_mut`] where
784    /// possible and only use this in cases where the actual component types
785    /// are not known at compile time.**
786    ///
787    /// Unlike [`EntityMut::get_mut`], this returns untyped reference(s) to
788    /// component(s), and it's the job of the caller to ensure the correct
789    /// type(s) are dereferenced (if necessary).
790    ///
791    /// # Errors
792    ///
793    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
794    ///   not have a component.
795    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
796    ///   is requested multiple times.
797    ///
798    /// # Examples
799    ///
800    /// ## Single [`ComponentId`]
801    ///
802    /// ```
803    /// # use bevy_ecs::prelude::*;
804    /// #
805    /// # #[derive(Component, PartialEq, Debug)]
806    /// # pub struct Foo(i32);
807    /// # let mut world = World::new();
808    /// let entity = world.spawn(Foo(42)).id();
809    ///
810    /// // Grab the component ID for `Foo` in whatever way you like.
811    /// let component_id = world.register_component::<Foo>();
812    ///
813    /// // Then, get the component by ID.
814    /// let mut entity_mut = world.entity_mut(entity);
815    /// let mut ptr = entity_mut.get_mut_by_id(component_id)
816    /// #   .unwrap();
817    /// # assert_eq!(unsafe { ptr.as_mut().deref_mut::<Foo>() }, &mut Foo(42));
818    /// ```
819    ///
820    /// ## Array of [`ComponentId`]s
821    ///
822    /// ```
823    /// # use bevy_ecs::prelude::*;
824    /// #
825    /// # #[derive(Component, PartialEq, Debug)]
826    /// # pub struct X(i32);
827    /// # #[derive(Component, PartialEq, Debug)]
828    /// # pub struct Y(i32);
829    /// # let mut world = World::new();
830    /// let entity = world.spawn((X(42), Y(10))).id();
831    ///
832    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
833    /// let x_id = world.register_component::<X>();
834    /// let y_id = world.register_component::<Y>();
835    ///
836    /// // Then, get the components by ID. You'll receive a same-sized array.
837    /// let mut entity_mut = world.entity_mut(entity);
838    /// let Ok([mut x_ptr, mut y_ptr]) = entity_mut.get_mut_by_id([x_id, y_id]) else {
839    ///     // Up to you to handle if a component is missing from the entity.
840    /// #   unreachable!();
841    /// };
842    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
843    /// ```
844    ///
845    /// ## Slice of [`ComponentId`]s
846    ///
847    /// ```
848    /// # use bevy_ecs::{prelude::*, component::ComponentId, change_detection::MutUntyped};
849    /// #
850    /// # #[derive(Component, PartialEq, Debug)]
851    /// # pub struct X(i32);
852    /// # #[derive(Component, PartialEq, Debug)]
853    /// # pub struct Y(i32);
854    /// # let mut world = World::new();
855    /// let entity = world.spawn((X(42), Y(10))).id();
856    ///
857    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
858    /// let x_id = world.register_component::<X>();
859    /// let y_id = world.register_component::<Y>();
860    ///
861    /// // Then, get the components by ID. You'll receive a vec of ptrs.
862    /// let mut entity_mut = world.entity_mut(entity);
863    /// let ptrs = entity_mut.get_mut_by_id(&[x_id, y_id] as &[ComponentId])
864    /// #   .unwrap();
865    /// # let [mut x_ptr, mut y_ptr]: [MutUntyped; 2] = ptrs.try_into().unwrap();
866    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
867    /// ```
868    ///
869    /// ## [`HashSet`] of [`ComponentId`]s
870    ///
871    /// ```
872    /// # use bevy_platform::collections::HashSet;
873    /// # use bevy_ecs::{prelude::*, component::ComponentId};
874    /// #
875    /// # #[derive(Component, PartialEq, Debug)]
876    /// # pub struct X(i32);
877    /// # #[derive(Component, PartialEq, Debug)]
878    /// # pub struct Y(i32);
879    /// # let mut world = World::new();
880    /// let entity = world.spawn((X(42), Y(10))).id();
881    ///
882    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
883    /// let x_id = world.register_component::<X>();
884    /// let y_id = world.register_component::<Y>();
885    ///
886    /// // Then, get the components by ID. You'll receive a `HashMap` of ptrs.
887    /// let mut entity_mut = world.entity_mut(entity);
888    /// let mut ptrs = entity_mut.get_mut_by_id(&HashSet::from_iter([x_id, y_id]))
889    /// #   .unwrap();
890    /// # let [Some(mut x_ptr), Some(mut y_ptr)] = ptrs.get_many_mut([&x_id, &y_id]) else { unreachable!() };
891    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
892    /// ```
893    #[inline]
894    pub fn get_mut_by_id<F: DynamicComponentFetch>(
895        &mut self,
896        component_ids: F,
897    ) -> Result<F::Mut<'_>, EntityComponentError> {
898        // SAFETY:
899        // - `&mut self` ensures that no references exist to this entity's components.
900        // - We have exclusive access to all components of this entity.
901        unsafe { component_ids.fetch_mut(self.cell) }
902    }
903
904    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
905    /// the current entity, based on the given [`ComponentId`]s.
906    /// Assumes the given [`ComponentId`]s refer to mutable components.
907    ///
908    /// **You should prefer to use the typed API [`EntityMut::get_mut_assume_mutable`] where
909    /// possible and only use this in cases where the actual component types
910    /// are not known at compile time.**
911    ///
912    /// Unlike [`EntityMut::get_mut_assume_mutable`], this returns untyped reference(s) to
913    /// component(s), and it's the job of the caller to ensure the correct
914    /// type(s) are dereferenced (if necessary).
915    ///
916    /// # Errors
917    ///
918    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
919    ///   not have a component.
920    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
921    ///   is requested multiple times.
922    ///
923    /// # Safety
924    /// It is the callers responsibility to ensure that
925    /// - the provided [`ComponentId`]s must refer to mutable components.
926    #[inline]
927    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
928        &mut self,
929        component_ids: F,
930    ) -> Result<F::Mut<'_>, EntityComponentError> {
931        // SAFETY:
932        // - `&mut self` ensures that no references exist to this entity's components.
933        // - We have exclusive access to all components of this entity.
934        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
935    }
936
937    /// Returns [untyped mutable reference](MutUntyped) to component for
938    /// the current entity, based on the given [`ComponentId`].
939    ///
940    /// Unlike [`EntityMut::get_mut_by_id`], this method borrows &self instead of
941    /// &mut self, allowing the caller to access multiple components simultaneously.
942    ///
943    /// # Errors
944    ///
945    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
946    ///   not have a component.
947    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
948    ///   is requested multiple times.
949    ///
950    /// # Safety
951    /// It is the callers responsibility to ensure that
952    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
953    /// - no other references to the component exist at the same time
954    #[inline]
955    pub unsafe fn get_mut_by_id_unchecked<F: DynamicComponentFetch>(
956        &self,
957        component_ids: F,
958    ) -> Result<F::Mut<'_>, EntityComponentError> {
959        // SAFETY:
960        // - The caller must ensure simultaneous access is limited
961        // - to components that are mutually independent.
962        unsafe { component_ids.fetch_mut(self.cell) }
963    }
964
965    /// Returns [untyped mutable reference](MutUntyped) to component for
966    /// the current entity, based on the given [`ComponentId`].
967    /// Assumes the given [`ComponentId`]s refer to mutable components.
968    ///
969    /// Unlike [`EntityMut::get_mut_assume_mutable_by_id`], this method borrows &self instead of
970    /// &mut self, allowing the caller to access multiple components simultaneously.
971    ///
972    /// # Errors
973    ///
974    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
975    ///   not have a component.
976    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
977    ///   is requested multiple times.
978    ///
979    /// # Safety
980    /// It is the callers responsibility to ensure that
981    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
982    /// - no other references to the component exist at the same time
983    /// - the provided [`ComponentId`]s must refer to mutable components.
984    #[inline]
985    pub unsafe fn get_mut_assume_mutable_by_id_unchecked<F: DynamicComponentFetch>(
986        &self,
987        component_ids: F,
988    ) -> Result<F::Mut<'_>, EntityComponentError> {
989        // SAFETY:
990        // - The caller must ensure simultaneous access is limited
991        // - to components that are mutually independent.
992        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
993    }
994
995    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
996    /// to component(s) with lifetime `'w` for the current entity, based on the
997    /// given [`ComponentId`]s.
998    ///
999    /// **You should prefer to use the typed API [`EntityMut::into_mut`] where
1000    /// possible and only use this in cases where the actual component types
1001    /// are not known at compile time.**
1002    ///
1003    /// Unlike [`EntityMut::into_mut`], this returns untyped reference(s) to
1004    /// component(s), and it's the job of the caller to ensure the correct
1005    /// type(s) are dereferenced (if necessary).
1006    ///
1007    /// # Errors
1008    ///
1009    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1010    ///   not have a component.
1011    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1012    ///   is requested multiple times.
1013    ///
1014    /// # Examples
1015    ///
1016    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1017    #[inline]
1018    pub fn into_mut_by_id<F: DynamicComponentFetch>(
1019        self,
1020        component_ids: F,
1021    ) -> Result<F::Mut<'w>, EntityComponentError> {
1022        // SAFETY:
1023        // - consuming `self` ensures that no references exist to this entity's components.
1024        // - We have exclusive access to all components of this entity.
1025        unsafe { component_ids.fetch_mut(self.cell) }
1026    }
1027
1028    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1029    /// to component(s) with lifetime `'w` for the current entity, based on the
1030    /// given [`ComponentId`]s.
1031    /// Assumes the given [`ComponentId`]s refer to mutable components.
1032    ///
1033    /// **You should prefer to use the typed API [`EntityMut::into_mut_assume_mutable`] where
1034    /// possible and only use this in cases where the actual component types
1035    /// are not known at compile time.**
1036    ///
1037    /// Unlike [`EntityMut::into_mut_assume_mutable`], this returns untyped reference(s) to
1038    /// component(s), and it's the job of the caller to ensure the correct
1039    /// type(s) are dereferenced (if necessary).
1040    ///
1041    /// # Errors
1042    ///
1043    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1044    ///   not have a component.
1045    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1046    ///   is requested multiple times.
1047    ///
1048    /// # Safety
1049    /// It is the callers responsibility to ensure that
1050    /// - the provided [`ComponentId`]s must refer to mutable components.
1051    #[inline]
1052    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1053        self,
1054        component_ids: F,
1055    ) -> Result<F::Mut<'w>, EntityComponentError> {
1056        // SAFETY:
1057        // - consuming `self` ensures that no references exist to this entity's components.
1058        // - We have exclusive access to all components of this entity.
1059        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
1060    }
1061
1062    /// Returns the source code location from which this entity has been spawned.
1063    pub fn spawned_by(&self) -> MaybeLocation {
1064        self.cell.spawned_by()
1065    }
1066
1067    /// Returns the [`Tick`] at which this entity has been spawned.
1068    pub fn spawn_tick(&self) -> Tick {
1069        self.cell.spawn_tick()
1070    }
1071}
1072
1073impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
1074    fn from(entity: &'w mut EntityMut<'_>) -> Self {
1075        entity.reborrow()
1076    }
1077}
1078
1079impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w> {
1080    fn from(entity: EntityWorldMut<'w>) -> Self {
1081        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
1082        unsafe { EntityMut::new(entity.into_unsafe_entity_cell()) }
1083    }
1084}
1085
1086impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a> {
1087    #[inline]
1088    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
1089        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
1090        unsafe { EntityMut::new(entity.as_unsafe_entity_cell()) }
1091    }
1092}
1093
1094impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityMut<'a> {
1095    type Error = TryFromFilteredError;
1096
1097    fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
1098        if !entity.access.has_read_all() {
1099            Err(TryFromFilteredError::MissingReadAllAccess)
1100        } else if !entity.access.has_write_all() {
1101            Err(TryFromFilteredError::MissingWriteAllAccess)
1102        } else {
1103            // SAFETY: check above guarantees exclusive access to all components of the entity.
1104            Ok(unsafe { EntityMut::new(entity.entity) })
1105        }
1106    }
1107}
1108
1109impl<'a> TryFrom<&'a mut FilteredEntityMut<'_, '_>> for EntityMut<'a> {
1110    type Error = TryFromFilteredError;
1111
1112    fn try_from(entity: &'a mut FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
1113        if !entity.access.has_read_all() {
1114            Err(TryFromFilteredError::MissingReadAllAccess)
1115        } else if !entity.access.has_write_all() {
1116            Err(TryFromFilteredError::MissingWriteAllAccess)
1117        } else {
1118            // SAFETY: check above guarantees exclusive access to all components of the entity.
1119            Ok(unsafe { EntityMut::new(entity.entity) })
1120        }
1121    }
1122}
1123
1124impl PartialEq for EntityMut<'_> {
1125    fn eq(&self, other: &Self) -> bool {
1126        self.entity() == other.entity()
1127    }
1128}
1129
1130impl Eq for EntityMut<'_> {}
1131
1132impl PartialOrd for EntityMut<'_> {
1133    /// [`EntityMut`]'s comparison trait implementations match the underlying [`Entity`],
1134    /// and cannot discern between different worlds.
1135    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1136        Some(self.cmp(other))
1137    }
1138}
1139
1140impl Ord for EntityMut<'_> {
1141    fn cmp(&self, other: &Self) -> Ordering {
1142        self.entity().cmp(&other.entity())
1143    }
1144}
1145
1146impl Hash for EntityMut<'_> {
1147    fn hash<H: Hasher>(&self, state: &mut H) {
1148        self.entity().hash(state);
1149    }
1150}
1151
1152impl ContainsEntity for EntityMut<'_> {
1153    fn entity(&self) -> Entity {
1154        self.id()
1155    }
1156}
1157
1158// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
1159unsafe impl EntityEquivalent for EntityMut<'_> {}
1160
1161/// A mutable reference to a particular [`Entity`], and the entire world.
1162///
1163/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
1164/// which caches the [`EntityLocation`] to reduce duplicate lookups.
1165///
1166/// Since this type provides mutable access to the entire world, only one
1167/// [`EntityWorldMut`] can exist at a time for a given world.
1168///
1169/// See also [`EntityMut`], which allows disjoint mutable access to multiple
1170/// entities at once.  Unlike `EntityMut`, this type allows adding and
1171/// removing components, and despawning the entity.
1172pub struct EntityWorldMut<'w> {
1173    world: &'w mut World,
1174    entity: Entity,
1175    location: EntityIdLocation,
1176}
1177
1178impl<'w> EntityWorldMut<'w> {
1179    #[track_caller]
1180    #[inline(never)]
1181    #[cold]
1182    fn panic_despawned(&self) -> ! {
1183        panic!(
1184            "Entity {} {}",
1185            self.entity,
1186            self.world
1187                .entities()
1188                .entity_does_not_exist_error_details(self.entity)
1189        );
1190    }
1191
1192    #[inline(always)]
1193    #[track_caller]
1194    pub(crate) fn assert_not_despawned(&self) {
1195        if self.location.is_none() {
1196            self.panic_despawned()
1197        }
1198    }
1199
1200    #[inline(always)]
1201    fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
1202        let location = self.location();
1203        let last_change_tick = self.world.last_change_tick;
1204        let change_tick = self.world.read_change_tick();
1205        UnsafeEntityCell::new(
1206            self.world.as_unsafe_world_cell_readonly(),
1207            self.entity,
1208            location,
1209            last_change_tick,
1210            change_tick,
1211        )
1212    }
1213
1214    #[inline(always)]
1215    fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
1216        let location = self.location();
1217        let last_change_tick = self.world.last_change_tick;
1218        let change_tick = self.world.change_tick();
1219        UnsafeEntityCell::new(
1220            self.world.as_unsafe_world_cell(),
1221            self.entity,
1222            location,
1223            last_change_tick,
1224            change_tick,
1225        )
1226    }
1227
1228    #[inline(always)]
1229    fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
1230        let location = self.location();
1231        let last_change_tick = self.world.last_change_tick;
1232        let change_tick = self.world.change_tick();
1233        UnsafeEntityCell::new(
1234            self.world.as_unsafe_world_cell(),
1235            self.entity,
1236            location,
1237            last_change_tick,
1238            change_tick,
1239        )
1240    }
1241
1242    /// # Safety
1243    ///
1244    ///  - `entity` must be valid for `world`: the generation should match that of the entity at the same index.
1245    ///  - `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`
1246    ///
1247    ///  The above is trivially satisfied if `location` was sourced from `world.entities().get(entity)`.
1248    #[inline]
1249    pub(crate) unsafe fn new(
1250        world: &'w mut World,
1251        entity: Entity,
1252        location: Option<EntityLocation>,
1253    ) -> Self {
1254        debug_assert!(world.entities().contains(entity));
1255        debug_assert_eq!(world.entities().get(entity), location);
1256
1257        EntityWorldMut {
1258            world,
1259            entity,
1260            location,
1261        }
1262    }
1263
1264    /// Consumes `self` and returns read-only access to all of the entity's
1265    /// components, with the world `'w` lifetime.
1266    pub fn into_readonly(self) -> EntityRef<'w> {
1267        EntityRef::from(self)
1268    }
1269
1270    /// Gets read-only access to all of the entity's components.
1271    #[inline]
1272    pub fn as_readonly(&self) -> EntityRef<'_> {
1273        EntityRef::from(self)
1274    }
1275
1276    /// Consumes `self` and returns non-structural mutable access to all of the
1277    /// entity's components, with the world `'w` lifetime.
1278    pub fn into_mutable(self) -> EntityMut<'w> {
1279        EntityMut::from(self)
1280    }
1281
1282    /// Gets non-structural mutable access to all of the entity's components.
1283    #[inline]
1284    pub fn as_mutable(&mut self) -> EntityMut<'_> {
1285        EntityMut::from(self)
1286    }
1287
1288    /// Returns the [ID](Entity) of the current entity.
1289    #[inline]
1290    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
1291    pub fn id(&self) -> Entity {
1292        self.entity
1293    }
1294
1295    /// Gets metadata indicating the location where the current entity is stored.
1296    ///
1297    /// # Panics
1298    ///
1299    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1300    #[inline]
1301    pub fn location(&self) -> EntityLocation {
1302        match self.location {
1303            Some(loc) => loc,
1304            None => self.panic_despawned(),
1305        }
1306    }
1307
1308    /// Returns the archetype that the current entity belongs to.
1309    ///
1310    /// # Panics
1311    ///
1312    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1313    #[inline]
1314    pub fn archetype(&self) -> &Archetype {
1315        let location = self.location();
1316        &self.world.archetypes[location.archetype_id]
1317    }
1318
1319    /// Returns `true` if the current entity has a component of type `T`.
1320    /// Otherwise, this returns `false`.
1321    ///
1322    /// ## Notes
1323    ///
1324    /// If you do not know the concrete type of a component, consider using
1325    /// [`Self::contains_id`] or [`Self::contains_type_id`].
1326    ///
1327    /// # Panics
1328    ///
1329    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1330    #[inline]
1331    pub fn contains<T: Component>(&self) -> bool {
1332        self.contains_type_id(TypeId::of::<T>())
1333    }
1334
1335    /// Returns `true` if the current entity has a component identified by `component_id`.
1336    /// Otherwise, this returns false.
1337    ///
1338    /// ## Notes
1339    ///
1340    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1341    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
1342    ///   [`Self::contains_type_id`].
1343    ///
1344    /// # Panics
1345    ///
1346    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1347    #[inline]
1348    pub fn contains_id(&self, component_id: ComponentId) -> bool {
1349        self.as_unsafe_entity_cell_readonly()
1350            .contains_id(component_id)
1351    }
1352
1353    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
1354    /// Otherwise, this returns false.
1355    ///
1356    /// ## Notes
1357    ///
1358    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1359    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
1360    ///
1361    /// # Panics
1362    ///
1363    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1364    #[inline]
1365    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
1366        self.as_unsafe_entity_cell_readonly()
1367            .contains_type_id(type_id)
1368    }
1369
1370    /// Gets access to the component of type `T` for the current entity.
1371    /// Returns `None` if the entity does not have a component of type `T`.
1372    ///
1373    /// # Panics
1374    ///
1375    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1376    #[inline]
1377    pub fn get<T: Component>(&self) -> Option<&'_ T> {
1378        self.as_readonly().get()
1379    }
1380
1381    /// Returns read-only components for the current entity that match the query `Q`.
1382    ///
1383    /// # Panics
1384    ///
1385    /// If the entity does not have the components required by the query `Q` or if the entity
1386    /// has been despawned while this `EntityWorldMut` is still alive.
1387    #[inline]
1388    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
1389        self.as_readonly().components::<Q>()
1390    }
1391
1392    /// Returns read-only components for the current entity that match the query `Q`,
1393    /// or `None` if the entity does not have the components required by the query `Q`.
1394    ///
1395    /// # Panics
1396    ///
1397    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1398    #[inline]
1399    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
1400        &self,
1401    ) -> Option<Q::Item<'_, 'static>> {
1402        self.as_readonly().get_components::<Q>()
1403    }
1404
1405    /// Returns components for the current entity that match the query `Q`,
1406    /// or `None` if the entity does not have the components required by the query `Q`.
1407    ///
1408    /// # Example
1409    ///
1410    /// ```
1411    /// # use bevy_ecs::prelude::*;
1412    /// #
1413    /// #[derive(Component)]
1414    /// struct X(usize);
1415    /// #[derive(Component)]
1416    /// struct Y(usize);
1417    ///
1418    /// # let mut world = World::default();
1419    /// let mut entity = world.spawn((X(0), Y(0)));
1420    /// // Get mutable access to two components at once
1421    /// // SAFETY: X and Y are different components
1422    /// let (mut x, mut y) =
1423    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
1424    /// *x = X(1);
1425    /// *y = Y(1);
1426    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
1427    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
1428    /// ```
1429    ///
1430    /// # Safety
1431    /// It is the caller's responsibility to ensure that
1432    /// the `QueryData` does not provide aliasing mutable references to the same component.
1433    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
1434        &mut self,
1435    ) -> Option<Q::Item<'_, 'static>> {
1436        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
1437        unsafe { self.as_mutable().into_components_mut_unchecked::<Q>() }
1438    }
1439
1440    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
1441    /// or `None` if the entity does not have the components required by the query `Q`.
1442    ///
1443    /// # Example
1444    ///
1445    /// ```
1446    /// # use bevy_ecs::prelude::*;
1447    /// #
1448    /// #[derive(Component)]
1449    /// struct X(usize);
1450    /// #[derive(Component)]
1451    /// struct Y(usize);
1452    ///
1453    /// # let mut world = World::default();
1454    /// let mut entity = world.spawn((X(0), Y(0)));
1455    /// // Get mutable access to two components at once
1456    /// // SAFETY: X and Y are different components
1457    /// let (mut x, mut y) =
1458    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
1459    /// *x = X(1);
1460    /// *y = Y(1);
1461    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
1462    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
1463    /// ```
1464    ///
1465    /// # Safety
1466    /// It is the caller's responsibility to ensure that
1467    /// the `QueryData` does not provide aliasing mutable references to the same component.
1468    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
1469        self,
1470    ) -> Option<Q::Item<'w, 'static>> {
1471        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
1472        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
1473    }
1474
1475    /// Consumes `self` and gets access to the component of type `T` with
1476    /// the world `'w` lifetime for the current entity.
1477    /// Returns `None` if the entity does not have a component of type `T`.
1478    ///
1479    /// # Panics
1480    ///
1481    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1482    #[inline]
1483    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
1484        self.into_readonly().get()
1485    }
1486
1487    /// Gets access to the component of type `T` for the current entity,
1488    /// including change detection information as a [`Ref`].
1489    ///
1490    /// Returns `None` if the entity does not have a component of type `T`.
1491    ///
1492    /// # Panics
1493    ///
1494    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1495    #[inline]
1496    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
1497        self.as_readonly().get_ref()
1498    }
1499
1500    /// Consumes `self` and gets access to the component of type `T`
1501    /// with the world `'w` lifetime for the current entity,
1502    /// including change detection information as a [`Ref`].
1503    ///
1504    /// Returns `None` if the entity does not have a component of type `T`.
1505    ///
1506    /// # Panics
1507    ///
1508    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1509    #[inline]
1510    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
1511        self.into_readonly().get_ref()
1512    }
1513
1514    /// Gets mutable access to the component of type `T` for the current entity.
1515    /// Returns `None` if the entity does not have a component of type `T`.
1516    ///
1517    /// # Panics
1518    ///
1519    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1520    #[inline]
1521    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
1522        self.as_mutable().into_mut()
1523    }
1524
1525    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
1526    /// provided closure on it, returning the result if `T` was available.
1527    /// This will trigger the `Remove` and `Replace` component hooks without
1528    /// causing an archetype move.
1529    ///
1530    /// This is most useful with immutable components, where removal and reinsertion
1531    /// is the only way to modify a value.
1532    ///
1533    /// If you do not need to ensure the above hooks are triggered, and your component
1534    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
1535    ///
1536    /// # Examples
1537    ///
1538    /// ```rust
1539    /// # use bevy_ecs::prelude::*;
1540    /// #
1541    /// #[derive(Component, PartialEq, Eq, Debug)]
1542    /// #[component(immutable)]
1543    /// struct Foo(bool);
1544    ///
1545    /// # let mut world = World::default();
1546    /// # world.register_component::<Foo>();
1547    /// #
1548    /// # let entity = world.spawn(Foo(false)).id();
1549    /// #
1550    /// # let mut entity = world.entity_mut(entity);
1551    /// #
1552    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
1553    /// #
1554    /// entity.modify_component(|foo: &mut Foo| {
1555    ///     foo.0 = true;
1556    /// });
1557    /// #
1558    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
1559    /// ```
1560    ///
1561    /// # Panics
1562    ///
1563    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1564    #[inline]
1565    pub fn modify_component<T: Component, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
1566        self.assert_not_despawned();
1567
1568        let result = self
1569            .world
1570            .modify_component(self.entity, f)
1571            .expect("entity access must be valid")?;
1572
1573        self.update_location();
1574
1575        Some(result)
1576    }
1577
1578    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
1579    /// provided closure on it, returning the result if `T` was available.
1580    /// This will trigger the `Remove` and `Replace` component hooks without
1581    /// causing an archetype move.
1582    ///
1583    /// This is most useful with immutable components, where removal and reinsertion
1584    /// is the only way to modify a value.
1585    ///
1586    /// If you do not need to ensure the above hooks are triggered, and your component
1587    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
1588    ///
1589    /// # Panics
1590    ///
1591    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1592    #[inline]
1593    pub fn modify_component_by_id<R>(
1594        &mut self,
1595        component_id: ComponentId,
1596        f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
1597    ) -> Option<R> {
1598        self.assert_not_despawned();
1599
1600        let result = self
1601            .world
1602            .modify_component_by_id(self.entity, component_id, f)
1603            .expect("entity access must be valid")?;
1604
1605        self.update_location();
1606
1607        Some(result)
1608    }
1609
1610    /// Gets mutable access to the component of type `T` for the current entity.
1611    /// Returns `None` if the entity does not have a component of type `T`.
1612    ///
1613    /// # Safety
1614    ///
1615    /// - `T` must be a mutable component
1616    #[inline]
1617    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
1618        self.as_mutable().into_mut_assume_mutable()
1619    }
1620
1621    /// Consumes `self` and gets mutable access to the component of type `T`
1622    /// with the world `'w` lifetime for the current entity.
1623    /// Returns `None` if the entity does not have a component of type `T`.
1624    ///
1625    /// # Panics
1626    ///
1627    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1628    #[inline]
1629    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
1630        // SAFETY: consuming `self` implies exclusive access
1631        unsafe { self.into_unsafe_entity_cell().get_mut() }
1632    }
1633
1634    /// Consumes `self` and gets mutable access to the component of type `T`
1635    /// with the world `'w` lifetime for the current entity.
1636    /// Returns `None` if the entity does not have a component of type `T`.
1637    ///
1638    /// # Panics
1639    ///
1640    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1641    ///
1642    /// # Safety
1643    ///
1644    /// - `T` must be a mutable component
1645    #[inline]
1646    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
1647        // SAFETY: consuming `self` implies exclusive access
1648        unsafe { self.into_unsafe_entity_cell().get_mut_assume_mutable() }
1649    }
1650
1651    /// Gets a reference to the resource of the given type
1652    ///
1653    /// # Panics
1654    ///
1655    /// Panics if the resource does not exist.
1656    /// Use [`get_resource`](EntityWorldMut::get_resource) instead if you want to handle this case.
1657    #[inline]
1658    #[track_caller]
1659    pub fn resource<R: Resource>(&self) -> &R {
1660        self.world.resource::<R>()
1661    }
1662
1663    /// Gets a mutable reference to the resource of the given type
1664    ///
1665    /// # Panics
1666    ///
1667    /// Panics if the resource does not exist.
1668    /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
1669    ///
1670    /// If you want to instead insert a value if the resource does not exist,
1671    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
1672    #[inline]
1673    #[track_caller]
1674    pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
1675        self.world.resource_mut::<R>()
1676    }
1677
1678    /// Gets a reference to the resource of the given type if it exists
1679    #[inline]
1680    pub fn get_resource<R: Resource>(&self) -> Option<&R> {
1681        self.world.get_resource()
1682    }
1683
1684    /// Gets a mutable reference to the resource of the given type if it exists
1685    #[inline]
1686    pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
1687        self.world.get_resource_mut()
1688    }
1689
1690    /// Temporarily removes the requested resource from the [`World`], runs custom user code,
1691    /// then re-adds the resource before returning.
1692    ///
1693    /// # Panics
1694    ///
1695    /// Panics if the resource does not exist.
1696    /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
1697    ///
1698    /// See [`World::resource_scope`] for further details.
1699    #[track_caller]
1700    pub fn resource_scope<R: Resource, U>(
1701        &mut self,
1702        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
1703    ) -> U {
1704        let id = self.id();
1705        self.world_scope(|world| {
1706            world.resource_scope(|world, res| {
1707                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
1708                // the outer `world_scope` will handle updating our location if it gets changed by the user code
1709                let mut this = world.entity_mut(id);
1710                f(&mut this, res)
1711            })
1712        })
1713    }
1714
1715    /// Temporarily removes the requested resource from the [`World`] if it exists, runs custom user code,
1716    /// then re-adds the resource before returning. Returns `None` if the resource does not exist in the [`World`].
1717    ///
1718    /// See [`World::try_resource_scope`] for further details.
1719    pub fn try_resource_scope<R: Resource, U>(
1720        &mut self,
1721        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
1722    ) -> Option<U> {
1723        let id = self.id();
1724        self.world_scope(|world| {
1725            world.try_resource_scope(|world, res| {
1726                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
1727                // the outer `world_scope` will handle updating our location if it gets changed by the user code
1728                let mut this = world.entity_mut(id);
1729                f(&mut this, res)
1730            })
1731        })
1732    }
1733
1734    /// Retrieves the change ticks for the given component. This can be useful for implementing change
1735    /// detection in custom runtimes.
1736    ///
1737    /// # Panics
1738    ///
1739    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1740    #[inline]
1741    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
1742        self.as_readonly().get_change_ticks::<T>()
1743    }
1744
1745    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
1746    /// detection in custom runtimes.
1747    ///
1748    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
1749    /// use this in cases where the actual component types are not known at
1750    /// compile time.**
1751    ///
1752    /// # Panics
1753    ///
1754    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1755    #[inline]
1756    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
1757        self.as_readonly().get_change_ticks_by_id(component_id)
1758    }
1759
1760    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
1761    /// current entity, based on the given [`ComponentId`]s.
1762    ///
1763    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where
1764    /// possible and only use this in cases where the actual component types
1765    /// are not known at compile time.**
1766    ///
1767    /// Unlike [`EntityWorldMut::get`], this returns untyped reference(s) to
1768    /// component(s), and it's the job of the caller to ensure the correct
1769    /// type(s) are dereferenced (if necessary).
1770    ///
1771    /// # Errors
1772    ///
1773    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
1774    /// not have a component.
1775    ///
1776    /// # Examples
1777    ///
1778    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
1779    ///
1780    /// # Panics
1781    ///
1782    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1783    #[inline]
1784    pub fn get_by_id<F: DynamicComponentFetch>(
1785        &self,
1786        component_ids: F,
1787    ) -> Result<F::Ref<'_>, EntityComponentError> {
1788        self.as_readonly().get_by_id(component_ids)
1789    }
1790
1791    /// Consumes `self` and returns [untyped read-only reference(s)](Ptr) to
1792    /// component(s) with lifetime `'w` for the current entity, based on the
1793    /// given [`ComponentId`]s.
1794    ///
1795    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`]
1796    /// where possible and only use this in cases where the actual component
1797    /// types are not known at compile time.**
1798    ///
1799    /// Unlike [`EntityWorldMut::into_borrow`], this returns untyped reference(s) to
1800    /// component(s), and it's the job of the caller to ensure the correct
1801    /// type(s) are dereferenced (if necessary).
1802    ///
1803    /// # Errors
1804    ///
1805    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
1806    /// not have a component.
1807    ///
1808    /// # Examples
1809    ///
1810    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
1811    ///
1812    /// # Panics
1813    ///
1814    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1815    #[inline]
1816    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
1817        self,
1818        component_ids: F,
1819    ) -> Result<F::Ref<'w>, EntityComponentError> {
1820        self.into_readonly().get_by_id(component_ids)
1821    }
1822
1823    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
1824    /// the current entity, based on the given [`ComponentId`]s.
1825    ///
1826    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where
1827    /// possible and only use this in cases where the actual component types
1828    /// are not known at compile time.**
1829    ///
1830    /// Unlike [`EntityWorldMut::get_mut`], this returns untyped reference(s) to
1831    /// component(s), and it's the job of the caller to ensure the correct
1832    /// type(s) are dereferenced (if necessary).
1833    ///
1834    /// # Errors
1835    ///
1836    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1837    ///   not have a component.
1838    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1839    ///   is requested multiple times.
1840    ///
1841    /// # Examples
1842    ///
1843    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1844    ///
1845    /// # Panics
1846    ///
1847    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1848    #[inline]
1849    pub fn get_mut_by_id<F: DynamicComponentFetch>(
1850        &mut self,
1851        component_ids: F,
1852    ) -> Result<F::Mut<'_>, EntityComponentError> {
1853        self.as_mutable().into_mut_by_id(component_ids)
1854    }
1855
1856    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
1857    /// the current entity, based on the given [`ComponentId`]s.
1858    /// Assumes the given [`ComponentId`]s refer to mutable components.
1859    ///
1860    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut_assume_mutable`] where
1861    /// possible and only use this in cases where the actual component types
1862    /// are not known at compile time.**
1863    ///
1864    /// Unlike [`EntityWorldMut::get_mut_assume_mutable`], this returns untyped reference(s) to
1865    /// component(s), and it's the job of the caller to ensure the correct
1866    /// type(s) are dereferenced (if necessary).
1867    ///
1868    /// # Errors
1869    ///
1870    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1871    ///   not have a component.
1872    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1873    ///   is requested multiple times.
1874    ///
1875    /// # Panics
1876    ///
1877    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1878    ///
1879    /// # Safety
1880    /// It is the callers responsibility to ensure that
1881    /// - the provided [`ComponentId`]s must refer to mutable components.
1882    #[inline]
1883    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1884        &mut self,
1885        component_ids: F,
1886    ) -> Result<F::Mut<'_>, EntityComponentError> {
1887        self.as_mutable()
1888            .into_mut_assume_mutable_by_id(component_ids)
1889    }
1890
1891    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1892    /// to component(s) with lifetime `'w` for the current entity, based on the
1893    /// given [`ComponentId`]s.
1894    ///
1895    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where
1896    /// possible and only use this in cases where the actual component types
1897    /// are not known at compile time.**
1898    ///
1899    /// Unlike [`EntityWorldMut::into_mut`], this returns untyped reference(s) to
1900    /// component(s), and it's the job of the caller to ensure the correct
1901    /// type(s) are dereferenced (if necessary).
1902    ///
1903    /// # Errors
1904    ///
1905    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1906    ///   not have a component.
1907    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1908    ///   is requested multiple times.
1909    ///
1910    /// # Examples
1911    ///
1912    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1913    ///
1914    /// # Panics
1915    ///
1916    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1917    #[inline]
1918    pub fn into_mut_by_id<F: DynamicComponentFetch>(
1919        self,
1920        component_ids: F,
1921    ) -> Result<F::Mut<'w>, EntityComponentError> {
1922        self.into_mutable().into_mut_by_id(component_ids)
1923    }
1924
1925    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1926    /// to component(s) with lifetime `'w` for the current entity, based on the
1927    /// given [`ComponentId`]s.
1928    /// Assumes the given [`ComponentId`]s refer to mutable components.
1929    ///
1930    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut_assume_mutable`] where
1931    /// possible and only use this in cases where the actual component types
1932    /// are not known at compile time.**
1933    ///
1934    /// Unlike [`EntityWorldMut::into_mut_assume_mutable`], this returns untyped reference(s) to
1935    /// component(s), and it's the job of the caller to ensure the correct
1936    /// type(s) are dereferenced (if necessary).
1937    ///
1938    /// # Errors
1939    ///
1940    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1941    ///   not have a component.
1942    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1943    ///   is requested multiple times.
1944    ///
1945    /// # Panics
1946    ///
1947    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1948    ///
1949    /// # Safety
1950    /// It is the callers responsibility to ensure that
1951    /// - the provided [`ComponentId`]s must refer to mutable components.
1952    #[inline]
1953    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1954        self,
1955        component_ids: F,
1956    ) -> Result<F::Mut<'w>, EntityComponentError> {
1957        self.into_mutable()
1958            .into_mut_assume_mutable_by_id(component_ids)
1959    }
1960
1961    /// Adds a [`Bundle`] of components to the entity.
1962    ///
1963    /// This will overwrite any previous value(s) of the same component type.
1964    ///
1965    /// # Panics
1966    ///
1967    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1968    #[track_caller]
1969    pub fn insert<T: Bundle>(&mut self, bundle: T) -> &mut Self {
1970        move_as_ptr!(bundle);
1971        self.insert_with_caller(
1972            bundle,
1973            InsertMode::Replace,
1974            MaybeLocation::caller(),
1975            RelationshipHookMode::Run,
1976        )
1977    }
1978
1979    /// Adds a [`Bundle`] of components to the entity.
1980    /// [`Relationship`](crate::relationship::Relationship) components in the bundle will follow the configuration
1981    /// in `relationship_hook_mode`.
1982    ///
1983    /// This will overwrite any previous value(s) of the same component type.
1984    ///
1985    /// # Warning
1986    ///
1987    /// This can easily break the integrity of relationships. This is intended to be used for cloning and spawning code internals,
1988    /// not most user-facing scenarios.
1989    ///
1990    /// # Panics
1991    ///
1992    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1993    #[track_caller]
1994    pub fn insert_with_relationship_hook_mode<T: Bundle>(
1995        &mut self,
1996        bundle: T,
1997        relationship_hook_mode: RelationshipHookMode,
1998    ) -> &mut Self {
1999        move_as_ptr!(bundle);
2000        self.insert_with_caller(
2001            bundle,
2002            InsertMode::Replace,
2003            MaybeLocation::caller(),
2004            relationship_hook_mode,
2005        )
2006    }
2007
2008    /// Adds a [`Bundle`] of components to the entity without overwriting.
2009    ///
2010    /// This will leave any previous value(s) of the same component type
2011    /// unchanged.
2012    ///
2013    /// # Panics
2014    ///
2015    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2016    #[track_caller]
2017    pub fn insert_if_new<T: Bundle>(&mut self, bundle: T) -> &mut Self {
2018        move_as_ptr!(bundle);
2019        self.insert_with_caller(
2020            bundle,
2021            InsertMode::Keep,
2022            MaybeLocation::caller(),
2023            RelationshipHookMode::Run,
2024        )
2025    }
2026
2027    /// Adds a [`Bundle`] of components to the entity.
2028    #[inline]
2029    pub(crate) fn insert_with_caller<T: Bundle>(
2030        &mut self,
2031        bundle: MovingPtr<'_, T>,
2032        mode: InsertMode,
2033        caller: MaybeLocation,
2034        relationship_hook_mode: RelationshipHookMode,
2035    ) -> &mut Self {
2036        let location = self.location();
2037        let change_tick = self.world.change_tick();
2038        let mut bundle_inserter =
2039            BundleInserter::new::<T>(self.world, location.archetype_id, change_tick);
2040        // SAFETY:
2041        // - `location` matches current entity and thus must currently exist in the source
2042        //   archetype for this inserter and its location within the archetype.
2043        // - `T` matches the type used to create the `BundleInserter`.
2044        // - `apply_effect` is called exactly once after this function.
2045        // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
2046        //   and the caller ensures that the value is not accessed or dropped after this function
2047        //   returns.
2048        let (bundle, location) = bundle.partial_move(|bundle| unsafe {
2049            bundle_inserter.insert(
2050                self.entity,
2051                location,
2052                bundle,
2053                mode,
2054                caller,
2055                relationship_hook_mode,
2056            )
2057        });
2058        self.location = Some(location);
2059        self.world.flush();
2060        self.update_location();
2061        // SAFETY:
2062        // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
2063        // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
2064        unsafe { T::apply_effect(bundle, self) };
2065        self
2066    }
2067
2068    /// Inserts a dynamic [`Component`] into the entity.
2069    ///
2070    /// This will overwrite any previous value(s) of the same component type.
2071    ///
2072    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
2073    ///
2074    /// # Safety
2075    ///
2076    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2077    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2078    ///
2079    /// # Panics
2080    ///
2081    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2082    #[track_caller]
2083    pub unsafe fn insert_by_id(
2084        &mut self,
2085        component_id: ComponentId,
2086        component: OwningPtr<'_>,
2087    ) -> &mut Self {
2088        self.insert_by_id_with_caller(
2089            component_id,
2090            component,
2091            InsertMode::Replace,
2092            MaybeLocation::caller(),
2093            RelationshipHookMode::Run,
2094        )
2095    }
2096
2097    /// # Safety
2098    ///
2099    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2100    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2101    #[inline]
2102    pub(crate) unsafe fn insert_by_id_with_caller(
2103        &mut self,
2104        component_id: ComponentId,
2105        component: OwningPtr<'_>,
2106        mode: InsertMode,
2107        caller: MaybeLocation,
2108        relationship_hook_insert_mode: RelationshipHookMode,
2109    ) -> &mut Self {
2110        let location = self.location();
2111        let change_tick = self.world.change_tick();
2112        let bundle_id = self.world.bundles.init_component_info(
2113            &mut self.world.storages,
2114            &self.world.components,
2115            component_id,
2116        );
2117        let storage_type = self.world.bundles.get_storage_unchecked(bundle_id);
2118
2119        let bundle_inserter =
2120            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
2121
2122        self.location = Some(insert_dynamic_bundle(
2123            bundle_inserter,
2124            self.entity,
2125            location,
2126            Some(component).into_iter(),
2127            Some(storage_type).iter().cloned(),
2128            mode,
2129            caller,
2130            relationship_hook_insert_mode,
2131        ));
2132        self.world.flush();
2133        self.update_location();
2134        self
2135    }
2136
2137    /// Inserts a dynamic [`Bundle`] into the entity.
2138    ///
2139    /// This will overwrite any previous value(s) of the same component type.
2140    ///
2141    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
2142    /// If your [`Bundle`] only has one component, use the cached API [`EntityWorldMut::insert_by_id`].
2143    ///
2144    /// If possible, pass a sorted slice of `ComponentId` to maximize caching potential.
2145    ///
2146    /// # Safety
2147    /// - Each [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2148    /// - Each [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2149    ///
2150    /// # Panics
2151    ///
2152    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2153    #[track_caller]
2154    pub unsafe fn insert_by_ids<'a, I: Iterator<Item = OwningPtr<'a>>>(
2155        &mut self,
2156        component_ids: &[ComponentId],
2157        iter_components: I,
2158    ) -> &mut Self {
2159        self.insert_by_ids_internal(component_ids, iter_components, RelationshipHookMode::Run)
2160    }
2161
2162    #[track_caller]
2163    pub(crate) unsafe fn insert_by_ids_internal<'a, I: Iterator<Item = OwningPtr<'a>>>(
2164        &mut self,
2165        component_ids: &[ComponentId],
2166        iter_components: I,
2167        relationship_hook_insert_mode: RelationshipHookMode,
2168    ) -> &mut Self {
2169        let location = self.location();
2170        let change_tick = self.world.change_tick();
2171        let bundle_id = self.world.bundles.init_dynamic_info(
2172            &mut self.world.storages,
2173            &self.world.components,
2174            component_ids,
2175        );
2176        let mut storage_types =
2177            core::mem::take(self.world.bundles.get_storages_unchecked(bundle_id));
2178        let bundle_inserter =
2179            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
2180
2181        self.location = Some(insert_dynamic_bundle(
2182            bundle_inserter,
2183            self.entity,
2184            location,
2185            iter_components,
2186            (*storage_types).iter().cloned(),
2187            InsertMode::Replace,
2188            MaybeLocation::caller(),
2189            relationship_hook_insert_mode,
2190        ));
2191        *self.world.bundles.get_storages_unchecked(bundle_id) = core::mem::take(&mut storage_types);
2192        self.world.flush();
2193        self.update_location();
2194        self
2195    }
2196
2197    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
2198    ///
2199    /// **Note:** If the entity does not have every component in the bundle, this method will not
2200    /// remove any of them.
2201    ///
2202    /// # Panics
2203    ///
2204    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2205    #[must_use]
2206    #[track_caller]
2207    pub fn take<T: Bundle + BundleFromComponents>(&mut self) -> Option<T> {
2208        let location = self.location();
2209        let entity = self.entity;
2210
2211        let mut remover =
2212            // SAFETY: The archetype id must be valid since this entity is in it.
2213            unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, true) }?;
2214        // SAFETY: The passed location has the sane archetype as the remover, since they came from the same location.
2215        let (new_location, result) = unsafe {
2216            remover.remove(
2217                entity,
2218                location,
2219                MaybeLocation::caller(),
2220                |sets, table, components, bundle_components| {
2221                    let mut bundle_components = bundle_components.iter().copied();
2222                    (
2223                        false,
2224                        T::from_components(&mut (sets, table), &mut |(sets, table)| {
2225                            let component_id = bundle_components.next().unwrap();
2226                            // SAFETY: the component existed to be removed, so its id must be valid.
2227                            let component_info = components.get_info_unchecked(component_id);
2228                            match component_info.storage_type() {
2229                                StorageType::Table => {
2230                                    table
2231                                        .as_mut()
2232                                        // SAFETY: The table must be valid if the component is in it.
2233                                        .debug_checked_unwrap()
2234                                        // SAFETY: The remover is cleaning this up.
2235                                        .take_component(component_id, location.table_row)
2236                                }
2237                                StorageType::SparseSet => sets
2238                                    .get_mut(component_id)
2239                                    .unwrap()
2240                                    .remove_and_forget(entity)
2241                                    .unwrap(),
2242                            }
2243                        }),
2244                    )
2245                },
2246            )
2247        };
2248        self.location = Some(new_location);
2249
2250        self.world.flush();
2251        self.update_location();
2252        Some(result)
2253    }
2254
2255    /// Removes any components in the [`Bundle`] from the entity.
2256    ///
2257    /// See [`EntityCommands::remove`](crate::system::EntityCommands::remove) for more details.
2258    ///
2259    /// # Panics
2260    ///
2261    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2262    #[track_caller]
2263    pub fn remove<T: Bundle>(&mut self) -> &mut Self {
2264        self.remove_with_caller::<T>(MaybeLocation::caller())
2265    }
2266
2267    #[inline]
2268    pub(crate) fn remove_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
2269        let location = self.location();
2270
2271        let Some(mut remover) =
2272            // SAFETY: The archetype id must be valid since this entity is in it.
2273            (unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, false) })
2274        else {
2275            return self;
2276        };
2277        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2278        let new_location = unsafe {
2279            remover.remove(
2280                self.entity,
2281                location,
2282                caller,
2283                BundleRemover::empty_pre_remove,
2284            )
2285        }
2286        .0;
2287
2288        self.location = Some(new_location);
2289        self.world.flush();
2290        self.update_location();
2291        self
2292    }
2293
2294    /// Removes all components in the [`Bundle`] and remove all required components for each component in the bundle
2295    ///
2296    /// # Panics
2297    ///
2298    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2299    #[track_caller]
2300    pub fn remove_with_requires<T: Bundle>(&mut self) -> &mut Self {
2301        self.remove_with_requires_with_caller::<T>(MaybeLocation::caller())
2302    }
2303
2304    pub(crate) fn remove_with_requires_with_caller<T: Bundle>(
2305        &mut self,
2306        caller: MaybeLocation,
2307    ) -> &mut Self {
2308        let location = self.location();
2309        let bundle_id = self.world.register_contributed_bundle_info::<T>();
2310
2311        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2312        let Some(mut remover) = (unsafe {
2313            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2314        }) else {
2315            return self;
2316        };
2317        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2318        let new_location = unsafe {
2319            remover.remove(
2320                self.entity,
2321                location,
2322                caller,
2323                BundleRemover::empty_pre_remove,
2324            )
2325        }
2326        .0;
2327
2328        self.location = Some(new_location);
2329        self.world.flush();
2330        self.update_location();
2331        self
2332    }
2333
2334    /// Removes any components except those in the [`Bundle`] (and its Required Components) from the entity.
2335    ///
2336    /// See [`EntityCommands::retain`](crate::system::EntityCommands::retain) for more details.
2337    ///
2338    /// # Panics
2339    ///
2340    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2341    #[track_caller]
2342    pub fn retain<T: Bundle>(&mut self) -> &mut Self {
2343        self.retain_with_caller::<T>(MaybeLocation::caller())
2344    }
2345
2346    #[inline]
2347    pub(crate) fn retain_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
2348        let old_location = self.location();
2349        let retained_bundle = self.world.register_bundle_info::<T>();
2350        let archetypes = &mut self.world.archetypes;
2351
2352        // SAFETY: `retained_bundle` exists as we just registered it.
2353        let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) };
2354        let old_archetype = &mut archetypes[old_location.archetype_id];
2355
2356        // PERF: this could be stored in an Archetype Edge
2357        let to_remove = &old_archetype
2358            .iter_components()
2359            .filter(|c| !retained_bundle_info.contributed_components().contains(c))
2360            .collect::<Vec<_>>();
2361        let remove_bundle = self.world.bundles.init_dynamic_info(
2362            &mut self.world.storages,
2363            &self.world.components,
2364            to_remove,
2365        );
2366
2367        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2368        let Some(mut remover) = (unsafe {
2369            BundleRemover::new_with_id(self.world, old_location.archetype_id, remove_bundle, false)
2370        }) else {
2371            return self;
2372        };
2373        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2374        let new_location = unsafe {
2375            remover.remove(
2376                self.entity,
2377                old_location,
2378                caller,
2379                BundleRemover::empty_pre_remove,
2380            )
2381        }
2382        .0;
2383
2384        self.location = Some(new_location);
2385        self.world.flush();
2386        self.update_location();
2387        self
2388    }
2389
2390    /// Removes a dynamic [`Component`] from the entity if it exists.
2391    ///
2392    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
2393    ///
2394    /// # Panics
2395    ///
2396    /// Panics if the provided [`ComponentId`] does not exist in the [`World`] or if the
2397    /// entity has been despawned while this `EntityWorldMut` is still alive.
2398    #[track_caller]
2399    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
2400        self.remove_by_id_with_caller(component_id, MaybeLocation::caller())
2401    }
2402
2403    #[inline]
2404    pub(crate) fn remove_by_id_with_caller(
2405        &mut self,
2406        component_id: ComponentId,
2407        caller: MaybeLocation,
2408    ) -> &mut Self {
2409        let location = self.location();
2410        let components = &mut self.world.components;
2411
2412        let bundle_id = self.world.bundles.init_component_info(
2413            &mut self.world.storages,
2414            components,
2415            component_id,
2416        );
2417
2418        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2419        let Some(mut remover) = (unsafe {
2420            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2421        }) else {
2422            return self;
2423        };
2424        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2425        let new_location = unsafe {
2426            remover.remove(
2427                self.entity,
2428                location,
2429                caller,
2430                BundleRemover::empty_pre_remove,
2431            )
2432        }
2433        .0;
2434
2435        self.location = Some(new_location);
2436        self.world.flush();
2437        self.update_location();
2438        self
2439    }
2440
2441    /// Removes a dynamic bundle from the entity if it exists.
2442    ///
2443    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
2444    ///
2445    /// # Panics
2446    ///
2447    /// Panics if any of the provided [`ComponentId`]s do not exist in the [`World`] or if the
2448    /// entity has been despawned while this `EntityWorldMut` is still alive.
2449    #[track_caller]
2450    pub fn remove_by_ids(&mut self, component_ids: &[ComponentId]) -> &mut Self {
2451        self.remove_by_ids_with_caller(
2452            component_ids,
2453            MaybeLocation::caller(),
2454            RelationshipHookMode::Run,
2455            BundleRemover::empty_pre_remove,
2456        )
2457    }
2458
2459    #[inline]
2460    pub(crate) fn remove_by_ids_with_caller<T: 'static>(
2461        &mut self,
2462        component_ids: &[ComponentId],
2463        caller: MaybeLocation,
2464        relationship_hook_mode: RelationshipHookMode,
2465        pre_remove: impl FnOnce(
2466            &mut SparseSets,
2467            Option<&mut Table>,
2468            &Components,
2469            &[ComponentId],
2470        ) -> (bool, T),
2471    ) -> &mut Self {
2472        let location = self.location();
2473        let components = &mut self.world.components;
2474
2475        let bundle_id = self.world.bundles.init_dynamic_info(
2476            &mut self.world.storages,
2477            components,
2478            component_ids,
2479        );
2480
2481        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2482        let Some(mut remover) = (unsafe {
2483            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2484        }) else {
2485            return self;
2486        };
2487        remover.relationship_hook_mode = relationship_hook_mode;
2488        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2489        let new_location = unsafe { remover.remove(self.entity, location, caller, pre_remove) }.0;
2490
2491        self.location = Some(new_location);
2492        self.world.flush();
2493        self.update_location();
2494        self
2495    }
2496
2497    /// Removes all components associated with the entity.
2498    ///
2499    /// # Panics
2500    ///
2501    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2502    #[track_caller]
2503    pub fn clear(&mut self) -> &mut Self {
2504        self.clear_with_caller(MaybeLocation::caller())
2505    }
2506
2507    #[inline]
2508    pub(crate) fn clear_with_caller(&mut self, caller: MaybeLocation) -> &mut Self {
2509        let location = self.location();
2510        // PERF: this should not be necessary
2511        let component_ids: Vec<ComponentId> = self.archetype().components().to_vec();
2512        let components = &mut self.world.components;
2513
2514        let bundle_id = self.world.bundles.init_dynamic_info(
2515            &mut self.world.storages,
2516            components,
2517            component_ids.as_slice(),
2518        );
2519
2520        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2521        let Some(mut remover) = (unsafe {
2522            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2523        }) else {
2524            return self;
2525        };
2526        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2527        let new_location = unsafe {
2528            remover.remove(
2529                self.entity,
2530                location,
2531                caller,
2532                BundleRemover::empty_pre_remove,
2533            )
2534        }
2535        .0;
2536
2537        self.location = Some(new_location);
2538        self.world.flush();
2539        self.update_location();
2540        self
2541    }
2542
2543    /// Despawns the current entity.
2544    ///
2545    /// See [`World::despawn`] for more details.
2546    ///
2547    /// # Note
2548    ///
2549    /// This will also despawn any [`Children`](crate::hierarchy::Children) entities, and any other [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
2550    /// to despawn descendants. This results in "recursive despawn" behavior.
2551    ///
2552    /// # Panics
2553    ///
2554    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2555    #[track_caller]
2556    pub fn despawn(self) {
2557        self.despawn_with_caller(MaybeLocation::caller());
2558    }
2559
2560    pub(crate) fn despawn_with_caller(self, caller: MaybeLocation) {
2561        let location = self.location();
2562        let world = self.world;
2563        let archetype = &world.archetypes[location.archetype_id];
2564
2565        // SAFETY: Archetype cannot be mutably aliased by DeferredWorld
2566        let (archetype, mut deferred_world) = unsafe {
2567            let archetype: *const Archetype = archetype;
2568            let world = world.as_unsafe_world_cell();
2569            (&*archetype, world.into_deferred())
2570        };
2571
2572        // SAFETY: All components in the archetype exist in world
2573        unsafe {
2574            if archetype.has_despawn_observer() {
2575                // SAFETY: the DESPAWN event_key corresponds to the Despawn event's type
2576                deferred_world.trigger_raw(
2577                    DESPAWN,
2578                    &mut Despawn {
2579                        entity: self.entity,
2580                    },
2581                    &mut EntityComponentsTrigger {
2582                        components: archetype.components(),
2583                    },
2584                    caller,
2585                );
2586            }
2587            deferred_world.trigger_on_despawn(
2588                archetype,
2589                self.entity,
2590                archetype.iter_components(),
2591                caller,
2592            );
2593            if archetype.has_replace_observer() {
2594                // SAFETY: the REPLACE event_key corresponds to the Replace event's type
2595                deferred_world.trigger_raw(
2596                    REPLACE,
2597                    &mut Replace {
2598                        entity: self.entity,
2599                    },
2600                    &mut EntityComponentsTrigger {
2601                        components: archetype.components(),
2602                    },
2603                    caller,
2604                );
2605            }
2606            deferred_world.trigger_on_replace(
2607                archetype,
2608                self.entity,
2609                archetype.iter_components(),
2610                caller,
2611                RelationshipHookMode::Run,
2612            );
2613            if archetype.has_remove_observer() {
2614                // SAFETY: the REMOVE event_key corresponds to the Remove event's type
2615                deferred_world.trigger_raw(
2616                    REMOVE,
2617                    &mut Remove {
2618                        entity: self.entity,
2619                    },
2620                    &mut EntityComponentsTrigger {
2621                        components: archetype.components(),
2622                    },
2623                    caller,
2624                );
2625            }
2626            deferred_world.trigger_on_remove(
2627                archetype,
2628                self.entity,
2629                archetype.iter_components(),
2630                caller,
2631            );
2632        }
2633
2634        for component_id in archetype.iter_components() {
2635            world.removed_components.write(component_id, self.entity);
2636        }
2637
2638        // Observers and on_remove hooks may reserve new entities, which
2639        // requires a flush before Entities::free may be called.
2640        world.flush_entities();
2641
2642        let location = world
2643            .entities
2644            .free(self.entity)
2645            .flatten()
2646            .expect("entity should exist at this point.");
2647        let table_row;
2648        let moved_entity;
2649        let change_tick = world.change_tick();
2650
2651        {
2652            let archetype = &mut world.archetypes[location.archetype_id];
2653            let remove_result = archetype.swap_remove(location.archetype_row);
2654            if let Some(swapped_entity) = remove_result.swapped_entity {
2655                let swapped_location = world.entities.get(swapped_entity).unwrap();
2656                // SAFETY: swapped_entity is valid and the swapped entity's components are
2657                // moved to the new location immediately after.
2658                unsafe {
2659                    world.entities.set(
2660                        swapped_entity.index(),
2661                        Some(EntityLocation {
2662                            archetype_id: swapped_location.archetype_id,
2663                            archetype_row: location.archetype_row,
2664                            table_id: swapped_location.table_id,
2665                            table_row: swapped_location.table_row,
2666                        }),
2667                    );
2668                    world
2669                        .entities
2670                        .mark_spawn_despawn(swapped_entity.index(), caller, change_tick);
2671                }
2672            }
2673            table_row = remove_result.table_row;
2674
2675            for component_id in archetype.sparse_set_components() {
2676                // set must have existed for the component to be added.
2677                let sparse_set = world.storages.sparse_sets.get_mut(component_id).unwrap();
2678                sparse_set.remove(self.entity);
2679            }
2680            // SAFETY: table rows stored in archetypes always exist
2681            moved_entity = unsafe {
2682                world.storages.tables[archetype.table_id()].swap_remove_unchecked(table_row)
2683            };
2684        };
2685
2686        if let Some(moved_entity) = moved_entity {
2687            let moved_location = world.entities.get(moved_entity).unwrap();
2688            // SAFETY: `moved_entity` is valid and the provided `EntityLocation` accurately reflects
2689            //         the current location of the entity and its component data.
2690            unsafe {
2691                world.entities.set(
2692                    moved_entity.index(),
2693                    Some(EntityLocation {
2694                        archetype_id: moved_location.archetype_id,
2695                        archetype_row: moved_location.archetype_row,
2696                        table_id: moved_location.table_id,
2697                        table_row,
2698                    }),
2699                );
2700                world
2701                    .entities
2702                    .mark_spawn_despawn(moved_entity.index(), caller, change_tick);
2703            }
2704            world.archetypes[moved_location.archetype_id]
2705                .set_entity_table_row(moved_location.archetype_row, table_row);
2706        }
2707        world.flush();
2708    }
2709
2710    /// Ensures any commands triggered by the actions of Self are applied, equivalent to [`World::flush`]
2711    pub fn flush(self) -> Entity {
2712        self.world.flush();
2713        self.entity
2714    }
2715
2716    /// Gets read-only access to the world that the current entity belongs to.
2717    #[inline]
2718    pub fn world(&self) -> &World {
2719        self.world
2720    }
2721
2722    /// Returns this entity's world.
2723    ///
2724    /// See [`EntityWorldMut::world_scope`] or [`EntityWorldMut::into_world_mut`] for a safe alternative.
2725    ///
2726    /// # Safety
2727    /// Caller must not modify the world in a way that changes the current entity's location
2728    /// If the caller _does_ do something that could change the location, `self.update_location()`
2729    /// must be called before using any other methods on this [`EntityWorldMut`].
2730    #[inline]
2731    pub unsafe fn world_mut(&mut self) -> &mut World {
2732        self.world
2733    }
2734
2735    /// Returns this entity's [`World`], consuming itself.
2736    #[inline]
2737    pub fn into_world_mut(self) -> &'w mut World {
2738        self.world
2739    }
2740
2741    /// Gives mutable access to this entity's [`World`] in a temporary scope.
2742    /// This is a safe alternative to using [`EntityWorldMut::world_mut`].
2743    ///
2744    /// # Examples
2745    ///
2746    /// ```
2747    /// # use bevy_ecs::prelude::*;
2748    /// #[derive(Resource, Default, Clone, Copy)]
2749    /// struct R(u32);
2750    ///
2751    /// # let mut world = World::new();
2752    /// # world.init_resource::<R>();
2753    /// # let mut entity = world.spawn_empty();
2754    /// // This closure gives us temporary access to the world.
2755    /// let new_r = entity.world_scope(|world: &mut World| {
2756    ///     // Mutate the world while we have access to it.
2757    ///     let mut r = world.resource_mut::<R>();
2758    ///     r.0 += 1;
2759    ///
2760    ///     // Return a value from the world before giving it back to the `EntityWorldMut`.
2761    ///     *r
2762    /// });
2763    /// # assert_eq!(new_r.0, 1);
2764    /// ```
2765    pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
2766        struct Guard<'w, 'a> {
2767            entity_mut: &'a mut EntityWorldMut<'w>,
2768        }
2769
2770        impl Drop for Guard<'_, '_> {
2771            #[inline]
2772            fn drop(&mut self) {
2773                self.entity_mut.update_location();
2774            }
2775        }
2776
2777        // When `guard` is dropped at the end of this scope,
2778        // it will update the cached `EntityLocation` for this instance.
2779        // This will run even in case the closure `f` unwinds.
2780        let guard = Guard { entity_mut: self };
2781        f(guard.entity_mut.world)
2782    }
2783
2784    /// Updates the internal entity location to match the current location in the internal
2785    /// [`World`].
2786    ///
2787    /// This is *only* required when using the unsafe function [`EntityWorldMut::world_mut`],
2788    /// which enables the location to change.
2789    pub fn update_location(&mut self) {
2790        self.location = self.world.entities().get(self.entity);
2791    }
2792
2793    /// Returns if the entity has been despawned.
2794    ///
2795    /// Normally it shouldn't be needed to explicitly check if the entity has been despawned
2796    /// between commands as this shouldn't happen. However, for some special cases where it
2797    /// is known that a hook or an observer might despawn the entity while a [`EntityWorldMut`]
2798    /// reference is still held, this method can be used to check if the entity is still alive
2799    /// to avoid panicking when calling further methods.
2800    #[inline]
2801    pub fn is_despawned(&self) -> bool {
2802        self.location.is_none()
2803    }
2804
2805    /// Gets an Entry into the world for this entity and component for in-place manipulation.
2806    ///
2807    /// The type parameter specifies which component to get.
2808    ///
2809    /// # Examples
2810    ///
2811    /// ```
2812    /// # use bevy_ecs::prelude::*;
2813    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
2814    /// struct Comp(u32);
2815    ///
2816    /// # let mut world = World::new();
2817    /// let mut entity = world.spawn_empty();
2818    /// entity.entry().or_insert_with(|| Comp(4));
2819    /// # let entity_id = entity.id();
2820    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
2821    ///
2822    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
2823    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
2824    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 5);
2825    /// ```
2826    ///
2827    /// # Panics
2828    ///
2829    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2830    pub fn entry<'a, T: Component>(&'a mut self) -> ComponentEntry<'w, 'a, T> {
2831        if self.contains::<T>() {
2832            ComponentEntry::Occupied(OccupiedComponentEntry {
2833                entity_world: self,
2834                _marker: PhantomData,
2835            })
2836        } else {
2837            ComponentEntry::Vacant(VacantComponentEntry {
2838                entity_world: self,
2839                _marker: PhantomData,
2840            })
2841        }
2842    }
2843
2844    /// Creates an [`Observer`] watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`]
2845    /// targets this entity.
2846    ///
2847    /// # Panics
2848    ///
2849    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2850    ///
2851    /// Panics if the given system is an exclusive system.
2852    #[track_caller]
2853    pub fn observe<E: EntityEvent, B: Bundle, M>(
2854        &mut self,
2855        observer: impl IntoObserverSystem<E, B, M>,
2856    ) -> &mut Self {
2857        self.observe_with_caller(observer, MaybeLocation::caller())
2858    }
2859
2860    pub(crate) fn observe_with_caller<E: EntityEvent, B: Bundle, M>(
2861        &mut self,
2862        observer: impl IntoObserverSystem<E, B, M>,
2863        caller: MaybeLocation,
2864    ) -> &mut Self {
2865        self.assert_not_despawned();
2866        let bundle = Observer::new(observer).with_entity(self.entity);
2867        move_as_ptr!(bundle);
2868        self.world.spawn_with_caller(bundle, caller);
2869        self.world.flush();
2870        self.update_location();
2871        self
2872    }
2873
2874    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2875    /// configured through [`EntityClonerBuilder`].
2876    ///
2877    /// The other entity will receive all the components of the original that implement
2878    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2879    /// [denied](EntityClonerBuilder::deny) in the `config`.
2880    ///
2881    /// # Example
2882    ///
2883    /// ```
2884    /// # use bevy_ecs::prelude::*;
2885    /// # #[derive(Component, Clone, PartialEq, Debug)]
2886    /// # struct ComponentA;
2887    /// # #[derive(Component, Clone, PartialEq, Debug)]
2888    /// # struct ComponentB;
2889    /// # let mut world = World::new();
2890    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2891    /// # let target = world.spawn_empty().id();
2892    /// // Clone all components except ComponentA onto the target.
2893    /// world.entity_mut(entity).clone_with_opt_out(target, |builder| {
2894    ///     builder.deny::<ComponentA>();
2895    /// });
2896    /// # assert_eq!(world.get::<ComponentA>(target), None);
2897    /// # assert_eq!(world.get::<ComponentB>(target), Some(&ComponentB));
2898    /// ```
2899    ///
2900    /// See [`EntityClonerBuilder<OptOut>`] for more options.
2901    ///
2902    /// # Panics
2903    ///
2904    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2905    /// - If the target entity does not exist.
2906    pub fn clone_with_opt_out(
2907        &mut self,
2908        target: Entity,
2909        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2910    ) -> &mut Self {
2911        self.assert_not_despawned();
2912
2913        let mut builder = EntityCloner::build_opt_out(self.world);
2914        config(&mut builder);
2915        builder.clone_entity(self.entity, target);
2916
2917        self.world.flush();
2918        self.update_location();
2919        self
2920    }
2921
2922    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2923    /// configured through [`EntityClonerBuilder`].
2924    ///
2925    /// The other entity will receive only the components of the original that implement
2926    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2927    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2928    ///
2929    /// # Example
2930    ///
2931    /// ```
2932    /// # use bevy_ecs::prelude::*;
2933    /// # #[derive(Component, Clone, PartialEq, Debug)]
2934    /// # struct ComponentA;
2935    /// # #[derive(Component, Clone, PartialEq, Debug)]
2936    /// # struct ComponentB;
2937    /// # let mut world = World::new();
2938    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2939    /// # let target = world.spawn_empty().id();
2940    /// // Clone only ComponentA onto the target.
2941    /// world.entity_mut(entity).clone_with_opt_in(target, |builder| {
2942    ///     builder.allow::<ComponentA>();
2943    /// });
2944    /// # assert_eq!(world.get::<ComponentA>(target), Some(&ComponentA));
2945    /// # assert_eq!(world.get::<ComponentB>(target), None);
2946    /// ```
2947    ///
2948    /// See [`EntityClonerBuilder<OptIn>`] for more options.
2949    ///
2950    /// # Panics
2951    ///
2952    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2953    /// - If the target entity does not exist.
2954    pub fn clone_with_opt_in(
2955        &mut self,
2956        target: Entity,
2957        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2958    ) -> &mut Self {
2959        self.assert_not_despawned();
2960
2961        let mut builder = EntityCloner::build_opt_in(self.world);
2962        config(&mut builder);
2963        builder.clone_entity(self.entity, target);
2964
2965        self.world.flush();
2966        self.update_location();
2967        self
2968    }
2969
2970    /// Spawns a clone of this entity and returns the [`Entity`] of the clone.
2971    ///
2972    /// The clone will receive all the components of the original that implement
2973    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2974    ///
2975    /// To configure cloning behavior (such as only cloning certain components),
2976    /// use [`EntityWorldMut::clone_and_spawn_with_opt_out`]/
2977    /// [`opt_in`](`EntityWorldMut::clone_and_spawn_with_opt_in`).
2978    ///
2979    /// # Panics
2980    ///
2981    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2982    pub fn clone_and_spawn(&mut self) -> Entity {
2983        self.clone_and_spawn_with_opt_out(|_| {})
2984    }
2985
2986    /// Spawns a clone of this entity and allows configuring cloning behavior
2987    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2988    ///
2989    /// The clone will receive all the components of the original that implement
2990    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2991    /// [denied](EntityClonerBuilder::deny) in the `config`.
2992    ///
2993    /// # Example
2994    ///
2995    /// ```
2996    /// # use bevy_ecs::prelude::*;
2997    /// # let mut world = World::new();
2998    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2999    /// # #[derive(Component, Clone, PartialEq, Debug)]
3000    /// # struct ComponentA;
3001    /// # #[derive(Component, Clone, PartialEq, Debug)]
3002    /// # struct ComponentB;
3003    /// // Create a clone of an entity but without ComponentA.
3004    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_out(|builder| {
3005    ///     builder.deny::<ComponentA>();
3006    /// });
3007    /// # assert_eq!(world.get::<ComponentA>(entity_clone), None);
3008    /// # assert_eq!(world.get::<ComponentB>(entity_clone), Some(&ComponentB));
3009    /// ```
3010    ///
3011    /// See [`EntityClonerBuilder<OptOut>`] for more options.
3012    ///
3013    /// # Panics
3014    ///
3015    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
3016    pub fn clone_and_spawn_with_opt_out(
3017        &mut self,
3018        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
3019    ) -> Entity {
3020        self.assert_not_despawned();
3021
3022        let entity_clone = self.world.entities.reserve_entity();
3023        self.world.flush();
3024
3025        let mut builder = EntityCloner::build_opt_out(self.world);
3026        config(&mut builder);
3027        builder.clone_entity(self.entity, entity_clone);
3028
3029        self.world.flush();
3030        self.update_location();
3031        entity_clone
3032    }
3033
3034    /// Spawns a clone of this entity and allows configuring cloning behavior
3035    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
3036    ///
3037    /// The clone will receive only the components of the original that implement
3038    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
3039    /// [allowed](EntityClonerBuilder::allow) in the `config`.
3040    ///
3041    /// # Example
3042    ///
3043    /// ```
3044    /// # use bevy_ecs::prelude::*;
3045    /// # let mut world = World::new();
3046    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
3047    /// # #[derive(Component, Clone, PartialEq, Debug)]
3048    /// # struct ComponentA;
3049    /// # #[derive(Component, Clone, PartialEq, Debug)]
3050    /// # struct ComponentB;
3051    /// // Create a clone of an entity but only with ComponentA.
3052    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_in(|builder| {
3053    ///     builder.allow::<ComponentA>();
3054    /// });
3055    /// # assert_eq!(world.get::<ComponentA>(entity_clone), Some(&ComponentA));
3056    /// # assert_eq!(world.get::<ComponentB>(entity_clone), None);
3057    /// ```
3058    ///
3059    /// See [`EntityClonerBuilder<OptIn>`] for more options.
3060    ///
3061    /// # Panics
3062    ///
3063    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
3064    pub fn clone_and_spawn_with_opt_in(
3065        &mut self,
3066        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
3067    ) -> Entity {
3068        self.assert_not_despawned();
3069
3070        let entity_clone = self.world.entities.reserve_entity();
3071        self.world.flush();
3072
3073        let mut builder = EntityCloner::build_opt_in(self.world);
3074        config(&mut builder);
3075        builder.clone_entity(self.entity, entity_clone);
3076
3077        self.world.flush();
3078        self.update_location();
3079        entity_clone
3080    }
3081
3082    /// Clones the specified components of this entity and inserts them into another entity.
3083    ///
3084    /// Components can only be cloned if they implement
3085    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
3086    ///
3087    /// # Panics
3088    ///
3089    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
3090    /// - If the target entity does not exist.
3091    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
3092        self.assert_not_despawned();
3093
3094        EntityCloner::build_opt_in(self.world)
3095            .allow::<B>()
3096            .clone_entity(self.entity, target);
3097
3098        self.world.flush();
3099        self.update_location();
3100        self
3101    }
3102
3103    /// Clones the specified components of this entity and inserts them into another entity,
3104    /// then removes the components from this entity.
3105    ///
3106    /// Components can only be cloned if they implement
3107    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
3108    ///
3109    /// # Panics
3110    ///
3111    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
3112    /// - If the target entity does not exist.
3113    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
3114        self.assert_not_despawned();
3115
3116        EntityCloner::build_opt_in(self.world)
3117            .allow::<B>()
3118            .move_components(true)
3119            .clone_entity(self.entity, target);
3120
3121        self.world.flush();
3122        self.update_location();
3123        self
3124    }
3125
3126    /// Returns the source code location from which this entity has last been spawned.
3127    pub fn spawned_by(&self) -> MaybeLocation {
3128        self.world()
3129            .entities()
3130            .entity_get_spawned_or_despawned_by(self.entity)
3131            .map(|location| location.unwrap())
3132    }
3133
3134    /// Returns the [`Tick`] at which this entity has last been spawned.
3135    pub fn spawn_tick(&self) -> Tick {
3136        self.assert_not_despawned();
3137
3138        // SAFETY: entity being alive was asserted
3139        unsafe {
3140            self.world()
3141                .entities()
3142                .entity_get_spawned_or_despawned_unchecked(self.entity)
3143                .1
3144        }
3145    }
3146
3147    /// Reborrows this entity in a temporary scope.
3148    /// This is useful for executing a function that requires a `EntityWorldMut`
3149    /// but you do not want to move out the entity ownership.
3150    pub fn reborrow_scope<U>(&mut self, f: impl FnOnce(EntityWorldMut) -> U) -> U {
3151        let Self {
3152            entity, location, ..
3153        } = *self;
3154        self.world_scope(move |world| {
3155            f(EntityWorldMut {
3156                world,
3157                entity,
3158                location,
3159            })
3160        })
3161    }
3162
3163    /// Passes the current entity into the given function, and triggers the [`EntityEvent`] returned by that function.
3164    /// See [`EntityCommands::trigger`] for usage examples
3165    ///
3166    /// [`EntityCommands::trigger`]: crate::system::EntityCommands::trigger
3167    #[track_caller]
3168    pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
3169        &mut self,
3170        event_fn: impl FnOnce(Entity) -> E,
3171    ) -> &mut Self {
3172        let mut event = (event_fn)(self.entity);
3173        let caller = MaybeLocation::caller();
3174        self.world_scope(|world| {
3175            world.trigger_ref_with_caller(
3176                &mut event,
3177                &mut <E::Trigger<'_> as Default>::default(),
3178                caller,
3179            );
3180        });
3181        self
3182    }
3183}
3184
3185/// A view into a single entity and component in a world, which may either be vacant or occupied.
3186///
3187/// This `enum` can only be constructed from the [`entry`] method on [`EntityWorldMut`].
3188///
3189/// [`entry`]: EntityWorldMut::entry
3190pub enum ComponentEntry<'w, 'a, T: Component> {
3191    /// An occupied entry.
3192    Occupied(OccupiedComponentEntry<'w, 'a, T>),
3193    /// A vacant entry.
3194    Vacant(VacantComponentEntry<'w, 'a, T>),
3195}
3196
3197impl<'w, 'a, T: Component<Mutability = Mutable>> ComponentEntry<'w, 'a, T> {
3198    /// Provides in-place mutable access to an occupied entry.
3199    ///
3200    /// # Examples
3201    ///
3202    /// ```
3203    /// # use bevy_ecs::prelude::*;
3204    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3205    /// struct Comp(u32);
3206    ///
3207    /// # let mut world = World::new();
3208    /// let mut entity = world.spawn(Comp(0));
3209    ///
3210    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
3211    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 1);
3212    /// ```
3213    #[inline]
3214    pub fn and_modify<F: FnOnce(Mut<'_, T>)>(self, f: F) -> Self {
3215        match self {
3216            ComponentEntry::Occupied(mut entry) => {
3217                f(entry.get_mut());
3218                ComponentEntry::Occupied(entry)
3219            }
3220            ComponentEntry::Vacant(entry) => ComponentEntry::Vacant(entry),
3221        }
3222    }
3223}
3224
3225impl<'w, 'a, T: Component> ComponentEntry<'w, 'a, T> {
3226    /// Replaces the component of the entry, and returns an [`OccupiedComponentEntry`].
3227    ///
3228    /// # Examples
3229    ///
3230    /// ```
3231    /// # use bevy_ecs::prelude::*;
3232    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3233    /// struct Comp(u32);
3234    ///
3235    /// # let mut world = World::new();
3236    /// let mut entity = world.spawn_empty();
3237    ///
3238    /// let entry = entity.entry().insert_entry(Comp(4));
3239    /// assert_eq!(entry.get(), &Comp(4));
3240    ///
3241    /// let entry = entity.entry().insert_entry(Comp(2));
3242    /// assert_eq!(entry.get(), &Comp(2));
3243    /// ```
3244    #[inline]
3245    pub fn insert_entry(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
3246        match self {
3247            ComponentEntry::Occupied(mut entry) => {
3248                entry.insert(component);
3249                entry
3250            }
3251            ComponentEntry::Vacant(entry) => entry.insert(component),
3252        }
3253    }
3254
3255    /// Ensures the entry has this component by inserting the given default if empty, and
3256    /// returns a mutable reference to this component in the entry.
3257    ///
3258    /// # Examples
3259    ///
3260    /// ```
3261    /// # use bevy_ecs::prelude::*;
3262    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3263    /// struct Comp(u32);
3264    ///
3265    /// # let mut world = World::new();
3266    /// let mut entity = world.spawn_empty();
3267    ///
3268    /// entity.entry().or_insert(Comp(4));
3269    /// # let entity_id = entity.id();
3270    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
3271    ///
3272    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
3273    /// entity.entry().or_insert(Comp(15)).into_mut().0 *= 2;
3274    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 8);
3275    /// ```
3276    #[inline]
3277    pub fn or_insert(self, default: T) -> OccupiedComponentEntry<'w, 'a, T> {
3278        match self {
3279            ComponentEntry::Occupied(entry) => entry,
3280            ComponentEntry::Vacant(entry) => entry.insert(default),
3281        }
3282    }
3283
3284    /// Ensures the entry has this component by inserting the result of the default function if
3285    /// empty, and returns a mutable reference to this component in the entry.
3286    ///
3287    /// # Examples
3288    ///
3289    /// ```
3290    /// # use bevy_ecs::prelude::*;
3291    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3292    /// struct Comp(u32);
3293    ///
3294    /// # let mut world = World::new();
3295    /// let mut entity = world.spawn_empty();
3296    ///
3297    /// entity.entry().or_insert_with(|| Comp(4));
3298    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
3299    /// ```
3300    #[inline]
3301    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> OccupiedComponentEntry<'w, 'a, T> {
3302        match self {
3303            ComponentEntry::Occupied(entry) => entry,
3304            ComponentEntry::Vacant(entry) => entry.insert(default()),
3305        }
3306    }
3307}
3308
3309impl<'w, 'a, T: Component + Default> ComponentEntry<'w, 'a, T> {
3310    /// Ensures the entry has this component by inserting the default value if empty, and
3311    /// returns a mutable reference to this component in the entry.
3312    ///
3313    /// # Examples
3314    ///
3315    /// ```
3316    /// # use bevy_ecs::prelude::*;
3317    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3318    /// struct Comp(u32);
3319    ///
3320    /// # let mut world = World::new();
3321    /// let mut entity = world.spawn_empty();
3322    ///
3323    /// entity.entry::<Comp>().or_default();
3324    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 0);
3325    /// ```
3326    #[inline]
3327    pub fn or_default(self) -> OccupiedComponentEntry<'w, 'a, T> {
3328        match self {
3329            ComponentEntry::Occupied(entry) => entry,
3330            ComponentEntry::Vacant(entry) => entry.insert(Default::default()),
3331        }
3332    }
3333}
3334
3335/// A view into an occupied entry in a [`EntityWorldMut`]. It is part of the [`OccupiedComponentEntry`] enum.
3336///
3337/// The contained entity must have the component type parameter if we have this struct.
3338pub struct OccupiedComponentEntry<'w, 'a, T: Component> {
3339    entity_world: &'a mut EntityWorldMut<'w>,
3340    _marker: PhantomData<T>,
3341}
3342
3343impl<'w, 'a, T: Component> OccupiedComponentEntry<'w, 'a, T> {
3344    /// Gets a reference to the component in the entry.
3345    ///
3346    /// # Examples
3347    ///
3348    /// ```
3349    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3350    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3351    /// struct Comp(u32);
3352    ///
3353    /// # let mut world = World::new();
3354    /// let mut entity = world.spawn(Comp(5));
3355    ///
3356    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3357    ///     assert_eq!(o.get().0, 5);
3358    /// }
3359    /// ```
3360    #[inline]
3361    pub fn get(&self) -> &T {
3362        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3363        self.entity_world.get::<T>().unwrap()
3364    }
3365
3366    /// Replaces the component of the entry.
3367    ///
3368    /// # Examples
3369    ///
3370    /// ```
3371    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3372    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3373    /// struct Comp(u32);
3374    ///
3375    /// # let mut world = World::new();
3376    /// let mut entity = world.spawn(Comp(5));
3377    ///
3378    /// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
3379    ///     o.insert(Comp(10));
3380    /// }
3381    ///
3382    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
3383    /// ```
3384    #[inline]
3385    pub fn insert(&mut self, component: T) {
3386        self.entity_world.insert(component);
3387    }
3388
3389    /// Removes the component from the entry and returns it.
3390    ///
3391    /// # Examples
3392    ///
3393    /// ```
3394    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3395    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3396    /// struct Comp(u32);
3397    ///
3398    /// # let mut world = World::new();
3399    /// let mut entity = world.spawn(Comp(5));
3400    ///
3401    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3402    ///     assert_eq!(o.take(), Comp(5));
3403    /// }
3404    ///
3405    /// assert_eq!(world.query::<&Comp>().iter(&world).len(), 0);
3406    /// ```
3407    #[inline]
3408    pub fn take(self) -> T {
3409        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3410        self.entity_world.take().unwrap()
3411    }
3412}
3413
3414impl<'w, 'a, T: Component<Mutability = Mutable>> OccupiedComponentEntry<'w, 'a, T> {
3415    /// Gets a mutable reference to the component in the entry.
3416    ///
3417    /// If you need a reference to the [`OccupiedComponentEntry`] which may outlive the destruction of
3418    /// the [`OccupiedComponentEntry`] value, see [`into_mut`].
3419    ///
3420    /// [`into_mut`]: Self::into_mut
3421    ///
3422    /// # Examples
3423    ///
3424    /// ```
3425    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3426    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3427    /// struct Comp(u32);
3428    ///
3429    /// # let mut world = World::new();
3430    /// let mut entity = world.spawn(Comp(5));
3431    ///
3432    /// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
3433    ///     o.get_mut().0 += 10;
3434    ///     assert_eq!(o.get().0, 15);
3435    ///
3436    ///     // We can use the same Entry multiple times.
3437    ///     o.get_mut().0 += 2
3438    /// }
3439    ///
3440    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 17);
3441    /// ```
3442    #[inline]
3443    pub fn get_mut(&mut self) -> Mut<'_, T> {
3444        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3445        self.entity_world.get_mut::<T>().unwrap()
3446    }
3447
3448    /// Converts the [`OccupiedComponentEntry`] into a mutable reference to the value in the entry with
3449    /// a lifetime bound to the `EntityWorldMut`.
3450    ///
3451    /// If you need multiple references to the [`OccupiedComponentEntry`], see [`get_mut`].
3452    ///
3453    /// [`get_mut`]: Self::get_mut
3454    ///
3455    /// # Examples
3456    ///
3457    /// ```
3458    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3459    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3460    /// struct Comp(u32);
3461    ///
3462    /// # let mut world = World::new();
3463    /// let mut entity = world.spawn(Comp(5));
3464    ///
3465    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3466    ///     o.into_mut().0 += 10;
3467    /// }
3468    ///
3469    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 15);
3470    /// ```
3471    #[inline]
3472    pub fn into_mut(self) -> Mut<'a, T> {
3473        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3474        self.entity_world.get_mut().unwrap()
3475    }
3476}
3477
3478/// A view into a vacant entry in a [`EntityWorldMut`]. It is part of the [`ComponentEntry`] enum.
3479pub struct VacantComponentEntry<'w, 'a, T: Component> {
3480    entity_world: &'a mut EntityWorldMut<'w>,
3481    _marker: PhantomData<T>,
3482}
3483
3484impl<'w, 'a, T: Component> VacantComponentEntry<'w, 'a, T> {
3485    /// Inserts the component into the [`VacantComponentEntry`] and returns an [`OccupiedComponentEntry`].
3486    ///
3487    /// # Examples
3488    ///
3489    /// ```
3490    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3491    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3492    /// struct Comp(u32);
3493    ///
3494    /// # let mut world = World::new();
3495    /// let mut entity = world.spawn_empty();
3496    ///
3497    /// if let ComponentEntry::Vacant(v) = entity.entry::<Comp>() {
3498    ///     v.insert(Comp(10));
3499    /// }
3500    ///
3501    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
3502    /// ```
3503    #[inline]
3504    pub fn insert(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
3505        self.entity_world.insert(component);
3506        OccupiedComponentEntry {
3507            entity_world: self.entity_world,
3508            _marker: PhantomData,
3509        }
3510    }
3511}
3512
3513/// Provides read-only access to a single entity and some of its components defined by the contained [`Access`].
3514///
3515/// To define the access when used as a [`QueryData`](crate::query::QueryData),
3516/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
3517/// The [`FilteredEntityRef`] must be the entire [`QueryData`](crate::query::QueryData), and not nested inside a tuple with other data.
3518///
3519/// ```
3520/// # use bevy_ecs::{prelude::*, world::FilteredEntityRef};
3521/// #
3522/// # #[derive(Component)]
3523/// # struct A;
3524/// #
3525/// # let mut world = World::new();
3526/// # world.spawn(A);
3527/// #
3528/// // This gives the `FilteredEntityRef` access to `&A`.
3529/// let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world)
3530///     .data::<&A>()
3531///     .build();
3532///
3533/// let filtered_entity: FilteredEntityRef = query.single(&mut world).unwrap();
3534/// let component: &A = filtered_entity.get().unwrap();
3535/// ```
3536#[derive(Clone, Copy)]
3537pub struct FilteredEntityRef<'w, 's> {
3538    entity: UnsafeEntityCell<'w>,
3539    access: &'s Access,
3540}
3541
3542impl<'w, 's> FilteredEntityRef<'w, 's> {
3543    /// # Safety
3544    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
3545    /// - If `access` takes read access to a component no mutable reference to that
3546    ///   component can exist at the same time as the returned [`FilteredEntityMut`]
3547    /// - If `access` takes any access for a component `entity` must have that component.
3548    #[inline]
3549    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
3550        Self { entity, access }
3551    }
3552
3553    /// Returns the [ID](Entity) of the current entity.
3554    #[inline]
3555    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
3556    pub fn id(&self) -> Entity {
3557        self.entity.id()
3558    }
3559
3560    /// Gets metadata indicating the location where the current entity is stored.
3561    #[inline]
3562    pub fn location(&self) -> EntityLocation {
3563        self.entity.location()
3564    }
3565
3566    /// Returns the archetype that the current entity belongs to.
3567    #[inline]
3568    pub fn archetype(&self) -> &Archetype {
3569        self.entity.archetype()
3570    }
3571
3572    /// Returns a reference to the underlying [`Access`].
3573    #[inline]
3574    pub fn access(&self) -> &Access {
3575        self.access
3576    }
3577
3578    /// Returns `true` if the current entity has a component of type `T`.
3579    /// Otherwise, this returns `false`.
3580    ///
3581    /// ## Notes
3582    ///
3583    /// If you do not know the concrete type of a component, consider using
3584    /// [`Self::contains_id`] or [`Self::contains_type_id`].
3585    #[inline]
3586    pub fn contains<T: Component>(&self) -> bool {
3587        self.contains_type_id(TypeId::of::<T>())
3588    }
3589
3590    /// Returns `true` if the current entity has a component identified by `component_id`.
3591    /// Otherwise, this returns false.
3592    ///
3593    /// ## Notes
3594    ///
3595    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3596    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
3597    ///   [`Self::contains_type_id`].
3598    #[inline]
3599    pub fn contains_id(&self, component_id: ComponentId) -> bool {
3600        self.entity.contains_id(component_id)
3601    }
3602
3603    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
3604    /// Otherwise, this returns false.
3605    ///
3606    /// ## Notes
3607    ///
3608    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3609    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
3610    #[inline]
3611    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
3612        self.entity.contains_type_id(type_id)
3613    }
3614
3615    /// Gets access to the component of type `T` for the current entity.
3616    /// Returns `None` if the entity does not have a component of type `T`.
3617    #[inline]
3618    pub fn get<T: Component>(&self) -> Option<&'w T> {
3619        let id = self
3620            .entity
3621            .world()
3622            .components()
3623            .get_valid_id(TypeId::of::<T>())?;
3624        self.access
3625            .has_component_read(id)
3626            // SAFETY: We have read access
3627            .then(|| unsafe { self.entity.get() })
3628            .flatten()
3629    }
3630
3631    /// Gets access to the component of type `T` for the current entity,
3632    /// including change detection information as a [`Ref`].
3633    ///
3634    /// Returns `None` if the entity does not have a component of type `T`.
3635    #[inline]
3636    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
3637        let id = self
3638            .entity
3639            .world()
3640            .components()
3641            .get_valid_id(TypeId::of::<T>())?;
3642        self.access
3643            .has_component_read(id)
3644            // SAFETY: We have read access
3645            .then(|| unsafe { self.entity.get_ref() })
3646            .flatten()
3647    }
3648
3649    /// Retrieves the change ticks for the given component. This can be useful for implementing change
3650    /// detection in custom runtimes.
3651    #[inline]
3652    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
3653        let id = self
3654            .entity
3655            .world()
3656            .components()
3657            .get_valid_id(TypeId::of::<T>())?;
3658        self.access
3659            .has_component_read(id)
3660            // SAFETY: We have read access
3661            .then(|| unsafe { self.entity.get_change_ticks::<T>() })
3662            .flatten()
3663    }
3664
3665    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
3666    /// detection in custom runtimes.
3667    ///
3668    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
3669    /// use this in cases where the actual component types are not known at
3670    /// compile time.**
3671    #[inline]
3672    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
3673        self.access
3674            .has_component_read(component_id)
3675            // SAFETY: We have read access
3676            .then(|| unsafe { self.entity.get_change_ticks_by_id(component_id) })
3677            .flatten()
3678    }
3679
3680    /// Gets the component of the given [`ComponentId`] from the entity.
3681    ///
3682    /// **You should prefer to use the typed API [`Self::get`] where possible and only
3683    /// use this in cases where the actual component types are not known at
3684    /// compile time.**
3685    ///
3686    /// Unlike [`FilteredEntityRef::get`], this returns a raw pointer to the component,
3687    /// which is only valid while the [`FilteredEntityRef`] is alive.
3688    #[inline]
3689    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
3690        self.access
3691            .has_component_read(component_id)
3692            // SAFETY: We have read access
3693            .then(|| unsafe { self.entity.get_by_id(component_id) })
3694            .flatten()
3695    }
3696
3697    /// Returns the source code location from which this entity has been spawned.
3698    pub fn spawned_by(&self) -> MaybeLocation {
3699        self.entity.spawned_by()
3700    }
3701
3702    /// Returns the [`Tick`] at which this entity has been spawned.
3703    pub fn spawn_tick(&self) -> Tick {
3704        self.entity.spawn_tick()
3705    }
3706}
3707
3708impl<'w, 's> From<FilteredEntityMut<'w, 's>> for FilteredEntityRef<'w, 's> {
3709    #[inline]
3710    fn from(entity: FilteredEntityMut<'w, 's>) -> Self {
3711        // SAFETY:
3712        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3713        unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
3714    }
3715}
3716
3717impl<'w, 's> From<&'w FilteredEntityMut<'_, 's>> for FilteredEntityRef<'w, 's> {
3718    #[inline]
3719    fn from(entity: &'w FilteredEntityMut<'_, 's>) -> Self {
3720        // SAFETY:
3721        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3722        unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
3723    }
3724}
3725
3726impl<'a> From<EntityRef<'a>> for FilteredEntityRef<'a, 'static> {
3727    fn from(entity: EntityRef<'a>) -> Self {
3728        // SAFETY:
3729        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3730        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3731    }
3732}
3733
3734impl<'a> From<&'a EntityRef<'_>> for FilteredEntityRef<'a, 'static> {
3735    fn from(entity: &'a EntityRef<'_>) -> Self {
3736        // SAFETY:
3737        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3738        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3739    }
3740}
3741
3742impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a, 'static> {
3743    fn from(entity: EntityMut<'a>) -> Self {
3744        // SAFETY:
3745        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3746        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3747    }
3748}
3749
3750impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a, 'static> {
3751    fn from(entity: &'a EntityMut<'_>) -> Self {
3752        // SAFETY:
3753        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3754        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3755    }
3756}
3757
3758impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a, 'static> {
3759    fn from(entity: EntityWorldMut<'a>) -> Self {
3760        // SAFETY:
3761        // - `EntityWorldMut` guarantees exclusive access to the entire world.
3762        unsafe {
3763            FilteredEntityRef::new(
3764                entity.into_unsafe_entity_cell(),
3765                const { &Access::new_read_all() },
3766            )
3767        }
3768    }
3769}
3770
3771impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static> {
3772    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
3773        // SAFETY:
3774        // - `EntityWorldMut` guarantees exclusive access to the entire world.
3775        unsafe {
3776            FilteredEntityRef::new(
3777                entity.as_unsafe_entity_cell_readonly(),
3778                const { &Access::new_read_all() },
3779            )
3780        }
3781    }
3782}
3783
3784impl<'w, 's, B: Bundle> From<&'w EntityRefExcept<'_, 's, B>> for FilteredEntityRef<'w, 's> {
3785    fn from(value: &'w EntityRefExcept<'_, 's, B>) -> Self {
3786        // SAFETY:
3787        // - The FilteredEntityRef has the same component access as the given EntityRefExcept.
3788        unsafe { FilteredEntityRef::new(value.entity, value.access) }
3789    }
3790}
3791
3792impl PartialEq for FilteredEntityRef<'_, '_> {
3793    fn eq(&self, other: &Self) -> bool {
3794        self.entity() == other.entity()
3795    }
3796}
3797
3798impl Eq for FilteredEntityRef<'_, '_> {}
3799
3800impl PartialOrd for FilteredEntityRef<'_, '_> {
3801    /// [`FilteredEntityRef`]'s comparison trait implementations match the underlying [`Entity`],
3802    /// and cannot discern between different worlds.
3803    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3804        Some(self.cmp(other))
3805    }
3806}
3807
3808impl Ord for FilteredEntityRef<'_, '_> {
3809    fn cmp(&self, other: &Self) -> Ordering {
3810        self.entity().cmp(&other.entity())
3811    }
3812}
3813
3814impl Hash for FilteredEntityRef<'_, '_> {
3815    fn hash<H: Hasher>(&self, state: &mut H) {
3816        self.entity().hash(state);
3817    }
3818}
3819
3820impl ContainsEntity for FilteredEntityRef<'_, '_> {
3821    fn entity(&self) -> Entity {
3822        self.id()
3823    }
3824}
3825
3826// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
3827unsafe impl EntityEquivalent for FilteredEntityRef<'_, '_> {}
3828
3829/// Provides mutable access to a single entity and some of its components defined by the contained [`Access`].
3830///
3831/// To define the access when used as a [`QueryData`](crate::query::QueryData),
3832/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
3833/// The `FilteredEntityMut` must be the entire `QueryData`, and not nested inside a tuple with other data.
3834///
3835/// ```
3836/// # use bevy_ecs::{prelude::*, world::FilteredEntityMut};
3837/// #
3838/// # #[derive(Component)]
3839/// # struct A;
3840/// #
3841/// # let mut world = World::new();
3842/// # world.spawn(A);
3843/// #
3844/// // This gives the `FilteredEntityMut` access to `&mut A`.
3845/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world)
3846///     .data::<&mut A>()
3847///     .build();
3848///
3849/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap();
3850/// let component: Mut<A> = filtered_entity.get_mut().unwrap();
3851/// ```
3852pub struct FilteredEntityMut<'w, 's> {
3853    entity: UnsafeEntityCell<'w>,
3854    access: &'s Access,
3855}
3856
3857impl<'w, 's> FilteredEntityMut<'w, 's> {
3858    /// # Safety
3859    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
3860    /// - If `access` takes read access to a component no mutable reference to that
3861    ///   component can exist at the same time as the returned [`FilteredEntityMut`]
3862    /// - If `access` takes write access to a component, no reference to that component
3863    ///   may exist at the same time as the returned [`FilteredEntityMut`]
3864    /// - If `access` takes any access for a component `entity` must have that component.
3865    #[inline]
3866    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
3867        Self { entity, access }
3868    }
3869
3870    /// Returns a new instance with a shorter lifetime.
3871    /// This is useful if you have `&mut FilteredEntityMut`, but you need `FilteredEntityMut`.
3872    pub fn reborrow(&mut self) -> FilteredEntityMut<'_, 's> {
3873        // SAFETY: We have exclusive access to the entire entity and its components.
3874        unsafe { Self::new(self.entity, self.access) }
3875    }
3876
3877    /// Gets read-only access to all of the entity's components.
3878    #[inline]
3879    pub fn as_readonly(&self) -> FilteredEntityRef<'_, 's> {
3880        FilteredEntityRef::from(self)
3881    }
3882
3883    /// Returns the [ID](Entity) of the current entity.
3884    #[inline]
3885    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
3886    pub fn id(&self) -> Entity {
3887        self.entity.id()
3888    }
3889
3890    /// Gets metadata indicating the location where the current entity is stored.
3891    #[inline]
3892    pub fn location(&self) -> EntityLocation {
3893        self.entity.location()
3894    }
3895
3896    /// Returns the archetype that the current entity belongs to.
3897    #[inline]
3898    pub fn archetype(&self) -> &Archetype {
3899        self.entity.archetype()
3900    }
3901
3902    /// Returns a reference to the underlying [`Access`].
3903    #[inline]
3904    pub fn access(&self) -> &Access {
3905        self.access
3906    }
3907
3908    /// Returns `true` if the current entity has a component of type `T`.
3909    /// Otherwise, this returns `false`.
3910    ///
3911    /// ## Notes
3912    ///
3913    /// If you do not know the concrete type of a component, consider using
3914    /// [`Self::contains_id`] or [`Self::contains_type_id`].
3915    #[inline]
3916    pub fn contains<T: Component>(&self) -> bool {
3917        self.contains_type_id(TypeId::of::<T>())
3918    }
3919
3920    /// Returns `true` if the current entity has a component identified by `component_id`.
3921    /// Otherwise, this returns false.
3922    ///
3923    /// ## Notes
3924    ///
3925    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3926    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
3927    ///   [`Self::contains_type_id`].
3928    #[inline]
3929    pub fn contains_id(&self, component_id: ComponentId) -> bool {
3930        self.entity.contains_id(component_id)
3931    }
3932
3933    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
3934    /// Otherwise, this returns false.
3935    ///
3936    /// ## Notes
3937    ///
3938    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3939    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
3940    #[inline]
3941    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
3942        self.entity.contains_type_id(type_id)
3943    }
3944
3945    /// Gets access to the component of type `T` for the current entity.
3946    /// Returns `None` if the entity does not have a component of type `T`.
3947    #[inline]
3948    pub fn get<T: Component>(&self) -> Option<&'_ T> {
3949        self.as_readonly().get()
3950    }
3951
3952    /// Gets access to the component of type `T` for the current entity,
3953    /// including change detection information as a [`Ref`].
3954    ///
3955    /// Returns `None` if the entity does not have a component of type `T`.
3956    #[inline]
3957    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
3958        self.as_readonly().get_ref()
3959    }
3960
3961    /// Gets mutable access to the component of type `T` for the current entity.
3962    /// Returns `None` if the entity does not have a component of type `T`.
3963    #[inline]
3964    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
3965        let id = self
3966            .entity
3967            .world()
3968            .components()
3969            .get_valid_id(TypeId::of::<T>())?;
3970        self.access
3971            .has_component_write(id)
3972            // SAFETY: We have write access
3973            .then(|| unsafe { self.entity.get_mut() })
3974            .flatten()
3975    }
3976
3977    /// Consumes self and gets mutable access to the component of type `T`
3978    /// with the world `'w` lifetime for the current entity.
3979    /// Returns `None` if the entity does not have a component of type `T`.
3980    #[inline]
3981    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
3982        // SAFETY:
3983        // - We have write access
3984        // - The bound `T: Component<Mutability = Mutable>` ensures the component is mutable
3985        unsafe { self.into_mut_assume_mutable() }
3986    }
3987
3988    /// Consumes self and gets mutable access to the component of type `T`
3989    /// with the world `'w` lifetime for the current entity.
3990    /// Returns `None` if the entity does not have a component of type `T`.
3991    ///
3992    /// # Safety
3993    ///
3994    /// - `T` must be a mutable component
3995    #[inline]
3996    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
3997        let id = self
3998            .entity
3999            .world()
4000            .components()
4001            .get_valid_id(TypeId::of::<T>())?;
4002        self.access
4003            .has_component_write(id)
4004            // SAFETY:
4005            // - We have write access
4006            // - Caller ensures `T` is a mutable component
4007            .then(|| unsafe { self.entity.get_mut_assume_mutable() })
4008            .flatten()
4009    }
4010
4011    /// Retrieves the change ticks for the given component. This can be useful for implementing change
4012    /// detection in custom runtimes.
4013    #[inline]
4014    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
4015        self.as_readonly().get_change_ticks::<T>()
4016    }
4017
4018    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
4019    /// detection in custom runtimes.
4020    ///
4021    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
4022    /// use this in cases where the actual component types are not known at
4023    /// compile time.**
4024    #[inline]
4025    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
4026        self.as_readonly().get_change_ticks_by_id(component_id)
4027    }
4028
4029    /// Gets the component of the given [`ComponentId`] from the entity.
4030    ///
4031    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4032    /// use this in cases where the actual component types are not known at
4033    /// compile time.**
4034    ///
4035    /// Unlike [`FilteredEntityMut::get`], this returns a raw pointer to the component,
4036    /// which is only valid while the [`FilteredEntityMut`] is alive.
4037    #[inline]
4038    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
4039        self.as_readonly().get_by_id(component_id)
4040    }
4041
4042    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
4043    ///
4044    /// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
4045    /// use this in cases where the actual component types are not known at
4046    /// compile time.**
4047    ///
4048    /// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component,
4049    /// which is only valid while the [`FilteredEntityMut`] is alive.
4050    #[inline]
4051    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
4052        self.access
4053            .has_component_write(component_id)
4054            // SAFETY: We have write access
4055            .then(|| unsafe { self.entity.get_mut_by_id(component_id).ok() })
4056            .flatten()
4057    }
4058
4059    /// Returns the source code location from which this entity has last been spawned.
4060    pub fn spawned_by(&self) -> MaybeLocation {
4061        self.entity.spawned_by()
4062    }
4063
4064    /// Returns the [`Tick`] at which this entity has been spawned.
4065    pub fn spawn_tick(&self) -> Tick {
4066        self.entity.spawn_tick()
4067    }
4068}
4069
4070impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a, 'static> {
4071    fn from(entity: EntityMut<'a>) -> Self {
4072        // SAFETY:
4073        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
4074        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
4075    }
4076}
4077
4078impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a, 'static> {
4079    fn from(entity: &'a mut EntityMut<'_>) -> Self {
4080        // SAFETY:
4081        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
4082        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
4083    }
4084}
4085
4086impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a, 'static> {
4087    fn from(entity: EntityWorldMut<'a>) -> Self {
4088        // SAFETY:
4089        // - `EntityWorldMut` guarantees exclusive access to the entire world.
4090        unsafe {
4091            FilteredEntityMut::new(
4092                entity.into_unsafe_entity_cell(),
4093                const { &Access::new_write_all() },
4094            )
4095        }
4096    }
4097}
4098
4099impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static> {
4100    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
4101        // SAFETY:
4102        // - `EntityWorldMut` guarantees exclusive access to the entire world.
4103        unsafe {
4104            FilteredEntityMut::new(
4105                entity.as_unsafe_entity_cell(),
4106                const { &Access::new_write_all() },
4107            )
4108        }
4109    }
4110}
4111
4112impl<'w, 's, B: Bundle> From<&'w EntityMutExcept<'_, 's, B>> for FilteredEntityMut<'w, 's> {
4113    fn from(value: &'w EntityMutExcept<'_, 's, B>) -> Self {
4114        // SAFETY:
4115        // - The FilteredEntityMut has the same component access as the given EntityMutExcept.
4116        unsafe { FilteredEntityMut::new(value.entity, value.access) }
4117    }
4118}
4119
4120impl PartialEq for FilteredEntityMut<'_, '_> {
4121    fn eq(&self, other: &Self) -> bool {
4122        self.entity() == other.entity()
4123    }
4124}
4125
4126impl Eq for FilteredEntityMut<'_, '_> {}
4127
4128impl PartialOrd for FilteredEntityMut<'_, '_> {
4129    /// [`FilteredEntityMut`]'s comparison trait implementations match the underlying [`Entity`],
4130    /// and cannot discern between different worlds.
4131    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4132        Some(self.cmp(other))
4133    }
4134}
4135
4136impl Ord for FilteredEntityMut<'_, '_> {
4137    fn cmp(&self, other: &Self) -> Ordering {
4138        self.entity().cmp(&other.entity())
4139    }
4140}
4141
4142impl Hash for FilteredEntityMut<'_, '_> {
4143    fn hash<H: Hasher>(&self, state: &mut H) {
4144        self.entity().hash(state);
4145    }
4146}
4147
4148impl ContainsEntity for FilteredEntityMut<'_, '_> {
4149    fn entity(&self) -> Entity {
4150        self.id()
4151    }
4152}
4153
4154// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4155unsafe impl EntityEquivalent for FilteredEntityMut<'_, '_> {}
4156
4157/// Error type returned by [`TryFrom`] conversions from filtered entity types
4158/// ([`FilteredEntityRef`]/[`FilteredEntityMut`]) to full-access entity types
4159/// ([`EntityRef`]/[`EntityMut`]).
4160#[derive(Error, Debug)]
4161pub enum TryFromFilteredError {
4162    /// Error indicating that the filtered entity does not have read access to
4163    /// all components.
4164    #[error("Conversion failed, filtered entity ref does not have read access to all components")]
4165    MissingReadAllAccess,
4166    /// Error indicating that the filtered entity does not have write access to
4167    /// all components.
4168    #[error("Conversion failed, filtered entity ref does not have write access to all components")]
4169    MissingWriteAllAccess,
4170}
4171
4172/// Provides read-only access to a single entity and all its components, save
4173/// for an explicitly-enumerated set.
4174pub struct EntityRefExcept<'w, 's, B>
4175where
4176    B: Bundle,
4177{
4178    entity: UnsafeEntityCell<'w>,
4179    access: &'s Access,
4180    phantom: PhantomData<B>,
4181}
4182
4183impl<'w, 's, B> EntityRefExcept<'w, 's, B>
4184where
4185    B: Bundle,
4186{
4187    /// # Safety
4188    /// Other users of `UnsafeEntityCell` must only have mutable access to the components in `B`.
4189    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
4190        Self {
4191            entity,
4192            access,
4193            phantom: PhantomData,
4194        }
4195    }
4196
4197    /// Returns the [ID](Entity) of the current entity.
4198    #[inline]
4199    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
4200    pub fn id(&self) -> Entity {
4201        self.entity.id()
4202    }
4203
4204    /// Gets access to the component of type `C` for the current entity. Returns
4205    /// `None` if the component doesn't have a component of that type or if the
4206    /// type is one of the excluded components.
4207    #[inline]
4208    pub fn get<C>(&self) -> Option<&'w C>
4209    where
4210        C: Component,
4211    {
4212        let components = self.entity.world().components();
4213        let id = components.valid_component_id::<C>()?;
4214        if bundle_contains_component::<B>(components, id) {
4215            None
4216        } else {
4217            // SAFETY: We have read access for all components that weren't
4218            // covered by the `contains` check above.
4219            unsafe { self.entity.get() }
4220        }
4221    }
4222
4223    /// Gets access to the component of type `C` for the current entity,
4224    /// including change detection information. Returns `None` if the component
4225    /// doesn't have a component of that type or if the type is one of the
4226    /// excluded components.
4227    #[inline]
4228    pub fn get_ref<C>(&self) -> Option<Ref<'w, C>>
4229    where
4230        C: Component,
4231    {
4232        let components = self.entity.world().components();
4233        let id = components.valid_component_id::<C>()?;
4234        if bundle_contains_component::<B>(components, id) {
4235            None
4236        } else {
4237            // SAFETY: We have read access for all components that weren't
4238            // covered by the `contains` check above.
4239            unsafe { self.entity.get_ref() }
4240        }
4241    }
4242
4243    /// Returns the source code location from which this entity has been spawned.
4244    pub fn spawned_by(&self) -> MaybeLocation {
4245        self.entity.spawned_by()
4246    }
4247
4248    /// Returns the [`Tick`] at which this entity has been spawned.
4249    pub fn spawn_tick(&self) -> Tick {
4250        self.entity.spawn_tick()
4251    }
4252
4253    /// Gets the component of the given [`ComponentId`] from the entity.
4254    ///
4255    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4256    /// use this in cases where the actual component types are not known at
4257    /// compile time.**
4258    ///
4259    /// Unlike [`EntityRefExcept::get`], this returns a raw pointer to the component,
4260    /// which is only valid while the [`EntityRefExcept`] is alive.
4261    #[inline]
4262    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
4263        let components = self.entity.world().components();
4264        (!bundle_contains_component::<B>(components, component_id))
4265            .then(|| {
4266                // SAFETY: We have read access for this component
4267                unsafe { self.entity.get_by_id(component_id) }
4268            })
4269            .flatten()
4270    }
4271
4272    /// Returns `true` if the current entity has a component of type `T`.
4273    /// Otherwise, this returns `false`.
4274    ///
4275    /// ## Notes
4276    ///
4277    /// If you do not know the concrete type of a component, consider using
4278    /// [`Self::contains_id`] or [`Self::contains_type_id`].
4279    #[inline]
4280    pub fn contains<T: Component>(&self) -> bool {
4281        self.contains_type_id(TypeId::of::<T>())
4282    }
4283
4284    /// Returns `true` if the current entity has a component identified by `component_id`.
4285    /// Otherwise, this returns false.
4286    ///
4287    /// ## Notes
4288    ///
4289    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4290    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
4291    ///   [`Self::contains_type_id`].
4292    #[inline]
4293    pub fn contains_id(&self, component_id: ComponentId) -> bool {
4294        self.entity.contains_id(component_id)
4295    }
4296
4297    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
4298    /// Otherwise, this returns false.
4299    ///
4300    /// ## Notes
4301    ///
4302    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4303    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
4304    #[inline]
4305    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
4306        self.entity.contains_type_id(type_id)
4307    }
4308
4309    /// Retrieves the change ticks for the given component. This can be useful for implementing change
4310    /// detection in custom runtimes.
4311    #[inline]
4312    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
4313        let component_id = self
4314            .entity
4315            .world()
4316            .components()
4317            .get_valid_id(TypeId::of::<T>())?;
4318        let components = self.entity.world().components();
4319        (!bundle_contains_component::<B>(components, component_id))
4320            .then(|| {
4321                // SAFETY: We have read access
4322                unsafe { self.entity.get_change_ticks::<T>() }
4323            })
4324            .flatten()
4325    }
4326
4327    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
4328    /// detection in custom runtimes.
4329    ///
4330    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
4331    /// use this in cases where the actual component types are not known at
4332    /// compile time.**
4333    #[inline]
4334    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
4335        let components = self.entity.world().components();
4336        (!bundle_contains_component::<B>(components, component_id))
4337            .then(|| {
4338                // SAFETY: We have read access
4339                unsafe { self.entity.get_change_ticks_by_id(component_id) }
4340            })
4341            .flatten()
4342    }
4343}
4344
4345impl<'w, 's, B> From<&'w EntityMutExcept<'_, 's, B>> for EntityRefExcept<'w, 's, B>
4346where
4347    B: Bundle,
4348{
4349    fn from(entity: &'w EntityMutExcept<'_, 's, B>) -> Self {
4350        // SAFETY: All accesses that `EntityRefExcept` provides are also
4351        // accesses that `EntityMutExcept` provides.
4352        unsafe { EntityRefExcept::new(entity.entity, entity.access) }
4353    }
4354}
4355
4356impl<B: Bundle> Clone for EntityRefExcept<'_, '_, B> {
4357    fn clone(&self) -> Self {
4358        *self
4359    }
4360}
4361
4362impl<B: Bundle> Copy for EntityRefExcept<'_, '_, B> {}
4363
4364impl<B: Bundle> PartialEq for EntityRefExcept<'_, '_, B> {
4365    fn eq(&self, other: &Self) -> bool {
4366        self.entity() == other.entity()
4367    }
4368}
4369
4370impl<B: Bundle> Eq for EntityRefExcept<'_, '_, B> {}
4371
4372impl<B: Bundle> PartialOrd for EntityRefExcept<'_, '_, B> {
4373    /// [`EntityRefExcept`]'s comparison trait implementations match the underlying [`Entity`],
4374    /// and cannot discern between different worlds.
4375    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4376        Some(self.cmp(other))
4377    }
4378}
4379
4380impl<B: Bundle> Ord for EntityRefExcept<'_, '_, B> {
4381    fn cmp(&self, other: &Self) -> Ordering {
4382        self.entity().cmp(&other.entity())
4383    }
4384}
4385
4386impl<B: Bundle> Hash for EntityRefExcept<'_, '_, B> {
4387    fn hash<H: Hasher>(&self, state: &mut H) {
4388        self.entity().hash(state);
4389    }
4390}
4391
4392impl<B: Bundle> ContainsEntity for EntityRefExcept<'_, '_, B> {
4393    fn entity(&self) -> Entity {
4394        self.id()
4395    }
4396}
4397
4398// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4399unsafe impl<B: Bundle> EntityEquivalent for EntityRefExcept<'_, '_, B> {}
4400
4401/// Provides mutable access to all components of an entity, with the exception
4402/// of an explicit set.
4403///
4404/// This is a rather niche type that should only be used if you need access to
4405/// *all* components of an entity, while still allowing you to consult other
4406/// queries that might match entities that this query also matches. If you don't
4407/// need access to all components, prefer a standard query with a
4408/// [`Without`](`crate::query::Without`) filter.
4409pub struct EntityMutExcept<'w, 's, B>
4410where
4411    B: Bundle,
4412{
4413    entity: UnsafeEntityCell<'w>,
4414    access: &'s Access,
4415    phantom: PhantomData<B>,
4416}
4417
4418impl<'w, 's, B> EntityMutExcept<'w, 's, B>
4419where
4420    B: Bundle,
4421{
4422    /// # Safety
4423    /// Other users of `UnsafeEntityCell` must not have access to any components not in `B`.
4424    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
4425        Self {
4426            entity,
4427            access,
4428            phantom: PhantomData,
4429        }
4430    }
4431
4432    /// Returns the [ID](Entity) of the current entity.
4433    #[inline]
4434    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
4435    pub fn id(&self) -> Entity {
4436        self.entity.id()
4437    }
4438
4439    /// Returns a new instance with a shorter lifetime.
4440    ///
4441    /// This is useful if you have `&mut EntityMutExcept`, but you need
4442    /// `EntityMutExcept`.
4443    pub fn reborrow(&mut self) -> EntityMutExcept<'_, 's, B> {
4444        // SAFETY: We have exclusive access to the entire entity and the
4445        // applicable components.
4446        unsafe { Self::new(self.entity, self.access) }
4447    }
4448
4449    /// Gets read-only access to all of the entity's components, except for the
4450    /// ones in `CL`.
4451    #[inline]
4452    pub fn as_readonly(&self) -> EntityRefExcept<'_, 's, B> {
4453        EntityRefExcept::from(self)
4454    }
4455
4456    /// Gets access to the component of type `C` for the current entity. Returns
4457    /// `None` if the component doesn't have a component of that type or if the
4458    /// type is one of the excluded components.
4459    #[inline]
4460    pub fn get<C>(&self) -> Option<&'_ C>
4461    where
4462        C: Component,
4463    {
4464        self.as_readonly().get()
4465    }
4466
4467    /// Gets access to the component of type `C` for the current entity,
4468    /// including change detection information. Returns `None` if the component
4469    /// doesn't have a component of that type or if the type is one of the
4470    /// excluded components.
4471    #[inline]
4472    pub fn get_ref<C>(&self) -> Option<Ref<'_, C>>
4473    where
4474        C: Component,
4475    {
4476        self.as_readonly().get_ref()
4477    }
4478
4479    /// Gets mutable access to the component of type `C` for the current entity.
4480    /// Returns `None` if the component doesn't have a component of that type or
4481    /// if the type is one of the excluded components.
4482    #[inline]
4483    pub fn get_mut<C>(&mut self) -> Option<Mut<'_, C>>
4484    where
4485        C: Component<Mutability = Mutable>,
4486    {
4487        let components = self.entity.world().components();
4488        let id = components.valid_component_id::<C>()?;
4489        if bundle_contains_component::<B>(components, id) {
4490            None
4491        } else {
4492            // SAFETY: We have write access for all components that weren't
4493            // covered by the `contains` check above.
4494            unsafe { self.entity.get_mut() }
4495        }
4496    }
4497
4498    /// Returns the source code location from which this entity has been spawned.
4499    pub fn spawned_by(&self) -> MaybeLocation {
4500        self.entity.spawned_by()
4501    }
4502
4503    /// Returns the [`Tick`] at which this entity has been spawned.
4504    pub fn spawn_tick(&self) -> Tick {
4505        self.entity.spawn_tick()
4506    }
4507
4508    /// Returns `true` if the current entity has a component of type `T`.
4509    /// Otherwise, this returns `false`.
4510    ///
4511    /// ## Notes
4512    ///
4513    /// If you do not know the concrete type of a component, consider using
4514    /// [`Self::contains_id`] or [`Self::contains_type_id`].
4515    #[inline]
4516    pub fn contains<T: Component>(&self) -> bool {
4517        self.contains_type_id(TypeId::of::<T>())
4518    }
4519
4520    /// Returns `true` if the current entity has a component identified by `component_id`.
4521    /// Otherwise, this returns false.
4522    ///
4523    /// ## Notes
4524    ///
4525    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4526    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
4527    ///   [`Self::contains_type_id`].
4528    #[inline]
4529    pub fn contains_id(&self, component_id: ComponentId) -> bool {
4530        self.entity.contains_id(component_id)
4531    }
4532
4533    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
4534    /// Otherwise, this returns false.
4535    ///
4536    /// ## Notes
4537    ///
4538    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4539    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
4540    #[inline]
4541    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
4542        self.entity.contains_type_id(type_id)
4543    }
4544
4545    /// Gets the component of the given [`ComponentId`] from the entity.
4546    ///
4547    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4548    /// use this in cases where the actual component types are not known at
4549    /// compile time.**
4550    ///
4551    /// Unlike [`EntityMutExcept::get`], this returns a raw pointer to the component,
4552    /// which is only valid while the [`EntityMutExcept`] is alive.
4553    #[inline]
4554    pub fn get_by_id(&'w self, component_id: ComponentId) -> Option<Ptr<'w>> {
4555        self.as_readonly().get_by_id(component_id)
4556    }
4557
4558    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
4559    ///
4560    /// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
4561    /// use this in cases where the actual component types are not known at
4562    /// compile time.**
4563    ///
4564    /// Unlike [`EntityMutExcept::get_mut`], this returns a raw pointer to the component,
4565    /// which is only valid while the [`EntityMutExcept`] is alive.
4566    #[inline]
4567    pub fn get_mut_by_id<F: DynamicComponentFetch>(
4568        &mut self,
4569        component_id: ComponentId,
4570    ) -> Option<MutUntyped<'_>> {
4571        let components = self.entity.world().components();
4572        (!bundle_contains_component::<B>(components, component_id))
4573            .then(|| {
4574                // SAFETY: We have write access
4575                unsafe { self.entity.get_mut_by_id(component_id).ok() }
4576            })
4577            .flatten()
4578    }
4579}
4580
4581impl<B: Bundle> PartialEq for EntityMutExcept<'_, '_, B> {
4582    fn eq(&self, other: &Self) -> bool {
4583        self.entity() == other.entity()
4584    }
4585}
4586
4587impl<B: Bundle> Eq for EntityMutExcept<'_, '_, B> {}
4588
4589impl<B: Bundle> PartialOrd for EntityMutExcept<'_, '_, B> {
4590    /// [`EntityMutExcept`]'s comparison trait implementations match the underlying [`Entity`],
4591    /// and cannot discern between different worlds.
4592    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4593        Some(self.cmp(other))
4594    }
4595}
4596
4597impl<B: Bundle> Ord for EntityMutExcept<'_, '_, B> {
4598    fn cmp(&self, other: &Self) -> Ordering {
4599        self.entity().cmp(&other.entity())
4600    }
4601}
4602
4603impl<B: Bundle> Hash for EntityMutExcept<'_, '_, B> {
4604    fn hash<H: Hasher>(&self, state: &mut H) {
4605        self.entity().hash(state);
4606    }
4607}
4608
4609impl<B: Bundle> ContainsEntity for EntityMutExcept<'_, '_, B> {
4610    fn entity(&self) -> Entity {
4611        self.id()
4612    }
4613}
4614
4615// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4616unsafe impl<B: Bundle> EntityEquivalent for EntityMutExcept<'_, '_, B> {}
4617
4618fn bundle_contains_component<B>(components: &Components, query_id: ComponentId) -> bool
4619where
4620    B: Bundle,
4621{
4622    let mut found = false;
4623    B::get_component_ids(components, &mut |maybe_id| {
4624        if let Some(id) = maybe_id {
4625            found = found || id == query_id;
4626        }
4627    });
4628    found
4629}
4630
4631/// Inserts a dynamic [`Bundle`] into the entity.
4632///
4633/// # Safety
4634///
4635/// - [`OwningPtr`] and [`StorageType`] iterators must correspond to the
4636///   [`BundleInfo`](crate::bundle::BundleInfo) used to construct [`BundleInserter`]
4637/// - [`Entity`] must correspond to [`EntityLocation`]
4638unsafe fn insert_dynamic_bundle<
4639    'a,
4640    I: Iterator<Item = OwningPtr<'a>>,
4641    S: Iterator<Item = StorageType>,
4642>(
4643    mut bundle_inserter: BundleInserter<'_>,
4644    entity: Entity,
4645    location: EntityLocation,
4646    components: I,
4647    storage_types: S,
4648    mode: InsertMode,
4649    caller: MaybeLocation,
4650    relationship_hook_insert_mode: RelationshipHookMode,
4651) -> EntityLocation {
4652    struct DynamicInsertBundle<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> {
4653        components: I,
4654    }
4655
4656    impl<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> DynamicBundle
4657        for DynamicInsertBundle<'a, I>
4658    {
4659        type Effect = ();
4660        unsafe fn get_components(
4661            mut ptr: MovingPtr<'_, Self>,
4662            func: &mut impl FnMut(StorageType, OwningPtr<'_>),
4663        ) {
4664            (&mut ptr.components).for_each(|(t, ptr)| func(t, ptr));
4665        }
4666
4667        unsafe fn apply_effect(
4668            _ptr: MovingPtr<'_, MaybeUninit<Self>>,
4669            _entity: &mut EntityWorldMut,
4670        ) {
4671        }
4672    }
4673
4674    let bundle = DynamicInsertBundle {
4675        components: storage_types.zip(components),
4676    };
4677
4678    move_as_ptr!(bundle);
4679
4680    // SAFETY:
4681    // - `location` matches `entity`.  and thus must currently exist in the source
4682    //   archetype for this inserter and its location within the archetype.
4683    // - The caller must ensure that the iterators and storage types match up with the `BundleInserter`
4684    // - `apply_effect` is never called on this bundle.
4685    // - `bundle` is not used or dropped after this point.
4686    unsafe {
4687        bundle_inserter.insert(
4688            entity,
4689            location,
4690            bundle,
4691            mode,
4692            caller,
4693            relationship_hook_insert_mode,
4694        )
4695    }
4696}
4697
4698/// Types that can be used to fetch components from an entity dynamically by
4699/// [`ComponentId`]s.
4700///
4701/// Provided implementations are:
4702/// - [`ComponentId`]: Returns a single untyped reference.
4703/// - `[ComponentId; N]` and `&[ComponentId; N]`: Returns a same-sized array of untyped references.
4704/// - `&[ComponentId]`: Returns a [`Vec`] of untyped references.
4705/// - [`&HashSet<ComponentId>`](HashSet): Returns a [`HashMap`] of IDs to untyped references.
4706///
4707/// # Performance
4708///
4709/// - The slice and array implementations perform an aliased mutability check in
4710///   [`DynamicComponentFetch::fetch_mut`] that is `O(N^2)`.
4711/// - The [`HashSet`] implementation performs no such check as the type itself
4712///   guarantees unique IDs.
4713/// - The single [`ComponentId`] implementation performs no such check as only
4714///   one reference is returned.
4715///
4716/// # Safety
4717///
4718/// Implementor must ensure that:
4719/// - No aliased mutability is caused by the returned references.
4720/// - [`DynamicComponentFetch::fetch_ref`] returns only read-only references.
4721pub unsafe trait DynamicComponentFetch {
4722    /// The read-only reference type returned by [`DynamicComponentFetch::fetch_ref`].
4723    type Ref<'w>;
4724
4725    /// The mutable reference type returned by [`DynamicComponentFetch::fetch_mut`].
4726    type Mut<'w>;
4727
4728    /// Returns untyped read-only reference(s) to the component(s) with the
4729    /// given [`ComponentId`]s, as determined by `self`.
4730    ///
4731    /// # Safety
4732    ///
4733    /// It is the caller's responsibility to ensure that:
4734    /// - The given [`UnsafeEntityCell`] has read-only access to the fetched components.
4735    /// - No other mutable references to the fetched components exist at the same time.
4736    ///
4737    /// # Errors
4738    ///
4739    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4740    unsafe fn fetch_ref(
4741        self,
4742        cell: UnsafeEntityCell<'_>,
4743    ) -> Result<Self::Ref<'_>, EntityComponentError>;
4744
4745    /// Returns untyped mutable reference(s) to the component(s) with the
4746    /// given [`ComponentId`]s, as determined by `self`.
4747    ///
4748    /// # Safety
4749    ///
4750    /// It is the caller's responsibility to ensure that:
4751    /// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
4752    /// - No other references to the fetched components exist at the same time.
4753    ///
4754    /// # Errors
4755    ///
4756    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4757    /// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
4758    unsafe fn fetch_mut(
4759        self,
4760        cell: UnsafeEntityCell<'_>,
4761    ) -> Result<Self::Mut<'_>, EntityComponentError>;
4762
4763    /// Returns untyped mutable reference(s) to the component(s) with the
4764    /// given [`ComponentId`]s, as determined by `self`.
4765    /// Assumes all [`ComponentId`]s refer to mutable components.
4766    ///
4767    /// # Safety
4768    ///
4769    /// It is the caller's responsibility to ensure that:
4770    /// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
4771    /// - No other references to the fetched components exist at the same time.
4772    /// - The requested components are all mutable.
4773    ///
4774    /// # Errors
4775    ///
4776    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4777    /// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
4778    unsafe fn fetch_mut_assume_mutable(
4779        self,
4780        cell: UnsafeEntityCell<'_>,
4781    ) -> Result<Self::Mut<'_>, EntityComponentError>;
4782}
4783
4784// SAFETY:
4785// - No aliased mutability is caused because a single reference is returned.
4786// - No mutable references are returned by `fetch_ref`.
4787unsafe impl DynamicComponentFetch for ComponentId {
4788    type Ref<'w> = Ptr<'w>;
4789    type Mut<'w> = MutUntyped<'w>;
4790
4791    unsafe fn fetch_ref(
4792        self,
4793        cell: UnsafeEntityCell<'_>,
4794    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4795        // SAFETY: caller ensures that the cell has read access to the component.
4796        unsafe { cell.get_by_id(self) }.ok_or(EntityComponentError::MissingComponent(self))
4797    }
4798
4799    unsafe fn fetch_mut(
4800        self,
4801        cell: UnsafeEntityCell<'_>,
4802    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4803        // SAFETY: caller ensures that the cell has mutable access to the component.
4804        unsafe { cell.get_mut_by_id(self) }
4805            .map_err(|_| EntityComponentError::MissingComponent(self))
4806    }
4807
4808    unsafe fn fetch_mut_assume_mutable(
4809        self,
4810        cell: UnsafeEntityCell<'_>,
4811    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4812        // SAFETY: caller ensures that the cell has mutable access to the component.
4813        unsafe { cell.get_mut_assume_mutable_by_id(self) }
4814            .map_err(|_| EntityComponentError::MissingComponent(self))
4815    }
4816}
4817
4818// SAFETY:
4819// - No aliased mutability is caused because the array is checked for duplicates.
4820// - No mutable references are returned by `fetch_ref`.
4821unsafe impl<const N: usize> DynamicComponentFetch for [ComponentId; N] {
4822    type Ref<'w> = [Ptr<'w>; N];
4823    type Mut<'w> = [MutUntyped<'w>; N];
4824
4825    unsafe fn fetch_ref(
4826        self,
4827        cell: UnsafeEntityCell<'_>,
4828    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4829        <&Self>::fetch_ref(&self, cell)
4830    }
4831
4832    unsafe fn fetch_mut(
4833        self,
4834        cell: UnsafeEntityCell<'_>,
4835    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4836        <&Self>::fetch_mut(&self, cell)
4837    }
4838
4839    unsafe fn fetch_mut_assume_mutable(
4840        self,
4841        cell: UnsafeEntityCell<'_>,
4842    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4843        <&Self>::fetch_mut_assume_mutable(&self, cell)
4844    }
4845}
4846
4847// SAFETY:
4848// - No aliased mutability is caused because the array is checked for duplicates.
4849// - No mutable references are returned by `fetch_ref`.
4850unsafe impl<const N: usize> DynamicComponentFetch for &'_ [ComponentId; N] {
4851    type Ref<'w> = [Ptr<'w>; N];
4852    type Mut<'w> = [MutUntyped<'w>; N];
4853
4854    unsafe fn fetch_ref(
4855        self,
4856        cell: UnsafeEntityCell<'_>,
4857    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4858        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4859        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4860            *ptr = MaybeUninit::new(
4861                // SAFETY: caller ensures that the cell has read access to the component.
4862                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
4863            );
4864        }
4865
4866        // SAFETY: Each ptr was initialized in the loop above.
4867        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4868
4869        Ok(ptrs)
4870    }
4871
4872    unsafe fn fetch_mut(
4873        self,
4874        cell: UnsafeEntityCell<'_>,
4875    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4876        // Check for duplicate component IDs.
4877        for i in 0..self.len() {
4878            for j in 0..i {
4879                if self[i] == self[j] {
4880                    return Err(EntityComponentError::AliasedMutability(self[i]));
4881                }
4882            }
4883        }
4884
4885        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4886        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4887            *ptr = MaybeUninit::new(
4888                // SAFETY: caller ensures that the cell has mutable access to the component.
4889                unsafe { cell.get_mut_by_id(id) }
4890                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4891            );
4892        }
4893
4894        // SAFETY: Each ptr was initialized in the loop above.
4895        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4896
4897        Ok(ptrs)
4898    }
4899
4900    unsafe fn fetch_mut_assume_mutable(
4901        self,
4902        cell: UnsafeEntityCell<'_>,
4903    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4904        // Check for duplicate component IDs.
4905        for i in 0..self.len() {
4906            for j in 0..i {
4907                if self[i] == self[j] {
4908                    return Err(EntityComponentError::AliasedMutability(self[i]));
4909                }
4910            }
4911        }
4912
4913        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4914        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4915            *ptr = MaybeUninit::new(
4916                // SAFETY: caller ensures that the cell has mutable access to the component.
4917                unsafe { cell.get_mut_assume_mutable_by_id(id) }
4918                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4919            );
4920        }
4921
4922        // SAFETY: Each ptr was initialized in the loop above.
4923        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4924
4925        Ok(ptrs)
4926    }
4927}
4928
4929// SAFETY:
4930// - No aliased mutability is caused because the slice is checked for duplicates.
4931// - No mutable references are returned by `fetch_ref`.
4932unsafe impl DynamicComponentFetch for &'_ [ComponentId] {
4933    type Ref<'w> = Vec<Ptr<'w>>;
4934    type Mut<'w> = Vec<MutUntyped<'w>>;
4935
4936    unsafe fn fetch_ref(
4937        self,
4938        cell: UnsafeEntityCell<'_>,
4939    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4940        let mut ptrs = Vec::with_capacity(self.len());
4941        for &id in self {
4942            ptrs.push(
4943                // SAFETY: caller ensures that the cell has read access to the component.
4944                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
4945            );
4946        }
4947        Ok(ptrs)
4948    }
4949
4950    unsafe fn fetch_mut(
4951        self,
4952        cell: UnsafeEntityCell<'_>,
4953    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4954        // Check for duplicate component IDs.
4955        for i in 0..self.len() {
4956            for j in 0..i {
4957                if self[i] == self[j] {
4958                    return Err(EntityComponentError::AliasedMutability(self[i]));
4959                }
4960            }
4961        }
4962
4963        let mut ptrs = Vec::with_capacity(self.len());
4964        for &id in self {
4965            ptrs.push(
4966                // SAFETY: caller ensures that the cell has mutable access to the component.
4967                unsafe { cell.get_mut_by_id(id) }
4968                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4969            );
4970        }
4971        Ok(ptrs)
4972    }
4973
4974    unsafe fn fetch_mut_assume_mutable(
4975        self,
4976        cell: UnsafeEntityCell<'_>,
4977    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4978        // Check for duplicate component IDs.
4979        for i in 0..self.len() {
4980            for j in 0..i {
4981                if self[i] == self[j] {
4982                    return Err(EntityComponentError::AliasedMutability(self[i]));
4983                }
4984            }
4985        }
4986
4987        let mut ptrs = Vec::with_capacity(self.len());
4988        for &id in self {
4989            ptrs.push(
4990                // SAFETY: caller ensures that the cell has mutable access to the component.
4991                unsafe { cell.get_mut_assume_mutable_by_id(id) }
4992                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4993            );
4994        }
4995        Ok(ptrs)
4996    }
4997}
4998
4999// SAFETY:
5000// - No aliased mutability is caused because `HashSet` guarantees unique elements.
5001// - No mutable references are returned by `fetch_ref`.
5002unsafe impl DynamicComponentFetch for &'_ HashSet<ComponentId> {
5003    type Ref<'w> = HashMap<ComponentId, Ptr<'w>>;
5004    type Mut<'w> = HashMap<ComponentId, MutUntyped<'w>>;
5005
5006    unsafe fn fetch_ref(
5007        self,
5008        cell: UnsafeEntityCell<'_>,
5009    ) -> Result<Self::Ref<'_>, EntityComponentError> {
5010        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5011        for &id in self {
5012            ptrs.insert(
5013                id,
5014                // SAFETY: caller ensures that the cell has read access to the component.
5015                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
5016            );
5017        }
5018        Ok(ptrs)
5019    }
5020
5021    unsafe fn fetch_mut(
5022        self,
5023        cell: UnsafeEntityCell<'_>,
5024    ) -> Result<Self::Mut<'_>, EntityComponentError> {
5025        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5026        for &id in self {
5027            ptrs.insert(
5028                id,
5029                // SAFETY: caller ensures that the cell has mutable access to the component.
5030                unsafe { cell.get_mut_by_id(id) }
5031                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
5032            );
5033        }
5034        Ok(ptrs)
5035    }
5036
5037    unsafe fn fetch_mut_assume_mutable(
5038        self,
5039        cell: UnsafeEntityCell<'_>,
5040    ) -> Result<Self::Mut<'_>, EntityComponentError> {
5041        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5042        for &id in self {
5043            ptrs.insert(
5044                id,
5045                // SAFETY: caller ensures that the cell has mutable access to the component.
5046                unsafe { cell.get_mut_assume_mutable_by_id(id) }
5047                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
5048            );
5049        }
5050        Ok(ptrs)
5051    }
5052}
5053
5054#[cfg(test)]
5055mod tests {
5056    use alloc::{vec, vec::Vec};
5057    use bevy_ptr::{OwningPtr, Ptr};
5058    use core::panic::AssertUnwindSafe;
5059    use std::sync::OnceLock;
5060
5061    use crate::component::Tick;
5062    use crate::lifecycle::HookContext;
5063    use crate::{
5064        change_detection::{MaybeLocation, MutUntyped},
5065        component::ComponentId,
5066        prelude::*,
5067        system::{assert_is_system, RunSystemOnce as _},
5068        world::{error::EntityComponentError, DeferredWorld, FilteredEntityMut, FilteredEntityRef},
5069    };
5070
5071    use super::{EntityMutExcept, EntityRefExcept};
5072
5073    #[derive(Component, Clone, Copy, Debug, PartialEq)]
5074    struct TestComponent(u32);
5075
5076    #[derive(Component, Clone, Copy, Debug, PartialEq)]
5077    #[component(storage = "SparseSet")]
5078    struct TestComponent2(u32);
5079
5080    #[test]
5081    fn entity_ref_get_by_id() {
5082        let mut world = World::new();
5083        let entity = world.spawn(TestComponent(42)).id();
5084        let component_id = world
5085            .components()
5086            .get_valid_id(core::any::TypeId::of::<TestComponent>())
5087            .unwrap();
5088
5089        let entity = world.entity(entity);
5090        let test_component = entity.get_by_id(component_id).unwrap();
5091        // SAFETY: points to a valid `TestComponent`
5092        let test_component = unsafe { test_component.deref::<TestComponent>() };
5093
5094        assert_eq!(test_component.0, 42);
5095    }
5096
5097    #[test]
5098    fn entity_mut_get_by_id() {
5099        let mut world = World::new();
5100        let entity = world.spawn(TestComponent(42)).id();
5101        let component_id = world
5102            .components()
5103            .get_valid_id(core::any::TypeId::of::<TestComponent>())
5104            .unwrap();
5105
5106        let mut entity_mut = world.entity_mut(entity);
5107        let mut test_component = entity_mut.get_mut_by_id(component_id).unwrap();
5108        {
5109            test_component.set_changed();
5110            let test_component =
5111                // SAFETY: `test_component` has unique access of the `EntityWorldMut` and is not used afterwards
5112                unsafe { test_component.into_inner().deref_mut::<TestComponent>() };
5113            test_component.0 = 43;
5114        }
5115
5116        let entity = world.entity(entity);
5117        let test_component = entity.get_by_id(component_id).unwrap();
5118        // SAFETY: `TestComponent` is the correct component type
5119        let test_component = unsafe { test_component.deref::<TestComponent>() };
5120
5121        assert_eq!(test_component.0, 43);
5122    }
5123
5124    #[test]
5125    fn entity_ref_get_by_id_invalid_component_id() {
5126        let invalid_component_id = ComponentId::new(usize::MAX);
5127
5128        let mut world = World::new();
5129        let entity = world.spawn_empty().id();
5130        let entity = world.entity(entity);
5131        assert!(entity.get_by_id(invalid_component_id).is_err());
5132    }
5133
5134    #[test]
5135    fn entity_mut_get_by_id_invalid_component_id() {
5136        let invalid_component_id = ComponentId::new(usize::MAX);
5137
5138        let mut world = World::new();
5139        let mut entity = world.spawn_empty();
5140        assert!(entity.get_by_id(invalid_component_id).is_err());
5141        assert!(entity.get_mut_by_id(invalid_component_id).is_err());
5142    }
5143
5144    #[derive(Resource)]
5145    struct R(usize);
5146
5147    #[test]
5148    fn entity_mut_resource_scope() {
5149        // Keep in sync with the `resource_scope` test in lib.rs
5150        let mut world = World::new();
5151        let mut entity = world.spawn_empty();
5152
5153        assert!(entity.try_resource_scope::<R, _>(|_, _| {}).is_none());
5154        entity.world_scope(|world| world.insert_resource(R(0)));
5155        entity.resource_scope(|entity: &mut EntityWorldMut, mut value: Mut<R>| {
5156            value.0 += 1;
5157            assert!(!entity.world().contains_resource::<R>());
5158        });
5159        assert_eq!(entity.resource::<R>().0, 1);
5160    }
5161
5162    #[test]
5163    fn entity_mut_resource_scope_panic() {
5164        let mut world = World::new();
5165        world.insert_resource(R(0));
5166
5167        let mut entity = world.spawn_empty();
5168        let old_location = entity.location();
5169        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
5170            entity.resource_scope(|entity: &mut EntityWorldMut, _: Mut<R>| {
5171                // Change the entity's `EntityLocation`.
5172                entity.insert(TestComponent(0));
5173
5174                // Ensure that the entity location still gets updated even in case of a panic.
5175                panic!("this should get caught by the outer scope")
5176            });
5177        }));
5178        assert!(result.is_err());
5179
5180        // Ensure that the location has been properly updated.
5181        assert_ne!(entity.location(), old_location);
5182    }
5183
5184    // regression test for https://github.com/bevyengine/bevy/pull/7387
5185    #[test]
5186    fn entity_mut_world_scope_panic() {
5187        let mut world = World::new();
5188
5189        let mut entity = world.spawn_empty();
5190        let old_location = entity.location();
5191        let id = entity.id();
5192        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
5193            entity.world_scope(|w| {
5194                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
5195                // This will get updated at the end of the scope.
5196                w.entity_mut(id).insert(TestComponent(0));
5197
5198                // Ensure that the entity location still gets updated even in case of a panic.
5199                panic!("this should get caught by the outer scope")
5200            });
5201        }));
5202        assert!(res.is_err());
5203
5204        // Ensure that the location has been properly updated.
5205        assert_ne!(entity.location(), old_location);
5206    }
5207
5208    #[test]
5209    fn entity_mut_reborrow_scope_panic() {
5210        let mut world = World::new();
5211
5212        let mut entity = world.spawn_empty();
5213        let old_location = entity.location();
5214        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
5215            entity.reborrow_scope(|mut entity| {
5216                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
5217                // This will get updated at the end of the scope.
5218                entity.insert(TestComponent(0));
5219
5220                // Ensure that the entity location still gets updated even in case of a panic.
5221                panic!("this should get caught by the outer scope")
5222            });
5223        }));
5224        assert!(res.is_err());
5225
5226        // Ensure that the location has been properly updated.
5227        assert_ne!(entity.location(), old_location);
5228    }
5229
5230    // regression test for https://github.com/bevyengine/bevy/pull/7805
5231    #[test]
5232    fn removing_sparse_updates_archetype_row() {
5233        #[derive(Component, PartialEq, Debug)]
5234        struct Dense(u8);
5235
5236        #[derive(Component)]
5237        #[component(storage = "SparseSet")]
5238        struct Sparse;
5239
5240        let mut world = World::new();
5241        let e1 = world.spawn((Dense(0), Sparse)).id();
5242        let e2 = world.spawn((Dense(1), Sparse)).id();
5243
5244        world.entity_mut(e1).remove::<Sparse>();
5245        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5246    }
5247
5248    // regression test for https://github.com/bevyengine/bevy/pull/7805
5249    #[test]
5250    fn removing_dense_updates_table_row() {
5251        #[derive(Component, PartialEq, Debug)]
5252        struct Dense(u8);
5253
5254        #[derive(Component)]
5255        #[component(storage = "SparseSet")]
5256        struct Sparse;
5257
5258        let mut world = World::new();
5259        let e1 = world.spawn((Dense(0), Sparse)).id();
5260        let e2 = world.spawn((Dense(1), Sparse)).id();
5261
5262        world.entity_mut(e1).remove::<Dense>();
5263        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5264    }
5265
5266    // Test that calling retain with `()` removes all components.
5267    #[test]
5268    fn retain_nothing() {
5269        #[derive(Component)]
5270        struct Marker<const N: usize>;
5271
5272        let mut world = World::new();
5273        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
5274
5275        world.entity_mut(ent).retain::<()>();
5276        assert_eq!(world.entity(ent).archetype().components().len(), 0);
5277    }
5278
5279    // Test removing some components with `retain`, including components not on the entity.
5280    #[test]
5281    fn retain_some_components() {
5282        #[derive(Component)]
5283        struct Marker<const N: usize>;
5284
5285        let mut world = World::new();
5286        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
5287
5288        world.entity_mut(ent).retain::<(Marker<2>, Marker<4>)>();
5289        // Check that marker 2 was retained.
5290        assert!(world.entity(ent).get::<Marker<2>>().is_some());
5291        // Check that only marker 2 was retained.
5292        assert_eq!(world.entity(ent).archetype().components().len(), 1);
5293    }
5294
5295    // regression test for https://github.com/bevyengine/bevy/pull/7805
5296    #[test]
5297    fn inserting_sparse_updates_archetype_row() {
5298        #[derive(Component, PartialEq, Debug)]
5299        struct Dense(u8);
5300
5301        #[derive(Component)]
5302        #[component(storage = "SparseSet")]
5303        struct Sparse;
5304
5305        let mut world = World::new();
5306        let e1 = world.spawn(Dense(0)).id();
5307        let e2 = world.spawn(Dense(1)).id();
5308
5309        world.entity_mut(e1).insert(Sparse);
5310        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5311    }
5312
5313    // regression test for https://github.com/bevyengine/bevy/pull/7805
5314    #[test]
5315    fn inserting_dense_updates_archetype_row() {
5316        #[derive(Component, PartialEq, Debug)]
5317        struct Dense(u8);
5318
5319        #[derive(Component)]
5320        struct Dense2;
5321
5322        #[derive(Component)]
5323        #[component(storage = "SparseSet")]
5324        struct Sparse;
5325
5326        let mut world = World::new();
5327        let e1 = world.spawn(Dense(0)).id();
5328        let e2 = world.spawn(Dense(1)).id();
5329
5330        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5331
5332        // archetype with [e2, e1]
5333        // table with [e1, e2]
5334
5335        world.entity_mut(e2).insert(Dense2);
5336
5337        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
5338    }
5339
5340    #[test]
5341    fn inserting_dense_updates_table_row() {
5342        #[derive(Component, PartialEq, Debug)]
5343        struct Dense(u8);
5344
5345        #[derive(Component)]
5346        struct Dense2;
5347
5348        #[derive(Component)]
5349        #[component(storage = "SparseSet")]
5350        struct Sparse;
5351
5352        let mut world = World::new();
5353        let e1 = world.spawn(Dense(0)).id();
5354        let e2 = world.spawn(Dense(1)).id();
5355
5356        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5357
5358        // archetype with [e2, e1]
5359        // table with [e1, e2]
5360
5361        world.entity_mut(e1).insert(Dense2);
5362
5363        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5364    }
5365
5366    // regression test for https://github.com/bevyengine/bevy/pull/7805
5367    #[test]
5368    fn despawning_entity_updates_archetype_row() {
5369        #[derive(Component, PartialEq, Debug)]
5370        struct Dense(u8);
5371
5372        #[derive(Component)]
5373        #[component(storage = "SparseSet")]
5374        struct Sparse;
5375
5376        let mut world = World::new();
5377        let e1 = world.spawn(Dense(0)).id();
5378        let e2 = world.spawn(Dense(1)).id();
5379
5380        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5381
5382        // archetype with [e2, e1]
5383        // table with [e1, e2]
5384
5385        world.entity_mut(e2).despawn();
5386
5387        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
5388    }
5389
5390    // regression test for https://github.com/bevyengine/bevy/pull/7805
5391    #[test]
5392    fn despawning_entity_updates_table_row() {
5393        #[derive(Component, PartialEq, Debug)]
5394        struct Dense(u8);
5395
5396        #[derive(Component)]
5397        #[component(storage = "SparseSet")]
5398        struct Sparse;
5399
5400        let mut world = World::new();
5401        let e1 = world.spawn(Dense(0)).id();
5402        let e2 = world.spawn(Dense(1)).id();
5403
5404        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5405
5406        // archetype with [e2, e1]
5407        // table with [e1, e2]
5408
5409        world.entity_mut(e1).despawn();
5410
5411        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5412    }
5413
5414    #[test]
5415    fn entity_mut_insert_by_id() {
5416        let mut world = World::new();
5417        let test_component_id = world.register_component::<TestComponent>();
5418
5419        let mut entity = world.spawn_empty();
5420        OwningPtr::make(TestComponent(42), |ptr| {
5421            // SAFETY: `ptr` matches the component id
5422            unsafe { entity.insert_by_id(test_component_id, ptr) };
5423        });
5424
5425        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5426
5427        assert_eq!(components, vec![&TestComponent(42)]);
5428
5429        // Compare with `insert_bundle_by_id`
5430
5431        let mut entity = world.spawn_empty();
5432        OwningPtr::make(TestComponent(84), |ptr| {
5433            // SAFETY: `ptr` matches the component id
5434            unsafe { entity.insert_by_ids(&[test_component_id], vec![ptr].into_iter()) };
5435        });
5436
5437        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5438
5439        assert_eq!(components, vec![&TestComponent(42), &TestComponent(84)]);
5440    }
5441
5442    #[test]
5443    fn entity_mut_insert_bundle_by_id() {
5444        let mut world = World::new();
5445        let test_component_id = world.register_component::<TestComponent>();
5446        let test_component_2_id = world.register_component::<TestComponent2>();
5447
5448        let component_ids = [test_component_id, test_component_2_id];
5449        let test_component_value = TestComponent(42);
5450        let test_component_2_value = TestComponent2(84);
5451
5452        let mut entity = world.spawn_empty();
5453        OwningPtr::make(test_component_value, |ptr1| {
5454            OwningPtr::make(test_component_2_value, |ptr2| {
5455                // SAFETY: `ptr1` and `ptr2` match the component ids
5456                unsafe { entity.insert_by_ids(&component_ids, vec![ptr1, ptr2].into_iter()) };
5457            });
5458        });
5459
5460        let dynamic_components: Vec<_> = world
5461            .query::<(&TestComponent, &TestComponent2)>()
5462            .iter(&world)
5463            .collect();
5464
5465        assert_eq!(
5466            dynamic_components,
5467            vec![(&TestComponent(42), &TestComponent2(84))]
5468        );
5469
5470        // Compare with `World` generated using static type equivalents
5471        let mut static_world = World::new();
5472
5473        static_world.spawn((test_component_value, test_component_2_value));
5474        let static_components: Vec<_> = static_world
5475            .query::<(&TestComponent, &TestComponent2)>()
5476            .iter(&static_world)
5477            .collect();
5478
5479        assert_eq!(dynamic_components, static_components);
5480    }
5481
5482    #[test]
5483    fn entity_mut_remove_by_id() {
5484        let mut world = World::new();
5485        let test_component_id = world.register_component::<TestComponent>();
5486
5487        let mut entity = world.spawn(TestComponent(42));
5488        entity.remove_by_id(test_component_id);
5489
5490        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5491
5492        assert_eq!(components, vec![] as Vec<&TestComponent>);
5493
5494        // remove non-existent component does not panic
5495        world.spawn_empty().remove_by_id(test_component_id);
5496    }
5497
5498    /// Tests that components can be accessed through an `EntityRefExcept`.
5499    #[test]
5500    fn entity_ref_except() {
5501        let mut world = World::new();
5502        world.register_component::<TestComponent>();
5503        world.register_component::<TestComponent2>();
5504
5505        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5506
5507        let mut query = world.query::<EntityRefExcept<TestComponent>>();
5508
5509        let mut found = false;
5510        for entity_ref in query.iter_mut(&mut world) {
5511            found = true;
5512            assert!(entity_ref.get::<TestComponent>().is_none());
5513            assert!(entity_ref.get_ref::<TestComponent>().is_none());
5514            assert!(matches!(
5515                entity_ref.get::<TestComponent2>(),
5516                Some(TestComponent2(0))
5517            ));
5518        }
5519
5520        assert!(found);
5521    }
5522
5523    // Test that a single query can't both contain a mutable reference to a
5524    // component C and an `EntityRefExcept` that doesn't include C among its
5525    // exclusions.
5526    #[test]
5527    #[should_panic]
5528    fn entity_ref_except_conflicts_with_self() {
5529        let mut world = World::new();
5530        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5531
5532        // This should panic, because we have a mutable borrow on
5533        // `TestComponent` but have a simultaneous indirect immutable borrow on
5534        // that component via `EntityRefExcept`.
5535        world.run_system_once(system).unwrap();
5536
5537        fn system(_: Query<(&mut TestComponent, EntityRefExcept<TestComponent2>)>) {}
5538    }
5539
5540    // Test that an `EntityRefExcept` that doesn't include a component C among
5541    // its exclusions can't coexist with a mutable query for that component.
5542    #[test]
5543    #[should_panic]
5544    fn entity_ref_except_conflicts_with_other() {
5545        let mut world = World::new();
5546        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5547
5548        // This should panic, because we have a mutable borrow on
5549        // `TestComponent` but have a simultaneous indirect immutable borrow on
5550        // that component via `EntityRefExcept`.
5551        world.run_system_once(system).unwrap();
5552
5553        fn system(_: Query<&mut TestComponent>, _: Query<EntityRefExcept<TestComponent2>>) {}
5554    }
5555
5556    // Test that an `EntityRefExcept` with an exception for some component C can
5557    // coexist with a query for that component C.
5558    #[test]
5559    fn entity_ref_except_doesnt_conflict() {
5560        let mut world = World::new();
5561        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5562
5563        world.run_system_once(system).unwrap();
5564
5565        fn system(_: Query<&mut TestComponent>, query: Query<EntityRefExcept<TestComponent>>) {
5566            for entity_ref in query.iter() {
5567                assert!(matches!(
5568                    entity_ref.get::<TestComponent2>(),
5569                    Some(TestComponent2(0))
5570                ));
5571            }
5572        }
5573    }
5574
5575    /// Tests that components can be mutably accessed through an
5576    /// `EntityMutExcept`.
5577    #[test]
5578    fn entity_mut_except() {
5579        let mut world = World::new();
5580        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5581
5582        let mut query = world.query::<EntityMutExcept<TestComponent>>();
5583
5584        let mut found = false;
5585        for mut entity_mut in query.iter_mut(&mut world) {
5586            found = true;
5587            assert!(entity_mut.get::<TestComponent>().is_none());
5588            assert!(entity_mut.get_ref::<TestComponent>().is_none());
5589            assert!(entity_mut.get_mut::<TestComponent>().is_none());
5590            assert!(matches!(
5591                entity_mut.get::<TestComponent2>(),
5592                Some(TestComponent2(0))
5593            ));
5594        }
5595
5596        assert!(found);
5597    }
5598
5599    // Test that a single query can't both contain a mutable reference to a
5600    // component C and an `EntityMutExcept` that doesn't include C among its
5601    // exclusions.
5602    #[test]
5603    #[should_panic]
5604    fn entity_mut_except_conflicts_with_self() {
5605        let mut world = World::new();
5606        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5607
5608        // This should panic, because we have a mutable borrow on
5609        // `TestComponent` but have a simultaneous indirect immutable borrow on
5610        // that component via `EntityRefExcept`.
5611        world.run_system_once(system).unwrap();
5612
5613        fn system(_: Query<(&mut TestComponent, EntityMutExcept<TestComponent2>)>) {}
5614    }
5615
5616    // Test that an `EntityMutExcept` that doesn't include a component C among
5617    // its exclusions can't coexist with a query for that component.
5618    #[test]
5619    #[should_panic]
5620    fn entity_mut_except_conflicts_with_other() {
5621        let mut world = World::new();
5622        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5623
5624        // This should panic, because we have a mutable borrow on
5625        // `TestComponent` but have a simultaneous indirect immutable borrow on
5626        // that component via `EntityRefExcept`.
5627        world.run_system_once(system).unwrap();
5628
5629        fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent2>>) {
5630            for mut entity_mut in query.iter_mut() {
5631                assert!(entity_mut
5632                    .get_mut::<TestComponent2>()
5633                    .is_some_and(|component| component.0 == 0));
5634            }
5635        }
5636    }
5637
5638    // Test that an `EntityMutExcept` with an exception for some component C can
5639    // coexist with a query for that component C.
5640    #[test]
5641    fn entity_mut_except_doesnt_conflict() {
5642        let mut world = World::new();
5643        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5644
5645        world.run_system_once(system).unwrap();
5646
5647        fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent>>) {
5648            for mut entity_mut in query.iter_mut() {
5649                assert!(entity_mut
5650                    .get_mut::<TestComponent2>()
5651                    .is_some_and(|component| component.0 == 0));
5652            }
5653        }
5654    }
5655
5656    #[test]
5657    fn entity_mut_except_registers_components() {
5658        // Checks for a bug where `EntityMutExcept` would not register the component and
5659        // would therefore not include an exception, causing it to conflict with the later query.
5660        fn system1(_query: Query<EntityMutExcept<TestComponent>>, _: Query<&mut TestComponent>) {}
5661        let mut world = World::new();
5662        world.run_system_once(system1).unwrap();
5663
5664        fn system2(_: Query<&mut TestComponent>, _query: Query<EntityMutExcept<TestComponent>>) {}
5665        let mut world = World::new();
5666        world.run_system_once(system2).unwrap();
5667    }
5668
5669    #[derive(Component)]
5670    struct A;
5671
5672    #[test]
5673    fn disjoint_access() {
5674        fn disjoint_readonly(_: Query<EntityMut, With<A>>, _: Query<EntityRef, Without<A>>) {}
5675
5676        fn disjoint_mutable(_: Query<EntityMut, With<A>>, _: Query<EntityMut, Without<A>>) {}
5677
5678        assert_is_system(disjoint_readonly);
5679        assert_is_system(disjoint_mutable);
5680    }
5681
5682    #[test]
5683    fn ref_compatible() {
5684        fn borrow_system(_: Query<(EntityRef, &A)>, _: Query<&A>) {}
5685
5686        assert_is_system(borrow_system);
5687    }
5688
5689    #[test]
5690    fn ref_compatible_with_resource() {
5691        fn borrow_system(_: Query<EntityRef>, _: Res<R>) {}
5692
5693        assert_is_system(borrow_system);
5694    }
5695
5696    #[test]
5697    fn ref_compatible_with_resource_mut() {
5698        fn borrow_system(_: Query<EntityRef>, _: ResMut<R>) {}
5699
5700        assert_is_system(borrow_system);
5701    }
5702
5703    #[test]
5704    #[should_panic]
5705    fn ref_incompatible_with_mutable_component() {
5706        fn incompatible_system(_: Query<(EntityRef, &mut A)>) {}
5707
5708        assert_is_system(incompatible_system);
5709    }
5710
5711    #[test]
5712    #[should_panic]
5713    fn ref_incompatible_with_mutable_query() {
5714        fn incompatible_system(_: Query<EntityRef>, _: Query<&mut A>) {}
5715
5716        assert_is_system(incompatible_system);
5717    }
5718
5719    #[test]
5720    fn mut_compatible_with_entity() {
5721        fn borrow_mut_system(_: Query<(Entity, EntityMut)>) {}
5722
5723        assert_is_system(borrow_mut_system);
5724    }
5725
5726    #[test]
5727    fn mut_compatible_with_resource() {
5728        fn borrow_mut_system(_: Res<R>, _: Query<EntityMut>) {}
5729
5730        assert_is_system(borrow_mut_system);
5731    }
5732
5733    #[test]
5734    fn mut_compatible_with_resource_mut() {
5735        fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut>) {}
5736
5737        assert_is_system(borrow_mut_system);
5738    }
5739
5740    #[test]
5741    #[should_panic]
5742    fn mut_incompatible_with_read_only_component() {
5743        fn incompatible_system(_: Query<(EntityMut, &A)>) {}
5744
5745        assert_is_system(incompatible_system);
5746    }
5747
5748    #[test]
5749    #[should_panic]
5750    fn mut_incompatible_with_mutable_component() {
5751        fn incompatible_system(_: Query<(EntityMut, &mut A)>) {}
5752
5753        assert_is_system(incompatible_system);
5754    }
5755
5756    #[test]
5757    #[should_panic]
5758    fn mut_incompatible_with_read_only_query() {
5759        fn incompatible_system(_: Query<EntityMut>, _: Query<&A>) {}
5760
5761        assert_is_system(incompatible_system);
5762    }
5763
5764    #[test]
5765    #[should_panic]
5766    fn mut_incompatible_with_mutable_query() {
5767        fn incompatible_system(_: Query<EntityMut>, _: Query<&mut A>) {}
5768
5769        assert_is_system(incompatible_system);
5770    }
5771
5772    #[test]
5773    fn filtered_entity_ref_normal() {
5774        let mut world = World::new();
5775        let a_id = world.register_component::<A>();
5776
5777        let e: FilteredEntityRef = world.spawn(A).into();
5778
5779        assert!(e.get::<A>().is_some());
5780        assert!(e.get_ref::<A>().is_some());
5781        assert!(e.get_change_ticks::<A>().is_some());
5782        assert!(e.get_by_id(a_id).is_some());
5783        assert!(e.get_change_ticks_by_id(a_id).is_some());
5784    }
5785
5786    #[test]
5787    fn filtered_entity_ref_missing() {
5788        let mut world = World::new();
5789        let a_id = world.register_component::<A>();
5790
5791        let e: FilteredEntityRef = world.spawn(()).into();
5792
5793        assert!(e.get::<A>().is_none());
5794        assert!(e.get_ref::<A>().is_none());
5795        assert!(e.get_change_ticks::<A>().is_none());
5796        assert!(e.get_by_id(a_id).is_none());
5797        assert!(e.get_change_ticks_by_id(a_id).is_none());
5798    }
5799
5800    #[test]
5801    fn filtered_entity_mut_normal() {
5802        let mut world = World::new();
5803        let a_id = world.register_component::<A>();
5804
5805        let mut e: FilteredEntityMut = world.spawn(A).into();
5806
5807        assert!(e.get::<A>().is_some());
5808        assert!(e.get_ref::<A>().is_some());
5809        assert!(e.get_mut::<A>().is_some());
5810        assert!(e.get_change_ticks::<A>().is_some());
5811        assert!(e.get_by_id(a_id).is_some());
5812        assert!(e.get_mut_by_id(a_id).is_some());
5813        assert!(e.get_change_ticks_by_id(a_id).is_some());
5814    }
5815
5816    #[test]
5817    fn filtered_entity_mut_missing() {
5818        let mut world = World::new();
5819        let a_id = world.register_component::<A>();
5820
5821        let mut e: FilteredEntityMut = world.spawn(()).into();
5822
5823        assert!(e.get::<A>().is_none());
5824        assert!(e.get_ref::<A>().is_none());
5825        assert!(e.get_mut::<A>().is_none());
5826        assert!(e.get_change_ticks::<A>().is_none());
5827        assert!(e.get_by_id(a_id).is_none());
5828        assert!(e.get_mut_by_id(a_id).is_none());
5829        assert!(e.get_change_ticks_by_id(a_id).is_none());
5830    }
5831
5832    #[derive(Component, PartialEq, Eq, Debug)]
5833    struct X(usize);
5834
5835    #[derive(Component, PartialEq, Eq, Debug)]
5836    struct Y(usize);
5837
5838    #[test]
5839    fn get_components() {
5840        let mut world = World::default();
5841        let e1 = world.spawn((X(7), Y(10))).id();
5842        let e2 = world.spawn(X(8)).id();
5843        let e3 = world.spawn_empty().id();
5844
5845        assert_eq!(
5846            Some((&X(7), &Y(10))),
5847            world.entity(e1).get_components::<(&X, &Y)>()
5848        );
5849        assert_eq!(None, world.entity(e2).get_components::<(&X, &Y)>());
5850        assert_eq!(None, world.entity(e3).get_components::<(&X, &Y)>());
5851    }
5852
5853    #[test]
5854    fn get_by_id_array() {
5855        let mut world = World::default();
5856        let e1 = world.spawn((X(7), Y(10))).id();
5857        let e2 = world.spawn(X(8)).id();
5858        let e3 = world.spawn_empty().id();
5859
5860        let x_id = world.register_component::<X>();
5861        let y_id = world.register_component::<Y>();
5862
5863        assert_eq!(
5864            Ok((&X(7), &Y(10))),
5865            world
5866                .entity(e1)
5867                .get_by_id([x_id, y_id])
5868                .map(|[x_ptr, y_ptr]| {
5869                    // SAFETY: components match the id they were fetched with
5870                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5871                })
5872        );
5873        assert_eq!(
5874            Err(EntityComponentError::MissingComponent(y_id)),
5875            world
5876                .entity(e2)
5877                .get_by_id([x_id, y_id])
5878                .map(|[x_ptr, y_ptr]| {
5879                    // SAFETY: components match the id they were fetched with
5880                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5881                })
5882        );
5883        assert_eq!(
5884            Err(EntityComponentError::MissingComponent(x_id)),
5885            world
5886                .entity(e3)
5887                .get_by_id([x_id, y_id])
5888                .map(|[x_ptr, y_ptr]| {
5889                    // SAFETY: components match the id they were fetched with
5890                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5891                })
5892        );
5893    }
5894
5895    #[test]
5896    fn get_by_id_vec() {
5897        let mut world = World::default();
5898        let e1 = world.spawn((X(7), Y(10))).id();
5899        let e2 = world.spawn(X(8)).id();
5900        let e3 = world.spawn_empty().id();
5901
5902        let x_id = world.register_component::<X>();
5903        let y_id = world.register_component::<Y>();
5904
5905        assert_eq!(
5906            Ok((&X(7), &Y(10))),
5907            world
5908                .entity(e1)
5909                .get_by_id(&[x_id, y_id] as &[ComponentId])
5910                .map(|ptrs| {
5911                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5912                        panic!("get_by_id(slice) didn't return 2 elements")
5913                    };
5914
5915                    // SAFETY: components match the id they were fetched with
5916                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5917                })
5918        );
5919        assert_eq!(
5920            Err(EntityComponentError::MissingComponent(y_id)),
5921            world
5922                .entity(e2)
5923                .get_by_id(&[x_id, y_id] as &[ComponentId])
5924                .map(|ptrs| {
5925                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5926                        panic!("get_by_id(slice) didn't return 2 elements")
5927                    };
5928
5929                    // SAFETY: components match the id they were fetched with
5930                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5931                })
5932        );
5933        assert_eq!(
5934            Err(EntityComponentError::MissingComponent(x_id)),
5935            world
5936                .entity(e3)
5937                .get_by_id(&[x_id, y_id] as &[ComponentId])
5938                .map(|ptrs| {
5939                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5940                        panic!("get_by_id(slice) didn't return 2 elements")
5941                    };
5942
5943                    // SAFETY: components match the id they were fetched with
5944                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5945                })
5946        );
5947    }
5948
5949    #[test]
5950    fn get_mut_by_id_array() {
5951        let mut world = World::default();
5952        let e1 = world.spawn((X(7), Y(10))).id();
5953        let e2 = world.spawn(X(8)).id();
5954        let e3 = world.spawn_empty().id();
5955
5956        let x_id = world.register_component::<X>();
5957        let y_id = world.register_component::<Y>();
5958
5959        assert_eq!(
5960            Ok((&mut X(7), &mut Y(10))),
5961            world
5962                .entity_mut(e1)
5963                .get_mut_by_id([x_id, y_id])
5964                .map(|[x_ptr, y_ptr]| {
5965                    // SAFETY: components match the id they were fetched with
5966                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5967                        y_ptr.into_inner().deref_mut::<Y>()
5968                    })
5969                })
5970        );
5971        assert_eq!(
5972            Err(EntityComponentError::MissingComponent(y_id)),
5973            world
5974                .entity_mut(e2)
5975                .get_mut_by_id([x_id, y_id])
5976                .map(|[x_ptr, y_ptr]| {
5977                    // SAFETY: components match the id they were fetched with
5978                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5979                        y_ptr.into_inner().deref_mut::<Y>()
5980                    })
5981                })
5982        );
5983        assert_eq!(
5984            Err(EntityComponentError::MissingComponent(x_id)),
5985            world
5986                .entity_mut(e3)
5987                .get_mut_by_id([x_id, y_id])
5988                .map(|[x_ptr, y_ptr]| {
5989                    // SAFETY: components match the id they were fetched with
5990                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5991                        y_ptr.into_inner().deref_mut::<Y>()
5992                    })
5993                })
5994        );
5995
5996        assert_eq!(
5997            Err(EntityComponentError::AliasedMutability(x_id)),
5998            world
5999                .entity_mut(e1)
6000                .get_mut_by_id([x_id, x_id])
6001                .map(|_| { unreachable!() })
6002        );
6003        assert_eq!(
6004            Err(EntityComponentError::AliasedMutability(x_id)),
6005            world
6006                .entity_mut(e3)
6007                .get_mut_by_id([x_id, x_id])
6008                .map(|_| { unreachable!() })
6009        );
6010    }
6011
6012    #[test]
6013    fn get_mut_by_id_vec() {
6014        let mut world = World::default();
6015        let e1 = world.spawn((X(7), Y(10))).id();
6016        let e2 = world.spawn(X(8)).id();
6017        let e3 = world.spawn_empty().id();
6018
6019        let x_id = world.register_component::<X>();
6020        let y_id = world.register_component::<Y>();
6021
6022        assert_eq!(
6023            Ok((&mut X(7), &mut Y(10))),
6024            world
6025                .entity_mut(e1)
6026                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6027                .map(|ptrs| {
6028                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6029                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6030                    };
6031
6032                    // SAFETY: components match the id they were fetched with
6033                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6034                        y_ptr.into_inner().deref_mut::<Y>()
6035                    })
6036                })
6037        );
6038        assert_eq!(
6039            Err(EntityComponentError::MissingComponent(y_id)),
6040            world
6041                .entity_mut(e2)
6042                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6043                .map(|ptrs| {
6044                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6045                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6046                    };
6047
6048                    // SAFETY: components match the id they were fetched with
6049                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6050                        y_ptr.into_inner().deref_mut::<Y>()
6051                    })
6052                })
6053        );
6054        assert_eq!(
6055            Err(EntityComponentError::MissingComponent(x_id)),
6056            world
6057                .entity_mut(e3)
6058                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6059                .map(|ptrs| {
6060                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6061                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6062                    };
6063
6064                    // SAFETY: components match the id they were fetched with
6065                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6066                        y_ptr.into_inner().deref_mut::<Y>()
6067                    })
6068                })
6069        );
6070
6071        assert_eq!(
6072            Err(EntityComponentError::AliasedMutability(x_id)),
6073            world
6074                .entity_mut(e1)
6075                .get_mut_by_id(&[x_id, x_id])
6076                .map(|_| { unreachable!() })
6077        );
6078        assert_eq!(
6079            Err(EntityComponentError::AliasedMutability(x_id)),
6080            world
6081                .entity_mut(e3)
6082                .get_mut_by_id(&[x_id, x_id])
6083                .map(|_| { unreachable!() })
6084        );
6085    }
6086
6087    #[test]
6088    fn get_mut_by_id_unchecked() {
6089        let mut world = World::default();
6090        let e1 = world.spawn((X(7), Y(10))).id();
6091        let x_id = world.register_component::<X>();
6092        let y_id = world.register_component::<Y>();
6093
6094        let e1_mut = &world.get_entity_mut([e1]).unwrap()[0];
6095        // SAFETY: The entity e1 contains component X.
6096        let x_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(x_id) }.unwrap();
6097        // SAFETY: The entity e1 contains component Y, with components X and Y being mutually independent.
6098        let y_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(y_id) }.unwrap();
6099
6100        // SAFETY: components match the id they were fetched with
6101        let x_component = unsafe { x_ptr.into_inner().deref_mut::<X>() };
6102        x_component.0 += 1;
6103        // SAFETY: components match the id they were fetched with
6104        let y_component = unsafe { y_ptr.into_inner().deref_mut::<Y>() };
6105        y_component.0 -= 1;
6106
6107        assert_eq!((&mut X(8), &mut Y(9)), (x_component, y_component));
6108    }
6109
6110    #[derive(EntityEvent)]
6111    struct TestEvent(Entity);
6112
6113    #[test]
6114    fn adding_observer_updates_location() {
6115        let mut world = World::new();
6116        let entity = world
6117            .spawn_empty()
6118            .observe(|event: On<TestEvent>, mut commands: Commands| {
6119                commands
6120                    .entity(event.event_target())
6121                    .insert(TestComponent(0));
6122            })
6123            .id();
6124
6125        // this should not be needed, but is currently required to tease out the bug
6126        world.flush();
6127
6128        let mut a = world.entity_mut(entity);
6129        // SAFETY: this _intentionally_ doesn't update the location, to ensure that we're actually testing
6130        // that observe() updates location
6131        unsafe { a.world_mut().trigger(TestEvent(entity)) }
6132        a.observe(|_: On<TestEvent>| {}); // this flushes commands implicitly by spawning
6133        let location = a.location();
6134        assert_eq!(world.entities().get(entity), Some(location));
6135    }
6136
6137    #[test]
6138    #[should_panic]
6139    fn location_on_despawned_entity_panics() {
6140        let mut world = World::new();
6141        world.add_observer(|add: On<Add, TestComponent>, mut commands: Commands| {
6142            commands.entity(add.entity).despawn();
6143        });
6144        let entity = world.spawn_empty().id();
6145        let mut a = world.entity_mut(entity);
6146        a.insert(TestComponent(0));
6147        a.location();
6148    }
6149
6150    #[derive(Resource)]
6151    struct TestFlush(usize);
6152
6153    fn count_flush(world: &mut World) {
6154        world.resource_mut::<TestFlush>().0 += 1;
6155    }
6156
6157    #[test]
6158    fn archetype_modifications_trigger_flush() {
6159        let mut world = World::new();
6160        world.insert_resource(TestFlush(0));
6161        world.add_observer(|_: On<Add, TestComponent>, mut commands: Commands| {
6162            commands.queue(count_flush);
6163        });
6164        world.add_observer(|_: On<Remove, TestComponent>, mut commands: Commands| {
6165            commands.queue(count_flush);
6166        });
6167        world.commands().queue(count_flush);
6168        let entity = world.spawn_empty().id();
6169        assert_eq!(world.resource::<TestFlush>().0, 1);
6170        world.commands().queue(count_flush);
6171        world.flush_commands();
6172        let mut a = world.entity_mut(entity);
6173        assert_eq!(a.world().resource::<TestFlush>().0, 2);
6174        a.insert(TestComponent(0));
6175        assert_eq!(a.world().resource::<TestFlush>().0, 3);
6176        a.remove::<TestComponent>();
6177        assert_eq!(a.world().resource::<TestFlush>().0, 4);
6178        a.insert(TestComponent(0));
6179        assert_eq!(a.world().resource::<TestFlush>().0, 5);
6180        let _ = a.take::<TestComponent>();
6181        assert_eq!(a.world().resource::<TestFlush>().0, 6);
6182        a.insert(TestComponent(0));
6183        assert_eq!(a.world().resource::<TestFlush>().0, 7);
6184        a.retain::<()>();
6185        assert_eq!(a.world().resource::<TestFlush>().0, 8);
6186        a.insert(TestComponent(0));
6187        assert_eq!(a.world().resource::<TestFlush>().0, 9);
6188        a.clear();
6189        assert_eq!(a.world().resource::<TestFlush>().0, 10);
6190        a.insert(TestComponent(0));
6191        assert_eq!(a.world().resource::<TestFlush>().0, 11);
6192        a.despawn();
6193        assert_eq!(world.resource::<TestFlush>().0, 12);
6194    }
6195
6196    #[derive(Resource)]
6197    struct TestVec(Vec<&'static str>);
6198
6199    #[derive(Component)]
6200    #[component(on_add = ord_a_hook_on_add, on_insert = ord_a_hook_on_insert, on_replace = ord_a_hook_on_replace, on_remove = ord_a_hook_on_remove)]
6201    struct OrdA;
6202
6203    fn ord_a_hook_on_add(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6204        world.resource_mut::<TestVec>().0.push("OrdA hook on_add");
6205        world.commands().entity(entity).insert(OrdB);
6206    }
6207
6208    fn ord_a_hook_on_insert(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6209        world
6210            .resource_mut::<TestVec>()
6211            .0
6212            .push("OrdA hook on_insert");
6213        world.commands().entity(entity).remove::<OrdA>();
6214        world.commands().entity(entity).remove::<OrdB>();
6215    }
6216
6217    fn ord_a_hook_on_replace(mut world: DeferredWorld, _: HookContext) {
6218        world
6219            .resource_mut::<TestVec>()
6220            .0
6221            .push("OrdA hook on_replace");
6222    }
6223
6224    fn ord_a_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
6225        world
6226            .resource_mut::<TestVec>()
6227            .0
6228            .push("OrdA hook on_remove");
6229    }
6230
6231    fn ord_a_observer_on_add(_event: On<Add, OrdA>, mut res: ResMut<TestVec>) {
6232        res.0.push("OrdA observer on_add");
6233    }
6234
6235    fn ord_a_observer_on_insert(_event: On<Insert, OrdA>, mut res: ResMut<TestVec>) {
6236        res.0.push("OrdA observer on_insert");
6237    }
6238
6239    fn ord_a_observer_on_replace(_event: On<Replace, OrdA>, mut res: ResMut<TestVec>) {
6240        res.0.push("OrdA observer on_replace");
6241    }
6242
6243    fn ord_a_observer_on_remove(_event: On<Remove, OrdA>, mut res: ResMut<TestVec>) {
6244        res.0.push("OrdA observer on_remove");
6245    }
6246
6247    #[derive(Component)]
6248    #[component(on_add = ord_b_hook_on_add, on_insert = ord_b_hook_on_insert, on_replace = ord_b_hook_on_replace, on_remove = ord_b_hook_on_remove)]
6249    struct OrdB;
6250
6251    fn ord_b_hook_on_add(mut world: DeferredWorld, _: HookContext) {
6252        world.resource_mut::<TestVec>().0.push("OrdB hook on_add");
6253        world.commands().queue(|world: &mut World| {
6254            world
6255                .resource_mut::<TestVec>()
6256                .0
6257                .push("OrdB command on_add");
6258        });
6259    }
6260
6261    fn ord_b_hook_on_insert(mut world: DeferredWorld, _: HookContext) {
6262        world
6263            .resource_mut::<TestVec>()
6264            .0
6265            .push("OrdB hook on_insert");
6266    }
6267
6268    fn ord_b_hook_on_replace(mut world: DeferredWorld, _: HookContext) {
6269        world
6270            .resource_mut::<TestVec>()
6271            .0
6272            .push("OrdB hook on_replace");
6273    }
6274
6275    fn ord_b_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
6276        world
6277            .resource_mut::<TestVec>()
6278            .0
6279            .push("OrdB hook on_remove");
6280    }
6281
6282    fn ord_b_observer_on_add(_event: On<Add, OrdB>, mut res: ResMut<TestVec>) {
6283        res.0.push("OrdB observer on_add");
6284    }
6285
6286    fn ord_b_observer_on_insert(_event: On<Insert, OrdB>, mut res: ResMut<TestVec>) {
6287        res.0.push("OrdB observer on_insert");
6288    }
6289
6290    fn ord_b_observer_on_replace(_event: On<Replace, OrdB>, mut res: ResMut<TestVec>) {
6291        res.0.push("OrdB observer on_replace");
6292    }
6293
6294    fn ord_b_observer_on_remove(_event: On<Remove, OrdB>, mut res: ResMut<TestVec>) {
6295        res.0.push("OrdB observer on_remove");
6296    }
6297
6298    #[test]
6299    fn command_ordering_is_correct() {
6300        let mut world = World::new();
6301        world.insert_resource(TestVec(Vec::new()));
6302        world.add_observer(ord_a_observer_on_add);
6303        world.add_observer(ord_a_observer_on_insert);
6304        world.add_observer(ord_a_observer_on_replace);
6305        world.add_observer(ord_a_observer_on_remove);
6306        world.add_observer(ord_b_observer_on_add);
6307        world.add_observer(ord_b_observer_on_insert);
6308        world.add_observer(ord_b_observer_on_replace);
6309        world.add_observer(ord_b_observer_on_remove);
6310        let _entity = world.spawn(OrdA).id();
6311        let expected = [
6312            "OrdA hook on_add", // adds command to insert OrdB
6313            "OrdA observer on_add",
6314            "OrdA hook on_insert", // adds command to despawn entity
6315            "OrdA observer on_insert",
6316            "OrdB hook on_add", // adds command to just add to this log
6317            "OrdB observer on_add",
6318            "OrdB hook on_insert",
6319            "OrdB observer on_insert",
6320            "OrdB command on_add", // command added by OrdB hook on_add, needs to run before despawn command
6321            "OrdA observer on_replace", // start of despawn
6322            "OrdA hook on_replace",
6323            "OrdA observer on_remove",
6324            "OrdA hook on_remove",
6325            "OrdB observer on_replace",
6326            "OrdB hook on_replace",
6327            "OrdB observer on_remove",
6328            "OrdB hook on_remove",
6329        ];
6330        world.flush();
6331        assert_eq!(world.resource_mut::<TestVec>().0.as_slice(), &expected[..]);
6332    }
6333
6334    #[test]
6335    fn entity_world_mut_clone_and_move_components() {
6336        #[derive(Component, Clone, PartialEq, Debug)]
6337        struct A;
6338
6339        #[derive(Component, Clone, PartialEq, Debug)]
6340        struct B;
6341
6342        #[derive(Component, Clone, PartialEq, Debug)]
6343        struct C(u32);
6344
6345        let mut world = World::new();
6346        let entity_a = world.spawn((A, B, C(5))).id();
6347        let entity_b = world.spawn((A, C(4))).id();
6348
6349        world.entity_mut(entity_a).clone_components::<B>(entity_b);
6350        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B));
6351        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B));
6352
6353        world.entity_mut(entity_a).move_components::<C>(entity_b);
6354        assert_eq!(world.entity(entity_a).get::<C>(), None);
6355        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(5)));
6356
6357        assert_eq!(world.entity(entity_a).get::<A>(), Some(&A));
6358        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));
6359    }
6360
6361    #[test]
6362    fn entity_world_mut_clone_with_move_and_require() {
6363        #[derive(Component, Clone, PartialEq, Debug)]
6364        #[require(B(3))]
6365        struct A;
6366
6367        #[derive(Component, Clone, PartialEq, Debug, Default)]
6368        #[require(C(3))]
6369        struct B(u32);
6370
6371        #[derive(Component, Clone, PartialEq, Debug, Default)]
6372        #[require(D)]
6373        struct C(u32);
6374
6375        #[derive(Component, Clone, PartialEq, Debug, Default)]
6376        struct D;
6377
6378        let mut world = World::new();
6379        let entity_a = world.spawn((A, B(5))).id();
6380        let entity_b = world.spawn_empty().id();
6381
6382        world
6383            .entity_mut(entity_a)
6384            .clone_with_opt_in(entity_b, |builder| {
6385                builder
6386                    .move_components(true)
6387                    .allow::<C>()
6388                    .without_required_components(|builder| {
6389                        builder.allow::<A>();
6390                    });
6391            });
6392
6393        assert_eq!(world.entity(entity_a).get::<A>(), None);
6394        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));
6395
6396        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B(5)));
6397        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B(3)));
6398
6399        assert_eq!(world.entity(entity_a).get::<C>(), None);
6400        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(3)));
6401
6402        assert_eq!(world.entity(entity_a).get::<D>(), None);
6403        assert_eq!(world.entity(entity_b).get::<D>(), Some(&D));
6404    }
6405
6406    #[test]
6407    fn update_despawned_by_after_observers() {
6408        let mut world = World::new();
6409
6410        #[derive(Component)]
6411        #[component(on_remove = get_tracked)]
6412        struct C;
6413
6414        static TRACKED: OnceLock<(MaybeLocation, Tick)> = OnceLock::new();
6415        fn get_tracked(world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6416            TRACKED.get_or_init(|| {
6417                let by = world
6418                    .entities
6419                    .entity_get_spawned_or_despawned_by(entity)
6420                    .map(|l| l.unwrap());
6421                let at = world
6422                    .entities
6423                    .entity_get_spawn_or_despawn_tick(entity)
6424                    .unwrap();
6425                (by, at)
6426            });
6427        }
6428
6429        #[track_caller]
6430        fn caller_spawn(world: &mut World) -> (Entity, MaybeLocation, Tick) {
6431            let caller = MaybeLocation::caller();
6432            (world.spawn(C).id(), caller, world.change_tick())
6433        }
6434        let (entity, spawner, spawn_tick) = caller_spawn(&mut world);
6435
6436        assert_eq!(
6437            spawner,
6438            world
6439                .entities()
6440                .entity_get_spawned_or_despawned_by(entity)
6441                .map(|l| l.unwrap())
6442        );
6443
6444        #[track_caller]
6445        fn caller_despawn(world: &mut World, entity: Entity) -> (MaybeLocation, Tick) {
6446            world.despawn(entity);
6447            (MaybeLocation::caller(), world.change_tick())
6448        }
6449        let (despawner, despawn_tick) = caller_despawn(&mut world, entity);
6450
6451        assert_eq!((spawner, spawn_tick), *TRACKED.get().unwrap());
6452        assert_eq!(
6453            despawner,
6454            world
6455                .entities()
6456                .entity_get_spawned_or_despawned_by(entity)
6457                .map(|l| l.unwrap())
6458        );
6459        assert_eq!(
6460            despawn_tick,
6461            world
6462                .entities()
6463                .entity_get_spawn_or_despawn_tick(entity)
6464                .unwrap()
6465        );
6466    }
6467
6468    #[test]
6469    fn with_component_activates_hooks() {
6470        use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
6471
6472        #[derive(Component, PartialEq, Eq, Debug)]
6473        #[component(immutable)]
6474        struct Foo(bool);
6475
6476        static EXPECTED_VALUE: AtomicBool = AtomicBool::new(false);
6477
6478        static ADD_COUNT: AtomicU8 = AtomicU8::new(0);
6479        static REMOVE_COUNT: AtomicU8 = AtomicU8::new(0);
6480        static REPLACE_COUNT: AtomicU8 = AtomicU8::new(0);
6481        static INSERT_COUNT: AtomicU8 = AtomicU8::new(0);
6482
6483        let mut world = World::default();
6484
6485        world.register_component::<Foo>();
6486        world
6487            .register_component_hooks::<Foo>()
6488            .on_add(|world, context| {
6489                ADD_COUNT.fetch_add(1, Ordering::Relaxed);
6490
6491                assert_eq!(
6492                    world.get(context.entity),
6493                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6494                );
6495            })
6496            .on_remove(|world, context| {
6497                REMOVE_COUNT.fetch_add(1, Ordering::Relaxed);
6498
6499                assert_eq!(
6500                    world.get(context.entity),
6501                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6502                );
6503            })
6504            .on_replace(|world, context| {
6505                REPLACE_COUNT.fetch_add(1, Ordering::Relaxed);
6506
6507                assert_eq!(
6508                    world.get(context.entity),
6509                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6510                );
6511            })
6512            .on_insert(|world, context| {
6513                INSERT_COUNT.fetch_add(1, Ordering::Relaxed);
6514
6515                assert_eq!(
6516                    world.get(context.entity),
6517                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6518                );
6519            });
6520
6521        let entity = world.spawn(Foo(false)).id();
6522
6523        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
6524        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
6525        assert_eq!(REPLACE_COUNT.load(Ordering::Relaxed), 0);
6526        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 1);
6527
6528        let mut entity = world.entity_mut(entity);
6529
6530        let archetype_pointer_before = &raw const *entity.archetype();
6531
6532        assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
6533
6534        entity.modify_component(|foo: &mut Foo| {
6535            foo.0 = true;
6536            EXPECTED_VALUE.store(foo.0, Ordering::Relaxed);
6537        });
6538
6539        let archetype_pointer_after = &raw const *entity.archetype();
6540
6541        assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
6542
6543        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
6544        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
6545        assert_eq!(REPLACE_COUNT.load(Ordering::Relaxed), 1);
6546        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 2);
6547
6548        assert_eq!(archetype_pointer_before, archetype_pointer_after);
6549    }
6550
6551    #[test]
6552    fn bundle_remove_only_triggers_for_present_components() {
6553        let mut world = World::default();
6554
6555        #[derive(Component)]
6556        struct A;
6557
6558        #[derive(Component)]
6559        struct B;
6560
6561        #[derive(Resource, PartialEq, Eq, Debug)]
6562        struct Tracker {
6563            a: bool,
6564            b: bool,
6565        }
6566
6567        world.insert_resource(Tracker { a: false, b: false });
6568        let entity = world.spawn(A).id();
6569
6570        world.add_observer(|_: On<Remove, A>, mut tracker: ResMut<Tracker>| {
6571            tracker.a = true;
6572        });
6573        world.add_observer(|_: On<Remove, B>, mut tracker: ResMut<Tracker>| {
6574            tracker.b = true;
6575        });
6576
6577        world.entity_mut(entity).remove::<(A, B)>();
6578
6579        assert_eq!(
6580            world.resource::<Tracker>(),
6581            &Tracker {
6582                a: true,
6583                // The entity didn't have a B component, so it should not have been triggered.
6584                b: false,
6585            }
6586        );
6587    }
6588}