Skip to content

[Merged by Bors] - add UnsafeWorldCell abstraction #6404

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
24eec8f
add InteriorMutableWorld with resource access methods
jakobhellermann Oct 29, 2022
ee4efc3
add some safe accessors to InteriorMutableWorld
jakobhellermann Dec 17, 2022
11956cc
move unchecked methods from world to InteriorMutableWorld
jakobhellermann Oct 29, 2022
6561462
add get_non_send_resource and get_non_send_resource_mut to InteriorMu…
jakobhellermann Dec 17, 2022
1580e28
use InteriorMutableWorld for
jakobhellermann Oct 29, 2022
f1a08a6
add InteriorMutableEntityRef
jakobhellermann Oct 29, 2022
fdc4a01
add as_interior_mutable(&mut self), as_interior_mutable_readonly(&sel…
jakobhellermann Dec 17, 2022
1416efb
migrate WorldCell to InteriorMutableWorld
jakobhellermann Dec 17, 2022
92a32d0
fix lints
jakobhellermann Dec 17, 2022
e896555
fix doc test
jakobhellermann Dec 17, 2022
62e5b34
remove : from Safety block
jakobhellermann Dec 17, 2022
4b27b65
fix bevy_asset doc test
jakobhellermann Dec 17, 2022
6fb762f
tweak safety comments
jakobhellermann Jan 13, 2023
a5f38c1
fix interiormutableworld doc comments
jakobhellermann Jan 13, 2023
dabfd0b
add {read,last,increment}_change_tick to interiormutableworld
jakobhellermann Jan 13, 2023
2ad5d25
use contains_resource as example for unexposed method
jakobhellermann Jan 13, 2023
3d263b5
remove extra space
jakobhellermann Jan 13, 2023
9503a66
add get_non_send_resource[_mut]_by_id
jakobhellermann Jan 19, 2023
17afd9b
pass self instead of &self
jakobhellermann Jan 19, 2023
b065073
implement EntityMut::get_mut in terms of InteriorMutableEntityRef
jakobhellermann Jan 19, 2023
a5754cc
add InteriorMutableEntityRef::get_change_ticks_by_id
jakobhellermann Jan 19, 2023
68a9bca
docs fixes
jakobhellermann Jan 19, 2023
4f19233
raw pointer -> untyped pointer
jakobhellermann Jan 19, 2023
d637af0
more docs fixes
jakobhellermann Jan 19, 2023
efbebce
add missing safety comment
jakobhellermann Jan 24, 2023
ed140f5
add missing newline
jakobhellermann Jan 24, 2023
e20ca25
make unsafe fn unsafe
jakobhellermann Jan 24, 2023
3b39018
reuse InteriorMutableEntityRef more
jakobhellermann Jan 24, 2023
d6f742b
InteriorMutableWorld -> UnsafeWorldCell
jakobhellermann Jan 24, 2023
118a822
UnsafeEntityRefCell -> UnsafeWorldCellEntityRef
jakobhellermann Jan 24, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 17 additions & 22 deletions crates/bevy_asset/src/reflect.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::any::{Any, TypeId};

use bevy_ecs::world::World;
use bevy_ecs::world::{unsafe_world_cell::UnsafeWorldCell, World};
use bevy_reflect::{FromReflect, FromType, Reflect, Uuid};

use crate::{Asset, Assets, Handle, HandleId, HandleUntyped};
Expand All @@ -18,8 +18,10 @@ pub struct ReflectAsset {
assets_resource_type_id: TypeId,

get: fn(&World, HandleUntyped) -> Option<&dyn Reflect>,
get_mut: fn(&mut World, HandleUntyped) -> Option<&mut dyn Reflect>,
get_unchecked_mut: unsafe fn(&World, HandleUntyped) -> Option<&mut dyn Reflect>,
// SAFETY:
// - may only be called with a [`IteriorMutableWorld`] which can be used to access the corresponding `Assets<T>` resource mutably
// - may only be used to access **at most one** access at once
get_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>, HandleUntyped) -> Option<&mut dyn Reflect>,
add: fn(&mut World, &dyn Reflect) -> HandleUntyped,
set: fn(&mut World, HandleUntyped, &dyn Reflect) -> HandleUntyped,
len: fn(&World) -> usize,
Expand Down Expand Up @@ -54,10 +56,11 @@ impl ReflectAsset {
world: &'w mut World,
handle: HandleUntyped,
) -> Option<&'w mut dyn Reflect> {
(self.get_mut)(world, handle)
// SAFETY: unique world access
unsafe { (self.get_unchecked_mut)(world.as_unsafe_world_cell(), handle) }
}

