bevy_ecs/world/entity_access/
entity_mut.rs

1use crate::{
2    archetype::Archetype,
3    change_detection::{ComponentTicks, MaybeLocation, Tick},
4    component::{Component, ComponentId, Mutable},
5    entity::{ContainsEntity, Entity, EntityEquivalent, EntityLocation},
6    query::{has_conflicts, Access, QueryAccessError, ReadOnlyQueryData, ReleaseStateQueryData},
7    world::{
8        error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, DynamicComponentFetch,
9        EntityRef, FilteredEntityMut, FilteredEntityRef, Mut, Ref,
10    },
11};
12
13use core::{
14    any::TypeId,
15    cmp::Ordering,
16    hash::{Hash, Hasher},
17};
18
19/// Provides mutable access to a single entity and all of its components.
20///
21/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
22/// despawning the entity, and provides mutable access to the entire world.
23/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
24///
25/// # Examples
26///
27/// Disjoint mutable access.
28///
29/// ```
30/// # use bevy_ecs::prelude::*;
31/// # #[derive(Component)] pub struct A;
32/// fn disjoint_system(
33///     query1: Query<EntityMut, With<A>>,
34///     query2: Query<EntityMut, Without<A>>,
35/// ) {
36///     // ...
37/// }
38/// # bevy_ecs::system::assert_is_system(disjoint_system);
39/// ```
40///
41/// [`EntityWorldMut`]: crate::world::EntityWorldMut
42pub struct EntityMut<'w> {
43    cell: UnsafeEntityCell<'w>,
44}
45
46impl<'w> EntityMut<'w> {
47    /// # Safety
48    /// - `cell` must have permission to mutate every component of the entity.
49    /// - No accesses to any of the entity's components may exist
50    ///   at the same time as the returned [`EntityMut`].
51    #[inline]
52    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
53        Self { cell }
54    }
55
56    /// Returns a new instance with a shorter lifetime.
57    /// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
58    pub fn reborrow(&mut self) -> EntityMut<'_> {
59        // SAFETY: We have exclusive access to the entire entity and its components.
60        unsafe { Self::new(self.cell) }
61    }
62
63    /// Consumes `self` and returns read-only access to all of the entity's
64    /// components, with the world `'w` lifetime.
65    pub fn into_readonly(self) -> EntityRef<'w> {
66        EntityRef::from(self)
67    }
68
69    /// Gets read-only access to all of the entity's components.
70    pub fn as_readonly(&self) -> EntityRef<'_> {
71        EntityRef::from(self)
72    }
73
74    /// Get access to the underlying [`UnsafeEntityCell`]
75    pub fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
76        self.cell
77    }
78
79    /// Returns the [ID](Entity) of the current entity.
80    #[inline]
81    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
82    pub fn id(&self) -> Entity {
83        self.cell.id()
84    }
85
86    /// Gets metadata indicating the location where the current entity is stored.
87    #[inline]
88    pub fn location(&self) -> EntityLocation {
89        self.cell.location()
90    }
91
92    /// Returns the archetype that the current entity belongs to.
93    #[inline]
94    pub fn archetype(&self) -> &Archetype {
95        self.cell.archetype()
96    }
97
98    /// Returns `true` if the current entity has a component of type `T`.
99    /// Otherwise, this returns `false`.
100    ///
101    /// ## Notes
102    ///
103    /// If you do not know the concrete type of a component, consider using
104    /// [`Self::contains_id`] or [`Self::contains_type_id`].
105    #[inline]
106    pub fn contains<T: Component>(&self) -> bool {
107        self.contains_type_id(TypeId::of::<T>())
108    }
109
110    /// Returns `true` if the current entity has a component identified by `component_id`.
111    /// Otherwise, this returns false.
112    ///
113    /// ## Notes
114    ///
115    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
116    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
117    ///   [`Self::contains_type_id`].
118    #[inline]
119    pub fn contains_id(&self, component_id: ComponentId) -> bool {
120        self.cell.contains_id(component_id)
121    }
122
123    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
124    /// Otherwise, this returns false.
125    ///
126    /// ## Notes
127    ///
128    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
129    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
130    #[inline]
131    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
132        self.cell.contains_type_id(type_id)
133    }
134
135    /// Gets access to the component of type `T` for the current entity.
136    /// Returns `None` if the entity does not have a component of type `T`.
137    #[inline]
138    pub fn get<T: Component>(&self) -> Option<&'_ T> {
139        self.as_readonly().get()
140    }
141
142    /// Returns read-only components for the current entity that match the query `Q`.
143    ///
144    /// # Panics
145    ///
146    /// If the entity does not have the components required by the query `Q`.
147    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
148        self.as_readonly().components::<Q>()
149    }
150
151    /// Returns read-only components for the current entity that match the query `Q`,
152    /// or `None` if the entity does not have the components required by the query `Q`.
153    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
154        &self,
155    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
156        self.as_readonly().get_components::<Q>()
157    }
158
159    /// Returns components for the current entity that match the query `Q`,
160    /// or `None` if the entity does not have the components required by the query `Q`.
161    ///
162    /// # Example
163    ///
164    /// ```
165    /// # use bevy_ecs::prelude::*;
166    /// #
167    /// #[derive(Component)]
168    /// struct X(usize);
169    /// #[derive(Component)]
170    /// struct Y(usize);
171    ///
172    /// # let mut world = World::default();
173    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
174    /// // Get mutable access to two components at once
175    /// // SAFETY: X and Y are different components
176    /// let (mut x, mut y) =
177    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
178    /// *x = X(1);
179    /// *y = Y(1);
180    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
181    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
182    /// ```
183    ///
184    /// # Safety
185    /// It is the caller's responsibility to ensure that
186    /// the `QueryData` does not provide aliasing mutable references to the same component.
187    ///
188    /// # See also
189    ///
190    /// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
191    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
192        &mut self,
193    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
194        // SAFETY: Caller ensures the `QueryData` does not provide aliasing mutable references to the same component
195        unsafe { self.reborrow().into_components_mut_unchecked::<Q>() }
196    }
197
198    /// Returns components for the current entity that match the query `Q`.
199    /// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
200    /// this will return a [`QueryAccessError`]
201    ///
202    /// # Example
203    ///
204    /// ```
205    /// # use bevy_ecs::prelude::*;
206    /// #
207    /// #[derive(Component)]
208    /// struct X(usize);
209    /// #[derive(Component)]
210    /// struct Y(usize);
211    ///
212    /// # let mut world = World::default();
213    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
214    /// // Get mutable access to two components at once
215    /// // SAFETY: X and Y are different components
216    /// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
217    /// ```
218    ///
219    /// Note that this does a O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
220    /// consideration you should use [`Self::get_components_mut_unchecked`] instead.
221    pub fn get_components_mut<Q: ReleaseStateQueryData>(
222        &mut self,
223    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
224        self.reborrow().into_components_mut::<Q>()
225    }
226
227    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
228    /// or `None` if the entity does not have the components required by the query `Q`.
229    ///
230    /// # Example
231    ///
232    /// ```
233    /// # use bevy_ecs::prelude::*;
234    /// #
235    /// #[derive(Component)]
236    /// struct X(usize);
237    /// #[derive(Component)]
238    /// struct Y(usize);
239    ///
240    /// # let mut world = World::default();
241    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
242    /// // Get mutable access to two components at once
243    /// // SAFETY: X and Y are different components
244    /// let (mut x, mut y) =
245    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
246    /// *x = X(1);
247    /// *y = Y(1);
248    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
249    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
250    /// ```
251    ///
252    /// # Safety
253    /// It is the caller's responsibility to ensure that
254    /// the `QueryData` does not provide aliasing mutable references to the same component.
255    ///
256    /// # See also
257    ///
258    /// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
259    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
260        self,
261    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
262        // SAFETY:
263        // - We have mutable access to all components of this entity.
264        // - Caller asserts the `QueryData` does not provide aliasing mutable references to the same component
265        unsafe { self.cell.get_components::<Q>() }
266    }
267
268    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
269    /// or `None` if the entity does not have the components required by the query `Q`.
270    ///
271    /// The checks for aliasing mutable references may be expensive.
272    /// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
273    /// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
274    ///
275    /// # Panics
276    ///
277    /// If the `QueryData` provides aliasing mutable references to the same component.
278    ///
279    /// # Example
280    ///
281    /// ```
282    /// # use bevy_ecs::prelude::*;
283    /// #
284    /// #[derive(Component)]
285    /// struct X(usize);
286    /// #[derive(Component)]
287    /// struct Y(usize);
288    ///
289    /// # let mut world = World::default();
290    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
291    /// // Get mutable access to two components at once
292    /// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
293    /// *x = X(1);
294    /// *y = Y(1);
295    /// ```
296    ///
297    /// ```should_panic
298    /// # use bevy_ecs::prelude::*;
299    /// #
300    /// # #[derive(Component)]
301    /// # struct X(usize);
302    /// #
303    /// # let mut world = World::default();
304    /// let mut entity = world.spawn((X(0))).into_mutable();
305    /// // This panics, as the `&mut X`s would alias:
306    /// entity.into_components_mut::<(&mut X, &mut X)>();
307    /// ```
308    pub fn into_components_mut<Q: ReleaseStateQueryData>(
309        self,
310    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
311        has_conflicts::<Q>(self.cell.world().components())?;
312
313        // SAFETY: we checked that there were not conflicting components above
314        unsafe { self.into_components_mut_unchecked::<Q>() }
315    }
316
317    /// Consumes `self` and gets access to the component of type `T` with the
318    /// world `'w` lifetime for the current entity.
319    ///
320    /// Returns `None` if the entity does not have a component of type `T`.
321    #[inline]
322    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
323        self.into_readonly().get()
324    }
325
326    /// Gets access to the component of type `T` for the current entity,
327    /// including change detection information as a [`Ref`].
328    ///
329    /// Returns `None` if the entity does not have a component of type `T`.
330    #[inline]
331    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
332        self.as_readonly().get_ref()
333    }
334
335    /// Consumes `self` and gets access to the component of type `T` with world
336    /// `'w` lifetime for the current entity, including change detection information
337    /// as a [`Ref<'w>`].
338    ///
339    /// Returns `None` if the entity does not have a component of type `T`.
340    #[inline]
341    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
342        self.into_readonly().get_ref()
343    }
344
345    /// Gets mutable access to the component of type `T` for the current entity.
346    /// Returns `None` if the entity does not have a component of type `T`.
347    #[inline]
348    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
349        // SAFETY: &mut self implies exclusive access for duration of returned value
350        unsafe { self.cell.get_mut() }
351    }
352
353    /// Gets mutable access to the component of type `T` for the current entity.
354    /// Returns `None` if the entity does not have a component of type `T`.
355    ///
356    /// # Safety
357    ///
358    /// - `T` must be a mutable component
359    #[inline]
360    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
361        // SAFETY:
362        // - &mut self implies exclusive access for duration of returned value
363        // - Caller ensures `T` is a mutable component
364        unsafe { self.cell.get_mut_assume_mutable() }
365    }
366
367    /// Consumes self and gets mutable access to the component of type `T`
368    /// with the world `'w` lifetime for the current entity.
369    /// Returns `None` if the entity does not have a component of type `T`.
370    #[inline]
371    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
372        // SAFETY: consuming `self` implies exclusive access
373        unsafe { self.cell.get_mut() }
374    }
375
376    /// Gets mutable access to the component of type `T` for the current entity.
377    /// Returns `None` if the entity does not have a component of type `T`.
378    ///
379    /// # Safety
380    ///
381    /// - `T` must be a mutable component
382    #[inline]
383    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
384        // SAFETY:
385        // - Consuming `self` implies exclusive access
386        // - Caller ensures `T` is a mutable component
387        unsafe { self.cell.get_mut_assume_mutable() }
388    }
389
390    /// Retrieves the change ticks for the given component. This can be useful for implementing change
391    /// detection in custom runtimes.
392    #[inline]
393    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
394        self.as_readonly().get_change_ticks::<T>()
395    }
396
397    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
398    /// detection in custom runtimes.
399    ///
400    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
401    /// use this in cases where the actual component types are not known at
402    /// compile time.**
403    ///
404    /// [`EntityWorldMut::get_change_ticks`]: crate::world::EntityWorldMut::get_change_ticks
405    #[inline]
406    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
407        self.as_readonly().get_change_ticks_by_id(component_id)
408    }
409
410    /// Returns untyped read-only reference(s) to component(s) for the
411    /// current entity, based on the given [`ComponentId`]s.
412    ///
413    /// **You should prefer to use the typed API [`EntityMut::get`] where
414    /// possible and only use this in cases where the actual component types
415    /// are not known at compile time.**
416    ///
417    /// Unlike [`EntityMut::get`], this returns untyped reference(s) to
418    /// component(s), and it's the job of the caller to ensure the correct
419    /// type(s) are dereferenced (if necessary).
420    ///
421    /// # Errors
422    ///
423    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
424    /// not have a component.
425    ///
426    /// # Examples
427    ///
428    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
429    #[inline]
430    pub fn get_by_id<F: DynamicComponentFetch>(
431        &self,
432        component_ids: F,
433    ) -> Result<F::Ref<'_>, EntityComponentError> {
434        self.as_readonly().get_by_id(component_ids)
435    }
436
437    /// Consumes `self` and returns untyped read-only reference(s) to
438    /// component(s) with lifetime `'w` for the current entity, based on the
439    /// given [`ComponentId`]s.
440    ///
441    /// **You should prefer to use the typed API [`EntityMut::into_borrow`]
442    /// where possible and only use this in cases where the actual component
443    /// types are not known at compile time.**
444    ///
445    /// Unlike [`EntityMut::into_borrow`], this returns untyped reference(s) to
446    /// component(s), and it's the job of the caller to ensure the correct
447    /// type(s) are dereferenced (if necessary).
448    ///
449    /// # Errors
450    ///
451    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
452    /// not have a component.
453    ///
454    /// # Examples
455    ///
456    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
457    #[inline]
458    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
459        self,
460        component_ids: F,
461    ) -> Result<F::Ref<'w>, EntityComponentError> {
462        self.into_readonly().get_by_id(component_ids)
463    }
464
465    /// Returns untyped mutable reference(s) to component(s) for
466    /// the current entity, based on the given [`ComponentId`]s.
467    ///
468    /// **You should prefer to use the typed API [`EntityMut::get_mut`] where
469    /// possible and only use this in cases where the actual component types
470    /// are not known at compile time.**
471    ///
472    /// Unlike [`EntityMut::get_mut`], this returns untyped reference(s) to
473    /// component(s), and it's the job of the caller to ensure the correct
474    /// type(s) are dereferenced (if necessary).
475    ///
476    /// # Errors
477    ///
478    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
479    ///   not have a component.
480    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
481    ///   is requested multiple times.
482    ///
483    /// # Examples
484    ///
485    /// ## Single [`ComponentId`]
486    ///
487    /// ```
488    /// # use bevy_ecs::prelude::*;
489    /// #
490    /// # #[derive(Component, PartialEq, Debug)]
491    /// # pub struct Foo(i32);
492    /// # let mut world = World::new();
493    /// let entity = world.spawn(Foo(42)).id();
494    ///
495    /// // Grab the component ID for `Foo` in whatever way you like.
496    /// let component_id = world.register_component::<Foo>();
497    ///
498    /// // Then, get the component by ID.
499    /// let mut entity_mut = world.entity_mut(entity);
500    /// let mut ptr = entity_mut.get_mut_by_id(component_id)
501    /// #   .unwrap();
502    /// # assert_eq!(unsafe { ptr.as_mut().deref_mut::<Foo>() }, &mut Foo(42));
503    /// ```
504    ///
505    /// ## Array of [`ComponentId`]s
506    ///
507    /// ```
508    /// # use bevy_ecs::prelude::*;
509    /// #
510    /// # #[derive(Component, PartialEq, Debug)]
511    /// # pub struct X(i32);
512    /// # #[derive(Component, PartialEq, Debug)]
513    /// # pub struct Y(i32);
514    /// # let mut world = World::new();
515    /// let entity = world.spawn((X(42), Y(10))).id();
516    ///
517    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
518    /// let x_id = world.register_component::<X>();
519    /// let y_id = world.register_component::<Y>();
520    ///
521    /// // Then, get the components by ID. You'll receive a same-sized array.
522    /// let mut entity_mut = world.entity_mut(entity);
523    /// let Ok([mut x_ptr, mut y_ptr]) = entity_mut.get_mut_by_id([x_id, y_id]) else {
524    ///     // Up to you to handle if a component is missing from the entity.
525    /// #   unreachable!();
526    /// };
527    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
528    /// ```
529    ///
530    /// ## Slice of [`ComponentId`]s
531    ///
532    /// ```
533    /// # use bevy_ecs::{prelude::*, component::ComponentId, change_detection::MutUntyped};
534    /// #
535    /// # #[derive(Component, PartialEq, Debug)]
536    /// # pub struct X(i32);
537    /// # #[derive(Component, PartialEq, Debug)]
538    /// # pub struct Y(i32);
539    /// # let mut world = World::new();
540    /// let entity = world.spawn((X(42), Y(10))).id();
541    ///
542    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
543    /// let x_id = world.register_component::<X>();
544    /// let y_id = world.register_component::<Y>();
545    ///
546    /// // Then, get the components by ID. You'll receive a vec of ptrs.
547    /// let mut entity_mut = world.entity_mut(entity);
548    /// let ptrs = entity_mut.get_mut_by_id(&[x_id, y_id] as &[ComponentId])
549    /// #   .unwrap();
550    /// # let [mut x_ptr, mut y_ptr]: [MutUntyped; 2] = ptrs.try_into().unwrap();
551    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
552    /// ```
553    ///
554    /// ## `HashSet` of [`ComponentId`]s
555    ///
556    /// ```
557    /// # use bevy_platform::collections::HashSet;
558    /// # use bevy_ecs::{prelude::*, component::ComponentId};
559    /// #
560    /// # #[derive(Component, PartialEq, Debug)]
561    /// # pub struct X(i32);
562    /// # #[derive(Component, PartialEq, Debug)]
563    /// # pub struct Y(i32);
564    /// # let mut world = World::new();
565    /// let entity = world.spawn((X(42), Y(10))).id();
566    ///
567    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
568    /// let x_id = world.register_component::<X>();
569    /// let y_id = world.register_component::<Y>();
570    ///
571    /// // Then, get the components by ID. You'll receive a `HashMap` of ptrs.
572    /// let mut entity_mut = world.entity_mut(entity);
573    /// let mut ptrs = entity_mut.get_mut_by_id(&HashSet::from_iter([x_id, y_id]))
574    /// #   .unwrap();
575    /// # let [Some(mut x_ptr), Some(mut y_ptr)] = ptrs.get_many_mut([&x_id, &y_id]) else { unreachable!() };
576    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
577    /// ```
578    #[inline]
579    pub fn get_mut_by_id<F: DynamicComponentFetch>(
580        &mut self,
581        component_ids: F,
582    ) -> Result<F::Mut<'_>, EntityComponentError> {
583        // SAFETY:
584        // - `&mut self` ensures that no references exist to this entity's components.
585        // - We have exclusive access to all components of this entity.
586        unsafe { component_ids.fetch_mut(self.cell) }
587    }
588
589    /// Returns untyped mutable reference(s) to component(s) for
590    /// the current entity, based on the given [`ComponentId`]s.
591    /// Assumes the given [`ComponentId`]s refer to mutable components.
592    ///
593    /// **You should prefer to use the typed API [`EntityMut::get_mut_assume_mutable`] where
594    /// possible and only use this in cases where the actual component types
595    /// are not known at compile time.**
596    ///
597    /// Unlike [`EntityMut::get_mut_assume_mutable`], this returns untyped reference(s) to
598    /// component(s), and it's the job of the caller to ensure the correct
599    /// type(s) are dereferenced (if necessary).
600    ///
601    /// # Errors
602    ///
603    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
604    ///   not have a component.
605    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
606    ///   is requested multiple times.
607    ///
608    /// # Safety
609    /// It is the callers responsibility to ensure that
610    /// - the provided [`ComponentId`]s must refer to mutable components.
611    #[inline]
612    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
613        &mut self,
614        component_ids: F,
615    ) -> Result<F::Mut<'_>, EntityComponentError> {
616        // SAFETY:
617        // - `&mut self` ensures that no references exist to this entity's components.
618        // - We have exclusive access to all components of this entity.
619        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
620    }
621
622    /// Returns untyped mutable reference to component for
623    /// the current entity, based on the given [`ComponentId`].
624    ///
625    /// Unlike [`EntityMut::get_mut_by_id`], this method borrows &self instead of
626    /// &mut self, allowing the caller to access multiple components simultaneously.
627    ///
628    /// # Errors
629    ///
630    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
631    ///   not have a component.
632    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
633    ///   is requested multiple times.
634    ///
635    /// # Safety
636    /// It is the callers responsibility to ensure that
637    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
638    /// - no other references to the component exist at the same time
639    #[inline]
640    pub unsafe fn get_mut_by_id_unchecked<F: DynamicComponentFetch>(
641        &self,
642        component_ids: F,
643    ) -> Result<F::Mut<'_>, EntityComponentError> {
644        // SAFETY:
645        // - The caller must ensure simultaneous access is limited
646        // - to components that are mutually independent.
647        unsafe { component_ids.fetch_mut(self.cell) }
648    }
649
650    /// Returns untyped mutable reference to component for
651    /// the current entity, based on the given [`ComponentId`].
652    /// Assumes the given [`ComponentId`]s refer to mutable components.
653    ///
654    /// Unlike [`EntityMut::get_mut_assume_mutable_by_id`], this method borrows &self instead of
655    /// &mut self, allowing the caller to access multiple components simultaneously.
656    ///
657    /// # Errors
658    ///
659    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
660    ///   not have a component.
661    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
662    ///   is requested multiple times.
663    ///
664    /// # Safety
665    /// It is the callers responsibility to ensure that
666    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
667    /// - no other references to the component exist at the same time
668    /// - the provided [`ComponentId`]s must refer to mutable components.
669    #[inline]
670    pub unsafe fn get_mut_assume_mutable_by_id_unchecked<F: DynamicComponentFetch>(
671        &self,
672        component_ids: F,
673    ) -> Result<F::Mut<'_>, EntityComponentError> {
674        // SAFETY:
675        // - The caller must ensure simultaneous access is limited
676        // - to components that are mutually independent.
677        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
678    }
679
680    /// Consumes `self` and returns untyped mutable reference(s)
681    /// to component(s) with lifetime `'w` for the current entity, based on the
682    /// given [`ComponentId`]s.
683    ///
684    /// **You should prefer to use the typed API [`EntityMut::into_mut`] where
685    /// possible and only use this in cases where the actual component types
686    /// are not known at compile time.**
687    ///
688    /// Unlike [`EntityMut::into_mut`], this returns untyped reference(s) to
689    /// component(s), and it's the job of the caller to ensure the correct
690    /// type(s) are dereferenced (if necessary).
691    ///
692    /// # Errors
693    ///
694    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
695    ///   not have a component.
696    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
697    ///   is requested multiple times.
698    ///
699    /// # Examples
700    ///
701    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
702    #[inline]
703    pub fn into_mut_by_id<F: DynamicComponentFetch>(
704        self,
705        component_ids: F,
706    ) -> Result<F::Mut<'w>, EntityComponentError> {
707        // SAFETY:
708        // - consuming `self` ensures that no references exist to this entity's components.
709        // - We have exclusive access to all components of this entity.
710        unsafe { component_ids.fetch_mut(self.cell) }
711    }
712
713    /// Consumes `self` and returns untyped mutable reference(s)
714    /// to component(s) with lifetime `'w` for the current entity, based on the
715    /// given [`ComponentId`]s.
716    /// Assumes the given [`ComponentId`]s refer to mutable components.
717    ///
718    /// **You should prefer to use the typed API [`EntityMut::into_mut_assume_mutable`] where
719    /// possible and only use this in cases where the actual component types
720    /// are not known at compile time.**
721    ///
722    /// Unlike [`EntityMut::into_mut_assume_mutable`], this returns untyped reference(s) to
723    /// component(s), and it's the job of the caller to ensure the correct
724    /// type(s) are dereferenced (if necessary).
725    ///
726    /// # Errors
727    ///
728    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
729    ///   not have a component.
730    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
731    ///   is requested multiple times.
732    ///
733    /// # Safety
734    /// It is the callers responsibility to ensure that
735    /// - the provided [`ComponentId`]s must refer to mutable components.
736    #[inline]
737    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
738        self,
739        component_ids: F,
740    ) -> Result<F::Mut<'w>, EntityComponentError> {
741        // SAFETY:
742        // - consuming `self` ensures that no references exist to this entity's components.
743        // - We have exclusive access to all components of this entity.
744        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
745    }
746
747    /// Returns the source code location from which this entity has been spawned.
748    pub fn spawned_by(&self) -> MaybeLocation {
749        self.cell.spawned_by()
750    }
751
752    /// Returns the [`Tick`] at which this entity has been spawned.
753    pub fn spawn_tick(&self) -> Tick {
754        self.cell.spawn_tick()
755    }
756}
757
758impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
759    fn from(entity: EntityMut<'w>) -> Self {
760        // SAFETY:
761        // - `EntityMut` guarantees exclusive access to all of the entity's components.
762        unsafe { EntityRef::new(entity.cell) }
763    }
764}
765
766impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
767    fn from(entity: &'a EntityMut<'_>) -> Self {
768        // SAFETY:
769        // - `EntityMut` guarantees exclusive access to all of the entity's components.
770        // - `&entity` ensures there are no mutable accesses.
771        unsafe { EntityRef::new(entity.cell) }
772    }
773}
774
775impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
776    fn from(entity: &'w mut EntityMut<'_>) -> Self {
777        entity.reborrow()
778    }
779}
780
781impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a, 'static> {
782    fn from(entity: EntityMut<'a>) -> Self {
783        // SAFETY:
784        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
785        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
786    }
787}
788
789impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a, 'static> {
790    fn from(entity: &'a EntityMut<'_>) -> Self {
791        // SAFETY:
792        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
793        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
794    }
795}
796
797impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a, 'static> {
798    fn from(entity: EntityMut<'a>) -> Self {
799        // SAFETY:
800        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
801        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
802    }
803}
804
805impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a, 'static> {
806    fn from(entity: &'a mut EntityMut<'_>) -> Self {
807        // SAFETY:
808        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
809        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
810    }
811}
812
813impl PartialEq for EntityMut<'_> {
814    fn eq(&self, other: &Self) -> bool {
815        self.entity() == other.entity()
816    }
817}
818
819impl Eq for EntityMut<'_> {}
820
821impl PartialOrd for EntityMut<'_> {
822    /// [`EntityMut`]'s comparison trait implementations match the underlying [`Entity`],
823    /// and cannot discern between different worlds.
824    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
825        Some(self.cmp(other))
826    }
827}
828
829impl Ord for EntityMut<'_> {
830    fn cmp(&self, other: &Self) -> Ordering {
831        self.entity().cmp(&other.entity())
832    }
833}
834
835impl Hash for EntityMut<'_> {
836    fn hash<H: Hasher>(&self, state: &mut H) {
837        self.entity().hash(state);
838    }
839}
840
841impl ContainsEntity for EntityMut<'_> {
842    fn entity(&self) -> Entity {
843        self.id()
844    }
845}
846
847// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
848unsafe impl EntityEquivalent for EntityMut<'_> {}