gecs 0.3.0

A generated entity component system.
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

use crate::error::EcsError;
use crate::index::{DataIndex, MAX_DATA_INDEX};
use crate::traits::{Archetype, EntityKey};
use crate::version::{VersionArchetype, VersionSlot};

// NOTE: While this is extremely unlikely to change, if it does, the proc
// macros need to be updated manually with the new type assumptions.
pub type ArchetypeId = u8;

// How many bits of a u32 entity index are reserved for the archetype ID.
pub(crate) const ARCHETYPE_ID_BITS: u32 = ArchetypeId::BITS;

/// A statically typed handle to an entity of a specific archetype.
///
/// On its own, this key does very little. Its primary purpose is to provide
/// indexed access to component data within an ECS world and its archetypes.
/// Entity handles are opaque and can't be accessed beyond type information.
///
/// As a data structure, an entity has two parts -- a slot index and a
/// generational version number. The slot index is used by the archetype data
/// structure to find the entity's component data, and the version number is
/// used to safely avoid attempts to access data for a stale `Entity` handle.
///
/// By default, when this version overflows (i.e., a single entity slot
/// was destroyed and reused for a new entity u32::MAX times), it will panic.
/// If instead you would like to allow entity slot versions to wrap, you can
/// enable the `wrapping_entity_version` crate feature instead. Note that this
/// could allow invalid entity access, but doing so will not access invalid
/// memory, and the chances of this happening are infinitesimally small.
pub struct Entity<A: Archetype> {
    inner: EntityAny,
    _type: PhantomData<fn() -> A>,
}

/// A statically typed, versioned raw entity index for accelerated lookup.
///
/// Unlike [`Entity`], this key points directly to the component index in
/// the archetype, rather than the version-checked slot. This skips one level
/// of indirection on lookup, but is sensitive to archetype order changes (e.g.
/// when removing an entity). Because of this, this handle keeps a version
/// number on the archetype itself, rather than the entity's slot. Attempting
/// to use a raw entity handle on an archetype that has added or removed an
/// entity since the handle was created will fail access due to invalidation,
/// even if the index may still be correct.
///
/// By default, when this version overflows (i.e., an archetype has added or
/// removed an entity `u32::MAX` times), it will cause a panic. If instead
/// you would like to allow archetype versions to wrap, you can enable the
/// `wrapping_entity_raw_version` crate feature instead. Note that this could
/// allow invalid entity access, but doing so will not access invalid memory,
/// and the chances of this happening are infinitesimally small.
pub struct EntityRaw<A: Archetype> {
    inner: EntityRawAny,
    _type: PhantomData<fn() -> A>,
}

/// A dynamically typed handle to an entity of some runtime archetype.
///
/// This behaves like an [`Entity`] key, but its type is only known at runtime.
/// To determine its type, use `archetype_id()`, or use the `resolve()` method
/// generated by the `ecs_world!` declaration to convert the `EntityAny` into
/// an enum with each possible archetype outcome.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct EntityAny {
    key: u32, // [ slot_index (u24) | archetype_id (u8) ]
    version: VersionSlot,
}

/// A dynamically typed, versioned raw entity index of some runtime archetype.
///
/// This behaves like an [`EntityRaw`] key, but its type is only known at runtime.
/// To determine its type, use `archetype_id()`, or use the `resolve()` method
/// generated by the `ecs_world!` declaration to convert the `EntityRawAny` into
/// an enum with each possible archetype outcome.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct EntityRawAny {
    key: u32, // [ dense_index (u24) | archetype_id (u8) ]
    version: VersionArchetype,
}

