Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
SparseSet.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16#pragma once
17
18// =============================================================================
19// Includes
20// =============================================================================
21
22// Project includes
23#include "../core/Log.hpp"
24#include "../core/Types.hpp"
25#include "Entity.hpp"
26
27// Standard library
28#include <algorithm>
29#include <array>
30#include <concepts>
31#include <cstring>
32#include <memory>
33#include <string>
34#include <string_view>
35#include <type_traits>
36#include <vector>
37
38namespace esengine::ecs {
39
40// =============================================================================
41// SparseSetBase
42// =============================================================================
43
52public:
54 virtual ~SparseSetBase() = default;
55
61 virtual bool contains(Entity entity) const = 0;
62
67 virtual void remove(Entity entity) = 0;
68
73 virtual usize size() const = 0;
74
79 virtual bool empty() const = 0;
80
84 virtual void clear() = 0;
85
90 virtual const std::vector<Entity>& entities() const = 0;
91
102 virtual u32 version() const = 0;
103
116 virtual void reorderBy(const std::vector<u32>& rank) = 0;
117
119 static constexpr u32 UNRANKED = 0xFFFFFFFFu;
120
121 // ---- Change stamps --------------------------------------------------------------------------------------------------------
122 // Every component carries the tick of its last write beside it (see Registry::changeTick for what a tick is). Written by
123 // whoever writes the component: Registry::patch and markChanged here, the generated setters from script.
124
126 virtual u32 changedTickOf(Entity entity) const = 0;
128 virtual void markChanged(Entity entity, u32 tick) = 0;
130 virtual u32 lastChangedTick() const = 0;
132 virtual void noteStructural(u32 tick) = 0;
134 virtual void clampStamps(u32 floor) = 0;
136 virtual std::string_view typeName() const = 0;
137
138 // ---- The audit -------------------------------------------------------------------------------------------------------------
139 // A write that left no stamp is a consumer that will never see it (a renderer drawing the old state). The audit keeps a copy
140 // of every component and reports each one that changed since the copy while its stamp did not move: by its bytes where they
141 // are its value (trivially copyable), by == where it says what equal is; a component that is neither is listed as unchecked.
142
144 struct AuditCopy {
145 std::vector<Entity> entities;
146 std::vector<u8> bytes;
147 std::shared_ptr<void> values;
149 };
150
151 virtual bool auditable() const = 0;
153 virtual void auditKeep(AuditCopy& copy, u32 tick) const = 0;
158 virtual u32 auditCompare(const AuditCopy& copy, void (*report)(void* user, Entity entity), void* user) const = 0;
159
166 [[gnu::noinline]] static std::vector<usize> stablePermutation(const std::vector<Entity>& dense, const std::vector<u32>& rank) {
167 const usize n = dense.size();
168 std::vector<usize> perm(n);
169 for (usize i = 0; i < n; ++i) perm[i] = i;
170 const auto rankOf = [&](usize i) {
171 const u32 idx = dense[i].index();
172 return idx < rank.size() ? rank[idx] : UNRANKED;
173 };
174 std::stable_sort(perm.begin(), perm.end(), [&](usize a, usize b) { return rankOf(a) < rankOf(b); });
175 return perm;
176 }
177};
178
180template<typename T>
181std::string_view componentTypeName() {
182#if defined(_MSC_VER) && !defined(__clang__)
183 constexpr std::string_view full = __FUNCSIG__;
184 constexpr std::string_view open = "componentTypeName<";
185 constexpr std::string_view close = ">(void)";
186#else
187 constexpr std::string_view full = __PRETTY_FUNCTION__;
188 constexpr std::string_view open = "T = ";
189 constexpr std::string_view close = "]";
190#endif
191 const usize start = full.find(open);
192 if (start == std::string_view::npos) return full;
193 std::string_view name = full.substr(start + open.size());
194 const usize end = name.rfind(close);
195 if (end != std::string_view::npos) name = name.substr(0, end);
196 const usize colon = name.rfind("::");
197 if (colon != std::string_view::npos) name = name.substr(colon + 2);
198 // MSVC writes "struct X" / "class X".
199 for (std::string_view tag : {std::string_view("struct "), std::string_view("class ")}) {
200 if (name.substr(0, tag.size()) == tag) name = name.substr(tag.size());
201 }
202 return name;
203}
204
206inline bool tickAfter(u32 a, u32 b) {
207 return static_cast<i32>(a - b) > 0;
208}
209
210// =============================================================================
211// SparseSet
212// =============================================================================
213
255template<typename T>
256class SparseSet : public SparseSetBase {
257public:
259 using Iterator = typename std::vector<Entity>::const_iterator;
260
262 static constexpr usize SPARSE_PAGE_SIZE = 4096;
263
266
268 using Page = std::array<u32, SPARSE_PAGE_SIZE>;
269
271 SparseSet() = default;
272
274 ~SparseSet() override = default;
275
276 // Non-copyable, movable
277 SparseSet(const SparseSet&) = delete;
278 SparseSet& operator=(const SparseSet&) = delete;
279 SparseSet(SparseSet&&) noexcept = default;
280 SparseSet& operator=(SparseSet&&) noexcept = default;
281
282 // =========================================================================
283 // Lookup Operations
284 // =========================================================================
285
294 bool contains(Entity entity) const override {
295 u32 di = denseIndexOf(entity);
296 return di != INVALID_INDEX && dense_[di] == entity;
297 }
298
308 T& get(Entity entity) {
309 const u32 di = denseIndexOf(entity);
310 ES_VERIFY_FATAL(di != INVALID_INDEX && dense_[di] == entity, missMessage(entity));
311 return components_[di];
312 }
313
315 const T& get(Entity entity) const {
316 const u32 di = denseIndexOf(entity);
317 ES_VERIFY_FATAL(di != INVALID_INDEX && dense_[di] == entity, missMessage(entity));
318 return components_[di];
319 }
320
321 T& getUnchecked(Entity entity) {
322 return components_[denseIndexOf(entity)];
323 }
324
325 const T& getUnchecked(Entity entity) const {
326 return components_[denseIndexOf(entity)];
327 }
328
334 T* tryGet(Entity entity) {
335 u32 di = denseIndexOf(entity);
336 if (di == INVALID_INDEX || dense_[di] != entity) return nullptr;
337 return &components_[di];
338 }
339
341 const T* tryGet(Entity entity) const {
342 u32 di = denseIndexOf(entity);
343 if (di == INVALID_INDEX || dense_[di] != entity) return nullptr;
344 return &components_[di];
345 }
346
347 // =========================================================================
348 // Change Stamps
349 // =========================================================================
350
352 u32 changedTick(Entity entity) const {
353 const u32 di = denseIndexOf(entity);
354 return di != INVALID_INDEX && dense_[di] == entity ? changed_[di] : 0;
355 }
356
357 u32 changedTickOf(Entity entity) const override { return changedTick(entity); }
358
360 void markChanged(Entity entity, u32 tick) override {
361 const u32 di = denseIndexOf(entity);
362 if (di == INVALID_INDEX || dense_[di] != entity) return;
363 changed_[di] = tick;
364 if (tickAfter(tick, last_changed_)) last_changed_ = tick;
365 }
366
368 u32* changeTicks() { return changed_.data(); }
369 const u32* changeTicks() const { return changed_.data(); }
370
372 u32* lastChangedSlot() { return &last_changed_; }
373
374 u32 lastChangedTick() const override { return last_changed_; }
375 void noteStructural(u32 tick) override {
376 if (tickAfter(tick, last_changed_)) last_changed_ = tick;
377 }
378 void clampStamps(u32 floor) override {
379 for (u32& t : changed_) if (tickAfter(floor, t)) t = floor;
380 if (tickAfter(floor, last_changed_)) last_changed_ = floor;
381 }
382 std::string_view typeName() const override { return componentTypeName<T>(); }
383
384 static constexpr bool kAuditBytes = std::is_trivially_copyable_v<T>;
385 static constexpr bool kAuditValues = !kAuditBytes && std::is_copy_constructible_v<T> && std::equality_comparable<T>;
386 bool auditable() const override { return kAuditBytes || kAuditValues; }
387 void auditKeep(AuditCopy& copy, u32 tick) const override {
388 copy.tick = tick;
389 copy.entities = dense_;
390 copy.bytes.clear();
391 copy.values.reset();
392 if constexpr (kAuditBytes) {
393 copy.bytes.resize(components_.size() * sizeof(T));
394 if (!components_.empty()) std::memcpy(copy.bytes.data(), components_.data(), copy.bytes.size());
395 } else if constexpr (kAuditValues) {
396 copy.values = std::make_shared<std::vector<T>>(components_);
397 }
398 }
399 u32 auditCompare(const AuditCopy& copy, void (*report)(void*, Entity), void* user) const override {
400 if constexpr (!kAuditBytes && !kAuditValues) {
401 return 0;
402 } else {
403 const auto* values = kAuditValues ? static_cast<const std::vector<T>*>(copy.values.get()) : nullptr;
404 if (kAuditValues && !values) return 0;
405 u32 found = 0;
406 for (usize k = 0; k < copy.entities.size(); ++k) {
407 const Entity entity = copy.entities[k];
408 const u32 di = denseIndexOf(entity);
409 if (di == INVALID_INDEX || dense_[di] != entity) continue; // removed since: the journal says so
410 if (tickAfter(changed_[di], copy.tick)) continue; // written, and said so
411 bool same = false;
412 if constexpr (requires(const T& now, const T& kept) { { now.auditSame(kept) } -> std::convertible_to<bool>; }) {
413 // The component says what unchanged is (a cache it fills lazily is no write): see Transform::auditSame.
414 same = kAuditBytes
415 ? components_[di].auditSame(*reinterpret_cast<const T*>(copy.bytes.data() + k * sizeof(T)))
416 : components_[di].auditSame((*values)[k]);
417 } else if constexpr (kAuditBytes) {
418 same = std::memcmp(&components_[di], copy.bytes.data() + k * sizeof(T), sizeof(T)) == 0;
419 } else {
420 same = components_[di] == (*values)[k];
421 }
422 if (same) continue;
423 ++found;
424 if (report) report(user, entity);
425 }
426 return found;
427 }
428 }
429
430 // =========================================================================
431 // Modification Operations
432 // =========================================================================
433
447 template<typename... Args>
448 T& emplace(Entity entity, Args&&... args) {
449 // Release-safe: a duplicate emplace would append a second dense slot and
450 // overwrite the sparse->dense mapping, corrupting the set (ES_ASSERT is
451 // stripped in release). Degrade to returning the existing component.
452 ES_VERIFY(!contains(entity), return get(entity));
453
454 const u32 idx = entity.index();
455 const auto pageIndex = idx / SPARSE_PAGE_SIZE;
456 const auto offset = idx % SPARSE_PAGE_SIZE;
457
458 if (pageIndex >= pages_.size()) {
459 pages_.resize(pageIndex + 1);
460 }
461
462 if (!pages_[pageIndex]) {
463 pages_[pageIndex] = std::make_unique<Page>();
464 std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_INDEX);
465 }
466
467 (*pages_[pageIndex])[offset] = static_cast<u32>(dense_.size());
468 dense_.push_back(entity);
469
470 // Bump the version only when the component buffer actually reallocates
471 // (base pointer moves) — that is exactly when previously-handed-out raw
472 // pointers into components_ become stale. A non-reallocating append
473 // leaves existing component addresses intact, so no bump is needed.
474 const T* before = components_.data();
475 const u32* stampsBefore = changed_.data();
476 components_.emplace_back(std::forward<Args>(args)...);
477 // Unstamped: whoever adds it stamps it with the tick it belongs to (Registry::emplace).
478 changed_.push_back(0);
479 if (components_.data() != before || changed_.data() != stampsBefore) ++version_;
480
481 return components_.back();
482 }
483
492 void remove(Entity entity) override {
493 if (!contains(entity)) return;
494
495 // Swap-and-pop relocates the last component into the freed slot, so any
496 // raw pointer previously handed out for the moved entity is now stale.
497 ++version_;
498
499 const u32 idx = entity.index();
500 const auto pageIndex = idx / SPARSE_PAGE_SIZE;
501 const auto offset = idx % SPARSE_PAGE_SIZE;
502 const u32 denseIdx = (*pages_[pageIndex])[offset];
503
504 if (denseIdx == static_cast<u32>(dense_.size()) - 1) {
505 dense_.pop_back();
506 components_.pop_back();
507 changed_.pop_back();
508 (*pages_[pageIndex])[offset] = INVALID_INDEX;
509 return;
510 }
511
512 const Entity last = dense_.back();
513
514 dense_[denseIdx] = last;
515 components_[denseIdx] = std::move(components_.back());
516 changed_[denseIdx] = changed_.back();
517 changed_.pop_back();
518
519 const u32 lastIdx = last.index();
520 (*pages_[lastIdx / SPARSE_PAGE_SIZE])[lastIdx % SPARSE_PAGE_SIZE] = denseIdx;
521
522 dense_.pop_back();
523 components_.pop_back();
524 (*pages_[pageIndex])[offset] = INVALID_INDEX;
525 }
526
527 // =========================================================================
528 // Container Operations
529 // =========================================================================
530
535 usize size() const override { return dense_.size(); }
536
541 bool empty() const override { return dense_.empty(); }
542
546 void clear() override {
547 ++version_;
548 pages_.clear();
549 dense_.clear();
550 components_.clear();
551 changed_.clear();
552 }
553
555 u32 version() const override { return version_; }
556
558 void reorderBy(const std::vector<u32>& rank) override {
559 const usize n = dense_.size();
560 if (n <= 1) return;
561
562 // perm[i] = which current slot belongs at position i. The sort keeps
563 // equal-ranked (and unranked) entities in their present order, and is
564 // one function for every component type (see stablePermutation).
565 std::vector<usize> perm = stablePermutation(dense_, rank);
566
567 permute(perm);
568 }
569
575 void permute(std::vector<usize>& perm) {
576 const usize n = dense_.size();
577 bool moved = false;
578 for (usize i = 0; i < n; ++i) {
579 if (perm[i] != i) { moved = true; break; }
580 }
581 if (!moved) return;
582
583 // Cycle-walk the permutation in place.
584 for (usize i = 0; i < n; ++i) {
585 if (perm[i] == i) continue;
586 usize j = i;
587 Entity tmpEntity = std::move(dense_[i]);
588 T tmpComponent = std::move(components_[i]);
589 const u32 tmpStamp = changed_[i];
590 while (perm[j] != i) {
591 const usize src = perm[j];
592 dense_[j] = std::move(dense_[src]);
593 components_[j] = std::move(components_[src]);
594 changed_[j] = changed_[src];
595 perm[j] = j;
596 j = src;
597 }
598 dense_[j] = std::move(tmpEntity);
599 components_[j] = std::move(tmpComponent);
600 changed_[j] = tmpStamp;
601 perm[j] = j;
602 }
604 }
605
607 // Called after permute() moves dense_/components_ in place —
608 // component addresses changed, so any handed-out raw pointer is stale.
609 ++version_;
610 pages_.clear();
611 for (usize i = 0; i < dense_.size(); ++i) {
612 const u32 idx = dense_[i].index();
613 const auto pageIndex = idx / SPARSE_PAGE_SIZE;
614 const auto offset = idx % SPARSE_PAGE_SIZE;
615 if (pageIndex >= pages_.size()) {
616 pages_.resize(pageIndex + 1);
617 }
618 if (!pages_[pageIndex]) {
619 pages_[pageIndex] = std::make_unique<Page>();
620 std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_INDEX);
621 }
622 (*pages_[pageIndex])[offset] = static_cast<u32>(i);
623 }
624 }
625
626 // =========================================================================
627 // Iteration
628 // =========================================================================
629
634 Iterator begin() const { return dense_.begin(); }
635
640 Iterator end() const { return dense_.end(); }
641
646 const std::vector<Entity>& entities() const override { return dense_; }
647
648
657 std::vector<T>& components() { return components_; }
658
660 const std::vector<T>& components() const { return components_; }
661
669 usize indexOf(Entity entity) const {
670 // Release-safe: a non-member would otherwise return INVALID_INDEX and be
671 // used as a dense-array subscript (OOB). Compute the dense index once and
672 // verify membership; callers must treat INVALID_INDEX as "not present".
673 const u32 di = denseIndexOf(entity);
674 ES_VERIFY(di != INVALID_INDEX && dense_[di] == entity, return INVALID_INDEX);
675 return di;
676 }
677
678private:
680 static std::string missMessage(Entity entity) {
681 return "SparseSet::get on an entity without this component (entity "
682 + std::to_string(entity.index()) + ":" + std::to_string(entity.generation())
683 + "); use tryGet() when absence is expected";
684 }
685
690 u32 denseIndexOf(Entity entity) const {
691 const u32 idx = entity.index();
692 const auto pageIndex = idx / SPARSE_PAGE_SIZE;
693 const auto offset = idx % SPARSE_PAGE_SIZE;
694 if (pageIndex >= pages_.size() || !pages_[pageIndex]) return INVALID_INDEX;
695 return (*pages_[pageIndex])[offset];
696 }
697
698 // =========================================================================
699 // Data Members
700 // =========================================================================
701
708 std::vector<std::unique_ptr<Page>> pages_;
709
714 std::vector<Entity> dense_;
715
720 std::vector<T> components_;
721
723 std::vector<u32> changed_;
724
726 u32 last_changed_ = 0;
727
729 u32 version_ = 0;
730};
731
732} // namespace esengine::ecs
Entity utilities for the ECS system.
Logging utilities for ESEngine.
#define ES_VERIFY_FATAL(cond, message)
Always-on fatal guard for invariants with no safe recovery.
Definition Log.hpp:413
#define ES_VERIFY(cond,...)
Always-on boundary guard — the release-safe counterpart to ES_ASSERT.
Definition Log.hpp:389
Core type definitions and utilities for ESEngine.
Type-erased base class for sparse set operations.
Definition SparseSet.hpp:51
virtual ~SparseSetBase()=default
Virtual destructor for proper cleanup.
virtual u32 changedTickOf(Entity entity) const =0
The tick of entity's last write here, 0 where it has no component: the type-erased changedTick.
virtual u32 version() const =0
Monotonic version, bumped whenever stored components may have moved in memory (buffer reallocation on...
virtual void clampStamps(u32 floor)=0
Lifts every stamp older than floor to it, so a stamp never reads as newer after the tick wraps.
virtual u32 auditCompare(const AuditCopy &copy, void(*report)(void *user, Entity entity), void *user) const =0
Calls report for each entity whose component changed since copy without a stamp after copy....
virtual bool auditable() const =0
Whether this pool's components can be audited (see above).
virtual std::string_view typeName() const =0
The component type's name, for what the audit says.
virtual void clear()=0
Removes all components from the set.
virtual void reorderBy(const std::vector< u32 > &rank)=0
Permutes storage so iteration follows rank.
virtual usize size() const =0
Gets the number of components in the set.
virtual bool empty() const =0
Checks if the set is empty.
static std::vector< usize > stablePermutation(const std::vector< Entity > &dense, const std::vector< u32 > &rank)
Which current slot belongs at each position when dense is put in rank order (stable).
virtual void auditKeep(AuditCopy &copy, u32 tick) const =0
Keeps the pool's state as it is at tick.
virtual void remove(Entity entity)=0
Removes an entity's component from the set.
virtual void markChanged(Entity entity, u32 tick)=0
Stamps entity's component as written at tick (no-op where it has none): the type-erased markChanged.
virtual const std::vector< Entity > & entities() const =0
Gets the dense entity array for iteration.
virtual bool contains(Entity entity) const =0
Checks if an entity exists in the set.
virtual void noteStructural(u32 tick)=0
Notes an add or a remove at tick, which no stamp of a component that is still there records.
virtual u32 lastChangedTick() const =0
The tick of the last write to any component of this pool, or of the last add or remove: "anything sin...
static constexpr u32 UNRANKED
Rank for an entity the caller did not order — sorts last, stably.
bool contains(Entity entity) const override
Checks if an entity has a component in this set.
void reorderBy(const std::vector< u32 > &rank) override
Permutes storage so iteration follows rank.
const std::vector< Entity > & entities() const override
Gets the dense entity array.
SparseSet(SparseSet &&) noexcept=default
void clampStamps(u32 floor) override
Lifts every stamp older than floor to it, so a stamp never reads as newer after the tick wraps.
void remove(Entity entity) override
Removes a component from an entity.
T & getUnchecked(Entity entity)
void markChanged(Entity entity, u32 tick) override
Stamps entity's component with tick: it was written. No-op for an entity without one.
T * tryGet(Entity entity)
Tries to get a component (returns nullptr if not found).
u32 lastChangedTick() const override
The tick of the last write to any component of this pool, or of the last add or remove: "anything sin...
std::array< u32, SPARSE_PAGE_SIZE > Page
Page type: array of dense indices.
SparseSet()=default
Default constructor.
static constexpr bool kAuditBytes
SparseSet & operator=(const SparseSet &)=delete
Iterator begin() const
Returns iterator to the first entity.
static constexpr bool kAuditValues
bool empty() const override
Checks if the set is empty.
u32 * changeTicks()
The stamps, parallel to components(): where a writer that holds a component's place stamps it.
const T & get(Entity entity) const
Gets the component for an entity (must exist).
static constexpr usize SPARSE_PAGE_SIZE
Page size for paged sparse array (entities per page).
u32 * lastChangedSlot()
Where the pool's last-change tick lives, for a writer that stamps through changeTicks() to lift with ...
u32 changedTick(Entity entity) const
The tick of entity's last write, 0 when it has none here.
usize size() const override
Gets the number of components in the set.
const std::vector< T > & components() const
Gets the component array for direct iteration.
usize indexOf(Entity entity) const
Gets the dense array index for an entity.
void clear() override
Removes all components.
u32 changedTickOf(Entity entity) const override
The tick of entity's last write here, 0 where it has no component: the type-erased changedTick.
const T & getUnchecked(Entity entity) const
SparseSet(const SparseSet &)=delete
std::string_view typeName() const override
The component type's name, for what the audit says.
void noteStructural(u32 tick) override
Notes an add or a remove at tick, which no stamp of a component that is still there records.
u32 auditCompare(const AuditCopy &copy, void(*report)(void *, Entity), void *user) const override
Calls report for each entity whose component changed since copy without a stamp after copy....
bool auditable() const override
Whether this pool's components can be audited (see above).
std::vector< T > & components()
Gets the component array for direct iteration.
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
void permute(std::vector< usize > &perm)
Puts slot perm[i] at position i, for every i: the entity, its component and its stamp together.
static constexpr u32 INVALID_INDEX
Sentinel for empty sparse slots.
const T * tryGet(Entity entity) const
Tries to get a component (returns nullptr if not found).
const u32 * changeTicks() const
u32 version() const override
Monotonic version, bumped whenever stored components may have moved in memory (buffer reallocation on...
~SparseSet() override=default
Destructor.
T & get(Entity entity)
Gets the component for an entity (must exist).
Iterator end() const
Returns iterator past the last entity.
typename std::vector< Entity >::const_iterator Iterator
Iterator type for entity iteration.
void auditKeep(AuditCopy &copy, u32 tick) const override
Keeps the pool's state as it is at tick.
std::string_view componentTypeName()
T's name as the compiler spells it, without a namespace: what an audit report says.
bool tickAfter(u32 a, u32 b)
Whether stamp a is later than tick b, across a wrap of the counter (stamps are kept within half its r...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
constexpr u32 INVALID_DENSE_INDEX
Sentinel for empty sparse set slots.
Definition Types.hpp:177
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 generation() const
Gets the generation number.
Definition Types.hpp:153
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150
What the audit kept of a pool: its entities and their components' bytes, as they were at tick.
std::shared_ptr< void > values
otherwise a copy of the components, compared with ==
std::vector< u8 > bytes
a trivially copyable component's bytes