/// Equivalent of [`Assets::get_mut`], but does not require a mutable reference to the world.
/// Equivalent of [`Assets::get_mut`], but works with an [`UnsafeWorldCell`].
///
/// Only use this method when you have ensured that you are the *only* one with access to the [`Assets`] resource of the asset type.
/// Furthermore, this does *not* allow you to have look up two distinct handles,
Expand All @@ -67,11 +70,12 @@ impl ReflectAsset {
/// # use bevy_asset::{ReflectAsset, HandleUntyped};
/// # use bevy_ecs::prelude::World;
/// # let reflect_asset: ReflectAsset = unimplemented!();
/// # let world: World = unimplemented!();
/// # let mut world: World = unimplemented!();
/// # let handle_1: HandleUntyped = unimplemented!();
/// # let handle_2: HandleUntyped = unimplemented!();
/// let a = unsafe { reflect_asset.get_unchecked_mut(&world, handle_1).unwrap() };
/// let b = unsafe { reflect_asset.get_unchecked_mut(&world, handle_2).unwrap() };
/// let unsafe_world_cell = world.as_unsafe_world_cell();
/// let a = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, handle_1).unwrap() };
/// let b = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, handle_2).unwrap() };
/// // ^ not allowed, two mutable references through the same asset resource, even though the
/// // handles are distinct
///
Expand All @@ -81,12 +85,11 @@ impl ReflectAsset {
/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method when you have exclusive access to the world
/// (or use a scheduler that enforces unique access to the `Assets` resource).
/// * Only call this method if you know that the [`UnsafeWorldCell`] may be used to access the corresponding `Assets<T>`
/// * Don't call this method more than once in the same scope.
pub unsafe fn get_unchecked_mut<'w>(
&self,
world: &'w World,
world: UnsafeWorldCell<'w>,
handle: HandleUntyped,
) -> Option<&'w mut dyn Reflect> {
// SAFETY: requirements are deferred to the caller
Expand Down Expand Up @@ -140,18 +143,10 @@ impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
let asset = assets.get(&handle.typed());
asset.map(|asset| asset as &dyn Reflect)
},
get_mut: |world, handle| {
let assets = world.resource_mut::<Assets<A>>().into_inner();
let asset = assets.get_mut(&handle.typed());
asset.map(|asset| asset as &mut dyn Reflect)
},
get_unchecked_mut: |world, handle| {
let assets = unsafe {
world
.get_resource_unchecked_mut::<Assets<A>>()
.unwrap()
.into_inner()
};
// SAFETY: `get_unchecked_mut` must be callied with `UnsafeWorldCell` having access to `Assets<A>`,
// and must ensure to only have at most one reference to it live at all times.
let assets = unsafe { world.get_resource_mut::<Assets<A>>().unwrap().into_inner() };
let asset = assets.get_mut(&handle.typed());
asset.map(|asset| asset as &mut dyn Reflect)
},
Expand Down
49 changes: 26 additions & 23 deletions crates/bevy_ecs/src/reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
component::Component,
entity::{Entity, EntityMap, MapEntities, MapEntitiesError},
system::Resource,
world::{FromWorld, World},
world::{unsafe_world_cell::UnsafeWorldCell, FromWorld, World},
};
use bevy_reflect::{
impl_from_reflect_value, impl_reflect_value, FromType, Reflect, ReflectDeserialize,
Expand Down Expand Up @@ -52,7 +52,10 @@ pub struct ReflectComponentFns {
/// Function pointer implementing [`ReflectComponent::reflect()`].
pub reflect: fn(&World, Entity) -> Option<&dyn Reflect>,
/// Function pointer implementing [`ReflectComponent::reflect_mut()`].
pub reflect_mut: unsafe fn(&World, Entity) -> Option<Mut<dyn Reflect>>,
///
/// # Safety
/// The function may only be called with an [`UnsafeWorldCell`] that can be used to mutably access the relevant component on the given entity.
pub reflect_mut: unsafe fn(UnsafeWorldCell<'_>, Entity) -> Option<Mut<'_, dyn Reflect>>,
/// Function pointer implementing [`ReflectComponent::copy()`].
pub copy: fn(&World, &mut World, Entity, Entity),
}
Expand Down Expand Up @@ -117,20 +120,20 @@ impl ReflectComponent {
entity: Entity,
) -> Option<Mut<'a, dyn Reflect>> {
// SAFETY: unique world access
unsafe { (self.0.reflect_mut)(world, entity) }
unsafe { (self.0.reflect_mut)(world.as_unsafe_world_cell(), entity) }
}

/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method in an exclusive system to avoid sharing across threads (or use a
/// scheduler that enforces safe memory access).
/// * Only call this method with a [`UnsafeWorldCell`] that may be used to mutably access the component on the entity `entity`
/// * Don't call this method more than once in the same scope for a given [`Component`].
pub unsafe fn reflect_unchecked_mut<'a>(
&self,
world: &'a World,
world: UnsafeWorldCell<'a>,
entity: Entity,
) -> Option<Mut<'a, dyn Reflect>> {
// SAFETY: safety requirements deferred to caller
(self.0.reflect_mut)(world, entity)
}

