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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278


mod sorted_archetype_key;

#[cfg(test)]
mod tests;
pub(crate) mod iterators;

use alloc::vec::*;
use core::ops::{Index, IndexMut};
use sorted_archetype_key::*;

use crate::archetype::Archetype;
use crate::descriptors::archetype_descriptor::ArchetypeDescriptor;
use crate::archetype_registry::iterators::*;
use crate::descriptors::component_descriptor::ComponentDescriptor;
use crate::descriptors::component_group::ComponentGroup;
use crate::constants::*;
use crate::Entity;

const DEFAULT_VECTOR_CAPACITY: usize = 64;

#[derive(Debug)]
/// Stores all archetypes.
pub struct ArchetypeRegistry {
    // TODO: Currently not a great approach, should become a graph
    sorted_mappings: [Vec<SortedArchetypeKey>; MAX_COMPONENTS_PER_ENTITY],
    archetypes: Vec<Archetype>,
}

impl Default for ArchetypeRegistry {
    fn default() -> Self {
        Self {
            sorted_mappings: [
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
                Vec::with_capacity(DEFAULT_VECTOR_CAPACITY),
            ],
            archetypes: Vec::with_capacity(128),
        }
    }
}

impl ArchetypeRegistry {
    #[allow(dead_code)]
    pub fn find_archetype(
        &self,
        archetype_descriptor: &ArchetypeDescriptor,
    ) -> Option<&Archetype> {
        let len = archetype_descriptor.len() as usize;
        if len > MAX_COMPONENTS_PER_ENTITY || !archetype_descriptor.is_valid() {
            return None;
        }
        return match self.sorted_mappings[len - 1]
            .binary_search_by_key(&archetype_descriptor.archetype_id(), |e| e.id)
        {
            Ok(found_index) => Some(
                &self.archetypes
                    [self.sorted_mappings[len - 1][found_index].archetype_index as usize],
            ),
            Err(_) => None,
        };
    }

    #[allow(dead_code)]
    pub fn find_archetype_mut(
        &mut self,
        archetype_descriptor: &ArchetypeDescriptor,
    ) -> Option<&mut Archetype> {
        let len = archetype_descriptor.len() as usize;
        if len > MAX_COMPONENTS_PER_ENTITY || !archetype_descriptor.is_valid() {
            return None;
        }
        return match self.sorted_mappings[len - 1]
            .binary_search_by_key(&archetype_descriptor.archetype_id(), |e| e.id)
        {
            Ok(found_index) => Some(
                &mut self.archetypes
                    [self.sorted_mappings[len - 1][found_index].archetype_index as usize],
            ),
            Err(_) => None,
        };
    }

    /// Returns mutable reference to source archetype and finds or creates a new archetype by adding
    /// the given component type as defined by component descriptor.
    pub fn find_or_create_archetype_adding_component(
        &mut self,
        source_archetype_index: u16,
        component_descriptor: &ComponentDescriptor,
    ) -> Option<(&mut Archetype, u16, &mut Archetype)> {
        // Range check
        if source_archetype_index as usize > self.archetypes.len() {
            return None;
        }

        unsafe {
            // Safety: this pointer always is into self, and since we are adding a component to
            // the archetype descriptor, this means that the destination_archetype is always a different
            // one than the source archetype. As such, we can safely do this rather than needing to go
            // through split_at_mut() and remapping indices.
            let source_archetype: *mut Archetype = self
                .archetypes
                .get_unchecked_mut(source_archetype_index as usize);

            let new_archetype_descriptor = (*source_archetype)
                .descriptor()
                .add_component(component_descriptor)?;
            let (destination_archetype_index, destination_archetype) =
                self.find_or_create_archetype(&new_archetype_descriptor)?;

            Some((
                &mut *source_archetype,
                destination_archetype_index,
                destination_archetype,
            ))
        }
    }

    /// Returns mutable reference to source archetype and finds or creates a new archetype by removing
    /// the given component type as defined by component descriptor.
    pub fn find_or_create_archetype_removing_component(
        &mut self,
        source_archetype_index: u16,
        component_descriptor: &ComponentDescriptor,
    ) -> Option<(&mut Archetype, u16, &mut Archetype)> {
        // Range check
        if source_archetype_index as usize > self.archetypes.len() {
            return None;
        }

        unsafe {
            // Safety: this pointer always is into self, and since we are removing a component from
            // the archetype descriptor, this means that the destination_archetype is always a different
            // one than the source archetype. As such, we can safely do this rather than needing to go
            // through split_at_mut() and remapping indices.
            let source_archetype: *mut Archetype = self
                .archetypes
                .get_unchecked_mut(source_archetype_index as usize);

            let new_archetype_descriptor = (*source_archetype)
                .descriptor()
                .remove_component(component_descriptor.component_type_id())?;
            let (destination_archetype_index, destination_archetype) =
                self.find_or_create_archetype(&new_archetype_descriptor)?;

            Some((
                &mut *source_archetype,
                destination_archetype_index,
                destination_archetype,
            ))
        }
    }

