diff --git a/src/engine.rs b/src/engine.rs index 24bab18..4a960c0 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -42,7 +42,7 @@ macro_rules! impl_from_T_for_Error { impl_from_T_for_Error!(String, WindowBuildError, IntegerOrSdlError); -pub struct Entity(u64); +pub struct Entity(u64, Vec>); pub trait Component { fn inner_type_id(&self) -> TypeId; @@ -61,12 +61,50 @@ where canvas: &'context mut Canvas, texture_creator: *const TextureCreator, entities: &'context mut Vec, - components: &'context mut Vec<(u64, Box)>, systems: &'context mut Vec>, textures: &'context mut HashMap>, } impl<'context, 'game> Context<'context, 'game> { + pub fn entities_with_component(&self) -> Vec { + let entity_type_id = TypeId::of::(); + self.entities + .iter() + .filter_map(|Entity(id, components)| { + let contains_component = components + .iter() + .any(|entity| (*entity).inner_type_id() == entity_type_id); + if contains_component { + Some(*id) + } else { + None + } + }) + .collect() + } + + pub fn entity_component(&mut self, entity_id: u64) -> &mut T { + let entity_type_id = TypeId::of::(); + let Entity(_id, components) = self + .entities + .iter_mut() + .find(|Entity(id, _)| *id == entity_id) + .unwrap(); + + let component = components + .iter_mut() + .find_map(|entity| { + let is_id = (*entity).inner_type_id() == entity_type_id; + if is_id { + Some(entity.as_any().downcast_mut::().unwrap()) + } else { + None + } + }) + .unwrap(); + component + } + pub fn load_sprite

(&mut self, path: P) -> Result where P: AsRef, @@ -95,9 +133,7 @@ impl<'context, 'game> Context<'context, 'game> { pub fn spawn(&mut self, components: Vec>) { let id = *self.id_counter; *self.id_counter += 1; - self.entities.push(Entity(id)); - self.components - .extend(components.into_iter().map(|component| (id, component))); + self.entities.push(Entity(id, components)); } pub fn add_system(&mut self, system: Box) { @@ -187,7 +223,6 @@ impl<'game> Game<'game> { canvas: &mut self.canvas, texture_creator: &self.texture_creator, entities: &mut self.entities, - components: &mut self.components, systems: &mut self.systems, textures: &mut self.textures, }