-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
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 by Bors] - add UnsafeWorldCell
abstraction
#6404
[Merged by Bors] - add UnsafeWorldCell
abstraction
#6404
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is very well-made and documented. Overall, I like this much better than unsafe accessor functions for every usage of the World
.
A couple of questions to get a better sense of the architectural direction:
- What external use cases do you see this being useful for?
- In the long-term, how does this fit in with
WorldCell
(which also allows split mutable access, but via reference counting)? Should we expandWorldCell
to match / use this API? Should we remove it entirely in favor ofInteriorMutableWorld
? Should we unify them and have an option to turn on ref-counting? - In the long-term, what would you like to use this for internally?
Good questions.
The use case I had is for &mut World
├── Handle@Entity1
└── everything -Handle@Entity1
├── Assets<StandardMaterial>
└── everything -Handle -Assets<StandardMaterial> Currently this stores a Another use case is running scripts in parallel (basically the same use case as bevy has with fn run_script(world: InteriorMutableWorld<'_>) {} is much more self-documenting than the
In this PR: Change the signature of the unsafe methods in |
It needs to be |
Right, the default can be a safe We still need a function to go from bevy/crates/bevy_ecs/src/system/function_system.rs Lines 163 to 174 in 688f13c
In the future, get_unchecked_manual will take a InteriorMutableWorld . But get should take a &World , that is correct.What is the safety contract of get_unchecked_manual ?Something like "You can only call this with a InteriorMutableWorld that may be used to access everything defined in this state's component_access_set ".
And the new safety comment here would be
Note that not the creation of the A fn some_safe_function(world: InteriorMutableWorld<'_>) {
// you can access *no* resources here, neither mutable nor immutable. What would you write as the Safety comment? You have no permission.
} The way that the /// SAFETY: may only be called with a interior mutable world that may be used to access MyResource mutably
unsafe fn some_unsafe_function(world: InteriorMutableWorld<'_>) {
// SAFETY: we're allowed to access it
let res = unsafe { world.get_resource_mut::<MyResource>() };
} So what should be the safety comment of a function |
Anything else (e.g. a world that can only access according to a |
59e58ee
to
c5afce8
Compare
As another example, bevy/crates/bevy_ecs/src/query/fetch.rs Lines 333 to 338 in 6763b31
Doing this is completely safe, both inside the function ( |
|
Agreed. impl World {
// Grants read-write access to the entire world
fn as_interior_mutable(&mut self) -> InteriorMutableWorld<'_> {}
// Grants read-only access to the entire world
fn as_interior_mutable_readonly(&self) -> InteriorMutableWorld<'_> {}
} ? |
Yeah that looks good to me |
Would something like |
I don't think so, it doesnt have anything making it seem like interior mutability is going on ( |
46fb354
to
31caf80
Compare
I added the methods /// Creates a new [`InteriorMutableWorld`] view with complete read+write access
pub fn as_interior_mutable(&mut self) -> InteriorMutableWorld<'_>:
/// Creates a new [`InteriorMutableWorld`] view only read access to everything
pub fn as_interior_mutable_readonly(&self) -> InteriorMutableWorld<'_>:
/// Creates a new [`InteriorMutableWorld`] with read+write access from a [&World](World).
/// This is only a temporary measure until every `&World` that is semantically a [InteriorMutableWorld]
/// has been replaced.
pub(crate) fn as_interior_mutable_migration_internal(&self) -> InteriorMutableWorld<'_>; The last one will be removed in a PR I will put up soon. There is one new change here I'd like feedback on, regarding The alternative would be to keep storing |
What's the motivation for a read-only interior |
If you have an unsafe method that takes a |
If the function doesn't write to anything, why not just have it take Edit: Nevermind, I see. In the example you linked, |
I think that I think that we should add a |
Isn't this unsound unless we put a |
yes |
Discussed with @BoxyUwU that their comments above are not blocking and can be done in a followup PR. Counting that as 2 SME approvals. bors r+ |
alternative to #5922, implements #5956 builds on top of #6402 # Objective #5956 goes into more detail, but the TLDR is: - bevy systems ensure disjoint accesses to resources and components, and for that to work there are methods `World::get_resource_unchecked_mut(&self)`, ..., `EntityRef::get_mut_unchecked(&self)` etc. - we don't have these unchecked methods for `by_id` variants, so third-party crate authors cannot build their own safe disjoint-access abstractions with these - having `_unchecked_mut` methods is not great, because in their presence safe code can accidentally violate subtle invariants. Having to go through `world.as_unsafe_world_cell().unsafe_method()` forces you to stop and think about what you want to write in your `// SAFETY` comment. The alternative is to keep exposing `_unchecked_mut` variants for every operation that we want third-party crates to build upon, but we'd prefer to avoid using these methods alltogether: #5922 (comment) Also, this is something that **cannot be implemented outside of bevy**, so having either this PR or #5922 as an escape hatch with lots of discouraging comments would be great. ## Solution - add `UnsafeWorldCell` with `unsafe fn get_resource(&self)`, `unsafe fn get_resource_mut(&self)` - add `fn World::as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>` (and `as_unsafe_world_cell_readonly(&self)`) - add `UnsafeWorldCellEntityRef` with `unsafe fn get`, `unsafe fn get_mut` and the other utilities on `EntityRef` (no methods for spawning, despawning, insertion) - use the `UnsafeWorldCell` abstraction in `ReflectComponent`, `ReflectResource` and `ReflectAsset`, so these APIs are easier to reason about - remove `World::get_resource_mut_unchecked`, `EntityRef::get_mut_unchecked` and use `unsafe { world.as_unsafe_world_cell().get_mut() }` and `unsafe { world.as_unsafe_world_cell().get_entity(entity)?.get_mut() }` instead This PR does **not** make use of `UnsafeWorldCell` for anywhere else in `bevy_ecs` such as `SystemParam` or `Query`. That is a much larger change, and I am convinced that having `UnsafeWorldCell` is already useful for third-party crates. Implemented API: ```rust struct World { .. } impl World { fn as_unsafe_world_cell(&self) -> UnsafeWorldCell<'_>; } struct UnsafeWorldCell<'w>(&'w World); impl<'w> UnsafeWorldCell { unsafe fn world(&self) -> &World; fn get_entity(&self) -> UnsafeWorldCellEntityRef<'w>; // returns 'w which is `'self` of the `World::as_unsafe_world_cell(&'w self)` unsafe fn get_resource<T>(&self) -> Option<&'w T>; unsafe fn get_resource_by_id(&self, ComponentId) -> Option<&'w T>; unsafe fn get_resource_mut<T>(&self) -> Option<Mut<'w, T>>; unsafe fn get_resource_mut_by_id(&self) -> Option<MutUntyped<'w>>; unsafe fn get_non_send_resource<T>(&self) -> Option<&'w T>; unsafe fn get_non_send_resource_mut<T>(&self) -> Option<Mut<'w, T>>>; // not included: remove, remove_resource, despawn, anything that might change archetypes } struct UnsafeWorldCellEntityRef<'w> { .. } impl UnsafeWorldCellEntityRef<'w> { unsafe fn get<T>(&self, Entity) -> Option<&'w T>; unsafe fn get_by_id(&self, Entity, ComponentId) -> Option<Ptr<'w>>; unsafe fn get_mut<T>(&self, Entity) -> Option<Mut<'w, T>>; unsafe fn get_mut_by_id(&self, Entity, ComponentId) -> Option<MutUntyped<'w>>; unsafe fn get_change_ticks<T>(&self, Entity) -> Option<Mut<'w, T>>; // fn id, archetype, contains, contains_id, containts_type_id } ``` <details> <summary>UnsafeWorldCell docs</summary> Variant of the [`World`] where resource and component accesses takes a `&World`, and the responsibility to avoid aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule. ### Rationale In rust, having a `&mut World` means that there are absolutely no other references to the safe world alive at the same time, without exceptions. Not even unsafe code can change this. But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the [`UnsafeCell`](std::cell::UnsafeCell) escape hatch, which allows you to get a `*mut T` from a `&UnsafeCell<T>` and around which safe abstractions can be built. Access to resources and components can be done uniquely using [`World::resource_mut`] and [`World::entity_mut`], and shared using [`World::resource`] and [`World::entity`]. These methods use lifetimes to check at compile time that no aliasing rules are being broken. This alone is not enough to implement bevy systems where multiple systems can access *disjoint* parts of the world concurrently. For this, bevy stores all values of resources and components (and [`ComponentTicks`](crate::component::ComponentTicks)) in [`UnsafeCell`](std::cell::UnsafeCell)s, and carefully validates disjoint access patterns using APIs like [`System::component_access`](crate::system::System::component_access). A system then can be executed using [`System::run_unsafe`](crate::system::System::run_unsafe) with a `&World` and use methods with interior mutability to access resource values. access resource values. ### Example Usage [`UnsafeWorldCell`] can be used as a building block for writing APIs that safely allow disjoint access into the world. In the following example, the world is split into a resource access half and a component access half, where each one can safely hand out mutable references. ```rust use bevy_ecs::world::World; use bevy_ecs::change_detection::Mut; use bevy_ecs::system::Resource; use bevy_ecs::world::unsafe_world_cell_world::UnsafeWorldCell; // INVARIANT: existance of this struct means that users of it are the only ones being able to access resources in the world struct OnlyResourceAccessWorld<'w>(UnsafeWorldCell<'w>); // INVARIANT: existance of this struct means that users of it are the only ones being able to access components in the world struct OnlyComponentAccessWorld<'w>(UnsafeWorldCell<'w>); impl<'w> OnlyResourceAccessWorld<'w> { fn get_resource_mut<T: Resource>(&mut self) -> Option<Mut<'w, T>> { // SAFETY: resource access is allowed through this UnsafeWorldCell unsafe { self.0.get_resource_mut::<T>() } } } // impl<'w> OnlyComponentAccessWorld<'w> { // ... // } // the two interior mutable worlds borrow from the `&mut World`, so it cannot be accessed while they are live fn split_world_access(world: &mut World) -> (OnlyResourceAccessWorld<'_>, OnlyComponentAccessWorld<'_>) { let resource_access = OnlyResourceAccessWorld(unsafe { world.as_unsafe_world_cell() }); let component_access = OnlyComponentAccessWorld(unsafe { world.as_unsafe_world_cell() }); (resource_access, component_access) } ``` </details>
Pull request successfully merged into main. Build succeeded:
|
UnsafeWorldCell
abstractionUnsafeWorldCell
abstraction
alternative to bevyengine#5922, implements bevyengine#5956 builds on top of bevyengine#6402 # Objective bevyengine#5956 goes into more detail, but the TLDR is: - bevy systems ensure disjoint accesses to resources and components, and for that to work there are methods `World::get_resource_unchecked_mut(&self)`, ..., `EntityRef::get_mut_unchecked(&self)` etc. - we don't have these unchecked methods for `by_id` variants, so third-party crate authors cannot build their own safe disjoint-access abstractions with these - having `_unchecked_mut` methods is not great, because in their presence safe code can accidentally violate subtle invariants. Having to go through `world.as_unsafe_world_cell().unsafe_method()` forces you to stop and think about what you want to write in your `// SAFETY` comment. The alternative is to keep exposing `_unchecked_mut` variants for every operation that we want third-party crates to build upon, but we'd prefer to avoid using these methods alltogether: bevyengine#5922 (comment) Also, this is something that **cannot be implemented outside of bevy**, so having either this PR or bevyengine#5922 as an escape hatch with lots of discouraging comments would be great. ## Solution - add `UnsafeWorldCell` with `unsafe fn get_resource(&self)`, `unsafe fn get_resource_mut(&self)` - add `fn World::as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>` (and `as_unsafe_world_cell_readonly(&self)`) - add `UnsafeWorldCellEntityRef` with `unsafe fn get`, `unsafe fn get_mut` and the other utilities on `EntityRef` (no methods for spawning, despawning, insertion) - use the `UnsafeWorldCell` abstraction in `ReflectComponent`, `ReflectResource` and `ReflectAsset`, so these APIs are easier to reason about - remove `World::get_resource_mut_unchecked`, `EntityRef::get_mut_unchecked` and use `unsafe { world.as_unsafe_world_cell().get_mut() }` and `unsafe { world.as_unsafe_world_cell().get_entity(entity)?.get_mut() }` instead This PR does **not** make use of `UnsafeWorldCell` for anywhere else in `bevy_ecs` such as `SystemParam` or `Query`. That is a much larger change, and I am convinced that having `UnsafeWorldCell` is already useful for third-party crates. Implemented API: ```rust struct World { .. } impl World { fn as_unsafe_world_cell(&self) -> UnsafeWorldCell<'_>; } struct UnsafeWorldCell<'w>(&'w World); impl<'w> UnsafeWorldCell { unsafe fn world(&self) -> &World; fn get_entity(&self) -> UnsafeWorldCellEntityRef<'w>; // returns 'w which is `'self` of the `World::as_unsafe_world_cell(&'w self)` unsafe fn get_resource<T>(&self) -> Option<&'w T>; unsafe fn get_resource_by_id(&self, ComponentId) -> Option<&'w T>; unsafe fn get_resource_mut<T>(&self) -> Option<Mut<'w, T>>; unsafe fn get_resource_mut_by_id(&self) -> Option<MutUntyped<'w>>; unsafe fn get_non_send_resource<T>(&self) -> Option<&'w T>; unsafe fn get_non_send_resource_mut<T>(&self) -> Option<Mut<'w, T>>>; // not included: remove, remove_resource, despawn, anything that might change archetypes } struct UnsafeWorldCellEntityRef<'w> { .. } impl UnsafeWorldCellEntityRef<'w> { unsafe fn get<T>(&self, Entity) -> Option<&'w T>; unsafe fn get_by_id(&self, Entity, ComponentId) -> Option<Ptr<'w>>; unsafe fn get_mut<T>(&self, Entity) -> Option<Mut<'w, T>>; unsafe fn get_mut_by_id(&self, Entity, ComponentId) -> Option<MutUntyped<'w>>; unsafe fn get_change_ticks<T>(&self, Entity) -> Option<Mut<'w, T>>; // fn id, archetype, contains, contains_id, containts_type_id } ``` <details> <summary>UnsafeWorldCell docs</summary> Variant of the [`World`] where resource and component accesses takes a `&World`, and the responsibility to avoid aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule. ### Rationale In rust, having a `&mut World` means that there are absolutely no other references to the safe world alive at the same time, without exceptions. Not even unsafe code can change this. But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the [`UnsafeCell`](std::cell::UnsafeCell) escape hatch, which allows you to get a `*mut T` from a `&UnsafeCell<T>` and around which safe abstractions can be built. Access to resources and components can be done uniquely using [`World::resource_mut`] and [`World::entity_mut`], and shared using [`World::resource`] and [`World::entity`]. These methods use lifetimes to check at compile time that no aliasing rules are being broken. This alone is not enough to implement bevy systems where multiple systems can access *disjoint* parts of the world concurrently. For this, bevy stores all values of resources and components (and [`ComponentTicks`](crate::component::ComponentTicks)) in [`UnsafeCell`](std::cell::UnsafeCell)s, and carefully validates disjoint access patterns using APIs like [`System::component_access`](crate::system::System::component_access). A system then can be executed using [`System::run_unsafe`](crate::system::System::run_unsafe) with a `&World` and use methods with interior mutability to access resource values. access resource values. ### Example Usage [`UnsafeWorldCell`] can be used as a building block for writing APIs that safely allow disjoint access into the world. In the following example, the world is split into a resource access half and a component access half, where each one can safely hand out mutable references. ```rust use bevy_ecs::world::World; use bevy_ecs::change_detection::Mut; use bevy_ecs::system::Resource; use bevy_ecs::world::unsafe_world_cell_world::UnsafeWorldCell; // INVARIANT: existance of this struct means that users of it are the only ones being able to access resources in the world struct OnlyResourceAccessWorld<'w>(UnsafeWorldCell<'w>); // INVARIANT: existance of this struct means that users of it are the only ones being able to access components in the world struct OnlyComponentAccessWorld<'w>(UnsafeWorldCell<'w>); impl<'w> OnlyResourceAccessWorld<'w> { fn get_resource_mut<T: Resource>(&mut self) -> Option<Mut<'w, T>> { // SAFETY: resource access is allowed through this UnsafeWorldCell unsafe { self.0.get_resource_mut::<T>() } } } // impl<'w> OnlyComponentAccessWorld<'w> { // ... // } // the two interior mutable worlds borrow from the `&mut World`, so it cannot be accessed while they are live fn split_world_access(world: &mut World) -> (OnlyResourceAccessWorld<'_>, OnlyComponentAccessWorld<'_>) { let resource_access = OnlyResourceAccessWorld(unsafe { world.as_unsafe_world_cell() }); let component_access = OnlyComponentAccessWorld(unsafe { world.as_unsafe_world_cell() }); (resource_access, component_access) } ``` </details>
# Objective Make the name less verbose without sacrificing clarity. --- ## Migration Guide *Note for maintainers:* This PR has no breaking changes relative to bevy 0.9. Instead of this PR having its own migration guide, we should just edit the changelog for #6404. The type `UnsafeWorldCellEntityRef` has been renamed to `UnsafeEntityCell`.
) # Objective Make the name less verbose without sacrificing clarity. --- ## Migration Guide *Note for maintainers:* This PR has no breaking changes relative to bevy 0.9. Instead of this PR having its own migration guide, we should just edit the changelog for bevyengine#6404. The type `UnsafeWorldCellEntityRef` has been renamed to `UnsafeEntityCell`.
) # Objective Make the name less verbose without sacrificing clarity. --- ## Migration Guide *Note for maintainers:* This PR has no breaking changes relative to bevy 0.9. Instead of this PR having its own migration guide, we should just edit the changelog for bevyengine#6404. The type `UnsafeWorldCellEntityRef` has been renamed to `UnsafeEntityCell`.
# Objective The type `&World` is currently in an awkward place, since it has two meanings: 1. Read-only access to the entire world. 2. Interior mutable access to the world; immutable and/or mutable access to certain portions of world data. This makes `&World` difficult to reason about, and surprising to see in function signatures if one does not know about the interior mutable property. The type `UnsafeWorldCell` was added in #6404, which is meant to alleviate this confusion by adding a dedicated type for interior mutable world access. However, much of the engine still treats `&World` as an interior mutable-ish type. One of those places is `SystemParam`. ## Solution Modify `SystemParam::get_param` to accept `UnsafeWorldCell` instead of `&World`. Simplify the safety invariants, since the `UnsafeWorldCell` type encapsulates the concept of constrained world access. --- ## Changelog `SystemParam::get_param` now accepts an `UnsafeWorldCell` instead of `&World`. This type provides a high-level API for unsafe interior mutable world access. ## Migration Guide For manual implementers of `SystemParam`: the function `get_item` now takes `UnsafeWorldCell` instead of `&World`. To access world data, use: * `.get_entity()`, which returns an `UnsafeEntityCell` which can be used to access component data. * `get_resource()` and its variants, to access resource data.
# Objective Follow-up to #6404 and #8292. Mutating the world through a shared reference is surprising, and it makes the meaning of `&World` unclear: sometimes it gives read-only access to the entire world, and sometimes it gives interior mutable access to only part of it. This is an up-to-date version of #6972. ## Solution Use `UnsafeWorldCell` for all interior mutability. Now, `&World` *always* gives you read-only access to the entire world. --- ## Changelog TODO - do we still care about changelogs? ## Migration Guide Mutating any world data using `&World` is now considered unsound -- the type `UnsafeWorldCell` must be used to achieve interior mutability. The following methods now accept `UnsafeWorldCell` instead of `&World`: - `QueryState`: `get_unchecked`, `iter_unchecked`, `iter_combinations_unchecked`, `for_each_unchecked`, `get_single_unchecked`, `get_single_unchecked_manual`. - `SystemState`: `get_unchecked_manual` ```rust let mut world = World::new(); let mut query = world.query::<&mut T>(); // Before: let t1 = query.get_unchecked(&world, entity_1); let t2 = query.get_unchecked(&world, entity_2); // After: let world_cell = world.as_unsafe_world_cell(); let t1 = query.get_unchecked(world_cell, entity_1); let t2 = query.get_unchecked(world_cell, entity_2); ``` The methods `QueryState::validate_world` and `SystemState::matches_world` now take a `WorldId` instead of `&World`: ```rust // Before: query_state.validate_world(&world); // After: query_state.validate_world(world.id()); ``` The methods `QueryState::update_archetypes` and `SystemState::update_archetypes` now take `UnsafeWorldCell` instead of `&World`: ```rust // Before: query_state.update_archetypes(&world); // After: query_state.update_archetypes(world.as_unsafe_world_cell_readonly()); ```
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (#6404, #8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (bevyengine#6404, bevyengine#8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (bevyengine#6404, bevyengine#8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (bevyengine#6404, bevyengine#8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (bevyengine#6404, bevyengine#8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
# Objective We've done a lot of work to remove the pattern of a `&World` with interior mutability (bevyengine#6404, bevyengine#8833). However, this pattern still persists within `bevy_ecs` via the `unsafe_world` method. ## Solution * Make `unsafe_world` private. Adjust any callsites to use `UnsafeWorldCell` for interior mutability. * Add `UnsafeWorldCell::removed_components`, since it is always safe to access the removed components collection through `UnsafeWorldCell`. ## Future Work Remove/hide `UnsafeWorldCell::world_metadata`, once we have provided safe ways of accessing all world metadata. --- ## Changelog + Added `UnsafeWorldCell::removed_components`, which provides read-only access to a world's collection of removed components.
alternative to #5922, implements #5956
builds on top of #6402
Objective
#5956 goes into more detail, but the TLDR is:
World::get_resource_unchecked_mut(&self)
, ...,EntityRef::get_mut_unchecked(&self)
etc.by_id
variants, so third-party crate authors cannot build their own safe disjoint-access abstractions with these_unchecked_mut
methods is not great, because in their presence safe code can accidentally violate subtle invariants. Having to go throughworld.as_unsafe_world_cell().unsafe_method()
forces you to stop and think about what you want to write in your// SAFETY
comment.The alternative is to keep exposing
_unchecked_mut
variants for every operation that we want third-party crates to build upon, but we'd prefer to avoid using these methods alltogether: #5922 (comment)Also, this is something that cannot be implemented outside of bevy, so having either this PR or #5922 as an escape hatch with lots of discouraging comments would be great.
Solution
UnsafeWorldCell
withunsafe fn get_resource(&self)
,unsafe fn get_resource_mut(&self)
fn World::as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>
(andas_unsafe_world_cell_readonly(&self)
)UnsafeWorldCellEntityRef
withunsafe fn get
,unsafe fn get_mut
and the other utilities onEntityRef
(no methods for spawning, despawning, insertion)UnsafeWorldCell
abstraction inReflectComponent
,ReflectResource
andReflectAsset
, so these APIs are easier to reason aboutWorld::get_resource_mut_unchecked
,EntityRef::get_mut_unchecked
and useunsafe { world.as_unsafe_world_cell().get_mut() }
andunsafe { world.as_unsafe_world_cell().get_entity(entity)?.get_mut() }
insteadThis PR does not make use of
UnsafeWorldCell
for anywhere else inbevy_ecs
such asSystemParam
orQuery
. That is a much larger change, and I am convinced that havingUnsafeWorldCell
is already useful for third-party crates.Implemented API:
UnsafeWorldCell docs
Variant of the [
World
] where resource and component accesses takes a&World
, and the responsibility to avoidaliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule.
Rationale
In rust, having a
&mut World
means that there are absolutely no other references to the safe world alive at the same time,without exceptions. Not even unsafe code can change this.
But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the
UnsafeCell
escape hatch, which allows you to get a
*mut T
from a&UnsafeCell<T>
and around which safe abstractions can be built.Access to resources and components can be done uniquely using [
World::resource_mut
] and [World::entity_mut
], and shared using [World::resource
] and [World::entity
].These methods use lifetimes to check at compile time that no aliasing rules are being broken.
This alone is not enough to implement bevy systems where multiple systems can access disjoint parts of the world concurrently. For this, bevy stores all values of
resources and components (and
ComponentTicks
) inUnsafeCell
s, and carefully validates disjoint access patterns usingAPIs like
System::component_access
.A system then can be executed using
System::run_unsafe
with a&World
and use methods with interior mutability to access resource values.access resource values.
Example Usage
[
UnsafeWorldCell
] can be used as a building block for writing APIs that safely allow disjoint access into the world.In the following example, the world is split into a resource access half and a component access half, where each one can
safely hand out mutable references.