reflect: ReflectedComponent takes ownership over reflected component when inserting into entity

This commit is contained in:
SeanOMik 2024-02-23 16:39:51 -05:00
parent 0373f68cc3
commit f2d302c6d4
Signed by: SeanOMik
GPG Key ID: FEC9E2FC15235964
1 changed files with 16 additions and 12 deletions

View File

@ -1,4 +1,4 @@
use std::{any::TypeId, cell::{Ref, RefMut}};
use std::{any::{Any, TypeId}, cell::{Ref, RefMut}};
use lyra_ecs::{Component, ComponentInfo, World, Entity, DynamicBundle};
@ -13,21 +13,21 @@ pub struct ReflectedComponent {
//from_world: for<'a> fn (world: &'a mut World) -> Box<dyn Reflect>,
/// Inserts component into entity in the world
fn_insert: for<'a> fn (world: &'a mut World, entity: Entity, component: &dyn Reflect),
fn_insert: for<'a> fn (world: &'a mut World, entity: Entity, component: Box<dyn Reflect>),
/// Inserts component into a bundle
fn_bundle_insert: for<'a> fn (dynamic_bundle: &'a mut DynamicBundle, component: &dyn Reflect),
fn_bundle_insert: for<'a> fn (dynamic_bundle: &'a mut DynamicBundle, component: Box<dyn Reflect>),
fn_reflect: for<'a> fn (world: &'a World, entity: Entity) -> Option<Ref<'a, dyn Reflect>>,
fn_reflect_mut: for<'a> fn (world: &'a mut World, entity: Entity) -> Option<RefMut<'a, dyn Reflect>>,
}
impl ReflectedComponent {
/// Insert the reflected component into an entity.
pub fn insert(&self, world: &mut World, entity: Entity, component: &dyn Reflect) {
pub fn insert(&self, world: &mut World, entity: Entity, component: Box<dyn Reflect>) {
(self.fn_insert)(world, entity, component);
}
/// Insert this component into a DynamicBundle
pub fn bundle_insert(&self, dynamic_bundle: &mut DynamicBundle, component: &dyn Reflect) {
pub fn bundle_insert(&self, dynamic_bundle: &mut DynamicBundle, component: Box<dyn Reflect>) {
(self.fn_bundle_insert)(dynamic_bundle, component)
}
@ -42,19 +42,23 @@ impl ReflectedComponent {
}
}
impl<C: Component + Reflect + Default> FromType<C> for ReflectedComponent {
impl<C: Component + Reflect> FromType<C> for ReflectedComponent {
fn from_type() -> Self {
ReflectedComponent {
type_id: TypeId::of::<C>(),
info: ComponentInfo::new::<C>(),
fn_insert: |world: &mut World, entity: Entity, component: &dyn Reflect| {
let mut c = C::default();
c.apply(component);
fn_insert: |world: &mut World, entity: Entity, component: Box<dyn Reflect>| {
let c = component as Box<dyn Any>;
let c = c.downcast::<C>()
.expect("Provided a non-matching type to ReflectedComponent insert method!");
let c = *c;
world.insert(entity, (c,));
},
fn_bundle_insert: |bundle: &mut DynamicBundle, component: &dyn Reflect| {
let mut c = C::default();
c.apply(component);
fn_bundle_insert: |bundle: &mut DynamicBundle, component: Box<dyn Reflect>| {
let c = component as Box<dyn Any>;
let c = c.downcast::<C>()
.expect("Provided a non-matching type to ReflectedComponent insert method!");
let c = *c;
bundle.push(c);
},
fn_reflect: |world: &World, entity: Entity| {