impl<A: Archetype> Entity<A> {
    #[inline(always)]
    pub(crate) fn new(
        slot_index: DataIndex, //.
        version: VersionSlot,
    ) -> Self {
        Self {
            inner: EntityAny::new(slot_index, A::ARCHETYPE_ID, version),
            _type: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn slot_index(&self) -> DataIndex {
        self.inner.slot_index()
    }

    #[inline(always)]
    pub(crate) fn version(&self) -> VersionSlot {
        self.inner.version()
    }

    /// Creates a new typed `Entity` from an `EntityAny`.
    ///
    /// In match statements, this tends to optimize better than `TryFrom`.
    ///
    /// # Panics
    ///
    /// Panics if the given `EntityAny` is not an entity of this type.
    #[inline(always)]
    pub fn from_any(entity: EntityAny) -> Self {
        if entity.archetype_id() != A::ARCHETYPE_ID {
            panic!("invalid entity conversion");
        }

        Self {
            inner: entity,
            _type: PhantomData,
        }
    }

    /// Creates new a typed `Entity` from an `EntityAny` without checking its archetype.
    ///
    /// While this is not an unsafe operation in the Rust sense (all bounds checks are still
    /// enforced), this should generally be avoided when possible. The intended use of this
    /// function is to skip redundant checks when using raw archetype IDs in a `match`
    /// statement. Improper use may result in logic errors from incorrect data access.
    #[inline(always)]
    pub fn from_any_unchecked(entity: EntityAny) -> Self {
        debug_assert!(entity.archetype_id() == A::ARCHETYPE_ID);

        Self {
            inner: entity,
            _type: PhantomData,
        }
    }

    /// Converts this `Entity<A>` directly into an `EntityAny`.
    ///
    /// Useful for situations where type inference can't deduce a conversion.
    #[inline(always)]
    pub fn into_any(self) -> EntityAny {
        self.inner
    }

    /// Returns this entity's raw `ARCHETYPE_ID` value.
    ///
    /// This is the same `ARCHETYPE_ID` as the archetype this entity belongs to.
    #[inline(always)]
    pub const fn archetype_id(self) -> ArchetypeId {
        A::ARCHETYPE_ID
    }
}

impl EntityAny {
    #[inline(always)]
    pub(crate) fn new(
        slot_index: DataIndex, //.
        archetype_id: ArchetypeId,
        version: VersionSlot,
    ) -> Self {
        let archetype_id: u32 = archetype_id.into();
        let key = (slot_index.get() << ARCHETYPE_ID_BITS) | archetype_id;
        Self { key, version }
    }

    #[inline(always)]
    pub(crate) fn slot_index(&self) -> DataIndex {
        unsafe {
            // SAFETY: We know the remaining data can fit in a DataIndex
            debug_assert!(self.key >> ARCHETYPE_ID_BITS <= MAX_DATA_INDEX);
            DataIndex::new_unchecked(self.key >> ARCHETYPE_ID_BITS)
        }
    }

    /// Returns this entity's raw `ARCHETYPE_ID` value.
    ///
    /// This is the same `ARCHETYPE_ID` as the archetype this entity belongs to.
    #[inline(always)]
    pub const fn archetype_id(self) -> ArchetypeId {
        self.key as ArchetypeId // Trim off the bottom to get the ID
    }

    #[inline(always)]
    pub(crate) const fn version(&self) -> VersionSlot {
        self.version
    }

    /// Returns self.
    #[inline(always)]
    pub fn into_any(self) -> EntityAny {
        self
    }
}

impl<A: Archetype> EntityRaw<A> {
    #[inline(always)]
    pub(crate) fn new(
        dense_index: DataIndex, //.
        version: VersionArchetype,
    ) -> Self {
        Self {
            inner: EntityRawAny::new(dense_index, A::ARCHETYPE_ID, version),
            _type: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn dense_index(&self) -> DataIndex {
        self.inner.dense_index()
    }

    #[inline(always)]
    pub(crate) fn version(&self) -> VersionArchetype {
        self.inner.version()
    }

    /// Creates a new typed `EntityRaw` from an `EntityRawAny`.
    ///
    /// In match statements, this tends to optimize better than `TryFrom`.
    ///
    /// # Panics
    ///
    /// Panics if the given `EntityRawAny` is not an entity of this type.
    #[inline(always)]
    pub fn from_any(entity: EntityRawAny) -> Self {
        if entity.archetype_id() != A::ARCHETYPE_ID {
            panic!("invalid entity conversion");
        }

        Self {
            inner: entity,
            _type: PhantomData,
        }
    }

    /// Creates new a typed `EntityRaw` from an `EntityRawAny` without checking its archetype.
    ///
    /// While this is not an unsafe operation in the Rust sense (all bounds checks are still
    /// enforced), this should generally be avoided when possible. The intended use of this
    /// function is to skip redundant checks when using raw archetype IDs in a `match`
    /// statement. Improper use may result in logic errors from incorrect data access.
    #[inline(always)]
    pub fn from_any_unchecked(entity: EntityRawAny) -> Self {
        debug_assert!(entity.archetype_id() == A::ARCHETYPE_ID);

        Self {
            inner: entity,
            _type: PhantomData,
        }
    }

    /// Converts this `EntityRaw<A>` directly into an `EntityRawAny`.
    ///
    /// Useful for situations where type inference can't deduce a conversion.
    #[inline(always)]
    pub fn into_any(self) -> EntityRawAny {
        self.inner
    }

    /// Returns this entity's raw `ARCHETYPE_ID` value.
    ///
    /// This is the same `ARCHETYPE_ID` as the archetype this entity belongs to.
    #[inline(always)]
    pub const fn archetype_id(self) -> ArchetypeId {
        A::ARCHETYPE_ID
    }
}

impl EntityRawAny {
    #[inline(always)]
    pub(crate) fn new(
        dense_index: DataIndex, //.
        archetype_id: ArchetypeId,
        version: VersionArchetype,
    ) -> Self {
        let archetype_id: u32 = archetype_id.into();
        let key = (dense_index.get() << ARCHETYPE_ID_BITS) | archetype_id;
        Self { key, version }
    }

    #[inline(always)]
    pub(crate) fn dense_index(&self) -> DataIndex {
        unsafe {
            // SAFETY: We know the remaining data can fit in a DataIndex
            debug_assert!(self.key >> ARCHETYPE_ID_BITS <= MAX_DATA_INDEX);
            DataIndex::new_unchecked(self.key >> ARCHETYPE_ID_BITS)
        }
    }

    /// Returns this entity's raw `ARCHETYPE_ID` value.
    ///
    /// This is the same `ARCHETYPE_ID` as the archetype this entity belongs to.
    #[inline(always)]
    pub const fn archetype_id(self) -> ArchetypeId {
        self.key as ArchetypeId // Trim off the bottom to get the ID
    }

    #[inline(always)]
    pub(crate) const fn version(&self) -> VersionArchetype {
        self.version
    }

    /// Returns self.
    #[inline(always)]
    pub fn into_any(self) -> EntityRawAny {
        self
    }
}

impl Hash for EntityAny {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash as a single u64 rather than two u32s.
        let index: u64 = self.key.into();
        let version: u64 = self.version.get().get().into();
        let combined = (index << 32) | version;
        combined.hash(state);
    }
}

impl Hash for EntityRawAny {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash as a single u64 rather than two u32s.
        let index: u64 = self.key.into();
        let version: u64 = self.version.get().get().into();
        let combined = (index << 32) | version;
        combined.hash(state);
    }
}

impl<A: Archetype> From<Entity<A>> for EntityAny {
    #[inline(always)]
    fn from(entity: Entity<A>) -> Self {
        entity.inner
    }
}

impl<A: Archetype> From<EntityRaw<A>> for EntityRawAny {
    #[inline(always)]
    fn from(entity: EntityRaw<A>) -> Self {
        entity.inner
    }
}

impl<A: Archetype> TryFrom<EntityAny> for Entity<A> {
    type Error = EcsError;

    #[inline(always)]
    fn try_from(entity: EntityAny) -> Result<Self, Self::Error> {
        if entity.archetype_id() == A::ARCHETYPE_ID {
            Ok(Self {
                inner: entity,
                _type: PhantomData,
            })
        } else {
            Err(EcsError::InvalidEntityType)
        }
    }
}

impl<A: Archetype> TryFrom<EntityRawAny> for EntityRaw<A> {
    type Error = EcsError;

    #[inline(always)]
    fn try_from(entity: EntityRawAny) -> Result<Self, Self::Error> {
        if entity.archetype_id() == A::ARCHETYPE_ID {
            Ok(Self {
                inner: entity,
                _type: PhantomData,
            })
        } else {
            Err(EcsError::InvalidEntityType)
        }
    }
}

// Derive boilerplate until https://github.com/rust-lang/rust/issues/26925 is resolved

impl<A: Archetype> Clone for Entity<A> {
    #[inline(always)]
    fn clone(&self) -> Entity<A> {
        Entity {
            inner: self.inner,
            _type: PhantomData,
        }
    }
}

impl<A: Archetype> Clone for EntityRaw<A> {
    #[inline(always)]
    fn clone(&self) -> EntityRaw<A> {
        EntityRaw {
            inner: self.inner,
            _type: PhantomData,
        }
    }
}

impl<A: Archetype> PartialEq for Entity<A> {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<A: Archetype> PartialEq for EntityRaw<A> {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<A: Archetype> Hash for Entity<A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state)
    }
}

impl<A: Archetype> Hash for EntityRaw<A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state)
    }
}

impl<A: Archetype> Copy for Entity<A> {}
impl<A: Archetype> Copy for EntityRaw<A> {}

impl<A: Archetype> Eq for Entity<A> {}
impl<A: Archetype> Eq for EntityRaw<A> {}

impl<A: Archetype> EntityKey for Entity<A> {
    type DestroyOutput = Option<A::Components>;
}

impl<A: Archetype> EntityKey for EntityRaw<A> {
    type DestroyOutput = Option<A::Components>;
}

impl EntityKey for EntityAny {
    type DestroyOutput = bool;
}

impl EntityKey for EntityRawAny {
    type DestroyOutput = bool;
}

#[doc(hidden)]
pub mod __internal {
    use super::*;

    #[doc(hidden)]
    #[inline(always)]
    pub fn new_entity_raw<A: Archetype>(index: usize, version: VersionArchetype) -> EntityRaw<A> {
        EntityRaw::new(DataIndex::new_usize(index).unwrap(), version)
    }
}