    pub fn find_or_create_archetype(
        &mut self,
        archetype_descriptor: &ArchetypeDescriptor,
    ) -> Option<(u16, &mut Archetype)> {
        let len = archetype_descriptor.len() as usize;
        if len > MAX_COMPONENTS_PER_ENTITY || !archetype_descriptor.is_valid() {
            return None;
        }
        return match self.sorted_mappings[len - 1]
            .binary_search_by_key(&archetype_descriptor.archetype_id(), |e| e.id)
        {
            Ok(found_index) => Some((
                self.sorted_mappings[len - 1][found_index].archetype_index,
                &mut self.archetypes
                    [self.sorted_mappings[len - 1][found_index].archetype_index as usize],
            )),
            Err(insertion_index) => {
                if self.archetypes.len() >= MAX_ARCHETYPE_COUNT {
                    return None;
                }

                let archetype = Archetype::with_capacity(
                    archetype_descriptor,
                    DEFAULT_ARCHETYPE_ALLOCATION_SIZE as u32,
                );
                let key = SortedArchetypeKey {
                    id: archetype_descriptor.archetype_id(),
                    archetype_index: self.archetypes.len() as u16,
                };
                self.archetypes.push(archetype);
                self.sorted_mappings[len - 1].insert(insertion_index, key);
                Some((
                    self.archetypes.len() as u16 - 1,
                    self.archetypes.last_mut().unwrap(),
                ))
            }
        };
    }

    pub unsafe fn get_unchecked(&self, index: u16) -> &Archetype {
        self.archetypes.get_unchecked(index as usize)
    }

    pub unsafe fn get_unchecked_mut(&mut self, index: u16) -> &mut Archetype {
        self.archetypes.get_unchecked_mut(index as usize)
    }

    pub fn iter_components_matching<'a, G: ComponentGroup<'a>>(
        &'a self,
    ) -> impl Iterator<Item = <G as ComponentGroup<'a>>::SliceRefTuple> {
        MatchingIter::<'a, G>::new(&self.sorted_mappings, &self.archetypes)
    }

    pub fn iter_components_matching_mut<'a, G: ComponentGroup<'a>>(
        &'a mut self,
    ) -> impl Iterator<Item = <G as ComponentGroup<'a>>::SliceMutRefTuple> {
        MatchingIterMut::<'a, G>::new(&self.sorted_mappings, &mut self.archetypes)
    }

    pub fn iter_entity_components_matching<'a, G: ComponentGroup<'a>>(
        &'a self,
    ) -> impl Iterator<Item = (&'a [Entity], <G as ComponentGroup<'a>>::SliceRefTuple)> {
        EntityMatchingIter::<'a, G>::new(&self.sorted_mappings, &self.archetypes)
    }

    pub fn iter_entity_components_matching_mut<'a, G: ComponentGroup<'a>>(
        &'a mut self,
    ) -> impl Iterator<Item = (&'a [Entity], <G as ComponentGroup<'a>>::SliceMutRefTuple)> {
        EntityMatchingIterMut::<'a, G>::new(&self.sorted_mappings, &mut self.archetypes)
    }

    pub fn iter_filtered_components_matching<'a, G: ComponentGroup<'a>, F: Fn(&ArchetypeDescriptor) -> bool>(
        &'a self,
        filter_closure: F,
    ) -> impl Iterator<Item = <G as ComponentGroup<'a>>::SliceRefTuple> {
        FilterMatchingIter::<'a, G, F>::new(&self.sorted_mappings, &self.archetypes, filter_closure)
    }

    pub fn iter_filtered_components_matching_mut<'a, G: ComponentGroup<'a>, F: Fn(&ArchetypeDescriptor) -> bool>(
        &'a mut self,
        filter_closure: F,
    ) -> impl Iterator<Item = <G as ComponentGroup<'a>>::SliceMutRefTuple> {
        FilterMatchingIterMut::<'a, G, F>::new(&self.sorted_mappings, &mut self.archetypes, filter_closure)
    }

    pub fn iter_filtered_entity_components_matching<'a, G: ComponentGroup<'a>, F: Fn(&ArchetypeDescriptor) -> bool>(
        &'a self,
        filter_closure: F,
    ) -> impl Iterator<Item = (&'a [Entity], <G as ComponentGroup<'a>>::SliceRefTuple)> {
        FilterEntityMatchingIter::<'a, G, F>::new(&self.sorted_mappings, &self.archetypes, filter_closure)
    }

    pub fn iter_filtered_entity_components_matching_mut<'a, G: ComponentGroup<'a>, F: Fn(&ArchetypeDescriptor) -> bool>(
        &'a mut self,
        filter_closure: F,
    ) -> impl Iterator<Item = (&'a [Entity], <G as ComponentGroup<'a>>::SliceMutRefTuple)> {
        FilterEntityMatchingIterMut::<'a, G, F>::new(&self.sorted_mappings, &mut self.archetypes, filter_closure)
    }
}

impl Index<u16> for ArchetypeRegistry {
    type Output = Archetype;

    fn index(&self, index: u16) -> &Self::Output {
        &self.archetypes[index as usize]
    }
}

impl IndexMut<u16> for ArchetypeRegistry {
    fn index_mut(&mut self, index: u16) -> &mut Self::Output {
        &mut self.archetypes[index as usize]
    }
}