summaryrefslogtreecommitdiff
path: root/ecs/src/lib.rs
blob: df46a5a6684379e7c113c583900d63d743e294c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#![deny(clippy::all, clippy::pedantic)]

use std::any::TypeId;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
use std::slice::IterMut as SliceIterMut;

use crate::component::{Component, Sequence as ComponentSequence};
use crate::system::{System, TypeErased as TypeErasedSystem};

pub mod component;
pub mod system;

#[derive(Debug)]
struct Entity
{
    components: Vec<Box<dyn Component>>,
}

#[derive(Debug)]
pub struct World<Event>
{
    systems: Vec<TypeErasedSystem>,
    events: HashMap<Event, Vec<usize>>,
    component_storage: ComponentStorage,
}

impl<Event> World<Event>
{
    #[must_use]
    pub fn new() -> Self
    {
        Self {
            systems: Vec::new(),
            component_storage: ComponentStorage { entities: Vec::new() },
            events: HashMap::new(),
        }
    }

    pub fn create_entity<Comps>(&mut self, components: Comps)
    where
        Comps: ComponentSequence,
    {
        self.component_storage
            .entities
            .push(Entity { components: components.into_vec() });
    }

    pub fn register_system<TSystem, SystemImpl>(&mut self, event: Event, system: TSystem)
    where
        Event: Hash + PartialEq + Eq,
        TSystem: System<SystemImpl>,
    {
        self.systems.push(system.into_type_erased());

        self.events
            .entry(event)
            .or_default()
            .push(self.systems.len() - 1);
    }

    /// Emits a event, running all systems listening to the event for each compatible
    /// entity.
    ///
    /// # Panics
    /// Will panic if a system has dissapeared.
    pub fn emit(&mut self, event: &Event)
    where
        Event: Hash + PartialEq + Eq,
    {
        let Some(system_indices) = self.events.get(event).cloned() else {
            return;
        };

        for system_index in system_indices {
            let system = self.systems.get_mut(system_index).unwrap();

            system.run(&mut self.component_storage);
        }
    }

    pub fn query<Comps>(&mut self) -> Query<Comps>
    where
        Comps: ComponentSequence,
    {
        Query::new(&mut self.component_storage)
    }
}

impl<Event> Default for World<Event>
{
    fn default() -> Self
    {
        Self::new()
    }
}

#[derive(Debug)]
pub struct Query<'world, Comps>
{
    component_storage: &'world mut ComponentStorage,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps> Query<'world, Comps>
{
    fn new(component_storage: &'world mut ComponentStorage) -> Self
    {
        Self {
            component_storage,
            comps_pd: PhantomData,
        }
    }
}

impl<'world, Comps> Query<'world, Comps>
where
    Comps: ComponentSequence,
{
    pub fn iter_mut(&mut self) -> QueryComponentIter<Comps>
    {
        QueryComponentIter {
            entity_iter: self.component_storage.entities.iter_mut(),
            component_type_ids: Comps::type_ids(),
            comps_pd: PhantomData,
        }
    }
}

impl<'world, Comps> IntoIterator for &'world mut Query<'world, Comps>
where
    Comps: ComponentSequence + 'world,
{
    type IntoIter = QueryComponentIter<'world, Comps>;
    type Item = Comps::MutRefs<'world>;

    fn into_iter(self) -> Self::IntoIter
    {
        self.iter_mut()
    }
}

pub struct QueryComponentIter<'world, Comps>
{
    entity_iter: SliceIterMut<'world, Entity>,
    component_type_ids: Vec<TypeId>,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps> Iterator for QueryComponentIter<'world, Comps>
where
    Comps: ComponentSequence + 'world,
{
    type Item = Comps::MutRefs<'world>;

    fn next(&mut self) -> Option<Self::Item>
    {
        // TODO: This is a really dumb and slow way to do this. Refactor the world
        // to store components in archetypes
        let entity =
            self.entity_iter.find(|entity| {
                let entity_components: HashSet<_> = entity
                    .components
                    .iter()
                    .map(|component| component.as_ref().type_id())
                    .collect();

                if self.component_type_ids.iter().all(|component_type_id| {
                    entity_components.contains(component_type_id)
                }) {
                    return true;
                }

                false
            })?;

        Some(Comps::from_components(&mut entity.components))
    }
}

#[derive(Debug)]
pub struct ComponentStorage
{
    entities: Vec<Entity>,
}