Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

world.h (8090B) · raw


      1 /// @file ecs/world.h
      2 /// @brief Entity registry and per-component SparseSet storage without RTTI.
      3 #pragma once
      4 
      5 #include <cassert>
      6 #include <memory>
      7 #include <tuple>
      8 #include <type_traits>
      9 #include <utility>
     10 #include <vector>
     11 
     12 #include "core/types.h"
     13 #include "ecs/entity.h"
     14 #include "ecs/sparse_set.h"
     15 
     16 namespace kumo {
     17 
     18 using ComponentId = uint32_t;
     19 
     20 namespace detail {
     21 
     22 inline ComponentId next_component_id() {
     23   static ComponentId next = 0;
     24   return next++;
     25 }
     26 
     27 template <typename T>
     28 ComponentId raw_component_id() {
     29   static const ComponentId id = next_component_id();
     30   return id;
     31 }
     32 
     33 }  // namespace detail
     34 
     35 /// @brief Returns a unique, dense integer ID for component type @p T.
     36 ///
     37 /// Strips cv-qualifiers so `const T` and `T` share the same pool without RTTI.
     38 template <typename T>
     39 ComponentId component_id() {
     40   return detail::raw_component_id<std::remove_cv_t<T>>();
     41 }
     42 
     43 /// @brief Owns all entities and component pools for one simulation world.
     44 class World {
     45  public:
     46   World() = default;
     47   World(const World&) = delete;
     48   World& operator=(const World&) = delete;
     49   World(World&&) = default;
     50   World& operator=(World&&) = default;
     51 
     52   /// @brief Allocates a new live entity, recycling freed slots when available.
     53   Entity create() {
     54     if (!free_indices_.empty()) {
     55       const uint32_t idx = free_indices_.back();
     56       free_indices_.pop_back();
     57       alive_[idx] = 1;
     58       ++alive_count_;
     59       return Entity::make(idx, generations_[idx]);
     60     }
     61 
     62     const uint32_t idx = static_cast<uint32_t>(generations_.size());
     63     assert(idx <= Entity::kMaxIndex);
     64     generations_.push_back(1);
     65     alive_.push_back(1);
     66     ++alive_count_;
     67     return Entity::make(idx, 1);
     68   }
     69 
     70   /// @brief Returns whether @p entity is currently alive in this world.
     71   bool alive(Entity entity) const {
     72     if (!entity.valid()) return false;
     73     const uint32_t idx = entity.index();
     74     return idx < generations_.size() && alive_[idx] != 0 &&
     75            generations_[idx] == entity.generation();
     76   }
     77 
     78   /// @brief Immediately destroys @p entity and removes all of its components.
     79   ///
     80   /// Do not call while iterating a pool that contains @p entity; use
     81   /// destroy_deferred() and flush_destroyed() instead.
     82   /// @return `true` if @p entity was alive and has been destroyed.
     83   bool destroy(Entity entity) {
     84     if (!alive(entity)) return false;
     85     for (const std::unique_ptr<PoolBase>& pool : pools_) {
     86       if (pool != nullptr) pool->remove(entity);
     87     }
     88     const uint32_t idx = entity.index();
     89     alive_[idx] = 0;
     90     generations_[idx] = next_generation(generations_[idx]);
     91     free_indices_.push_back(idx);
     92     --alive_count_;
     93     return true;
     94   }
     95 
     96   /// @brief Marks @p entity to be destroyed when flush_destroyed() is called.
     97   void destroy_deferred(Entity entity) {
     98     if (alive(entity)) pending_destroy_.push_back(entity);
     99   }
    100 
    101   /// @brief Destroys all entities queued by destroy_deferred().
    102   void flush_destroyed() {
    103     for (const Entity entity : pending_destroy_) {
    104       destroy(entity);
    105     }
    106     pending_destroy_.clear();
    107   }
    108 
    109   /// @brief Removes all entities and components from the world.
    110   void clear() {
    111     for (const std::unique_ptr<PoolBase>& pool : pools_) {
    112       if (pool != nullptr) pool->clear();
    113     }
    114     generations_.clear();
    115     alive_.clear();
    116     free_indices_.clear();
    117     pending_destroy_.clear();
    118     alive_count_ = 0;
    119   }
    120 
    121   size_t alive_count() const { return alive_count_; }
    122 
    123   /// @brief Adds or replaces component @p T on a live @p entity.
    124   template <typename T, typename... Args>
    125   T& emplace(Entity entity, Args&&... args) {
    126     assert(alive(entity));
    127     return get_or_create_pool<T>().emplace(entity, std::forward<Args>(args)...);
    128   }
    129 
    130   /// @brief Removes component @p T from @p entity if present.
    131   template <typename T>
    132   bool remove(Entity entity) {
    133     auto* pool = find_pool<T>();
    134     return pool != nullptr && pool->remove(entity);
    135   }
    136 
    137   template <typename T>
    138   bool has(Entity entity) const {
    139     const auto* pool = find_pool<T>();
    140     return pool != nullptr && pool->has(entity);
    141   }
    142 
    143   template <typename T>
    144   T& get(Entity entity) {
    145     auto* pool = find_pool<T>();
    146     assert(pool != nullptr);
    147     return pool->get(entity);
    148   }
    149 
    150   template <typename T>
    151   const T& get(Entity entity) const {
    152     const auto* pool = find_pool<T>();
    153     assert(pool != nullptr);
    154     return pool->get(entity);
    155   }
    156 
    157   template <typename T>
    158   T* try_get(Entity entity) {
    159     auto* pool = find_pool<T>();
    160     return pool != nullptr ? pool->try_get(entity) : nullptr;
    161   }
    162   template <typename T>
    163   const T* try_get(Entity entity) const {
    164     const auto* pool = find_pool<T>();
    165     return pool != nullptr ? pool->try_get(entity) : nullptr;
    166   }
    167   /// @brief Number of live entities that currently have component @p T.
    168   template <typename T>
    169   size_t count() const {
    170     const auto* pool = find_pool<T>();
    171     return pool != nullptr ? pool->size() : 0;
    172   }
    173   /// @brief Invokes `fn(Entity, Ts&...)` for every entity having all of @p Ts.
    174   ///
    175   /// Drives iteration from the smallest component pool among @p Ts.
    176   template <typename... Ts, typename Fn>
    177   void each(Fn&& fn) {
    178     static_assert(sizeof...(Ts) > 0,
    179                   "World::each requires at least one component type");
    180     auto pools = std::make_tuple(find_pool<Ts>()...);
    181     const PoolBase* smallest = smallest_pool(pools);
    182     if (smallest == nullptr) return;
    183     for (const Entity entity : smallest->entities()) {
    184       const bool has_all = std::apply(
    185           [entity](auto*... p) { return (p->has(entity) && ...); }, pools);
    186       if (has_all) {
    187         std::apply([&](auto*... p) { fn(entity, p->get(entity)...); }, pools);
    188       }
    189     }
    190   }
    191   /// @brief Const overload: invokes `fn(Entity, const Ts&...)`.
    192   template <typename... Ts, typename Fn>
    193   void each(Fn&& fn) const {
    194     static_assert(sizeof...(Ts) > 0,
    195                   "World::each requires at least one component type");
    196     auto pools = std::make_tuple(find_pool<Ts>()...);
    197     const PoolBase* smallest = smallest_pool(pools);
    198     if (smallest == nullptr) return;
    199     for (const Entity entity : smallest->entities()) {
    200       const bool has_all = std::apply(
    201           [entity](const auto*... p) { return (p->has(entity) && ...); },
    202           pools);
    203       if (has_all) {
    204         std::apply([&](const auto*... p) { fn(entity, p->get(entity)...); },
    205                    pools);
    206       }
    207     }
    208   }
    209 
    210  private:
    211   template <typename T>
    212   using PoolType = SparseSet<std::remove_cv_t<T>>;
    213 
    214   template <typename T>
    215   PoolType<T>& get_or_create_pool() {
    216     const ComponentId id = component_id<T>();
    217     if (id >= pools_.size()) {
    218       pools_.resize(static_cast<size_t>(id) + 1);
    219     }
    220     if (pools_[id] == nullptr) {
    221       pools_[id] = std::make_unique<PoolType<T>>();
    222     }
    223     return *static_cast<PoolType<T>*>(pools_[id].get());
    224   }
    225 
    226   template <typename T>
    227   PoolType<T>* find_pool() {
    228     const ComponentId id = component_id<T>();
    229     if (id >= pools_.size() || pools_[id] == nullptr) return nullptr;
    230     return static_cast<PoolType<T>*>(pools_[id].get());
    231   }
    232 
    233   template <typename T>
    234   const PoolType<T>* find_pool() const {
    235     const ComponentId id = component_id<T>();
    236     if (id >= pools_.size() || pools_[id] == nullptr) return nullptr;
    237     return static_cast<const PoolType<T>*>(pools_[id].get());
    238   }
    239 
    240   template <typename... PoolPtrs>
    241   static const PoolBase* smallest_pool(const std::tuple<PoolPtrs...>& pools) {
    242     const PoolBase* best = nullptr;
    243     bool empty = false;
    244     std::apply(
    245         [&](auto*... p) {
    246           for (const PoolBase* cur : {static_cast<const PoolBase*>(p)...}) {
    247             if (cur == nullptr || cur->size() == 0) {
    248               empty = true;
    249               return;
    250             }
    251             if (best == nullptr || cur->size() < best->size()) best = cur;
    252           }
    253         },
    254         pools);
    255     return empty ? nullptr : best;
    256   }
    257 
    258   std::vector<uint32_t> generations_;
    259   std::vector<uint8_t> alive_;
    260   std::vector<uint32_t> free_indices_;
    261   std::vector<Entity> pending_destroy_;
    262   std::vector<std::unique_ptr<PoolBase>> pools_;
    263   size_t alive_count_ = 0;
    264 };
    265 
    266 }  // namespace kumo