Kumo

A hand-rolled game engine.

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

sparse_set.h (3779B) · raw


      1 /// @file ecs/sparse_set.h
      2 /// @brief Contiguous per-component storage with O(1) lookup, insert and erase.
      3 #pragma once
      4 
      5 #include <cassert>
      6 #include <limits>
      7 #include <utility>
      8 #include <vector>
      9 
     10 #include "core/types.h"
     11 #include "ecs/entity.h"
     12 
     13 namespace kumo {
     14 
     15 /// @brief Type-erased interface shared by every component pool in a World.
     16 ///
     17 /// Kept minimal so World can destroy an entity across all pools without RTTI.
     18 class PoolBase {
     19  public:
     20   virtual ~PoolBase() = default;
     21 
     22   virtual bool has(Entity entity) const = 0;
     23   virtual bool remove(Entity entity) = 0;
     24   virtual void clear() = 0;
     25   virtual size_t size() const = 0;
     26   virtual const std::vector<Entity>& entities() const = 0;
     27 };
     28 
     29 /// @brief Sparse-set component storage for one component type @p T.
     30 ///
     31 /// `sparse_` maps `entity.index()` to a dense index in `dense_` / `data_`.
     32 /// `dense_` stores the full Entity handle (including generation), so stale
     33 /// handles to a reused slot never match. Removal uses swap-and-pop, keeping
     34 /// `data_` tightly packed and deterministic.
     35 template <typename T>
     36 class SparseSet final : public PoolBase {
     37  public:
     38   static constexpr uint32_t kInvalid = std::numeric_limits<uint32_t>::max();
     39 
     40   /// @brief Adds or replaces the component for @p entity.
     41   template <typename... Args>
     42   T& emplace(Entity entity, Args&&... args) {
     43     assert(entity.valid());
     44     const uint32_t idx = entity.index();
     45     if (idx >= sparse_.size()) {
     46       sparse_.resize(static_cast<size_t>(idx + 1), kInvalid);
     47     }
     48 
     49     const uint32_t existing = sparse_[idx];
     50     if (existing != kInvalid) {
     51       assert(dense_[existing] == entity);
     52       data_[existing] = T{std::forward<Args>(args)...};
     53       return data_[existing];
     54     }
     55 
     56     const uint32_t dense_idx = static_cast<uint32_t>(dense_.size());
     57     sparse_[idx] = dense_idx;
     58     dense_.push_back(entity);
     59     data_.push_back(T{std::forward<Args>(args)...});
     60     return data_.back();
     61   }
     62 
     63   bool has(Entity entity) const override {
     64     if (!entity.valid()) return false;
     65     const uint32_t idx = entity.index();
     66     if (idx >= sparse_.size()) return false;
     67     const uint32_t dense_idx = sparse_[idx];
     68     return dense_idx != kInvalid && dense_[dense_idx] == entity;
     69   }
     70 
     71   /// @brief Removes the component for @p entity via swap-and-pop.
     72   /// @return `true` if the component existed and was removed.
     73   bool remove(Entity entity) override {
     74     if (!has(entity)) return false;
     75     const uint32_t dense_idx = sparse_[entity.index()];
     76     const uint32_t last_idx = static_cast<uint32_t>(dense_.size() - 1);
     77     if (dense_idx != last_idx) {
     78       const Entity moved = dense_[last_idx];
     79       dense_[dense_idx] = moved;
     80       data_[dense_idx] = std::move(data_[last_idx]);
     81       sparse_[moved.index()] = dense_idx;
     82     }
     83     dense_.pop_back();
     84     data_.pop_back();
     85     sparse_[entity.index()] = kInvalid;
     86     return true;
     87   }
     88 
     89   T& get(Entity entity) {
     90     assert(has(entity));
     91     return data_[sparse_[entity.index()]];
     92   }
     93 
     94   const T& get(Entity entity) const {
     95     assert(has(entity));
     96     return data_[sparse_[entity.index()]];
     97   }
     98 
     99   T* try_get(Entity entity) {
    100     return has(entity) ? &data_[sparse_[entity.index()]] : nullptr;
    101   }
    102 
    103   const T* try_get(Entity entity) const {
    104     return has(entity) ? &data_[sparse_[entity.index()]] : nullptr;
    105   }
    106 
    107   void clear() override {
    108     sparse_.clear();
    109     dense_.clear();
    110     data_.clear();
    111   }
    112 
    113   size_t size() const override { return dense_.size(); }
    114   bool empty() const { return dense_.empty(); }
    115 
    116   const std::vector<Entity>& entities() const override { return dense_; }
    117   std::vector<T>& data() { return data_; }
    118   const std::vector<T>& data() const { return data_; }
    119 
    120  private:
    121   std::vector<uint32_t> sparse_;
    122   std::vector<Entity> dense_;
    123   std::vector<T> data_;
    124 };
    125 
    126 }  // namespace kumo