blizzard_engine/ecs/
mod.rs

1//! # ECS architecture
2//!
3//! The engine follows an ECS architecture.
4
5use blizzard_id::Uid;
6use std::collections::HashMap;
7use std::vec::Vec;
8
9/// World definition
10/// # Example
11/// For a working example, please see official github repo workspace inside the example lib.
12pub trait World<I> {
13    fn new() -> Self;
14    fn run_systems(&mut self, input: I);
15}
16
17/// Entity manager
18#[derive(Debug, Clone)]
19pub struct EntityManager {
20    entities: HashMap<u32, bool>,
21}
22
23impl EntityManager {
24    /// Creates a new entity manager
25    pub fn new() -> Self {
26        Self {
27            entities: HashMap::new(),
28        }
29    }
30
31    /// Creates entity and returns it's id
32    pub fn create_entity(&mut self) -> u32 {
33        let mut id = Uid::new_numerical(4);
34        if self.entities.contains_key(&id) {
35            id = self.create_entity();
36        } else {
37            self.entities.insert(id, false);
38        }
39        id
40    }
41
42    /// Create multiple entities and return the id's inside a vector
43    pub fn create_n_entities(&mut self, n: i32) -> Vec<u32> {
44        let mut entities = vec![];
45        for _ in 0..n {
46            let entity = self.create_entity();
47            entities.push(entity);
48        }
49        entities
50    }
51
52    /// Get an entity if it exists
53    pub fn get_one(&self, entity: u32) -> Option<u32> {
54        match self.entities.get(&entity) {
55            Some(_) => Some(entity),
56            None => None,
57        }
58    }
59
60    /// Returns all the entities
61    pub fn get_all(&self) -> &HashMap<u32, bool> {
62        &self.entities
63    }
64
65    /// Mark entity for removal
66    pub fn mark_remove(&mut self, entity: u32) {
67        self.entities.insert(entity, true);
68    }
69
70    /// Remove entity
71    pub fn remove_entity(&mut self, entity: u32) {
72        self.entities.remove_entry(&entity);
73    }
74
75    /// Remove all entities that are marked as remove
76    pub fn remove_entities(&mut self) {
77        let entities: Vec<u32> = self
78            .entities
79            .iter()
80            .filter(|(_, remove)| **remove)
81            .map(|(id, _)| *id)
82            .collect();
83        entities.iter().for_each(|id| {
84            self.remove_entity(*id);
85        });
86    }
87}
88
89/// Component registry definition.
90/// Macro exists to generate a component on the fly.
91pub trait ComponentRegistry<T: Copy> {
92    fn new() -> Self;
93    fn add(&mut self, entity: u32, component: T);
94    fn add_many(&mut self, entities: &Vec<u32>, component: T);
95    fn remove(&mut self, entity: u32);
96    fn get(&self, entity: u32) -> Option<&T>;
97}