fennel_engine/
registry.rs

1use ron::Value;
2use specs::{Entity, World};
3use std::collections::HashMap;
4
5/// All components must have a factory implementing this trait to be able created from a scene
6/// config
7pub trait ComponentFactory: Send + Sync {
8    fn insert(&self, world: &mut World, entity: Entity, value: &Value);
9}
10
11/// Registry of component name - component factory
12pub struct ComponentRegistry {
13    map: HashMap<String, Box<dyn ComponentFactory>>,
14}
15
16impl ComponentRegistry {
17    /// Creates a new instance of [`ComponentRegistry`]
18    pub fn new() -> Self {
19        Self {
20            map: HashMap::new(),
21        }
22    }
23
24    /// Registers a component factory
25    pub fn register(&mut self, name: &str, f: Box<dyn ComponentFactory>) {
26        self.map.insert(name.to_string(), f);
27    }
28
29    /// Fetches a component factory by name
30    pub fn get(&self, name: &str) -> Option<&dyn ComponentFactory> {
31        self.map.get(name).map(|v| &**v)
32    }
33}
34
35impl Default for ComponentRegistry {
36    fn default() -> Self {
37        Self::new()
38    }
39}