From 142b97381b3c6fc2e823884f55a05897cc27a9e1 Mon Sep 17 00:00:00 2001 From: HampusM Date: Fri, 26 Sep 2025 13:41:24 +0200 Subject: refactor(ecs): make ObserveIter return EventMatch struct --- ecs/examples/component_changed_event.rs | 8 ++++++-- ecs/examples/component_removed_event.rs | 4 ++-- ecs/src/system/observer.rs | 32 ++++++++++++++++++++++++++++---- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/ecs/examples/component_changed_event.rs b/ecs/examples/component_changed_event.rs index f707255..6dde384 100644 --- a/ecs/examples/component_changed_event.rs +++ b/ecs/examples/component_changed_event.rs @@ -32,8 +32,12 @@ fn print_changed_greetings(observe: Observe<'_, Pair>) { println!("\nChanged greetings:"); - for ent in &observe { - let Some(greeting) = ent.get::() else { + for evt_match in &observe { + let Some(changed_ent) = evt_match.get_entity() else { + continue; + }; + + let Some(greeting) = changed_ent.get::() else { unreachable!(); }; diff --git a/ecs/examples/component_removed_event.rs b/ecs/examples/component_removed_event.rs index ffa37f4..e8d1a47 100644 --- a/ecs/examples/component_removed_event.rs +++ b/ecs/examples/component_removed_event.rs @@ -20,8 +20,8 @@ fn eat_cheese(query: Query<(&Cheese,)>, mut actions: Actions) fn on_cheese_removed(observe: Observe>) { - for cheese_ent in &observe { - println!("Cheese entity {} was eaten", cheese_ent.uid()); + for evt_match in &observe { + println!("Cheese entity {} was eaten", evt_match.id()); } } diff --git a/ecs/src/system/observer.rs b/ecs/src/system/observer.rs index 1496d40..b7d84be 100644 --- a/ecs/src/system/observer.rs +++ b/ecs/src/system/observer.rs @@ -94,7 +94,7 @@ impl Observe<'_, ObservedT> impl<'a, ObservedT: Observed> IntoIterator for &'a Observe<'_, ObservedT> { type IntoIter = ObserveIter<'a>; - type Item = EntityHandle<'a>; + type Item = ::Item; fn into_iter(self) -> Self::IntoIter { @@ -110,13 +110,37 @@ pub struct ObserveIter<'observe> impl<'observe> Iterator for ObserveIter<'observe> { - type Item = EntityHandle<'observe>; + type Item = EventMatch<'observe>; fn next(&mut self) -> Option { - let target = *self.inner.next()?; + let match_id = *self.inner.next()?; - self.world.get_entity(target) + Some(EventMatch { world: self.world, id: match_id }) + } +} + +/// A event match. +#[derive(Debug)] +pub struct EventMatch<'world> +{ + world: &'world World, + id: Uid, +} + +impl<'world> EventMatch<'world> +{ + #[must_use] + pub fn id(&self) -> Uid + { + self.id + } + + /// Attempts to get the entity with the id of this match. + #[must_use] + pub fn get_entity(&self) -> Option> + { + self.world.get_entity(self.id) } } -- cgit v1.2.3-18-g5258