102 if (!
valid(e))
return false;
103 const u8 off = enabled ? 0 : 1;
104 if (disabled_[e.
index()] == off)
return true;
105 disabled_[e.
index()] = off;
106 if (off) ++disabled_count_;
else --disabled_count_;
116 if (!
valid(e))
return false;
117 if (disabled_count_ == 0)
return true;
119 return inactive_[e.
index()] == 0;
124 if (disabled_count_) ++activity_epoch_;
132 return entity_reset_epoch_ == RESET_EPOCH_LIMIT ? -1 :
static_cast<double>(entity_reset_epoch_);
135 return entity_changes_.componentRevision(component, topology);
138 return entity_changes_.read(after, output);
143 entity_changes_.record(entity.
id(), flags, component);
174 const u32 seen = change_tick_;
176 if (change_tick_ == 0) change_tick_ = 1;
177 if ((change_tick_ & ((1u << 20) - 1)) == 0) {
178 const u32 floor = change_tick_ - (1u << 30);
179 for (
auto& pool : pools_)
if (pool) pool->clampStamps(floor);
187 auto* pool = getPool<T>();
189 T& component = pool->get(entity);
190 pool->markChanged(entity, change_tick_);
197 if (
auto* pool = getPool<T>()) pool->markChanged(entity, change_tick_);
202 if (typeId < pools_.size() && pools_[typeId]) pools_[typeId]->markChanged(entity, change_tick_);
208 const auto* pool = getPool<T>();
209 return pool &&
tickAfter(pool->changedTick(entity), tick);
214 if (typeId >= pools_.size() || !pools_[typeId])
return false;
215 return tickAfter(pools_[typeId]->changedTickOf(entity), tick);
221 const auto* pool = getPool<T>();
222 return pool &&
tickAfter(pool->lastChangedTick(), tick);
231 template<
typename T,
typename Visit>
233 const auto* pool = getPool<T>();
234 if (!pool || !
tickAfter(pool->lastChangedTick(), tick))
return false;
235 const u32* stamps = pool->changeTicks();
236 const auto& entities = pool->entities();
237 for (
usize i = 0, n = entities.size(); i < n; ++i) {
238 if (
tickAfter(stamps[i], tick) && visit(entities[i]))
return true;
247 template<
typename Visit>
249 for (
const auto& pool : pools_) {
250 if (!pool || !
tickAfter(pool->lastChangedTick(), tick))
continue;
251 for (
const Entity entity : pool->entities()) {
252 if (
tickAfter(pool->changedTickOf(entity), tick) && visit(entity))
return true;
261 const auto* pool = getPool<T>();
262 return pool ? pool->version() : 0;
270 template<
typename T,
typename Visit>
272 auto* pool = getPool<T>();
273 if (!pool || !
tickAfter(pool->lastChangedTick(), tick))
return;
274 const u32* stamps = pool->changeTicks();
275 const auto& entities = pool->entities();
276 auto& components = pool->components();
277 for (
usize i = 0, n = entities.size(); i < n; ++i) {
278 if (
tickAfter(stamps[i], tick)) visit(entities[i], components[i]);
285 const auto* pool = getPool<T>();
286 return pool ? pool->size() : 0;
292 const auto* pool = getPool<T>();
293 return pool ? pool->lastChangedTick() : 0;
302 change_audit_ = enabled;
303 audit_copies_.clear();
304 audit_reported_.clear();
315 if (!change_audit_)
return 0;
317 if (audit_copies_.size() < pools_.size()) audit_copies_.resize(pools_.size());
318 if (audit_reported_.size() < pools_.size()) audit_reported_.resize(pools_.size(), 0);
319 for (
usize id = 0;
id < pools_.size(); ++id) {
320 const auto& pool = pools_[id];
322 if (!pool->auditable()) {
323 if (!audit_reported_[
id]) {
324 audit_reported_[id] = 2;
325 ES_LOG_INFO(
"change audit: {} can be neither copied as bytes nor compared with ==, and is not checked", std::string(pool->typeName()));
329 auto& copy = audit_copies_[id];
330 if (!copy.entities.empty() || copy.tick != 0) {
333 const u32 here = pool->auditCompare(copy, [](
void* user,
Entity entity) {
334 auto* s =
static_cast<Sink*
>(user);
337 if (here && audit_reported_[
id] != 1) {
338 audit_reported_[id] = 1;
339 ES_LOG_WARN(
"change audit: {} was written without a stamp (entity {}, {} this frame) - a consumer of changes "
340 "will not see it", std::string(pool->typeName()),
sink.first.index(), here);
343 audit_unstamped_total_ += here;
345 pool->auditKeep(copy, change_tick_);
373 while (!recycled_.empty()) {
374 index = recycled_.front();
376 if (index < entityValid_.size() && entityValid_[index]) {
379 return activateIndex(index);
381 index = next_index_++;
382 return activateIndex(index);
391 std::vector<Entity> entities;
392 entities.reserve(count);
393 for (
usize i = 0; i < count; ++i) {
394 entities.push_back(
create());
410 if (index < entityValid_.size() && entityValid_[index]) {
414 if (index >= next_index_) {
415 next_index_ = index + 1;
418 return activateIndex(index);
424 if (!
valid(entity) || destruction_pending_[entity.
index()])
return false;
425 destruction_pending_[entity.
index()] = 1;
432 if (index < destruction_pending_.size() && generations_[index] == entity.
generation()) {
433 destruction_pending_[index] = 0;
438 return index < destruction_pending_.size() && destruction_pending_[index]
439 && generations_[index] == entity.
generation();
450 if (!
valid(entity))
return;
452 if (entity_changes_.readerCount()) {
463 entityValid_[idx] =
false;
464 const bool hadDisabled = disabled_count_ != 0;
465 if (disabled_[idx]) { disabled_[idx] = 0; --disabled_count_; }
466 if (hadDisabled) ++activity_epoch_;
471 on_destroy_signal_.publish(entity);
475 child_of_.onDestroy(entity);
477 component_masks_[idx].forEachSet([&](
u32 bit) {
478 if (bit < pools_.size() && pools_[bit]) {
479 pools_[bit]->remove(entity);
480 pools_[bit]->noteStructural(change_tick_);
484 component_masks_[idx].reset();
493 ES_LOG_TRACE(
"Retired entity slot {} (generation exhausted)", idx);
510 return sink(on_destroy_signal_).connect(std::move(callback));
520 return idx < entityValid_.size() &&
526 return entity_count_;
551 template<
typename Func>
553 for (
u32 i = 0; i < entityValid_.size(); ++i) {
554 if (entityValid_[i]) {
575 template<
typename T,
typename... Args>
580 auto& pool = assurePool<T>();
581 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
583 pool.markChanged(entity, change_tick_);
584 recordComponentChange<T>(entity);
598 template<
typename T,
typename... Args>
601 auto& pool = assurePool<T>();
603 if (pool.contains(entity)) {
604 auto& comp = pool.get(entity);
605 comp = T(std::forward<Args>(args)...);
606 pool.markChanged(entity, change_tick_);
610 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
612 pool.markChanged(entity, change_tick_);
613 recordComponentChange<T>(entity);
626 auto* pool = getPool<T>();
627 if (pool && pool->contains(entity)) {
628 pool->remove(entity);
629 pool->noteStructural(change_tick_);
630 recordComponentChange<T>(entity);
632 if (idx < component_masks_.size()) {
650 auto* pool = getPool<T>();
652 return pool->get(entity);
658 auto* pool = getPool<T>();
660 return pool->get(entity);
671 auto* pool = getPool<T>();
672 return pool ? pool->tryGet(entity) :
nullptr;
678 auto* pool = getPool<T>();
679 return pool ? pool->tryGet(entity) :
nullptr;
690 template<
typename T,
typename... Args>
692 auto& pool = assurePool<T>();
693 if (pool.contains(entity)) {
694 return pool.get(entity);
697 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
699 pool.markChanged(entity, change_tick_);
700 recordComponentChange<T>(entity);
712 auto* pool = getPool<T>();
713 return pool && pool->contains(entity);
722 template<
typename... Ts>
724 return (
has<Ts>(entity) && ...);
733 template<
typename... Ts>
735 return (
has<Ts>(entity) || ...);
760 template<
typename... Components>
762 if constexpr (
sizeof...(Components) == 1) {
763 return View<Components...>(&assurePool<Components...>());
765 return View<Components...>(
766 std::make_tuple(&assurePool<Components>()...));
779 if (entity_reset_epoch_ < RESET_EPOCH_LIMIT) ++entity_reset_epoch_;
781 for (
auto& pool : pools_) {
786 entityValid_.clear();
790 activity_state_.clear();
793 generations_.clear();
794 component_masks_.clear();
795 while (!recycled_.empty()) recycled_.pop();
819 if (!order || count == 0)
return;
833 if (!order)
return rank;
835 for (
usize i = 0; i < count; ++i) {
837 if (idx >= rank.size())
continue;
839 rank[idx] = nextRank++;
855 for (
const auto& pool : pools_) {
856 if (pool) sum += pool->version();
858 return static_cast<double>(sum);
863 for (
auto& pool : pools_) {
864 if (pool) pool->reorderBy(rank);
880 template<
typename... Components,
typename Func>
882 view<Components...>().
each(std::forward<Func>(func));
889 template<
typename... Components,
typename Func>
891 view<Components...>().
eachLive(std::forward<Func>(func));
903 template<
typename T,
typename Compare>
905 auto* pool = getPool<T>();
908 const auto& components = pool->components();
909 const usize n = components.size();
912 std::vector<usize> perm(n);
913 for (
usize i = 0; i < n; ++i) perm[i] = i;
915 std::sort(perm.begin(), perm.end(), [&](
usize a,
usize b) {
916 return compare(components[a], components[b]);
932 const auto* pool = getPool<T>();
933 if (pool ==
nullptr)
return {};
934 const std::vector<Entity>& dense = pool->entities();
935 return std::span<const Entity>(dense.data(), dense.size());
941 static inline std::atomic<u64> next_instance_id_{0};
942 u64 instance_id_{++next_instance_id_};
954 SparseSet<T>& assurePool() {
956 if (typeId >= pools_.size()) {
957 pools_.resize(typeId + 1);
959 if (!pools_[typeId]) {
962 return *
static_cast<SparseSet<T>*
>(pools_[typeId].get());
971 SparseSet<T>* getPool() {
973 if (typeId >= pools_.size() || !pools_[typeId])
return nullptr;
974 return static_cast<SparseSet<T>*
>(pools_[typeId].get());
978 const SparseSet<T>* getPool()
const {
980 if (typeId >= pools_.size() || !pools_[typeId])
return nullptr;
981 return static_cast<const SparseSet<T>*
>(pools_[typeId].get());
985 static std::string noPoolMessage(Entity entity) {
986 return "Registry::get: no pool for this component type (entity "
987 + std::to_string(entity.index()) +
":" + std::to_string(entity.generation())
988 +
"); use tryGet() when absence is expected";
990 static std::string invalidEntityMessage(
const char* op, Entity entity) {
991 return std::string(
"Registry::") + op +
" on an invalid entity ("
992 + std::to_string(entity.index()) +
":" + std::to_string(entity.generation()) +
")";
998 Entity activateIndex(
u32 index) {
1006 ES_LOG_ERROR(
"Registry: entity index space exhausted ({} slots, {} retired to "
1007 "generation wrap); create() returns an invalid entity from here on",
1011 if (index >= entityValid_.size()) {
1012 entityValid_.resize(index + 1,
false);
1013 disabled_.resize(index + 1, 0);
1014 destruction_pending_.resize(index + 1, 0);
1015 generations_.resize(index + 1, 0);
1016 component_masks_.resize(index + 1);
1018 entityValid_[index] =
true;
1019 disabled_[index] = 0;
1020 destruction_pending_[index] = 0;
1021 if (disabled_count_) ++activity_epoch_;
1023 if (generations_[index] == 0) generations_[index] = 1;
1024 component_masks_[index].reset();
1026 const auto entity =
Entity::make(index, generations_[index]);
1035 std::vector<u8> entityValid_;
1036 ExclusiveRelation child_of_;
1037 EntityChangeJournal entity_changes_;
1038 static constexpr u64 RESET_EPOCH_LIMIT = (
u64{1} << 53) - 1;
1039 u64 entity_reset_epoch_ = 0;
1041 template<
typename T>
1042 void recordComponentChange(Entity entity,
u32 flags = 0) {
1044 if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) {
1045 if (disabled_count_) ++activity_epoch_;
1049 std::vector<u8> disabled_;
1050 usize disabled_count_ = 0;
1051 u32 activity_epoch_ = 1;
1052 mutable u32 resolved_activity_epoch_ = 0;
1053 mutable u32 resolved_child_of_epoch_ = 0;
1054 mutable std::vector<u8> inactive_, activity_state_;
1055 mutable std::vector<u32> activity_path_;
1057 void ensureActivity()
const {
1059 if (resolved_activity_epoch_ == activity_epoch_ && resolved_child_of_epoch_ == child_of_.epoch())
return;
1060 inactive_.assign(entityValid_.size(), 0);
1061 activity_state_.assign(entityValid_.size(), 0);
1064 for (
usize start = 0; start < entityValid_.size(); ++start) {
1065 if (!entityValid_[start] || activity_state_[start] == 2)
continue;
1066 activity_path_.clear();
1067 u32 at =
static_cast<u32>(start);
1070 if (activity_state_[at] == 2) { off = inactive_[at] != 0;
break; }
1071 if (activity_state_[at] == 1) { off =
true;
break; }
1072 activity_state_[at] = 1;
1073 activity_path_.push_back(at);
1074 if (disabled_[at]) { off =
true;
break; }
1075 const Entity parent = child_of_.target(
Entity::make(at, generations_[at]));
1076 if (!parent.isValid())
break;
1077 at = parent.index();
1079 for (
u32 index : activity_path_) {
1080 inactive_[index] = off ? 1 : 0;
1081 activity_state_[index] = 2;
1084 resolved_activity_epoch_ = activity_epoch_;
1085 resolved_child_of_epoch_ = child_of_.epoch();
1087 std::vector<u32> generations_;
1088 std::vector<ComponentMask> component_masks_;
1089 std::queue<u32> recycled_;
1093 u32 retired_slots_ = 0;
1094 u32 next_index_ = 0;
1095 usize entity_count_ = 0;
1098 std::vector<Unique<SparseSetBase>> pools_;
1101 u32 change_tick_ = 1;
1104 bool change_audit_ =
false;
1105 std::vector<SparseSetBase::AuditCopy> audit_copies_;
1106 std::vector<u8> audit_reported_;
1107 u32 audit_unstamped_total_ = 0;
1109 Signal<void(Entity)> on_destroy_signal_;
1113 std::vector<u8> destruction_pending_;
Dynamic bitset for tracking entity component membership.
Entity utilities for the ECS system.
Hierarchy components for parent-child relationships.
Logging utilities for ESEngine.
#define ES_VERIFY_FATAL(cond, message)
Always-on fatal guard for invariants with no safe recovery.
#define ES_LOG_TRACE(...)
#define ES_VERIFY(cond,...)
Always-on boundary guard — the release-safe counterpart to ES_ASSERT.
#define ES_LOG_WARN(...)
Logs a warning message.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_INFO(...)
Logs an info message.
A relationship between entities, stored as one: (Relation, target) pairs in the manner of Flecs.
What a resource's content is, as a number that changes whenever it does.
Connection interface for signals.
Sparse set data structure for efficient ECS component storage.
Core type definitions and utilities for ESEngine.
ECS View for querying entities with specific components.
RAII handle for signal connections.
u32 changeAuditTotal() const
Unstamped writes the audit has found since it was turned on.
bool isEntityActive(Entity e) const
u32 lastChangedTick() const
The tick of the latest write, addition or removal of any T; 0 when there has been none.
const T * tryGet(Entity entity) const
Tries to get a component from an entity.
T & getOrEmplace(Entity entity, Args &&... args)
Gets an existing component or creates a new one.
ExclusiveRelation & childOf()
double entityChangeResetEpoch() const
double entityChangeSequence() const
bool reserveDestruction(Entity entity)
void eachChangedSince(u32 tick, Visit &&visit)
Calls visit(entity, component) for each T written, added or replaced after tick, in storage order.
std::function< void(Entity)> DestroyCallback
void releaseDestruction(Entity entity)
bool anyChangedSince(u32 tick) const
Whether any T was written, added or removed after tick: the question a frame that may skip its walk a...
void unwatchEntityChanges(u32 reader)
void eachLive(Func &&func)
each() without the per-call snapshot copy, for read-only passes.
u32 activityEpoch() const
Registry(Registry &&) noexcept=default
bool changedSinceById(u32 typeId, Entity entity, u32 tick) const
changedSince by a component type id (componentTypeId), for a reader that names the type at run time.
T & get(Entity entity)
Gets a component from an entity (must exist).
usize countOf() const
How many entities have a T.
void each(Func &&func)
Executes a function for each entity with specified components.
u32 poolVersion() const
T's pool version: moves when a T is removed or the pool's storage moves (SparseSetBase::version)....
bool isEntityEnabled(Entity e) const
void invalidateActivityHierarchy(Entity root=INVALID_ENTITY)
bool anyChangedSinceWhere(u32 tick, Visit &&visit) const
Calls visit(entity) for each T written or added after tick, until it returns true; returns whether on...
const ExclusiveRelation & childOf() const
The (ChildOf, parent) relation: each entity's parent, and each parent's children in order.
Registry(const Registry &)=delete
bool hasAny(Entity entity) const
Checks if an entity has any of the specified components.
std::span< const Entity > entitiesWith() const
The entities that carry T, densely.
std::vector< u32 > buildEntityRank(const Entity *order, usize count) const
Rank table (by Entity::index()) for an ordered entity list.
bool has(Entity entity) const
Checks if an entity has a specific component.
bool hasInactiveEntities() const
double componentMutationRevision(u32 component, bool topology) const
void applyEntityOrder(const Entity *order, usize count)
Reorders every component pool to follow the given entity order.
Registry & operator=(const Registry &)=delete
u32 beginChangeRead()
For a reader about to look: the tick it is looking at, after which the clock moves on.
void markChangedById(u32 typeId, Entity entity)
markChanged by a component type id (componentTypeId): for a writer that names the type at run time,...
const T & get(Entity entity) const
Gets a component from an entity (must exist).
Connection onDestroy(DestroyCallback callback)
Subscribe to entity destruction.
usize entityCount() const
u32 changeTick() const
The tick a write made now is stamped with.
bool anyComponentChangedSinceWhere(u32 tick, Visit &&visit) const
anyChangedSinceWhere over every component type: calls visit(entity) for each component written or add...
bool setEntityEnabled(Entity e, bool enabled)
void markChanged(Entity entity)
Says entity's T was written, through a reference held from before.
bool changedSince(Entity entity, u32 tick) const
Whether entity's T was written, added or replaced after tick (an answer of beginChangeRead).
bool valid(Entity entity) const
Checks if an entity is currently valid.
void remove(Entity entity)
Removes a component from an entity.
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
void destroy(Entity entity)
Destroys an entity and removes all its components.
bool changeAuditEnabled() const
void clear()
Clears all entities and components.
i32 readEntityChanges(double after, std::span< EntityChangeRow > output) const
T & emplaceOrReplace(Entity entity, Args &&... args)
Adds or replaces a component on an entity.
void applyEntityRank(const std::vector< u32 > &rank)
Reorders every component pool by a rank table from buildEntityRank.
void forEachEntity(Func &&func) const
Executes a function for each valid entity.
Entity create()
Creates a new entity.
u64 instanceId() const
Which registry this is — unique for the process, never reused.
u32 auditChanges()
Compares, reports, and keeps a new copy.
T & patch(Entity entity)
Mutable access that says it writes: entity's T, stamped. Fatal where it has none, as get<T>() is.
T * tryGet(Entity entity)
Tries to get a component from an entity.
double layoutEpoch() const
Sum of every pool's version — one number for "did anything move".
void setChangeAudit(bool enabled)
Turns the change audit on or off. On, auditChanges() compares every auditable component with the copy...
void sort(Compare compare)
Sorts components by a comparison function.
Entity restore(u32 index)
Restores an entity at a specific index.
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
bool destructionPending(Entity entity) const
u32 retiredSlots() const
Slots permanently out of circulation, their generation spent.
bool hasAll(Entity entity) const
Checks if an entity has all specified components.
void recordEntityChange(Entity entity, u32 flags=0, u32 component=ENTITY_CHANGE_NO_COMPONENT)
View< Components... > view()
Creates a view for iterating entities with specific components.
std::vector< Entity > create(usize count)
Creates multiple entities at once.
static constexpr u32 UNRANKED
Rank for an entity the caller did not order — sorts last, stably.
View for iterating entities with multiple required components.
static constexpr u32 ENTITY_CHANGE_SUBTREE
static constexpr u32 ENTITY_CHANGE_REPLACED
static constexpr u32 ENTITY_CHANGE_RESET
static constexpr u32 ENTITY_CHANGE_NO_COMPONENT
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...
void invalidateTransformComposition()
Say that composed world transforms are stale.
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
std::int32_t i32
Signed 32-bit integer.
TypeId componentTypeId()
Dense 0-based runtime id for a component type (ECS pool index + mask bit).
std::uint64_t u64
Unsigned 64-bit integer.
std::size_t usize
Size type for indexing and sizes.
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
std::uint32_t u32
Unsigned 32-bit integer.
std::uint8_t u8
Unsigned 8-bit integer.
u32 TypeId
Runtime type identifier.
u64 nextRevision()
A revision no content has had before. Never 0, which reads as "none".
auto sink(SignalType &signal)
Create a sink for a signal.
Entity identifier with packed index + generation.
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
static constexpr u32 GEN_MASK
static constexpr Entity make(u32 idx, u32 gen)
Creates an Entity from index and generation.
static constexpr u32 INDEX_MASK
constexpr u32 generation() const
Gets the generation number.
constexpr u32 index() const
Gets the entity index.