From a2eb0a235b738864a107eb9d859878c68f7d5bbf Mon Sep 17 00:00:00 2001 From: HampusM Date: Mon, 5 Aug 2024 23:22:49 +0200 Subject: fix(ecs): always sort components & component metadata --- ecs/src/component/storage.rs | 11 ++++++++-- ecs/src/lib.rs | 1 + ecs/src/util.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 ecs/src/util.rs (limited to 'ecs') diff --git a/ecs/src/component/storage.rs b/ecs/src/component/storage.rs index e909395..9c149ed 100644 --- a/ecs/src/component/storage.rs +++ b/ecs/src/component/storage.rs @@ -12,6 +12,7 @@ use crate::component::{ use crate::entity::Uid as EntityUid; use crate::lock::Lock; use crate::type_name::TypeName; +use crate::util::Sortable; use crate::EntityComponent; #[derive(Debug, Default)] @@ -26,9 +27,12 @@ impl Storage { pub fn find_entities( &self, - components_metadata: impl IntoIterator, + mut components_metadata: impl IntoIterator + + Sortable, ) -> ArchetypeRefIter<'_> { + components_metadata.sort_by_key_b(|component_metadata| component_metadata.id); + self.archetype_lookup .get(&ArchetypeId::from_components_metadata(components_metadata)) .map_or_else(ArchetypeRefIter::new_empty, |archetypes_indices| { @@ -114,9 +118,12 @@ impl Storage pub fn add_archetype_lookup_entry( &mut self, - components_metadata: impl IntoIterator, + mut components_metadata: impl IntoIterator + + Sortable, ) { + components_metadata.sort_by_key_b(|component_metadata| component_metadata.id); + self.pending_archetype_lookup_entries .push(components_metadata.into_iter().collect()); } diff --git a/ecs/src/lib.rs b/ecs/src/lib.rs index b920b48..cf2f198 100644 --- a/ecs/src/lib.rs +++ b/ecs/src/lib.rs @@ -35,6 +35,7 @@ pub mod tuple; pub mod type_name; mod archetype; +mod util; pub use ecs_macros::{Component, Sole}; diff --git a/ecs/src/util.rs b/ecs/src/util.rs new file mode 100644 index 0000000..f4f8632 --- /dev/null +++ b/ecs/src/util.rs @@ -0,0 +1,48 @@ +pub trait Sortable +{ + type Item; + + fn sort_by_key_b(&mut self, func: Func) + where + Func: FnMut(&Self::Item) -> Key, + Key: Ord; +} + +impl Sortable for [Item] +{ + type Item = Item; + + fn sort_by_key_b(&mut self, func: Func) + where + Func: FnMut(&Self::Item) -> Key, + Key: Ord, + { + self.sort_by_key(func) + } +} + +impl Sortable for [Item; LENGTH] +{ + type Item = Item; + + fn sort_by_key_b(&mut self, func: Func) + where + Func: FnMut(&Self::Item) -> Key, + Key: Ord, + { + self.sort_by_key(func) + } +} + +impl Sortable for Vec +{ + type Item = Item; + + fn sort_by_key_b(&mut self, func: Func) + where + Func: FnMut(&Self::Item) -> Key, + Key: Ord, + { + self.sort_by_key(func) + } +} -- cgit v1.2.3-18-g5258