From 951060882e202361009ac3e6e00ac40e699bc6ea Mon Sep 17 00:00:00 2001 From: hodasemi Date: Fri, 11 Apr 2025 08:42:38 +0200 Subject: [PATCH] Use system also for events and updates --- ecs/src/world.rs | 61 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/ecs/src/world.rs b/ecs/src/world.rs index 5d322a7..436076a 100644 --- a/ecs/src/world.rs +++ b/ecs/src/world.rs @@ -24,8 +24,24 @@ pub struct WorldBuilder { )>, } +impl AddSystem<(), Func, &mut World> for WorldBuilder +where + Func: Fn(&mut World) -> Result + Send + Sync + 'static, +{ + fn add_system(&mut self, priority: u32, func: Func) { + self.systems.push(( + priority, + Box::new(move |world: &mut World, _commands: &mut Commands| func(world)), + )); + self.systems.sort_by_key(|(priority, _)| *priority); + } +} + impl WorldBuilder { - pub fn build(self) -> World { + pub fn build(mut self) -> World { + self.add_system(1000, World::process_events); + self.add_system(2000, World::process_updates); + World { updates: self.updates, events: self.events, @@ -412,33 +428,40 @@ impl World { let systems = std::mem::take(&mut self.systems); loop { - // we need to take all events because of borrowing rules - let mut events = self.events.take_events(); - events.fire_events(self)?; - - { - // actually safe: - // - updates can't be altered on a running world - // - entity changes are processed afterwards - let w = unsafe { remove_life_time_mut(self) }; - - self.updates.update(w)?; - } - - self.commit_entity_changes()?; - - let mut commands = Commands::new(self.now()); + let now = self.now(); for system in systems.iter() { + let mut commands = Commands::new(now); + if !system(self, &mut commands)? { return Ok(()); } - } - commands.apply_deferred(self)?; + commands.apply_deferred(self)?; + } // reset flag self.had_entity_changes = false; } } + + fn process_events(world: &mut World) -> Result { + // we need to take all events because of borrowing rules + let mut events = world.events.take_events(); + events.fire_events(world)?; + + Ok(true) + } + + fn process_updates(world: &mut World) -> Result { + // actually safe: + // - updates can't be altered on a running world + // - entity changes are processed afterwards + let w = unsafe { remove_life_time_mut(world) }; + + world.updates.update(w)?; + world.commit_entity_changes()?; + + Ok(true) + } }