Enable dynamic mutable access to component data (#1284)

* Enable dynamic mutable access to component data

* Add clippy allowance, more documentation
This commit is contained in:
Will Crichton 2021-01-22 18:15:08 -05:00 committed by GitHub
parent ebcab3638a
commit 7166a28baf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 6 deletions

View file

@ -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())

View file

@ -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),
}
@ -38,6 +39,20 @@ 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.
/// 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 a thread-local system to avoid sharing across threads.
/// * Don't call this method more than once in the same scope for a given component.
#[allow(clippy::mut_from_ref)]
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,
@ -87,6 +102,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
}
},
}
}
}