90 virtual const std::vector<Entity>&
entities()
const = 0;
116 virtual void reorderBy(
const std::vector<u32>& rank) = 0;
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;
174 std::stable_sort(perm.begin(), perm.end(), [&](
usize a,
usize b) { return rankOf(a) < rankOf(b); });
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)";
187 constexpr std::string_view full = __PRETTY_FUNCTION__;
188 constexpr std::string_view open =
"T = ";
189 constexpr std::string_view close =
"]";
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);
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());
207 return static_cast<i32>(a - b) > 0;
259 using Iterator =
typename std::vector<Entity>::const_iterator;
268 using Page = std::array<u32, SPARSE_PAGE_SIZE>;
295 u32 di = denseIndexOf(entity);
309 const u32 di = denseIndexOf(entity);
311 return components_[di];
316 const u32 di = denseIndexOf(entity);
318 return components_[di];
322 return components_[denseIndexOf(entity)];
326 return components_[denseIndexOf(entity)];
335 u32 di = denseIndexOf(entity);
336 if (di ==
INVALID_INDEX || dense_[di] != entity)
return nullptr;
337 return &components_[di];
342 u32 di = denseIndexOf(entity);
343 if (di ==
INVALID_INDEX || dense_[di] != entity)
return nullptr;
344 return &components_[di];
353 const u32 di = denseIndexOf(entity);
354 return di !=
INVALID_INDEX && dense_[di] == entity ? changed_[di] : 0;
361 const u32 di = denseIndexOf(entity);
364 if (
tickAfter(tick, last_changed_)) last_changed_ = tick;
376 if (
tickAfter(tick, last_changed_)) last_changed_ = tick;
379 for (
u32& t : changed_)
if (
tickAfter(floor, t)) t = floor;
380 if (
tickAfter(floor, last_changed_)) last_changed_ = floor;
384 static constexpr bool kAuditBytes = std::is_trivially_copyable_v<T>;
393 copy.
bytes.resize(components_.size() *
sizeof(T));
394 if (!components_.empty()) std::memcpy(copy.
bytes.data(), components_.data(), copy.
bytes.size());
396 copy.
values = std::make_shared<std::vector<T>>(components_);
403 const auto* values =
kAuditValues ?
static_cast<const std::vector<T>*
>(copy.
values.get()) :
nullptr;
408 const u32 di = denseIndexOf(entity);
412 if constexpr (
requires(
const T& now,
const T& kept) { { now.auditSame(kept) } -> std::convertible_to<bool>; }) {
415 ? components_[di].auditSame(*
reinterpret_cast<const T*
>(copy.
bytes.data() + k *
sizeof(T)))
416 : components_[di].auditSame((*values)[k]);
418 same = std::memcmp(&components_[di], copy.
bytes.data() + k *
sizeof(T),
sizeof(T)) == 0;
420 same = components_[di] == (*values)[k];
424 if (report) report(user, entity);
447 template<
typename... Args>
458 if (pageIndex >= pages_.size()) {
459 pages_.resize(pageIndex + 1);
462 if (!pages_[pageIndex]) {
463 pages_[pageIndex] = std::make_unique<Page>();
467 (*pages_[pageIndex])[offset] =
static_cast<u32>(dense_.size());
468 dense_.push_back(entity);
474 const T* before = components_.data();
475 const u32* stampsBefore = changed_.data();
476 components_.emplace_back(std::forward<Args>(args)...);
478 changed_.push_back(0);
479 if (components_.data() != before || changed_.data() != stampsBefore) ++version_;
481 return components_.back();
502 const u32 denseIdx = (*pages_[pageIndex])[offset];
504 if (denseIdx ==
static_cast<u32>(dense_.size()) - 1) {
506 components_.pop_back();
512 const Entity last = dense_.back();
514 dense_[denseIdx] = last;
515 components_[denseIdx] = std::move(components_.back());
516 changed_[denseIdx] = changed_.back();
523 components_.pop_back();
541 bool empty()
const override {
return dense_.empty(); }
559 const usize n = dense_.size();
576 const usize n = dense_.size();
578 for (
usize i = 0; i < n; ++i) {
579 if (perm[i] != i) { moved =
true;
break; }
584 for (
usize i = 0; i < n; ++i) {
585 if (perm[i] == i)
continue;
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];
598 dense_[j] = std::move(tmpEntity);
599 components_[j] = std::move(tmpComponent);
600 changed_[j] = tmpStamp;
611 for (
usize i = 0; i < dense_.size(); ++i) {
612 const u32 idx = dense_[i].index();
615 if (pageIndex >= pages_.size()) {
616 pages_.resize(pageIndex + 1);
618 if (!pages_[pageIndex]) {
619 pages_[pageIndex] = std::make_unique<Page>();
622 (*pages_[pageIndex])[offset] =
static_cast<u32>(i);
646 const std::vector<Entity>&
entities()
const override {
return dense_; }
660 const std::vector<T>&
components()
const {
return components_; }
673 const u32 di = denseIndexOf(entity);
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";
694 if (pageIndex >= pages_.size() || !pages_[pageIndex])
return INVALID_INDEX;
695 return (*pages_[pageIndex])[offset];
708 std::vector<std::unique_ptr<Page>> pages_;
714 std::vector<Entity> dense_;
720 std::vector<T> components_;
723 std::vector<u32> changed_;
726 u32 last_changed_ = 0;
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.
#define ES_VERIFY(cond,...)
Always-on boundary guard — the release-safe counterpart to ES_ASSERT.
Core type definitions and utilities for ESEngine.
Type-erased base class for sparse set operations.
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 ©, 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 ©, 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 ©, 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 ©, 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.
constexpr u32 INVALID_DENSE_INDEX
Sentinel for empty sparse set slots.
std::size_t usize
Size type for indexing and sizes.
std::uint32_t u32
Unsigned 32-bit integer.
Entity identifier with packed index + generation.
constexpr u32 generation() const
Gets the generation number.
constexpr u32 index() const
Gets the entity index.
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
std::vector< Entity > entities