Kumo
A hand-rolled game engine.
git clone https://git.sentomk.me/Kumo.git
entity.h (1706B) · raw
1 /// @file ecs/entity.h 2 /// @brief Compact generational entity handle. 3 #pragma once 4 5 #include <cassert> 6 7 #include "core/types.h" 8 9 namespace kumo { 10 11 /// @brief Opaque handle identifying one entity in a World. 12 /// 13 /// The low 20 bits hold the slot index (up to 1,048,576 concurrent entities) 14 /// and the high 12 bits hold a generation counter that advances each time a 15 /// slot is reused. Zero is always the null/invalid entity, so valid generations 16 /// start at 1 (wrapping from kMaxGeneration back to 1). 17 struct Entity { 18 static constexpr uint32_t kIndexBits = 20; 19 static constexpr uint32_t kGenerationBits = 32 - kIndexBits; 20 static constexpr uint32_t kIndexMask = (uint32_t{1} << kIndexBits) - 1; 21 static constexpr uint32_t kMaxIndex = kIndexMask; 22 static constexpr uint32_t kMaxGeneration = 23 (uint32_t{1} << kGenerationBits) - 1; 24 25 uint32_t raw = 0; 26 27 static constexpr Entity null() { return Entity{0}; } 28 29 static constexpr Entity make(uint32_t index, uint32_t generation) { 30 assert(index <= kMaxIndex); 31 assert(generation >= 1 && generation <= kMaxGeneration); 32 return Entity{(generation << kIndexBits) | index}; 33 } 34 35 constexpr uint32_t index() const { return raw & kIndexMask; } 36 constexpr uint32_t generation() const { return raw >> kIndexBits; } 37 constexpr bool valid() const { return raw != 0; } 38 39 constexpr explicit operator bool() const { return valid(); } 40 constexpr bool operator==(const Entity&) const = default; 41 }; 42 43 /// @brief Advances a generation counter, skipping 0 so Entity::null() stays 44 /// unique. 45 constexpr uint32_t next_generation(uint32_t generation) { 46 return generation >= Entity::kMaxGeneration ? 1u : generation + 1u; 47 } 48 49 } // namespace kumo
