-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Allow querying multiple components from FilteredEntityMut #21182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alice-i-cecile
merged 7 commits into
bevyengine:main
from
cBournhonesque:cb/filtered-entity-mut-unchecked
Sep 29, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
bcf0a2c
Provide a way to query multiple mutable components from FilteredEntit…
cBournhonesque 74ce71e
fix docs
cBournhonesque 157fbc6
add get_mut_unsafe and get_mut_by_id_unsafe + split out UnsafeFiltere…
cBournhonesque 1d7e0b0
Clean up doc comment
alice-i-cecile 99a965e
Improve safety comment
alice-i-cecile 52ee877
address comments
cBournhonesque 46e7ab0
fix
cBournhonesque File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3819,6 +3819,62 @@ impl ContainsEntity for FilteredEntityRef<'_, '_> { | |
// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity. | ||
unsafe impl EntityEquivalent for FilteredEntityRef<'_, '_> {} | ||
|
||
/// Variant of [`FilteredEntityMut`] that can be used to create copies of a [`FilteredEntityMut`], as long | ||
/// as the user ensures that these won't cause aliasing violations. | ||
/// | ||
/// This can be useful to mutably query multiple components from a single `FilteredEntityMut`. | ||
/// | ||
/// ### Example Usage | ||
/// | ||
/// ``` | ||
/// # use bevy_ecs::{prelude::*, world::{FilteredEntityMut, UnsafeFilteredEntityMut}}; | ||
/// # | ||
/// # #[derive(Component)] | ||
/// # struct A; | ||
/// # #[derive(Component)] | ||
/// # struct B; | ||
/// # | ||
/// # let mut world = World::new(); | ||
/// # world.spawn((A, B)); | ||
/// # | ||
/// // This gives the `FilteredEntityMut` access to `&mut A` and `&mut B`. | ||
/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world) | ||
/// .data::<(&mut A, &mut B)>() | ||
/// .build(); | ||
/// | ||
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap(); | ||
/// let unsafe_filtered_entity = UnsafeFilteredEntityMut::new_readonly(&filtered_entity); | ||
/// // SAFETY: the original FilteredEntityMut accesses `&mut A` and the clone accesses `&mut B`, so no aliasing violations occur. | ||
/// let mut filtered_entity_clone: FilteredEntityMut = unsafe { unsafe_filtered_entity.into_mut() }; | ||
/// let a: Mut<A> = filtered_entity.get_mut().unwrap(); | ||
/// let b: Mut<B> = filtered_entity_clone.get_mut().unwrap(); | ||
/// ``` | ||
#[derive(Copy, Clone)] | ||
pub struct UnsafeFilteredEntityMut<'w, 's> { | ||
entity: UnsafeEntityCell<'w>, | ||
access: &'s Access, | ||
} | ||
|
||
impl<'w, 's> UnsafeFilteredEntityMut<'w, 's> { | ||
/// Creates a [`UnsafeFilteredEntityMut`] that can be used to have multiple concurrent [`FilteredEntityMut`]s. | ||
#[inline] | ||
pub fn new_readonly(filtered_entity_mut: &FilteredEntityMut<'w, 's>) -> Self { | ||
Self { | ||
entity: filtered_entity_mut.entity, | ||
access: filtered_entity_mut.access, | ||
} | ||
} | ||
|
||
/// Returns a new instance of [`FilteredEntityMut`]. | ||
/// | ||
/// # Safety | ||
/// - The user must ensure that no aliasing violations occur when using the returned `FilteredEntityMut`. | ||
#[inline] | ||
pub unsafe fn into_mut(self) -> FilteredEntityMut<'w, 's> { | ||
FilteredEntityMut::new(self.entity, self.access) | ||
} | ||
} | ||
|
||
/// Provides mutable access to a single entity and some of its components defined by the contained [`Access`]. | ||
/// | ||
/// To define the access when used as a [`QueryData`](crate::query::QueryData), | ||
|
@@ -3842,6 +3898,8 @@ unsafe impl EntityEquivalent for FilteredEntityRef<'_, '_> {} | |
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap(); | ||
/// let component: Mut<A> = filtered_entity.get_mut().unwrap(); | ||
/// ``` | ||
/// | ||
/// Also see [`UnsafeFilteredEntityMut`] for a way to bypass borrow-checker restrictions. | ||
pub struct FilteredEntityMut<'w, 's> { | ||
entity: UnsafeEntityCell<'w>, | ||
access: &'s Access, | ||
|
@@ -3952,17 +4010,70 @@ impl<'w, 's> FilteredEntityMut<'w, 's> { | |
} | ||
|
||
/// Gets mutable access to the component of type `T` for the current entity. | ||
/// Returns `None` if the entity does not have a component of type `T`. | ||
/// Returns `None` if the entity does not have a component of type `T` or if | ||
/// the access does not include write access to `T`. | ||
#[inline] | ||
pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> { | ||
// SAFETY: we use a mutable reference to self, so we cannot use the `FilteredEntityMut` to access | ||
// another component | ||
unsafe { self.get_mut_unchecked() } | ||
} | ||
|
||
/// Gets mutable access to the component of type `T` for the current entity. | ||
/// Returns `None` if the entity does not have a component of type `T` or if | ||
/// the access does not include write access to `T`. | ||
/// | ||
/// This only requires `&self`, and so may be used to get mutable access to multiple components. | ||
/// | ||
/// # Example | ||
/// | ||
/// ``` | ||
/// # use bevy_ecs::{prelude::*, world::FilteredEntityMut}; | ||
/// # | ||
/// #[derive(Component)] | ||
/// struct X(usize); | ||
/// #[derive(Component)] | ||
/// struct Y(usize); | ||
/// | ||
/// # let mut world = World::default(); | ||
/// let mut entity = world.spawn((X(0), Y(0))).into_mutable(); | ||
/// | ||
/// // This gives the `FilteredEntityMut` access to `&mut X` and `&mut Y`. | ||
/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world) | ||
/// .data::<(&mut X, &mut Y)>() | ||
/// .build(); | ||
/// | ||
/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap(); | ||
/// | ||
/// // Get mutable access to two components at once | ||
/// // SAFETY: We don't take any other references to `X` from this entity | ||
/// let mut x = unsafe { filtered_entity.get_mut_unchecked::<X>() }.unwrap(); | ||
/// // SAFETY: We don't take any other references to `Y` from this entity | ||
/// let mut y = unsafe { filtered_entity.get_mut_unchecked::<Y>() }.unwrap(); | ||
/// *x = X(1); | ||
/// *y = Y(1); | ||
/// ``` | ||
/// | ||
/// # Safety | ||
/// | ||
/// No other references to the same component may exist at the same time as the returned reference. | ||
/// | ||
/// # See also | ||
/// | ||
/// - [`get_mut`](Self::get_mut) for the safe version. | ||
#[inline] | ||
pub unsafe fn get_mut_unchecked<T: Component<Mutability = Mutable>>( | ||
&self, | ||
) -> Option<Mut<'_, T>> { | ||
let id = self | ||
cBournhonesque marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.entity | ||
.world() | ||
.components() | ||
.get_valid_id(TypeId::of::<T>())?; | ||
self.access | ||
.has_component_write(id) | ||
// SAFETY: We have write access | ||
// SAFETY: We have permission to access the component mutable | ||
// and we promise to not create other references to the same component | ||
.then(|| unsafe { self.entity.get_mut() }) | ||
.flatten() | ||
} | ||
|
@@ -4042,9 +4153,38 @@ impl<'w, 's> FilteredEntityMut<'w, 's> { | |
/// which is only valid while the [`FilteredEntityMut`] is alive. | ||
#[inline] | ||
pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> { | ||
// SAFETY: we use a mutable reference to self, so we cannot use the `FilteredEntityMut` to access | ||
// another component | ||
unsafe { self.get_mut_by_id_unchecked(component_id) } | ||
} | ||
|
||
/// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity. | ||
/// | ||
/// **You should prefer to use the typed API [`Self::get_mut`] where possible and only | ||
/// use this in cases where the actual component types are not known at | ||
/// compile time.** | ||
/// | ||
/// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Copying the existing doc comment seems good for this PR, but |
||
/// which is only valid while the [`FilteredEntityMut`] is alive. | ||
/// | ||
/// This only requires `&self`, and so may be used to get mutable access to multiple components. | ||
/// | ||
/// # Safety | ||
/// | ||
/// No other references to the same component may exist at the same time as the returned reference. | ||
/// | ||
/// # See also | ||
/// | ||
/// - [`get_mut_by_id`](Self::get_mut_by_id) for the safe version. | ||
#[inline] | ||
pub unsafe fn get_mut_by_id_unchecked( | ||
&self, | ||
component_id: ComponentId, | ||
) -> Option<MutUntyped<'_>> { | ||
self.access | ||
.has_component_write(component_id) | ||
// SAFETY: We have write access | ||
// SAFETY: We have permission to access the component mutable | ||
// and we promise to not create other references to the same component | ||
.then(|| unsafe { self.entity.get_mut_by_id(component_id).ok() }) | ||
.flatten() | ||
} | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.