Skip to content
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

Add World::try_clone() #372

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
76 changes: 75 additions & 1 deletion src/archetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
use crate::alloc::alloc::{alloc, dealloc, Layout};
use crate::alloc::boxed::Box;
use crate::alloc::{vec, vec::Vec};
use core::any::{type_name, TypeId};
use crate::cloning::TypeUnknownToCloner;
use core::any::{type_name, Any, TypeId};
use core::fmt;
use core::hash::{BuildHasher, BuildHasherDefault, Hasher};
use core::ops::{Deref, DerefMut};
Expand Down Expand Up @@ -420,6 +421,78 @@ impl Archetype {
pub fn ids(&self) -> &[u32] {
&self.entities[0..self.len as usize]
}

pub(crate) fn try_clone(
&mut self,
cloner: &crate::cloning::Cloner,
) -> Result<Self, TypeUnknownToCloner> {
// Make sure all sized component types are known, so we don't leak memory if we fail halfway
if let Some(unsupported_type) = self
.types
.iter()
.filter(|info| info.layout.size() != 0)
.find(|info| cloner.typeid_to_clone_fn.get(&info.id).is_none())
{
return Err(TypeUnknownToCloner {
#[cfg(debug_assertions)]
type_name: unsupported_type.type_name,
type_id: unsupported_type.type_id(),
});
}

// Allocate the new data block with the same number of entities & same component types
let new_data: Box<[Data]> = self
.types
.iter()
.zip(&*self.data)
.map(|(info, old)| {
let storage: NonNull<u8> = if info.layout.size() == 0 {
// This is a zero-sized type, so no need to allocate or copy any data
NonNull::new(info.layout.align() as *mut u8).unwrap()
} else {
// Allocate memory for the cloned data
let layout = Layout::from_size_align(
info.layout.size() * self.capacity() as usize,
info.layout.align(),
)
.unwrap();
let new_storage = {
let mem = unsafe { alloc(layout) };
NonNull::new(mem)
.unwrap_or_else(|| alloc::alloc::handle_alloc_error(layout))
};

// Clone the data for all instances of the component
let clone_fn = cloner.typeid_to_clone_fn.get(&info.id).expect(
"all types should be supported by cloner (because we checked earlier)",
);
unsafe {
clone_fn.call(
old.storage.as_ptr(),
new_storage.as_ptr(),
self.len as usize,
)
};

new_storage
};
Ok(Data {
state: AtomicBorrow::new(), // &mut self guarantees no outstanding borrows
storage,
})
})
.collect::<Result<_, _>>()?;

// Clone the other fields of the archetype and return the new instance
Ok(Self {
types: self.types.clone(),
type_ids: self.type_ids.clone(),
index: self.index.clone(),
len: self.len,
entities: self.entities.clone(),
data: new_data,
})
}
}

impl Drop for Archetype {
Expand Down Expand Up @@ -493,6 +566,7 @@ impl Hasher for TypeIdHasher {
/// faster no-op hash.
pub(crate) type TypeIdMap<V> = HashMap<TypeId, V, BuildHasherDefault<TypeIdHasher>>;

#[derive(Clone)]
struct OrderedTypeIdMap<V>(Box<[(TypeId, V)]>);

impl<V> OrderedTypeIdMap<V> {
Expand Down
2 changes: 1 addition & 1 deletion src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub struct DynamicClone {
}

impl DynamicClone {
/// Create a new type ereased cloner for the type T
/// Create a new type erased cloner for the type T
pub fn new<T: Component + Clone>() -> Self {
Self {
func: |src, f| {
Expand Down
Loading