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
//! Archetypes are sets of entities which all contain extactly the same
//! set of component types.
//!
//! Entities in the same archetype have all of their components stored next
//! to each other and in the same order, allowing their components to be
//! accessed as zipped slices.
//!
//! Legion performs all entity filtering at the archetype level; decisions are
//! never made per-entity.

use std::{
    ops::{Index, IndexMut},
    rc::Rc,
    sync::Arc,
};

use super::{
    component::{Component, ComponentTypeId},
    UnknownComponentStorage,
};
use crate::internals::{
    entity::Entity,
    event::{Event, Subscriber, Subscribers},
    query::filter::{FilterResult, LayoutFilter},
};

/// The index of an archetype in a world.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct ArchetypeIndex(pub u32);

impl Index<ArchetypeIndex> for [Archetype] {
    type Output = Archetype;

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

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

impl Index<ArchetypeIndex> for Vec<Archetype> {
    type Output = Archetype;

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

impl IndexMut<ArchetypeIndex> for Vec<Archetype> {
    fn index_mut(&mut self, index: ArchetypeIndex) -> &mut Self::Output {
        &mut self[index.0 as usize]
    }
}

/// An archetype is a collection of entities which all have identical component types.
#[derive(Debug)]
pub struct Archetype {
    index: ArchetypeIndex,
    entities: Vec<Entity>,
    layout: Arc<EntityLayout>,
    subscribers: Subscribers,
}

impl Archetype {
    pub(crate) fn new(
        index: ArchetypeIndex,
        layout: EntityLayout,
        mut subscribers: Subscribers,
    ) -> Self {
        subscribers.send(Event::ArchetypeCreated(index));
        Self {
            index,
            layout: Arc::new(layout),
            entities: Vec::new(),
            subscribers,
        }
    }

    /// Returns the index of the archetype.
    pub fn index(&self) -> ArchetypeIndex {
        self.index
    }

    /// Returns the layout of the archetype, describing which components are attached
    /// to all entities contained within the archetype.
    pub fn layout(&self) -> &Arc<EntityLayout> {
        &self.layout
    }

    /// Returns a slice of entity IDs for all entities which belong to the archetype.
    pub fn entities(&self) -> &[Entity] {
        &self.entities
    }

    pub(crate) fn push(&mut self, entity: Entity) {
        self.entities.push(entity);
        self.subscribers
            .send(Event::EntityInserted(entity, self.index));
    }

    pub(crate) fn reserve(&mut self, additional: usize) {
        self.entities.reserve(additional)
    }

    pub(crate) fn swap_remove(&mut self, entity_index: usize) -> Entity {
        let removed = self.entities.swap_remove(entity_index);
        self.subscribers
            .send(Event::EntityRemoved(removed, self.index));
        removed
    }

    pub(crate) fn subscribe(&mut self, subscriber: Subscriber) {
        subscriber.send(Event::ArchetypeCreated(self.index));
        for entity in &self.entities {
            subscriber.send(Event::EntityInserted(*entity, self.index));
        }
        self.subscribers.push(subscriber);
    }

    pub(crate) fn drain(&mut self) -> Vec<Entity> {
        let mut entities = Vec::new();
        std::mem::swap(&mut self.entities, &mut entities);
        for entity in &entities {
            self.subscribers
                .send(Event::EntityRemoved(*entity, self.index));
        }
        entities
    }
}

impl Drop for Archetype {
    fn drop(&mut self) {
        for entity in &self.entities {
            self.subscribers
                .send(Event::EntityRemoved(*entity, self.index));
        }
    }
}

/// Describes the component types which are attached to an entity.
#[derive(Default, Debug, Clone)]
pub struct EntityLayout {
    components: Vec<ComponentTypeId>,
    component_constructors: Vec<fn() -> Box<dyn UnknownComponentStorage>>,
}

impl EntityLayout {
    /// Constructs a new entity layout.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a new component to the layout.
    pub fn register_component<T: Component>(&mut self) {
        let type_id = ComponentTypeId::of::<T>();
        assert!(
            !self.components.contains(&type_id),
            "only one component of a given type may be attached to a single entity"
        );
        self.components.push(type_id);
        self.component_constructors
            .push(|| Box::new(T::Storage::default()));
    }

    /// Adds a new component to the layout.
    ///
    /// # Safety
    /// The storage returned from the storage constructor function must be capable
    /// of storing the component type identified by `type_id`.
    pub unsafe fn register_component_raw(
        &mut self,
        type_id: ComponentTypeId,
        f: fn() -> Box<dyn UnknownComponentStorage>,
    ) {
        assert!(
            !self.components.contains(&type_id),
            "only one component of a given type may be attached to a single entity"
        );
        self.components.push(type_id);
        self.component_constructors.push(f);
    }

    /// Returns a slice of component type IDs for the components inside the layout.
    pub fn component_types(&self) -> &[ComponentTypeId] {
        &self.components
    }

    /// Returns a slice of storage constructors for each component type in the layout.
    #[doc(hidden)]
    pub fn component_constructors(&self) -> &[fn() -> Box<dyn UnknownComponentStorage>] {
        &self.component_constructors
    }

    /// Returns `true` if the layout contains the given component type.
    pub fn has_component<T: Component>(&self) -> bool {
        self.has_component_by_id(ComponentTypeId::of::<T>())
    }

    /// Returns `true` if the layout contains the given component type.
    pub fn has_component_by_id(&self, type_id: ComponentTypeId) -> bool {
        self.components.contains(&type_id)
    }
}

impl LayoutFilter for EntityLayout {
    fn matches_layout(&self, components: &[ComponentTypeId]) -> FilterResult {
        FilterResult::Match(
            components.len() == self.components.len()
                && self.components.iter().all(|t| components.contains(t)),
        )
    }
}

impl LayoutFilter for Rc<EntityLayout> {
    fn matches_layout(&self, components: &[ComponentTypeId]) -> FilterResult {
        FilterResult::Match(
            components.len() == self.components.len()
                && self.components.iter().all(|t| components.contains(t)),
        )
    }
}