diff options
Diffstat (limited to 'ecs/src/component.rs')
-rw-r--r-- | ecs/src/component.rs | 446 |
1 files changed, 217 insertions, 229 deletions
diff --git a/ecs/src/component.rs b/ecs/src/component.rs index a9894b7..e4ecfce 100644 --- a/ecs/src/component.rs +++ b/ecs/src/component.rs @@ -1,79 +1,54 @@ use std::any::{type_name, Any}; use std::fmt::Debug; +use std::ops::{Deref, DerefMut}; use seq_macro::seq; -use crate::lock::{ReadGuard, WriteGuard}; -use crate::system::{ComponentRef, ComponentRefMut, Input as SystemInput}; -use crate::type_name::TypeName; +use crate::event::component::Changed; +use crate::event::Submitter as EventSubmitter; +use crate::lock::{ + Error as LockError, + MappedReadGuard, + MappedWriteGuard, + ReadGuard, + WriteGuard, +}; +use crate::pair::Pair; +use crate::system::Input as SystemInput; use crate::uid::Uid; -use crate::{EntityComponent, World}; +use crate::util::Array; +use crate::{EntityComponentRef, World}; pub mod local; pub(crate) mod storage; -pub trait Component: SystemInput + Any + TypeName +pub trait Component: SystemInput + Any { - /// The component type in question. Will usually be `Self` - type Component: Component - where - Self: Sized; - - type RefMut<'component> - where - Self: Sized; - - type Ref<'component> - where - Self: Sized; - /// Returns the ID of this component. fn id() -> Uid where Self: Sized; - /// The ID of the component `self`. Returns the same value as [`Component::id`]. - fn self_id(&self) -> Uid; - - #[doc(hidden)] - fn as_any_mut(&mut self) -> &mut dyn Any; - - #[doc(hidden)] - fn as_any(&self) -> &dyn Any; - - /// Whether the component `self` is optional. Returns the same value as - /// [`Component::is_optional`]. - fn self_is_optional(&self) -> IsOptional - { - IsOptional::No - } - - /// Returns whether this component is optional. - #[must_use] - fn is_optional() -> IsOptional - where - Self: Sized, - { - IsOptional::No - } + /// Returns the name of this component. + fn name(&self) -> &'static str; } impl dyn Component { pub fn downcast_mut<Real: 'static>(&mut self) -> Option<&mut Real> { - self.as_any_mut().downcast_mut() + (self as &mut dyn Any).downcast_mut() } pub fn downcast_ref<Real: 'static>(&self) -> Option<&Real> { - self.as_any().downcast_ref() + (self as &dyn Any).downcast_ref() } pub fn is<Other: 'static>(&self) -> bool { - self.as_any().is::<Other>() + (self as &dyn Any).is::<Other>() } } @@ -85,249 +60,262 @@ impl Debug for dyn Component } } -impl TypeName for Box<dyn Component> +/// A sequence of components. +pub trait Sequence { - fn type_name(&self) -> &'static str - { - self.as_ref().type_name() - } + /// The number of components in this component sequence. + const COUNT: usize; + + type PartsArray: Array<Parts>; + + fn into_parts_array(self) -> Self::PartsArray; } -impl<ComponentT> Component for Option<ComponentT> -where - ComponentT: Component, +#[derive(Debug)] +pub struct Handle<'a, DataT: 'static> { - type Component = ComponentT; - type Ref<'component> = Option<ComponentRef<'component, ComponentT>>; - type RefMut<'component> = Option<ComponentRefMut<'component, ComponentT>>; + inner: MappedReadGuard<'a, DataT>, +} - fn id() -> Uid +impl<'comp, DataT: 'static> Handle<'comp, DataT> +{ + /// Creates a new handle instance from a [`EntityComponentRef`]. + /// + /// # Errors + /// Will return `Err` if acquiring the component's lock fails. + pub fn from_entity_component_ref( + entity_component_ref: &EntityComponentRef<'comp>, + ) -> Result<Self, HandleError> { - ComponentT::id() + Self::new( + entity_component_ref + .component() + .read_nonblock() + .map_err(AcquireLockError)?, + ) } - fn self_id(&self) -> Uid + fn new(inner: ReadGuard<'comp, Box<dyn Any>>) -> Result<Self, HandleError> { - Self::id() + Ok(Self { + inner: ReadGuard::try_map(inner, |component| { + component.downcast_ref::<DataT>() + }) + .map_err(|_| HandleError::IncorrectType)?, + }) } +} + +impl<DataT: 'static> Deref for Handle<'_, DataT> +{ + type Target = DataT; - fn as_any_mut(&mut self) -> &mut dyn Any + fn deref(&self) -> &Self::Target { - self + &self.inner } +} + +#[derive(Debug)] +pub struct HandleMut<'a, DataT: 'static> +{ + entity_component_ref: EntityComponentRef<'a>, + inner: MappedWriteGuard<'a, DataT>, + event_submitter: EventSubmitter<'a>, +} - fn as_any(&self) -> &dyn Any +impl<'comp, DataT: 'static> HandleMut<'comp, DataT> +{ + /// Creates a new handle instance from a [`EntityComponentRef`]. + /// + /// # Errors + /// Will return `Err` if acquiring the component's lock fails. + pub fn from_entity_component_ref( + entity_component_ref: &EntityComponentRef<'comp>, + world: &'comp World, + ) -> Result<Self, HandleError> { - self + let inner = entity_component_ref + .component() + .write_nonblock() + .map_err(AcquireLockError)?; + + Ok(Self { + entity_component_ref: entity_component_ref.clone(), + inner: WriteGuard::try_map(inner, |component| { + component.downcast_mut::<DataT>() + }) + .map_err(|_| HandleError::IncorrectType)?, + event_submitter: world.event_submitter(), + }) } - fn self_is_optional(&self) -> IsOptional + pub fn set_changed(&self) { - Self::is_optional() + self.event_submitter.submit_event( + &Pair::new::<Changed>(self.entity_component_ref.id()), + self.entity_component_ref.entity_id(), + ); } +} + +impl<DataT: 'static> Deref for HandleMut<'_, DataT> +{ + type Target = DataT; - fn is_optional() -> IsOptional + fn deref(&self) -> &Self::Target { - IsOptional::Yes + &self.inner } } -impl<ComponentT> TypeName for Option<ComponentT> -where - ComponentT: Component, +impl<DataT: 'static> DerefMut for HandleMut<'_, DataT> { - fn type_name(&self) -> &'static str + fn deref_mut(&mut self) -> &mut Self::Target { - type_name::<Self>() + &mut self.inner } } -impl<ComponentT> SystemInput for Option<ComponentT> where ComponentT: Component {} - -/// A sequence of components. -pub trait Sequence +#[derive(Debug, thiserror::Error)] +pub enum HandleError { - type MutRefs<'component> - where - Self: 'component; + #[error(transparent)] + AcquireLockFailed(#[from] AcquireLockError), - type Refs<'component> - where - Self: 'component; - - fn into_vec(self) -> Vec<Box<dyn Component>>; - - fn metadata() -> Vec<Metadata>; - - fn from_components_mut<'component>( - components: impl Iterator<Item = &'component EntityComponent>, - world: &'component World, - lock_component: fn( - entity_component: &EntityComponent, - ) -> WriteGuard<'_, Box<dyn Component>>, - ) -> Self::MutRefs<'component>; - - fn from_components<'component>( - components: impl Iterator<Item = &'component EntityComponent>, - world: &'component World, - lock_component: fn( - entity_component: &EntityComponent, - ) -> ReadGuard<'_, Box<dyn Component>>, - ) -> Self::Refs<'component>; + #[error("Incorrect component type")] + IncorrectType, } -/// [`Component`] metadata. -#[derive(Debug, Clone)] -#[non_exhaustive] -pub struct Metadata -{ - pub id: Uid, - pub is_optional: IsOptional, +#[derive(Debug, thiserror::Error)] +#[error("Failed to acquire component lock")] +pub struct AcquireLockError(#[source] LockError); + +macro_rules! inner { + ($c: tt) => { + seq!(I in 0..=$c { + impl<#(IntoCompParts~I: IntoParts,)*> Sequence for (#(IntoCompParts~I,)*) + { + const COUNT: usize = $c + 1; + + type PartsArray = [Parts; $c + 1]; + + fn into_parts_array(self) -> Self::PartsArray + { + [#({ + self.I.into_parts() + },)*] + } + } + }); + }; } -impl Metadata +seq!(C in 0..=16 { + inner!(C); +}); + +impl Sequence for () { - pub fn get<ComponentT: Component + ?Sized>(component: &ComponentT) -> Self - { - Self { - id: component.self_id(), - is_optional: component.self_is_optional(), - } - } + type PartsArray = [Parts; 0]; + + const COUNT: usize = 0; - pub fn of<ComponentT: Component>() -> Self + fn into_parts_array(self) -> Self::PartsArray { - Self { - id: ComponentT::id(), - is_optional: ComponentT::is_optional(), - } + [] } } -/// Whether or not a `Component` is optional. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum IsOptional +pub trait IntoParts { - Yes, - No, + fn into_parts(self) -> Parts; } -impl From<bool> for IsOptional +impl<ComponentT> IntoParts for ComponentT +where + ComponentT: Component, { - fn from(is_optional: bool) -> Self + fn into_parts(self) -> Parts { - if is_optional { - return IsOptional::Yes; - } - - IsOptional::No + Parts::builder() + .name(type_name::<Self>()) + .build(Self::id(), self) } } -pub trait FromOptionalMut<'comp> +/// The parts of a component. +#[derive(Debug)] +#[non_exhaustive] +pub struct Parts { - fn from_optional_mut_component( - optional_component: Option<WriteGuard<'comp, Box<dyn Component>>>, - world: &'comp World, - ) -> Self; + id: Uid, + name: &'static str, + data: Box<dyn Any>, } -pub trait FromOptional<'comp> +impl Parts { - fn from_optional_component( - optional_component: Option<ReadGuard<'comp, Box<dyn Component>>>, - world: &'comp World, - ) -> Self; -} + #[must_use] + pub fn id(&self) -> Uid + { + self.id + } -macro_rules! inner { - ($c: tt) => { - seq!(I in 0..=$c { - impl<#(Comp~I: Component,)*> Sequence for (#(Comp~I,)*) - where - #(for<'comp> Comp~I::RefMut<'comp>: FromOptionalMut<'comp>,)* - #(for<'comp> Comp~I::Ref<'comp>: FromOptional<'comp>,)* - { - type MutRefs<'component> = (#(Comp~I::RefMut<'component>,)*) - where Self: 'component; + #[must_use] + pub fn name(&self) -> &'static str + { + self.name + } - type Refs<'component> = (#(Comp~I::Ref<'component>,)*) - where Self: 'component; + #[must_use] + pub fn builder() -> PartsBuilder + { + PartsBuilder::default() + } - fn into_vec(self) -> Vec<Box<dyn Component>> - { - Vec::from_iter([#(Box::new(self.I) as Box<dyn Component>,)*]) - } + pub(crate) fn into_data(self) -> Box<dyn Any> + { + self.data + } +} - fn metadata() -> Vec<Metadata> - { - vec![ - #( - Metadata { - id: Comp~I::id(), - is_optional: Comp~I::is_optional() - }, - )* - ] - } +#[derive(Debug)] +pub struct PartsBuilder +{ + name: &'static str, +} - fn from_components_mut<'component>( - components: impl Iterator<Item = &'component EntityComponent>, - world: &'component World, - lock_component: fn( - entity_component: &EntityComponent, - ) -> WriteGuard<'_, Box<dyn Component>>, - ) -> Self::MutRefs<'component> - { - #( - let mut comp_~I: Option<WriteGuard<Box<dyn Component>>> = None; - )* - - for comp in components { - #( - if comp.id == Comp~I::Component::id() { - comp_~I = Some(lock_component(comp)); - continue; - } - )* - } - - (#( - Comp~I::RefMut::from_optional_mut_component(comp_~I, world), - )*) - } +impl PartsBuilder +{ + #[must_use] + pub fn name(mut self, name: &'static str) -> Self + { + self.name = name; + self + } - fn from_components<'component>( - components: impl Iterator<Item = &'component EntityComponent>, - world: &'component World, - lock_component: fn( - entity_component: &EntityComponent, - ) -> ReadGuard<'_, Box<dyn Component>>, - ) -> Self::Refs<'component> - { + #[must_use] + pub fn build<Data: 'static>(self, id: Uid, data: Data) -> Parts + { + Parts { + id, + name: self.name, + data: Box::new(data), + } + } - #( - let mut comp_~I: Option<ReadGuard<Box<dyn Component>>> = None; - )* - - for comp in components { - #( - if comp.id == Comp~I::Component::id() { - comp_~I = Some(lock_component(comp)); - continue; - } - )* - } - - (#( - Comp~I::Ref::from_optional_component(comp_~I, world), - )*) - } - } - }); - }; + #[must_use] + pub fn build_with_any_data(self, id: Uid, data: Box<dyn Any>) -> Parts + { + Parts { id, name: self.name, data } + } } -seq!(C in 0..=64 { - inner!(C); -}); +impl Default for PartsBuilder +{ + fn default() -> Self + { + Self { name: "(unspecified)" } + } +} |