Expand Down Expand Up @@ -209,16 +212,14 @@ impl<C: Component + Reflect + FromWorld> FromType<C> for ReflectComponent {
.map(|c| c as &dyn Reflect)
},
reflect_mut: |world, entity| {
// SAFETY: reflect_mut is an unsafe function pointer used by `reflect_unchecked_mut` which promises to never
// produce aliasing mutable references, and reflect_mut, which has mutable world access
// SAFETY: reflect_mut is an unsafe function pointer used by
// 1. `reflect_unchecked_mut` which must be called with an UnsafeWorldCell with access to the the component `C` on the `entity`, and
// 2. `reflect_mut`, which has mutable world access
unsafe {
world
.get_entity(entity)?
.get_unchecked_mut::<C>(world.last_change_tick(), world.read_change_tick())
.map(|c| Mut {
value: c.value as &mut dyn Reflect,
ticks: c.ticks,
})
world.get_entity(entity)?.get_mut::<C>().map(|c| Mut {
value: c.value as &mut dyn Reflect,
ticks: c.ticks,
})
}
},
})
Expand Down Expand Up @@ -265,7 +266,10 @@ pub struct ReflectResourceFns {
/// Function pointer implementing [`ReflectResource::reflect()`].
pub reflect: fn(&World) -> Option<&dyn Reflect>,
/// Function pointer implementing [`ReflectResource::reflect_unchecked_mut()`].
pub reflect_unchecked_mut: unsafe fn(&World) -> Option<Mut<dyn Reflect>>,
///
/// # Safety
/// The function may only be called with an [`UnsafeWorldCell`] that can be used to mutably access the relevant resource.
pub reflect_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
/// Function pointer implementing [`ReflectResource::copy()`].
pub copy: fn(&World, &mut World),
}
Expand Down Expand Up @@ -314,19 +318,18 @@ impl ReflectResource {
/// Gets the value of this [`Resource`] type from the world as a mutable reflected reference.
pub fn reflect_mut<'a>(&self, world: &'a mut World) -> Option<Mut<'a, dyn Reflect>> {
// SAFETY: unique world access
unsafe { (self.0.reflect_unchecked_mut)(world) }
unsafe { (self.0.reflect_unchecked_mut)(world.as_unsafe_world_cell()) }
}

/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method in an exclusive system to avoid sharing across threads (or use a
/// scheduler that enforces safe memory access).
/// * Only call this method with an [`UnsafeWorldCell`] which can be used to mutably access the resource.
/// * Don't call this method more than once in the same scope for a given [`Resource`].
pub unsafe fn reflect_unchecked_mut<'a>(
pub unsafe fn reflect_unchecked_mut<'w>(
&self,
world: &'a World,
) -> Option<Mut<'a, dyn Reflect>> {
world: UnsafeWorldCell<'w>,
) -> Option<Mut<'w, dyn Reflect>> {
// SAFETY: caller promises to uphold uniqueness guarantees
(self.0.reflect_unchecked_mut)(world)
}
Expand Down Expand Up @@ -385,7 +388,7 @@ impl<C: Resource + Reflect + FromWorld> FromType<C> for ReflectResource {
// SAFETY: all usages of `reflect_unchecked_mut` guarantee that there is either a single mutable
// reference or multiple immutable ones alive at any given point
unsafe {
world.get_resource_unchecked_mut::<C>().map(|res| Mut {
world.get_resource_mut::<C>().map(|res| Mut {
value: res.value as &mut dyn Reflect,
ticks: res.ticks,
})
Expand Down
3 changes: 2 additions & 1 deletion crates/bevy_ecs/src/system/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,7 @@ impl<'w, 's, Q: WorldQuery, F: ReadOnlyWorldQuery> Query<'w, 's, Q, F> {
}
let world = self.world;
let entity_ref = world
.as_unsafe_world_cell_migration_internal()
.get_entity(entity)
.ok_or(QueryComponentError::NoSuchEntity)?;
let component_id = world
Expand All @@ -1150,7 +1151,7 @@ impl<'w, 's, Q: WorldQuery, F: ReadOnlyWorldQuery> Query<'w, 's, Q, F> {
.has_write(archetype_component)
{
entity_ref
.get_unchecked_mut::<T>(self.last_change_tick, self.change_tick)
.get_mut_using_ticks::<T>(self.last_change_tick, self.change_tick)
.ok_or(QueryComponentError::MissingComponent)
} else {
Err(QueryComponentError::MissingWriteAccess)
Expand Down
6 changes: 4 additions & 2 deletions crates/bevy_ecs/src/system/system_param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,8 @@ unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> {
change_tick: u32,
) -> Self::Item<'w, 's> {
let value = world
.get_resource_unchecked_mut_with_id(component_id)
.as_unsafe_world_cell_migration_internal()
.get_resource_mut_with_id(component_id)
.unwrap_or_else(|| {
panic!(
"Resource requested by {} does not exist: {}",
Expand Down Expand Up @@ -578,7 +579,8 @@ unsafe impl<'a, T: Resource> SystemParam for Option<ResMut<'a, T>> {
change_tick: u32,
) -> Self::Item<'w, 's> {
world
.get_resource_unchecked_mut_with_id(component_id)
.as_unsafe_world_cell_migration_internal()
.get_resource_mut_with_id(component_id)
.map(|value| ResMut {
value: value.value,
ticks: TicksMut {
Expand Down
Loading