Skip to content

Commit

Permalink
Enable dynamic mutable access to component data
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Jan 22, 2021
1 parent 7aefd72 commit 5383ca6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
7 changes: 1 addition & 6 deletions crates/bevy_ecs/src/core/archetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,7 @@ impl Archetype {

/// # Safety
/// `index` must be in-bounds
pub(crate) unsafe fn get_dynamic(
&self,
ty: TypeId,
size: usize,
index: usize,
) -> Option<NonNull<u8>> {
pub unsafe fn get_dynamic(&self, ty: TypeId, size: usize, index: usize) -> Option<NonNull<u8>> {
debug_assert!(index < self.len);
Some(NonNull::new_unchecked(
(*self.data.get())
Expand Down
19 changes: 19 additions & 0 deletions crates/bevy_reflect/src/impls/bevy_ecs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub struct ReflectComponent {
add_component: fn(&mut World, resources: &Resources, Entity, &dyn Reflect),
apply_component: fn(&mut World, Entity, &dyn Reflect),
reflect_component: unsafe fn(&Archetype, usize) -> &dyn Reflect,
reflect_component_mut: unsafe fn(&Archetype, usize) -> &mut dyn Reflect,
copy_component: fn(&World, &mut World, &Resources, Entity, Entity),
}

Expand Down Expand Up @@ -38,6 +39,17 @@ impl ReflectComponent {
(self.reflect_component)(archetype, entity_index)
}

/// # Safety
/// This does not do bound checks on entity_index. You must make sure entity_index is within bounds before calling.
/// To avoid having multiple mutable pointers to the same data, this method can only be called in a thread-local system.
pub unsafe fn reflect_component_mut<'a>(
&self,
archetype: &'a Archetype,
entity_index: usize,
) -> &'a mut dyn Reflect {
(self.reflect_component_mut)(archetype, entity_index)
}

pub fn copy_component(
&self,
source_world: &World,
Expand Down Expand Up @@ -87,6 +99,13 @@ impl<C: Component + Reflect + FromResources> FromType<C> for ReflectComponent {
ptr.as_ref().unwrap()
}
},
reflect_component_mut: |archetype, index| {
unsafe {
// the type has been looked up by the caller, so this is safe
let ptr = archetype.get::<C>().unwrap().as_ptr().add(index);
&mut *ptr
}
},
}
}
}
Expand Down

0 comments on commit 5383ca6

Please sign in to comment.