Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Registry.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/Revision.hpp"
25#include "../core/Types.hpp"
26#include "ComponentMask.hpp"
27#include "Entity.hpp"
28#include "SparseSet.hpp"
29#include "View.hpp"
30#include "ActiveView.hpp"
32#include "Relation.hpp"
33#include "TransformEpoch.hpp"
35#include "../events/Sink.hpp"
36
37// Standard library
38#include <algorithm>
39#include <any>
40#include <functional>
41#include <queue>
42#include <span>
43#include <string>
44
45namespace esengine::ecs {
46
47// =============================================================================
48// Registry Class
49// =============================================================================
50
73class Registry {
74public:
75 Registry() = default;
76 ~Registry() = default;
77
78 // Non-copyable, movable
79 Registry(const Registry&) = delete;
80 Registry& operator=(const Registry&) = delete;
81 Registry(Registry&&) noexcept = default;
82 Registry& operator=(Registry&&) noexcept = default;
83
96 u64 instanceId() const { return instance_id_; }
97
98 // Local authoring state is distinct from effective activity. Disabling a
99 // parent never overwrites a child's own switch. All engine consumers share
100 // this derived answer, including JS queries through the registry binding.
101 bool setEntityEnabled(Entity e, bool enabled) {
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_;
107 ++activity_epoch_;
109 return true;
110 }
111 bool isEntityEnabled(Entity e) const {
112 return valid(e) && disabled_[e.index()] == 0;
113 }
114
115 bool isEntityActive(Entity e) const {
116 if (!valid(e)) return false;
117 if (disabled_count_ == 0) return true;
118 ensureActivity();
119 return inactive_[e.index()] == 0;
120 }
121 bool hasInactiveEntities() const { return disabled_count_ != 0; }
122 u32 activityEpoch() const { return activity_epoch_; }
124 if (disabled_count_) ++activity_epoch_;
126 }
127
128 u32 watchEntityChanges() { return entity_changes_.watch(); }
129 void unwatchEntityChanges(u32 reader) { entity_changes_.unwatch(reader); }
130 double entityChangeSequence() const { return entity_changes_.sequence(); }
131 double entityChangeResetEpoch() const {
132 return entity_reset_epoch_ == RESET_EPOCH_LIMIT ? -1 : static_cast<double>(entity_reset_epoch_);
133 }
134 double componentMutationRevision(u32 component, bool topology) const {
135 return entity_changes_.componentRevision(component, topology);
136 }
137 i32 readEntityChanges(double after, std::span<EntityChangeRow> output) const {
138 return entity_changes_.read(after, output);
139 }
140 // Raw component producers publish their logical mutation here; merely
141 // borrowing a mutable reference does not announce a write.
142 void recordEntityChange(Entity entity, u32 flags = 0, u32 component = ENTITY_CHANGE_NO_COMPONENT) {
143 entity_changes_.record(entity.id(), flags, component);
144 }
145
146 // =========================================================================
147 // Change Detection
148 // =========================================================================
149 //
150 // Every component carries the tick of its last write. A write stamps the tick that is current; a reader asks
151 // beginChangeRead(), which hands back the tick it read at and moves the clock on, and next time takes as changed whatever is
152 // stamped after that. A write made after a reader looked is stamped later than what it read at, so it is seen the next time,
153 // whichever frame it happened in.
154 //
155 // What writes says so: patch<T>() (a mutable reference that stamps), markChanged<T>() (after writing through a reference
156 // already held), add, replace and remove. get<T>() announces nothing; setChangeAudit() reports what changed without saying.
157
159 u32 changeTick() const { return change_tick_; }
160
166 u64 identity() const { return identity_; }
167
174 const u32 seen = change_tick_;
175 ++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);
180 }
181 return seen;
182 }
183
185 template<typename T>
186 T& patch(Entity entity) {
187 auto* pool = getPool<T>();
188 ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));
189 T& component = pool->get(entity);
190 pool->markChanged(entity, change_tick_);
191 return component;
192 }
193
195 template<typename T>
196 void markChanged(Entity entity) {
197 if (auto* pool = getPool<T>()) pool->markChanged(entity, change_tick_);
198 }
199
201 void markChangedById(u32 typeId, Entity entity) {
202 if (typeId < pools_.size() && pools_[typeId]) pools_[typeId]->markChanged(entity, change_tick_);
203 }
204
206 template<typename T>
207 bool changedSince(Entity entity, u32 tick) const {
208 const auto* pool = getPool<T>();
209 return pool && tickAfter(pool->changedTick(entity), tick);
210 }
211
213 bool changedSinceById(u32 typeId, Entity entity, u32 tick) const {
214 if (typeId >= pools_.size() || !pools_[typeId]) return false;
215 return tickAfter(pools_[typeId]->changedTickOf(entity), tick);
216 }
217
219 template<typename T>
220 bool anyChangedSince(u32 tick) const {
221 const auto* pool = getPool<T>();
222 return pool && tickAfter(pool->lastChangedTick(), tick);
223 }
224
231 template<typename T, typename Visit>
232 bool anyChangedSinceWhere(u32 tick, Visit&& visit) const {
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;
239 }
240 return false;
241 }
242
247 template<typename Visit>
248 bool anyComponentChangedSinceWhere(u32 tick, Visit&& visit) const {
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;
253 }
254 }
255 return false;
256 }
257
259 template<typename T>
260 u32 poolVersion() const {
261 const auto* pool = getPool<T>();
262 return pool ? pool->version() : 0;
263 }
264
270 template<typename T, typename Visit>
271 void eachChangedSince(u32 tick, Visit&& 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]);
279 }
280 }
281
283 template<typename T>
284 usize countOf() const {
285 const auto* pool = getPool<T>();
286 return pool ? pool->size() : 0;
287 }
288
290 template<typename T>
292 const auto* pool = getPool<T>();
293 return pool ? pool->lastChangedTick() : 0;
294 }
295
301 void setChangeAudit(bool enabled) {
302 change_audit_ = enabled;
303 audit_copies_.clear();
304 audit_reported_.clear();
305 if (enabled) auditChanges();
306 }
307 bool changeAuditEnabled() const { return change_audit_; }
308
315 if (!change_audit_) return 0;
316 u32 found = 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];
321 if (!pool) continue;
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()));
326 }
327 continue;
328 }
329 auto& copy = audit_copies_[id];
330 if (!copy.entities.empty() || copy.tick != 0) {
331 struct Sink { Registry* self; usize id; Entity first = INVALID_ENTITY; };
332 Sink sink{this, id};
333 const u32 here = pool->auditCompare(copy, [](void* user, Entity entity) {
334 auto* s = static_cast<Sink*>(user);
335 if (s->first == INVALID_ENTITY) s->first = entity;
336 }, &sink);
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);
341 }
342 found += here;
343 audit_unstamped_total_ += here;
344 }
345 pool->auditKeep(copy, change_tick_);
346 }
347 // The copies were taken at this tick: a write from here on has to be stamped later than it to count as said.
349 return found;
350 }
351
353 u32 changeAuditTotal() const { return audit_unstamped_total_; }
354
355 template<class... C> auto activeView() {
356 return ActiveView<View<C...>, Registry>(view<C...>(), *this);
357 }
358
359 // =========================================================================
360 // Entity Management
361 // =========================================================================
362
372 u32 index;
373 while (!recycled_.empty()) {
374 index = recycled_.front();
375 recycled_.pop();
376 if (index < entityValid_.size() && entityValid_[index]) {
377 continue;
378 }
379 return activateIndex(index);
380 }
381 index = next_index_++;
382 return activateIndex(index);
383 }
384
390 std::vector<Entity> create(usize count) {
391 std::vector<Entity> entities;
392 entities.reserve(count);
393 for (usize i = 0; i < count; ++i) {
394 entities.push_back(create());
395 }
396 return entities;
397 }
398
405 // Release-safe: reject a deserialized index beyond the addressable range
406 // up front, before mutating next_index_ below (activateIndex would also
407 // refuse, but only after next_index_ was already advanced, leaving the
408 // registry unable to allocate fresh indices).
410 if (index < entityValid_.size() && entityValid_[index]) {
411 return INVALID_ENTITY;
412 }
413
414 if (index >= next_index_) {
415 next_index_ = index + 1;
416 }
417
418 return activateIndex(index);
419 }
420
424 if (!valid(entity) || destruction_pending_[entity.index()]) return false;
425 destruction_pending_[entity.index()] = 1;
426 return true;
427 }
429 const u32 index = entity.index();
430 // An old owner's finalizer can run after this slot was recycled and
431 // reserved by a new owner. Only its original generation may clear it.
432 if (index < destruction_pending_.size() && generations_[index] == entity.generation()) {
433 destruction_pending_[index] = 0;
434 }
435 }
436 bool destructionPending(Entity entity) const {
437 const u32 index = entity.index();
438 return index < destruction_pending_.size() && destruction_pending_[index]
439 && generations_[index] == entity.generation();
440 }
441
449 void destroy(Entity entity) {
450 if (!valid(entity)) return;
451
452 if (entity_changes_.readerCount()) {
453 recordEntityChange(entity);
454 child_of_.eachSource(entity, [this](Entity child) { recordEntityChange(child, ENTITY_CHANGE_SUBTREE); });
455 }
456
457 const u32 idx = entity.index();
458
459 // Mark invalid up-front so a re-entrant destroy(entity) from an onDestroy
460 // callback short-circuits at valid() above. Otherwise the teardown below
461 // runs twice: entity_count_ underflows and idx is pushed onto recycled_
462 // twice, later aliasing two distinct entities to the same index.
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_;
467
468 // Signal handles re-entrant connect/disconnect during publish; its RAII
469 // Connection (via Sink::connect) keeps subscriber lifetimes safe in both
470 // teardown orders — Registry-first or system-first (RC12, fixes A12).
471 on_destroy_signal_.publish(entity);
472 // After the callbacks, which may still ask where the entity stood; before the slot can be handed to anyone else. Children
473 // it leaves behind are roots now, composed under no parent: their world transforms are stale.
474 if (child_of_.hasSources(entity)) invalidateTransformComposition();
475 child_of_.onDestroy(entity);
476
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_);
481 }
482 });
483
484 component_masks_[idx].reset();
485 --entity_count_;
486 // A slot on its last generation is RETIRED, not recycled: reusing it wraps
487 // the counter to 1 and mints an id this slot already issued, which a caller
488 // may hold and valid() would confirm. Costs index space, only where it aliases.
489 if (generations_[idx] < Entity::GEN_MASK) {
490 recycled_.push(idx);
491 } else {
492 ++retired_slots_;
493 ES_LOG_TRACE("Retired entity slot {} (generation exhausted)", idx);
494 }
495
496 ES_LOG_TRACE("Destroyed entity raw={} (index={})", entity.raw, idx);
497 }
498
499 using DestroyCallback = std::function<void(Entity)>;
500
509 [[nodiscard]] Connection onDestroy(DestroyCallback callback) {
510 return sink(on_destroy_signal_).connect(std::move(callback));
511 }
512
518 bool valid(Entity entity) const {
519 const u32 idx = entity.index();
520 return idx < entityValid_.size() &&
521 entityValid_[idx] &&
522 generations_[idx] == entity.generation();
523 }
524
526 return entity_count_;
527 }
528
534 const ExclusiveRelation& childOf() const { return child_of_; }
535 ExclusiveRelation& childOf() { return child_of_; }
536
544 u32 retiredSlots() const { return retired_slots_; }
545
551 template<typename Func>
552 void forEachEntity(Func&& func) const {
553 for (u32 i = 0; i < entityValid_.size(); ++i) {
554 if (entityValid_[i]) {
555 func(Entity::make(i, generations_[i]));
556 }
557 }
558 }
559
560 // =========================================================================
561 // Component Management
562 // =========================================================================
563
575 template<typename T, typename... Args>
576 T& emplace(Entity entity, Args&&... args) {
577 // An invalid entity would index component_masks_ out of bounds below (the
578 // sentinel's index() is the mask), and there is no component to hand back.
579 ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("emplace", entity));
580 auto& pool = assurePool<T>();
581 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
582 component_masks_[entity.index()].set(componentTypeId<T>());
583 pool.markChanged(entity, change_tick_);
584 recordComponentChange<T>(entity);
585 return result;
586 }
587
598 template<typename T, typename... Args>
599 T& emplaceOrReplace(Entity entity, Args&&... args) {
600 ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("emplaceOrReplace", entity));
601 auto& pool = assurePool<T>();
602
603 if (pool.contains(entity)) {
604 auto& comp = pool.get(entity);
605 comp = T(std::forward<Args>(args)...);
606 pool.markChanged(entity, change_tick_);
607 recordComponentChange<T>(entity, ENTITY_CHANGE_REPLACED);
608 return comp;
609 }
610 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
611 component_masks_[entity.index()].set(componentTypeId<T>());
612 pool.markChanged(entity, change_tick_);
613 recordComponentChange<T>(entity);
614 return result;
615 }
616
624 template<typename T>
625 void remove(Entity 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);
631 const u32 idx = entity.index();
632 if (idx < component_masks_.size()) {
633 component_masks_[idx].clear(componentTypeId<T>());
634 }
635 }
636 }
637
648 template<typename T>
649 T& get(Entity entity) {
650 auto* pool = getPool<T>();
651 ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));
652 return pool->get(entity); // itself fatal on a non-member
653 }
654
656 template<typename T>
657 const T& get(Entity entity) const {
658 auto* pool = getPool<T>();
659 ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));
660 return pool->get(entity);
661 }
662
669 template<typename T>
670 T* tryGet(Entity entity) {
671 auto* pool = getPool<T>();
672 return pool ? pool->tryGet(entity) : nullptr;
673 }
674
676 template<typename T>
677 const T* tryGet(Entity entity) const {
678 auto* pool = getPool<T>();
679 return pool ? pool->tryGet(entity) : nullptr;
680 }
681
690 template<typename T, typename... Args>
691 T& getOrEmplace(Entity entity, Args&&... args) {
692 auto& pool = assurePool<T>();
693 if (pool.contains(entity)) {
694 return pool.get(entity);
695 }
696 ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("getOrEmplace", entity));
697 auto& result = pool.emplace(entity, std::forward<Args>(args)...);
698 component_masks_[entity.index()].set(componentTypeId<T>());
699 pool.markChanged(entity, change_tick_);
700 recordComponentChange<T>(entity);
701 return result;
702 }
703
710 template<typename T>
711 bool has(Entity entity) const {
712 auto* pool = getPool<T>();
713 return pool && pool->contains(entity);
714 }
715
722 template<typename... Ts>
723 bool hasAll(Entity entity) const {
724 return (has<Ts>(entity) && ...);
725 }
726
733 template<typename... Ts>
734 bool hasAny(Entity entity) const {
735 return (has<Ts>(entity) || ...);
736 }
737
738 // =========================================================================
739 // View Query System
740 // =========================================================================
741
760 template<typename... Components>
761 View<Components...> view() {
762 if constexpr (sizeof...(Components) == 1) {
763 return View<Components...>(&assurePool<Components...>());
764 } else {
765 return View<Components...>(
766 std::make_tuple(&assurePool<Components>()...));
767 }
768 }
769
770 // =========================================================================
771 // Utility
772 // =========================================================================
773
778 void clear() {
779 if (entity_reset_epoch_ < RESET_EPOCH_LIMIT) ++entity_reset_epoch_;
781 for (auto& pool : pools_) {
782 if (pool) {
783 pool->clear();
784 }
785 }
786 entityValid_.clear();
787 child_of_.clear();
788 disabled_.clear();
789 inactive_.clear();
790 activity_state_.clear();
791 disabled_count_ = 0;
792 ++activity_epoch_;
793 generations_.clear();
794 component_masks_.clear();
795 while (!recycled_.empty()) recycled_.pop();
796 next_index_ = 0;
797 entity_count_ = 0;
798 retired_slots_ = 0;
799 }
800
818 void applyEntityOrder(const Entity* order, usize count) {
819 if (!order || count == 0) return;
820 applyEntityRank(buildEntityRank(order, count));
821 }
822
829 std::vector<u32> buildEntityRank(const Entity* order, usize count) const {
830 // entityValid_ spans every index ever activated (activateIndex grows it),
831 // so it is the safe bound for a rank table keyed by Entity::index().
832 std::vector<u32> rank(entityValid_.size(), SparseSetBase::UNRANKED);
833 if (!order) return rank;
834 u32 nextRank = 0;
835 for (usize i = 0; i < count; ++i) {
836 const u32 idx = order[i].index();
837 if (idx >= rank.size()) continue; // never allocated here
838 if (rank[idx] != SparseSetBase::UNRANKED) continue; // duplicate: first wins
839 rank[idx] = nextRank++;
840 }
841 return rank;
842 }
843
853 double layoutEpoch() const {
854 u64 sum = 0;
855 for (const auto& pool : pools_) {
856 if (pool) sum += pool->version();
857 }
858 return static_cast<double>(sum);
859 }
860
862 void applyEntityRank(const std::vector<u32>& rank) {
863 for (auto& pool : pools_) {
864 if (pool) pool->reorderBy(rank);
865 }
866 }
867
880 template<typename... Components, typename Func>
881 void each(Func&& func) {
882 view<Components...>().each(std::forward<Func>(func));
883 }
884
889 template<typename... Components, typename Func>
890 void eachLive(Func&& func) {
891 view<Components...>().eachLive(std::forward<Func>(func));
892 }
893
903 template<typename T, typename Compare>
904 void sort(Compare compare) {
905 auto* pool = getPool<T>();
906 if (!pool) return;
907
908 const auto& components = pool->components();
909 const usize n = components.size();
910 if (n <= 1) return;
911
912 std::vector<usize> perm(n);
913 for (usize i = 0; i < n; ++i) perm[i] = i;
914
915 std::sort(perm.begin(), perm.end(), [&](usize a, usize b) {
916 return compare(components[a], components[b]);
917 });
918 // The entity, its component and its stamp move together.
919 pool->permute(perm);
920 }
921
930 template<typename T>
931 std::span<const Entity> entitiesWith() const {
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());
936 }
937
938private:
939 // Handed out once per registry and never recycled, so it survives one being
940 // destroyed and the next taking its address. See instanceId().
941 static inline std::atomic<u64> next_instance_id_{0};
942 u64 instance_id_{++next_instance_id_};
943
944 // =========================================================================
945 // Private Helpers
946 // =========================================================================
947
953 template<typename T>
954 SparseSet<T>& assurePool() {
955 TypeId typeId = componentTypeId<T>();
956 if (typeId >= pools_.size()) {
957 pools_.resize(typeId + 1);
958 }
959 if (!pools_[typeId]) {
960 pools_[typeId] = makeUnique<SparseSet<T>>();
961 }
962 return *static_cast<SparseSet<T>*>(pools_[typeId].get());
963 }
964
970 template<typename T>
971 SparseSet<T>* getPool() {
972 TypeId typeId = componentTypeId<T>();
973 if (typeId >= pools_.size() || !pools_[typeId]) return nullptr;
974 return static_cast<SparseSet<T>*>(pools_[typeId].get());
975 }
976
977 template<typename T>
978 const SparseSet<T>* getPool() const {
979 TypeId typeId = componentTypeId<T>();
980 if (typeId >= pools_.size() || !pools_[typeId]) return nullptr;
981 return static_cast<const SparseSet<T>*>(pools_[typeId].get());
982 }
983
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";
989 }
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()) + ")";
993 }
994
998 Entity activateIndex(u32 index) {
999 // Release-safe: an index past the index field would silently alias an
1000 // existing slot via Entity::make's mask (ES_ASSERT is stripped in
1001 // release). Refuse before any state mutation. restore() passes a
1002 // deserialized index here, so this also guards scene loading. Say it out
1003 // loud: running out is a state someone has to be able to see, and slot
1004 // retirement below spends this space to buy handle uniqueness.
1005 if (index > Entity::INDEX_MASK) {
1006 ES_LOG_ERROR("Registry: entity index space exhausted ({} slots, {} retired to "
1007 "generation wrap); create() returns an invalid entity from here on",
1008 static_cast<u32>(Entity::INDEX_MASK) + 1u, retired_slots_);
1009 return INVALID_ENTITY;
1010 }
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);
1017 }
1018 entityValid_[index] = true;
1019 disabled_[index] = 0;
1020 destruction_pending_[index] = 0;
1021 if (disabled_count_) ++activity_epoch_;
1022 generations_[index] = (generations_[index] + 1) & Entity::GEN_MASK;
1023 if (generations_[index] == 0) generations_[index] = 1;
1024 component_masks_[index].reset();
1025 ++entity_count_;
1026 const auto entity = Entity::make(index, generations_[index]);
1027 recordEntityChange(entity);
1028 return entity;
1029 }
1030
1031 // =========================================================================
1032 // Data Members
1033 // =========================================================================
1034
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;
1040
1041 template<typename T>
1042 void recordComponentChange(Entity entity, u32 flags = 0) {
1043 if constexpr (std::is_same_v<T, Parent>) flags |= ENTITY_CHANGE_SUBTREE;
1044 if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) {
1045 if (disabled_count_) ++activity_epoch_;
1046 }
1047 recordEntityChange(entity, flags, componentTypeId<T>());
1048 }
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_;
1056
1057 void ensureActivity() const {
1058 // A link edited through the relation itself, not setParent, moves its epoch rather than this one.
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);
1062 // Each entity is resolved once, iteratively: deep chains do not recurse
1063 // or repeatedly walk their ancestors. O(entities + parent links).
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);
1068 bool off = false;
1069 for (;;) {
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();
1078 }
1079 for (u32 index : activity_path_) {
1080 inactive_[index] = off ? 1 : 0;
1081 activity_state_[index] = 2;
1082 }
1083 }
1084 resolved_activity_epoch_ = activity_epoch_;
1085 resolved_child_of_epoch_ = child_of_.epoch();
1086 }
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;
1096
1098 std::vector<Unique<SparseSetBase>> pools_;
1099
1101 u32 change_tick_ = 1;
1103 u64 identity_ = nextRevision();
1104 bool change_audit_ = false;
1105 std::vector<SparseSetBase::AuditCopy> audit_copies_;
1106 std::vector<u8> audit_reported_;
1107 u32 audit_unstamped_total_ = 0;
1108
1109 Signal<void(Entity)> on_destroy_signal_;
1110 // Indexed by the canonical entity slot/generation. Grow during activation,
1111 // never allocate one hash node per teardown or a whole-world array on the
1112 // first deletion. Recycled slots start unreserved.
1113 std::vector<u8> destruction_pending_;
1114};
1115
1116} // namespace esengine::ecs
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.
Definition Log.hpp:413
#define ES_LOG_TRACE(...)
Definition Log.hpp:281
#define ES_VERIFY(cond,...)
Always-on boundary guard — the release-safe counterpart to ES_ASSERT.
Definition Log.hpp:389
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
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.
The words that say composed world transforms are stale, apart from the composer so the registry can s...
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.
Definition Registry.hpp:353
bool isEntityActive(Entity e) const
Definition Registry.hpp:115
u32 lastChangedTick() const
The tick of the latest write, addition or removal of any T; 0 when there has been none.
Definition Registry.hpp:291
const T * tryGet(Entity entity) const
Tries to get a component from an entity.
Definition Registry.hpp:677
T & getOrEmplace(Entity entity, Args &&... args)
Gets an existing component or creates a new one.
Definition Registry.hpp:691
ExclusiveRelation & childOf()
Definition Registry.hpp:535
double entityChangeResetEpoch() const
Definition Registry.hpp:131
double entityChangeSequence() const
Definition Registry.hpp:130
bool reserveDestruction(Entity entity)
Definition Registry.hpp:423
void eachChangedSince(u32 tick, Visit &&visit)
Calls visit(entity, component) for each T written, added or replaced after tick, in storage order.
Definition Registry.hpp:271
std::function< void(Entity)> DestroyCallback
Definition Registry.hpp:499
void releaseDestruction(Entity entity)
Definition Registry.hpp:428
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...
Definition Registry.hpp:220
void unwatchEntityChanges(u32 reader)
Definition Registry.hpp:129
void eachLive(Func &&func)
each() without the per-call snapshot copy, for read-only passes.
Definition Registry.hpp:890
u32 activityEpoch() const
Definition Registry.hpp:122
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.
Definition Registry.hpp:213
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
usize countOf() const
How many entities have a T.
Definition Registry.hpp:284
void each(Func &&func)
Executes a function for each entity with specified components.
Definition Registry.hpp:881
u32 poolVersion() const
T's pool version: moves when a T is removed or the pool's storage moves (SparseSetBase::version)....
Definition Registry.hpp:260
bool isEntityEnabled(Entity e) const
Definition Registry.hpp:111
void invalidateActivityHierarchy(Entity root=INVALID_ENTITY)
Definition Registry.hpp:123
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...
Definition Registry.hpp:232
const ExclusiveRelation & childOf() const
The (ChildOf, parent) relation: each entity's parent, and each parent's children in order.
Definition Registry.hpp:534
Registry(const Registry &)=delete
bool hasAny(Entity entity) const
Checks if an entity has any of the specified components.
Definition Registry.hpp:734
std::span< const Entity > entitiesWith() const
The entities that carry T, densely.
Definition Registry.hpp:931
std::vector< u32 > buildEntityRank(const Entity *order, usize count) const
Rank table (by Entity::index()) for an ordered entity list.
Definition Registry.hpp:829
bool has(Entity entity) const
Checks if an entity has a specific component.
Definition Registry.hpp:711
bool hasInactiveEntities() const
Definition Registry.hpp:121
double componentMutationRevision(u32 component, bool topology) const
Definition Registry.hpp:134
void applyEntityOrder(const Entity *order, usize count)
Reorders every component pool to follow the given entity order.
Definition Registry.hpp:818
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.
Definition Registry.hpp:173
void markChangedById(u32 typeId, Entity entity)
markChanged by a component type id (componentTypeId): for a writer that names the type at run time,...
Definition Registry.hpp:201
const T & get(Entity entity) const
Gets a component from an entity (must exist).
Definition Registry.hpp:657
Connection onDestroy(DestroyCallback callback)
Subscribe to entity destruction.
Definition Registry.hpp:509
usize entityCount() const
Definition Registry.hpp:525
u32 changeTick() const
The tick a write made now is stamped with.
Definition Registry.hpp:159
bool anyComponentChangedSinceWhere(u32 tick, Visit &&visit) const
anyChangedSinceWhere over every component type: calls visit(entity) for each component written or add...
Definition Registry.hpp:248
bool setEntityEnabled(Entity e, bool enabled)
Definition Registry.hpp:101
void markChanged(Entity entity)
Says entity's T was written, through a reference held from before.
Definition Registry.hpp:196
bool changedSince(Entity entity, u32 tick) const
Whether entity's T was written, added or replaced after tick (an answer of beginChangeRead).
Definition Registry.hpp:207
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
void remove(Entity entity)
Removes a component from an entity.
Definition Registry.hpp:625
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
Definition Registry.hpp:166
void destroy(Entity entity)
Destroys an entity and removes all its components.
Definition Registry.hpp:449
bool changeAuditEnabled() const
Definition Registry.hpp:307
void clear()
Clears all entities and components.
Definition Registry.hpp:778
i32 readEntityChanges(double after, std::span< EntityChangeRow > output) const
Definition Registry.hpp:137
T & emplaceOrReplace(Entity entity, Args &&... args)
Adds or replaces a component on an entity.
Definition Registry.hpp:599
void applyEntityRank(const std::vector< u32 > &rank)
Reorders every component pool by a rank table from buildEntityRank.
Definition Registry.hpp:862
void forEachEntity(Func &&func) const
Executes a function for each valid entity.
Definition Registry.hpp:552
Entity create()
Creates a new entity.
Definition Registry.hpp:371
u64 instanceId() const
Which registry this is — unique for the process, never reused.
Definition Registry.hpp:96
u32 auditChanges()
Compares, reports, and keeps a new copy.
Definition Registry.hpp:314
T & patch(Entity entity)
Mutable access that says it writes: entity's T, stamped. Fatal where it has none, as get<T>() is.
Definition Registry.hpp:186
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
double layoutEpoch() const
Sum of every pool's version — one number for "did anything move".
Definition Registry.hpp:853
void setChangeAudit(bool enabled)
Turns the change audit on or off. On, auditChanges() compares every auditable component with the copy...
Definition Registry.hpp:301
void sort(Compare compare)
Sorts components by a comparison function.
Definition Registry.hpp:904
Entity restore(u32 index)
Restores an entity at a specific index.
Definition Registry.hpp:404
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
Definition Registry.hpp:576
bool destructionPending(Entity entity) const
Definition Registry.hpp:436
u32 retiredSlots() const
Slots permanently out of circulation, their generation spent.
Definition Registry.hpp:544
bool hasAll(Entity entity) const
Checks if an entity has all specified components.
Definition Registry.hpp:723
void recordEntityChange(Entity entity, u32 flags=0, u32 component=ENTITY_CHANGE_NO_COMPONENT)
Definition Registry.hpp:142
View< Components... > view()
Creates a view for iterating entities with specific components.
Definition Registry.hpp:761
std::vector< Entity > create(usize count)
Creates multiple entities at once.
Definition Registry.hpp:390
static constexpr u32 UNRANKED
Rank for an entity the caller did not order — sorts last, stably.
View for iterating entities with multiple required components.
Definition View.hpp:184
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.
Definition Types.hpp:99
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
TypeId componentTypeId()
Dense 0-based runtime id for a component type (ECS pool index + mask bit).
Definition Types.hpp:231
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
u32 TypeId
Runtime type identifier.
Definition Types.hpp:187
u64 nextRevision()
A revision no content has had before. Never 0, which reads as "none".
Definition Revision.hpp:24
auto sink(SignalType &signal)
Create a sink for a signal.
Definition Sink.hpp:175
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159
static constexpr u32 GEN_MASK
Definition Types.hpp:142
static constexpr Entity make(u32 idx, u32 gen)
Creates an Entity from index and generation.
Definition Types.hpp:165
static constexpr u32 INDEX_MASK
Definition Types.hpp:141
constexpr u32 generation() const
Gets the generation number.
Definition Types.hpp:153
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150