diff options
| author | HampusM <hampus@hampusmat.com> | 2025-06-07 20:16:40 +0200 | 
|---|---|---|
| committer | HampusM <hampus@hampusmat.com> | 2025-06-07 20:16:40 +0200 | 
| commit | caf56d34449b471169b7c71eddabad230449dfe3 (patch) | |
| tree | a1ce343c8a091ff7269037efab8c7a23dce84d89 | |
| parent | 15c6cde9b01d8d62a21d61ca620aff4ef61b12dd (diff) | |
refactor(ecs): remove component::HandleFromEntityComponentRef
| -rw-r--r-- | ecs/src/component.rs | 110 | ||||
| -rw-r--r-- | ecs/src/entity.rs | 25 | ||||
| -rw-r--r-- | ecs/src/query.rs | 49 | ||||
| -rw-r--r-- | ecs/src/query/term.rs | 23 | 
4 files changed, 92 insertions, 115 deletions
diff --git a/ecs/src/component.rs b/ecs/src/component.rs index 4bf38e7..6fb1230 100644 --- a/ecs/src/component.rs +++ b/ecs/src/component.rs @@ -1,5 +1,4 @@  use std::any::{type_name, Any}; -use std::error::Error;  use std::fmt::Debug;  use std::ops::{Deref, DerefMut}; @@ -15,7 +14,7 @@ use crate::lock::{  use crate::system::Input as SystemInput;  use crate::uid::Uid;  use crate::util::Array; -use crate::{EntityComponentRef, World}; +use crate::EntityComponentRef;  pub mod local; @@ -69,29 +68,31 @@ pub trait Sequence      fn into_parts_array(self) -> Self::PartsArray;  } -pub trait HandleFromEntityComponentRef<'comp>: Sized -{ -    type Error: Error; - -    /// Creates a new handle instance from a [`EntityComponentRef`]. -    /// -    /// # Errors -    /// See the implementation's [`Self::Error`] type. -    fn from_entity_component_ref( -        entity_component_ref: Option<EntityComponentRef<'comp>>, -        world: &'comp World, -    ) -> Result<Self, Self::Error>; -} -  #[derive(Debug)]  pub struct Handle<'a, ComponentData: 'static>  {      inner: MappedReadGuard<'a, ComponentData>,  } -impl<'a, ComponentData: 'static> Handle<'a, ComponentData> +impl<'comp, ComponentData: 'static> Handle<'comp, ComponentData>  { -    pub(crate) fn new(inner: ReadGuard<'a, Box<dyn Any>>) -> Self +    /// 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> +    { +        Ok(Self::new( +            entity_component_ref +                .component() +                .read_nonblock() +                .map_err(AcquireLockError)?, +        )) +    } + +    pub(crate) fn new(inner: ReadGuard<'comp, Box<dyn Any>>) -> Self      {          Self {              inner: inner.map(|component| { @@ -108,28 +109,6 @@ impl<'a, ComponentData: 'static> Handle<'a, ComponentData>      }  } -impl<'comp, ComponentData: 'static> HandleFromEntityComponentRef<'comp> -    for Handle<'comp, ComponentData> -{ -    type Error = HandleError; - -    fn from_entity_component_ref( -        entity_component_ref: Option<EntityComponentRef<'comp>>, -        _world: &'comp World, -    ) -> Result<Self, Self::Error> -    { -        let entity_comp = -            entity_component_ref.ok_or(HandleError::ComponentDoesNotExist)?; - -        Ok(Self::new( -            entity_comp -                .component() -                .read_nonblock() -                .map_err(AcquireComponentLockFailed)?, -        )) -    } -} -  impl<ComponentData: 'static> Deref for Handle<'_, ComponentData>  {      type Target = ComponentData; @@ -146,9 +125,25 @@ pub struct HandleMut<'a, ComponentData: 'static>      inner: MappedWriteGuard<'a, ComponentData>,  } -impl<'a, ComponentData: 'static> HandleMut<'a, ComponentData> +impl<'comp, ComponentData: 'static> HandleMut<'comp, ComponentData>  { -    pub(crate) fn new(inner: WriteGuard<'a, Box<dyn Any>>) -> Self +    /// 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> +    { +        Ok(Self::new( +            entity_component_ref +                .component() +                .write_nonblock() +                .map_err(AcquireLockError)?, +        )) +    } + +    pub(crate) fn new(inner: WriteGuard<'comp, Box<dyn Any>>) -> Self      {          Self {              inner: inner.map(|component| { @@ -165,28 +160,6 @@ impl<'a, ComponentData: 'static> HandleMut<'a, ComponentData>      }  } -impl<'comp, ComponentData: 'static> HandleFromEntityComponentRef<'comp> -    for HandleMut<'comp, ComponentData> -{ -    type Error = HandleError; - -    fn from_entity_component_ref( -        entity_component_ref: Option<EntityComponentRef<'comp>>, -        _world: &'comp World, -    ) -> Result<Self, Self::Error> -    { -        let entity_comp = -            entity_component_ref.ok_or(HandleError::ComponentDoesNotExist)?; - -        Ok(Self::new( -            entity_comp -                .component() -                .write_nonblock() -                .map_err(AcquireComponentLockFailed)?, -        )) -    } -} -  impl<ComponentData: 'static> Deref for HandleMut<'_, ComponentData>  {      type Target = ComponentData; @@ -209,15 +182,12 @@ impl<ComponentData: 'static> DerefMut for HandleMut<'_, ComponentData>  pub enum HandleError  {      #[error(transparent)] -    AcquireComponentLockFailed(#[from] AcquireComponentLockFailed), - -    #[error("Component does not exist")] -    ComponentDoesNotExist, +    AcquireLockFailed(#[from] AcquireLockError),  }  #[derive(Debug, thiserror::Error)] -#[error(transparent)] -pub struct AcquireComponentLockFailed(LockError); +#[error("Failed to acquire component lock")] +pub struct AcquireLockError(#[source] LockError);  macro_rules! inner {      ($c: tt) => { diff --git a/ecs/src/entity.rs b/ecs/src/entity.rs index 562f7ea..196bd01 100644 --- a/ecs/src/entity.rs +++ b/ecs/src/entity.rs @@ -10,7 +10,6 @@ use crate::component::storage::archetype::{  use crate::component::{      Component,      Handle as ComponentHandle, -    HandleFromEntityComponentRef,      HandleMut as ComponentHandleMut,  };  use crate::uid::{Kind as UidKind, Uid}; @@ -20,7 +19,7 @@ use crate::{EntityComponentRef, World};  #[derive(Debug)]  pub struct Handle<'a>  { -    world: &'a World, +    _world: &'a World,      archetype: &'a Archetype,      entity: &'a ArchetypeEntity,  } @@ -50,13 +49,12 @@ impl<'a> Handle<'a>          let component = self.get_matching_components(ComponentT::id()).next()?;          Some( -            ComponentHandle::from_entity_component_ref(Some(component), self.world) -                .unwrap_or_else(|err| { -                    panic!( -                        "Taking component {} lock failed: {err}", -                        type_name::<ComponentT>() -                    ); -                }), +            ComponentHandle::from_entity_component_ref(component).unwrap_or_else(|err| { +                panic!( +                    "Taking component {} lock failed: {err}", +                    type_name::<ComponentT>() +                ); +            }),          )      } @@ -77,13 +75,14 @@ impl<'a> Handle<'a>          let component = self.get_matching_components(ComponentT::id()).next()?;          Some( -            ComponentHandleMut::from_entity_component_ref(Some(component), self.world) -                .unwrap_or_else(|err| { +            ComponentHandleMut::from_entity_component_ref(component).unwrap_or_else( +                |err| {                      panic!(                          "Taking component {} lock failed: {err}",                          type_name::<ComponentT>()                      ); -                }), +                }, +            ),          )      } @@ -104,7 +103,7 @@ impl<'a> Handle<'a>          entity: &'a ArchetypeEntity,      ) -> Self      { -        Self { world, archetype, entity } +        Self { _world: world, archetype, entity }      }  } diff --git a/ecs/src/query.rs b/ecs/src/query.rs index 7e10c5b..ccb7add 100644 --- a/ecs/src/query.rs +++ b/ecs/src/query.rs @@ -6,7 +6,6 @@ use seq_macro::seq;  use crate::component::{      Component,      Handle as ComponentHandle, -    HandleFromEntityComponentRef,      HandleMut as ComponentHandleMut,  };  use crate::entity::Handle as EntityHandle; @@ -342,18 +341,26 @@ impl<ComponentT: Component> TermWithField for &ComponentT      fn get_field<'world>(          entity_handle: &EntityHandle<'world>, -        world: &'world World, +        _world: &'world World,      ) -> Self::Field<'world>      {          assert_eq!(ComponentT::id().kind(), UidKind::Component); -        Self::Field::from_entity_component_ref( -            entity_handle -                .get_matching_components(ComponentT::id()) -                .next(), -            world, -        ) -        .unwrap_or_else(|err| { +        let Some(component) = entity_handle +            .get_matching_components(ComponentT::id()) +            .next() +        else { +            panic!( +                concat!( +                    "Component {} was not found in entity {}. There ", +                    "is most likely a bug in the entity querying" +                ), +                type_name::<ComponentT>(), +                entity_handle.uid() +            ); +        }; + +        Self::Field::from_entity_component_ref(component).unwrap_or_else(|err| {              panic!(                  "Creating handle to component {} failed: {err}",                  type_name::<ComponentT>() @@ -375,18 +382,26 @@ impl<ComponentT: Component> TermWithField for &mut ComponentT      fn get_field<'world>(          entity_handle: &EntityHandle<'world>, -        world: &'world World, +        _world: &'world World,      ) -> Self::Field<'world>      {          assert_eq!(ComponentT::id().kind(), UidKind::Component); -        Self::Field::from_entity_component_ref( -            entity_handle -                .get_matching_components(ComponentT::id()) -                .next(), -            world, -        ) -        .unwrap_or_else(|err| { +        let Some(component) = entity_handle +            .get_matching_components(ComponentT::id()) +            .next() +        else { +            panic!( +                concat!( +                    "Component {} was not found in entity {}. There ", +                    "is most likely a bug in the entity querying" +                ), +                type_name::<ComponentT>(), +                entity_handle.uid() +            ); +        }; + +        Self::Field::from_entity_component_ref(component).unwrap_or_else(|err| {              panic!(                  "Creating handle to component {} failed: {err}",                  type_name::<ComponentT>() diff --git a/ecs/src/query/term.rs b/ecs/src/query/term.rs index 2e1ecca..9c772da 100644 --- a/ecs/src/query/term.rs +++ b/ecs/src/query/term.rs @@ -4,7 +4,6 @@ use std::marker::PhantomData;  use crate::component::{      Component,      Handle as ComponentHandle, -    HandleFromEntityComponentRef,      HandleMut as ComponentHandleMut,  };  use crate::query::{ @@ -65,17 +64,14 @@ impl<ComponentT: Component> TermWithField for Option<&ComponentT>      fn get_field<'world>(          entity_handle: &crate::entity::Handle<'world>, -        world: &'world crate::World, +        _world: &'world crate::World,      ) -> Self::Field<'world>      {          Some(              ComponentHandle::<'world, ComponentT>::from_entity_component_ref( -                Some( -                    entity_handle -                        .get_matching_components(ComponentT::id()) -                        .next()?, -                ), -                world, +                entity_handle +                    .get_matching_components(ComponentT::id()) +                    .next()?,              )              .unwrap_or_else(|err| {                  panic!( @@ -99,17 +95,14 @@ impl<ComponentT: Component> TermWithField for Option<&mut ComponentT>      fn get_field<'world>(          entity_handle: &crate::entity::Handle<'world>, -        world: &'world crate::World, +        _world: &'world crate::World,      ) -> Self::Field<'world>      {          Some(              ComponentHandleMut::<'world, ComponentT>::from_entity_component_ref( -                Some( -                    entity_handle -                        .get_matching_components(ComponentT::id()) -                        .next()?, -                ), -                world, +                entity_handle +                    .get_matching_components(ComponentT::id()) +                    .next()?,              )              .unwrap_or_else(|err| {                  panic!(  | 
