A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor: packed Entity, World context, SharedHandle, and ECS cleanup
esengine835415ca6291
diff --git a/src/esengine/core/ServiceRegistry.hpp b/src/esengine/core/ServiceRegistry.hppindex 2673dedff..67839ceea 100644--- a/src/esengine/core/ServiceRegistry.hpp+++ b/src/esengine/core/ServiceRegistry.hpp@@ -59,7 +59,10 @@ public:*/template<typename T>void registerService(T* service) {- services_[getTypeId<T>()] = static_cast<void*>(service);+ TypeId id = getTypeId<T>();+ ES_ASSERT(services_.find(id) == services_.end(),+ "Service already registered, use removeService first");+ services_[id] = static_cast<void*>(service);}/**@@ -69,8 +72,11 @@ public:*/template<typename T>void registerOwned(Unique<T> service) {+ TypeId id = getTypeId<T>();+ ES_ASSERT(services_.find(id) == services_.end(),+ "Service already registered, use removeService first");T* raw = service.get();- services_[getTypeId<T>()] = static_cast<void*>(raw);+ services_[id] = static_cast<void*>(raw);auto deleter = [](void* ptr) {delete static_cast<T*>(ptr);diff --git a/src/esengine/core/Types.hpp b/src/esengine/core/Types.hppindex d227f4051..3c5f4d06f 100644--- a/src/esengine/core/Types.hpp+++ b/src/esengine/core/Types.hpp@@ -111,17 +111,54 @@ constexpr Shared<T> makeShared(Args&&... args) {// =============================================================================/**- * @brief Entity identifier type- * @details Entities are simple integer IDs used as keys in the ECS system.- * Components are associated with entities via the Registry.+ * @brief Entity identifier with packed index + generation+ *+ * @details Entities pack a 20-bit index and 12-bit generation into a single+ * u32. The generation detects stale references after an entity is+ * destroyed and its index recycled (ABA problem).+ *+ * Layout: [generation(12) | index(20)]+ * - Max entities: 1,048,575 (2^20 - 1)+ * - Max generations: 4,095 (2^12 - 1) before wrap*/-using Entity = u32;+struct Entity {+ u32 raw;-/**- * @brief Invalid entity sentinel value- * @details Used to represent null/invalid entity references- */-constexpr Entity INVALID_ENTITY = std::numeric_limits<Entity>::max();+ static constexpr u32 INDEX_BITS = 20;+ static constexpr u32 GEN_BITS = 12;+ static constexpr u32 INDEX_MASK = (1u << INDEX_BITS) - 1;+ static constexpr u32 GEN_MASK = (1u << GEN_BITS) - 1;+ static constexpr u32 INVALID_RAW = 0xFFFFFFFF;++ constexpr Entity() : raw(INVALID_RAW) {}+ explicit constexpr Entity(u32 r) : raw(r) {}+ explicit constexpr operator u32() const { return raw; }++ /** @brief Gets the 20-bit entity index */+ constexpr u32 index() const { return raw & INDEX_MASK; }++ /** @brief Gets the 12-bit generation number */+ constexpr u32 generation() const { return (raw >> INDEX_BITS) & GEN_MASK; }++ /** @brief Checks if this is not the invalid sentinel */+ constexpr bool isValid() const { return raw != INVALID_RAW; }++ /** @brief Creates an Entity from index and generation */+ static constexpr Entity make(u32 idx, u32 gen) {+ return Entity(((gen & GEN_MASK) << INDEX_BITS) | (idx & INDEX_MASK));+ }++ constexpr bool operator==(Entity other) const { return raw == other.raw; }+ constexpr bool operator!=(Entity other) const { return raw != other.raw; }+};++static_assert(sizeof(Entity) == sizeof(u32), "Entity must be 4 bytes for FFI and dense array performance");++/** @brief Invalid entity sentinel value */+constexpr Entity INVALID_ENTITY{};++/** @brief Sentinel for empty sparse set slots */+constexpr u32 INVALID_DENSE_INDEX = std::numeric_limits<u32>::max();// =============================================================================// Type ID System@@ -243,3 +280,14 @@ template<typename T>using ConstSpan = std::span<const T>;} // namespace esengine++// =============================================================================+// std::hash specialization+// =============================================================================++template<>+struct std::hash<esengine::Entity> {+ std::size_t operator()(esengine::Entity e) const noexcept {+ return std::hash<esengine::u32>{}(e.raw);+ }+};diff --git a/src/esengine/core/World.hpp b/src/esengine/core/World.hppnew file mode 100644index 000000000..880c3743b--- /dev/null+++ b/src/esengine/core/World.hpp@@ -0,0 +1,49 @@+/**+ * @file World.hpp+ * @brief Unified context passed to all ECS systems+ * @details Bundles Registry, ServiceRegistry, and frame timing into a single+ * object so systems can access any engine service without globals.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++#include "Types.hpp"++namespace esengine {++class ServiceRegistry;++namespace ecs {+class Registry;+}++/**+ * @brief Context passed to every System::update call+ *+ * @details Provides access to the ECS registry, all registered services,+ * and frame timing. Systems should use this instead of global state.+ *+ * @code+ * void update(World& world) override {+ * auto& registry = world.registry;+ * auto& input = world.services.require<Input>();+ * f32 dt = world.deltaTime;+ * }+ * @endcode+ */+struct World {+ ecs::Registry& registry; ///< ECS entity/component storage+ ServiceRegistry& services; ///< All engine services+ f32 deltaTime; ///< Seconds since last frame++ /** @brief Convenience accessor for services */+ template<typename T>+ T& require() { return services.require<T>(); }+};++} // namespace esenginediff --git a/src/esengine/ecs/DynamicComponent.hpp b/src/esengine/ecs/DynamicComponent.hppindex 1b7abc8c0..ac2b1cc15 100644--- a/src/esengine/ecs/DynamicComponent.hpp+++ b/src/esengine/ecs/DynamicComponent.hpp@@ -68,27 +68,28 @@ public:/** @brief Checks if entity has this component */bool contains(Entity entity) const {- return entity < sparse_.size() &&- sparse_[entity] < dense_.size() &&- dense_[sparse_[entity]] == entity;+ const u32 idx = entity.index();+ return idx < sparse_.size() &&+ sparse_[idx] < dense_.size() &&+ dense_[sparse_[idx]] == entity;}/** @brief Gets component data (must exist) */DynamicValue& get(Entity entity) {ES_ASSERT(contains(entity), "Entity does not have component");- return values_[sparse_[entity]];+ return values_[sparse_[entity.index()]];}/** @brief Gets component data (const) */const DynamicValue& get(Entity entity) const {ES_ASSERT(contains(entity), "Entity does not have component");- return values_[sparse_[entity]];+ return values_[sparse_[entity.index()]];}/** @brief Tries to get component data (returns nullptr if not found) */DynamicValue* tryGet(Entity entity) {if (!contains(entity)) return nullptr;- return &values_[sparse_[entity]];+ return &values_[sparse_[entity.index()]];}// =========================================================================@@ -99,11 +100,12 @@ public:void emplace(Entity entity, DynamicValue value) {ES_ASSERT(!contains(entity), "Entity already has component");- if (entity >= sparse_.size()) {- sparse_.resize(entity + 1, INVALID_ENTITY);+ const u32 idx = entity.index();+ if (idx >= sparse_.size()) {+ sparse_.resize(idx + 1, INVALID_DENSE_INDEX);}- sparse_[entity] = static_cast<Entity>(dense_.size());+ sparse_[idx] = static_cast<u32>(dense_.size());dense_.push_back(entity);values_.push_back(std::move(value));}@@ -111,7 +113,7 @@ public:/** @brief Adds or replaces component data */void emplaceOrReplace(Entity entity, DynamicValue value) {if (contains(entity)) {- values_[sparse_[entity]] = std::move(value);+ values_[sparse_[entity.index()]] = std::move(value);} else {emplace(entity, std::move(value));}@@ -121,16 +123,17 @@ public:void remove(Entity entity) {if (!contains(entity)) return;- const auto last = dense_.back();- const auto index = sparse_[entity];+ const u32 idx = entity.index();+ const Entity last = dense_.back();+ const u32 denseIdx = sparse_[idx];- dense_[index] = last;- std::swap(values_[index], values_.back());- sparse_[last] = index;+ dense_[denseIdx] = last;+ std::swap(values_[denseIdx], values_.back());+ sparse_[last.index()] = denseIdx;dense_.pop_back();values_.pop_back();- sparse_[entity] = INVALID_ENTITY;+ sparse_[idx] = INVALID_DENSE_INDEX;}// =========================================================================@@ -149,8 +152,8 @@ public:const std::vector<Entity>& entities() const { return dense_; }private:- std::vector<Entity> sparse_;- std::vector<Entity> dense_;+ std::vector<u32> sparse_; ///< Entity index -> dense index+ std::vector<Entity> dense_; ///< Dense entity array (packed entities)std::vector<DynamicValue> values_;};@@ -192,10 +195,10 @@ public:return id;}- /** @brief Gets component ID by name (returns UINT32_MAX if not found) */+ /** @brief Gets component ID by name (returns INVALID_DENSE_INDEX if not found) */u32 getComponentId(const std::string& name) const {auto it = nameToId_.find(name);- return it != nameToId_.end() ? it->second : UINT32_MAX;+ return it != nameToId_.end() ? it->second : INVALID_DENSE_INDEX;}/** @brief Gets component name by ID */@@ -246,12 +249,12 @@ public:bool hasByName(Entity entity, const std::string& name) const {u32 id = getComponentId(name);- return id != UINT32_MAX && has(entity, id);+ return id != INVALID_DENSE_INDEX && has(entity, id);}DynamicValue* getByName(Entity entity, const std::string& name) {u32 id = getComponentId(name);- if (id == UINT32_MAX) return nullptr;+ if (id == INVALID_DENSE_INDEX) return nullptr;return pools_[id].tryGet(entity);}@@ -262,7 +265,7 @@ public:void removeByName(Entity entity, const std::string& name) {u32 id = getComponentId(name);- if (id != UINT32_MAX) {+ if (id != INVALID_DENSE_INDEX) {pools_[id].remove(entity);}}diff --git a/src/esengine/ecs/Entity.hpp b/src/esengine/ecs/Entity.hppindex 619943be9..6cf81aa39 100644--- a/src/esengine/ecs/Entity.hpp+++ b/src/esengine/ecs/Entity.hpp@@ -1,8 +1,8 @@/*** @file Entity.hpp- * @brief Entity types and utilities for the ECS system- * @details Provides entity versioning, handle encoding/decoding,- * and entity traits. The core Entity type is defined in Types.hpp.+ * @brief Entity utilities for the ECS system+ * @details The core Entity type is defined in Types.hpp as a packed struct+ * with 20-bit index and 12-bit generation.** @author ESEngine Team* @date 2025@@ -22,86 +22,17 @@namespace esengine::ecs {// =============================================================================-// Entity Versioning+// Entity Handle Functions (64-bit, for FFI)// =============================================================================/**- * @brief Entity with version information for safe recycling- *- * @details When entities are destroyed and recycled, the version- * is incremented. This allows detecting stale entity references.- */-struct EntityVersion {- /** @brief The entity ID */- Entity id;- /** @brief Version number (incremented on recycle) */- u32 version;-};--// =============================================================================-// Entity Handle Functions-// =============================================================================--/**- * @brief Combines entity ID and version into a single 64-bit handle- * @param id The entity ID (lower 32 bits)- * @param version The version number (upper 32 bits)+ * @brief Combines entity index and generation into a single 64-bit handle+ * @param index The entity index (lower 32 bits)+ * @param generation The generation number (upper 32 bits)* @return A packed 64-bit handle- *- * @see getEntityId(), getEntityVersion()- */-inline constexpr u64 makeEntityHandle(Entity id, u32 version) {- return (static_cast<u64>(version) << 32) | static_cast<u64>(id);-}--/**- * @brief Extracts the entity ID from a packed handle- * @param handle The 64-bit entity handle- * @return The entity ID*/-inline constexpr Entity getEntityId(u64 handle) {- return static_cast<Entity>(handle & 0xFFFFFFFF);+inline constexpr u64 makeEntityHandle(u32 index, u32 generation) {+ return (static_cast<u64>(generation) << 32) | static_cast<u64>(index);}-/**- * @brief Extracts the version from a packed handle- * @param handle The 64-bit entity handle- * @return The version number- */-inline constexpr u32 getEntityVersion(u64 handle) {- return static_cast<u32>(handle >> 32);-}--// =============================================================================-// Entity Traits-// =============================================================================--/**- * @brief Utility traits for working with entities- *- * @details Provides static helper functions for common entity operations.- *- * @code- * Entity e = registry.create();- * if (EntityTraits::isValid(e)) {- * // Use entity- * }- * @endcode- */-struct EntityTraits {- /**- * @brief Returns the null/invalid entity value- * @return INVALID_ENTITY constant- */- static constexpr Entity null() { return INVALID_ENTITY; }-- /**- * @brief Checks if an entity ID is valid (not null)- * @param entity The entity to check- * @return True if entity != INVALID_ENTITY- * @note This only checks the ID value, not registry validity- */- static constexpr bool isValid(Entity entity) { return entity != INVALID_ENTITY; }-};-} // namespace esengine::ecsdiff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex 14368fa79..055f328b7 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -83,26 +83,15 @@ public:* entities exist.*/Entity create() {- Entity entity;+ u32 index;if (!recycled_.empty()) {- entity = recycled_.front();+ index = recycled_.front();recycled_.pop();} else {- entity = nextEntity_++;+ index = next_index_++;}- if (entity >= entityValid_.size()) {- entityValid_.resize(entity + 1, false);- generations_.resize(entity + 1, 0);- component_masks_.resize(entity + 1);- }- entityValid_[entity] = true;- generations_[entity]++;- component_masks_[entity].reset();- ++entity_count_;-- ES_LOG_TRACE("Created entity {}", entity);- return entity;+ return activateIndex(index);}/**@@ -120,31 +109,20 @@ public:}/**- * @brief Restores a previously destroyed entity with the same ID- * @param entity The entity ID to restore- * @return true if restored successfully, false if entity is already valid+ * @brief Restores an entity at a specific index+ * @param index The entity index to restore+ * @return The newly created Entity, or INVALID_ENTITY if index is already alive*/- bool restore(Entity entity) {- if (valid(entity)) {- return false;- }-- if (entity >= entityValid_.size()) {- entityValid_.resize(entity + 1, false);- generations_.resize(entity + 1, 0);- component_masks_.resize(entity + 1);+ Entity restore(u32 index) {+ if (index < entityValid_.size() && entityValid_[index]) {+ return INVALID_ENTITY;}- entityValid_[entity] = true;- generations_[entity]++;- component_masks_[entity].reset();- ++entity_count_;- if (entity >= nextEntity_) {- nextEntity_ = entity + 1;+ if (index >= next_index_) {+ next_index_ = index + 1;}- ES_LOG_TRACE("Restored entity {}", entity);- return true;+ return activateIndex(index);}/**@@ -157,11 +135,13 @@ public:void destroy(Entity entity) {if (!valid(entity)) return;- for (auto& callback : on_destroy_callbacks_) {- callback(entity);+ const u32 idx = entity.index();++ for (auto& entry : on_destroy_entries_) {+ entry.callback(entity);}- component_masks_[entity].forEachSet([&](u32 bit) {+ component_masks_[idx].forEachSet([&](u32 bit) {if (bit < pools_.size() && pools_[bit]) {pools_[bit]->remove(entity);}@@ -169,29 +149,27 @@ public:schemaRegistry_.removeAll(entity);- component_masks_[entity].reset();- entityValid_[entity] = false;+ component_masks_[idx].reset();+ entityValid_[idx] = false;--entity_count_;- recycled_.push(entity);+ recycled_.push(idx);- ES_LOG_TRACE("Destroyed entity {}", entity);+ ES_LOG_TRACE("Destroyed entity raw={} (index={})", entity.raw, idx);}using DestroyCallback = std::function<void(Entity)>;u32 onDestroy(DestroyCallback callback) {u32 id = next_callback_id_++;- on_destroy_callbacks_.emplace_back(std::move(callback));- on_destroy_callback_ids_.push_back(id);+ on_destroy_entries_.push_back({id, std::move(callback)});return id;}void removeOnDestroy(u32 callbackId) {- for (usize i = 0; i < on_destroy_callback_ids_.size(); ++i) {- if (on_destroy_callback_ids_[i] == callbackId) {+ for (usize i = 0; i < on_destroy_entries_.size(); ++i) {+ if (on_destroy_entries_[i].id == callbackId) {auto pos = static_cast<std::ptrdiff_t>(i);- on_destroy_callbacks_.erase(on_destroy_callbacks_.begin() + pos);- on_destroy_callback_ids_.erase(on_destroy_callback_ids_.begin() + pos);+ on_destroy_entries_.erase(on_destroy_entries_.begin() + pos);return;}}@@ -200,26 +178,18 @@ public:/*** @brief Checks if an entity is currently valid* @param entity The entity to check- * @return True if the entity exists and is not destroyed+ * @return True if the entity exists and generation matches*/bool valid(Entity entity) const {- return entity < entityValid_.size() && entityValid_[entity];- }-- bool valid(Entity entity, u32 generation) const {- return valid(entity) && entity < generations_.size() &&- generations_[entity] == generation;- }-- u32 generation(Entity entity) const {- if (entity < generations_.size()) {- return generations_[entity];- }- return 0;+ const u32 idx = entity.index();+ return idx < entityValid_.size() &&+ entityValid_[idx] &&+ generations_[idx] == entity.generation();}+ /** @brief Gets the packed u64 handle (for legacy/FFI compatibility) */u64 entityHandle(Entity entity) const {- return makeEntityHandle(entity, generation(entity));+ return makeEntityHandle(entity.index(), entity.generation());}usize entityCount() const {@@ -233,9 +203,9 @@ public:*/template<typename Func>void forEachEntity(Func&& func) const {- for (Entity e = 0; e < entityValid_.size(); ++e) {- if (entityValid_[e]) {- func(e);+ for (u32 i = 0; i < entityValid_.size(); ++i) {+ if (entityValid_[i]) {+ func(Entity::make(i, generations_[i]));}}}@@ -259,7 +229,7 @@ public:ES_ASSERT(valid(entity), "Invalid entity");auto& pool = assurePool<T>();auto& result = pool.emplace(entity, std::forward<Args>(args)...);- component_masks_[entity].set(getTypeId<T>());+ component_masks_[entity.index()].set(getTypeId<T>());return result;}@@ -279,11 +249,12 @@ public:auto& pool = assurePool<T>();if (pool.contains(entity)) {- pool.get(entity) = T(std::forward<Args>(args)...);- return pool.get(entity);+ auto& comp = pool.get(entity);+ comp = T(std::forward<Args>(args)...);+ return comp;}auto& result = pool.emplace(entity, std::forward<Args>(args)...);- component_masks_[entity].set(getTypeId<T>());+ component_masks_[entity.index()].set(getTypeId<T>());return result;}@@ -299,8 +270,9 @@ public:auto* pool = getPool<T>();if (pool) {pool->remove(entity);- if (entity < component_masks_.size()) {- component_masks_[entity].clear(getTypeId<T>());+ const u32 idx = entity.index();+ if (idx < component_masks_.size()) {+ component_masks_[idx].clear(getTypeId<T>());}}}@@ -362,7 +334,7 @@ public:return pool.get(entity);}auto& result = pool.emplace(entity, std::forward<Args>(args)...);- component_masks_[entity].set(getTypeId<T>());+ component_masks_[entity.index()].set(getTypeId<T>());return result;}@@ -449,7 +421,7 @@ public:generations_.clear();component_masks_.clear();while (!recycled_.empty()) recycled_.pop();- nextEntity_ = 0;+ next_index_ = 0;entity_count_ = 0;}@@ -618,6 +590,23 @@ private:return static_cast<const SparseSet<T>*>(pools_[typeId].get());}+ /**+ * @brief Activates an entity index: resizes arrays, bumps generation, returns packed Entity+ */+ Entity activateIndex(u32 index) {+ if (index >= entityValid_.size()) {+ entityValid_.resize(index + 1, false);+ generations_.resize(index + 1, 0);+ component_masks_.resize(index + 1);+ }+ entityValid_[index] = true;+ generations_[index] = (generations_[index] + 1) & Entity::GEN_MASK;+ if (generations_[index] == 0) generations_[index] = 1;+ component_masks_[index].reset();+ ++entity_count_;+ return Entity::make(index, generations_[index]);+ }+// =========================================================================// Data Members// =========================================================================@@ -625,8 +614,8 @@ private:std::vector<u8> entityValid_;std::vector<u32> generations_;std::vector<ComponentMask> component_masks_;- std::queue<Entity> recycled_;- Entity nextEntity_ = 0;+ std::queue<u32> recycled_; ///< Recycled entity indices+ u32 next_index_ = 0; ///< Next fresh entity indexusize entity_count_ = 0;/** @brief Type-erased component pools indexed by TypeId */@@ -635,9 +624,12 @@ private:/** @brief Schema component registry for script-defined components */SchemaRegistry schemaRegistry_;- /** @brief Entity destruction callbacks */- std::vector<DestroyCallback> on_destroy_callbacks_;- std::vector<u32> on_destroy_callback_ids_;+ struct DestroyEntry {+ u32 id;+ DestroyCallback callback;+ };++ std::vector<DestroyEntry> on_destroy_entries_;u32 next_callback_id_ = 0;};diff --git a/src/esengine/ecs/SchemaComponent.hpp b/src/esengine/ecs/SchemaComponent.hppindex 54137f0e8..13ebf3a0d 100644--- a/src/esengine/ecs/SchemaComponent.hpp+++ b/src/esengine/ecs/SchemaComponent.hpp@@ -72,12 +72,13 @@ public:return getOffset(entity);}- if (entity >= sparse_.size()) {- sparse_.resize(entity + 1, INVALID_ENTITY);+ const u32 idx = entity.index();+ if (idx >= sparse_.size()) {+ sparse_.resize(idx + 1, INVALID_DENSE_INDEX);}- u32 index = static_cast<u32>(dense_.size());- sparse_[entity] = index;+ u32 denseIdx = static_cast<u32>(dense_.size());+ sparse_[idx] = denseIdx;dense_.push_back(entity);usize oldSize = data_.size();@@ -97,16 +98,17 @@ public:*/u32 getOffset(Entity entity) const {ES_ASSERT(contains(entity), "Entity does not have component");- return sparse_[entity] * stride_;+ return sparse_[entity.index()] * stride_;}/*** @brief Checks if entity has this component*/bool contains(Entity entity) const {- return entity < sparse_.size() &&- sparse_[entity] < dense_.size() &&- dense_[sparse_[entity]] == entity;+ const u32 idx = entity.index();+ return idx < sparse_.size() &&+ sparse_[idx] < dense_.size() &&+ dense_[sparse_[idx]] == entity;}/**@@ -115,23 +117,23 @@ public:void remove(Entity entity) {if (!contains(entity)) return;- u32 index = sparse_[entity];+ const u32 idx = entity.index();+ u32 denseIdx = sparse_[idx];Entity lastEntity = dense_.back();- u32 lastIndex = static_cast<u32>(dense_.size() - 1);+ u32 lastDenseIdx = static_cast<u32>(dense_.size() - 1);- // Swap data- if (index != lastIndex) {- u8* dstPtr = data_.data() + index * stride_;- u8* srcPtr = data_.data() + lastIndex * stride_;+ if (denseIdx != lastDenseIdx) {+ u8* dstPtr = data_.data() + denseIdx * stride_;+ u8* srcPtr = data_.data() + lastDenseIdx * stride_;std::memcpy(dstPtr, srcPtr, stride_);- dense_[index] = lastEntity;- sparse_[lastEntity] = index;+ dense_[denseIdx] = lastEntity;+ sparse_[lastEntity.index()] = denseIdx;}dense_.pop_back();data_.resize(data_.size() - stride_);- sparse_[entity] = INVALID_ENTITY;+ sparse_[idx] = INVALID_DENSE_INDEX;}// =========================================================================@@ -186,8 +188,8 @@ private:u32 stride_; ///< Bytes per componentu32 pool_version_ = 0; ///< Incremented on potential reallocationstd::vector<u8> data_; ///< Contiguous component data- std::vector<u32> sparse_; ///< Entity -> dense index- std::vector<Entity> dense_; ///< Dense entity array+ std::vector<u32> sparse_; ///< Entity index -> dense index+ std::vector<Entity> dense_; ///< Dense entity array (packed entities)};// =============================================================================@@ -228,7 +230,7 @@ public:/** @brief Gets pool ID by name */u32 getPoolId(const std::string& name) const {auto it = nameToId_.find(name);- return it != nameToId_.end() ? it->second : UINT32_MAX;+ return it != nameToId_.end() ? it->second : INVALID_DENSE_INDEX;}/** @brief Gets pool by ID */diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hppindex e8fd10690..700cbe55f 100644--- a/src/esengine/ecs/SparseSet.hpp+++ b/src/esengine/ecs/SparseSet.hpp@@ -135,8 +135,11 @@ public:/** @brief Page size for paged sparse array (entities per page) */static constexpr usize SPARSE_PAGE_SIZE = 4096;- /** @brief Page type: array of entity indices */- using Page = std::array<Entity, SPARSE_PAGE_SIZE>;+ /** @brief Sentinel for empty sparse slots */+ static constexpr u32 INVALID_INDEX = INVALID_DENSE_INDEX;++ /** @brief Page type: array of dense indices */+ using Page = std::array<u32, SPARSE_PAGE_SIZE>;/** @brief Default constructor */SparseSet() = default;@@ -163,15 +166,8 @@ public:* Uses paged lookup to avoid unbounded memory growth.*/bool contains(Entity entity) const override {- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;-- if (pageIndex >= pages_.size() || !pages_[pageIndex]) {- return false;- }-- const Entity denseIndex = (*pages_[pageIndex])[offset];- return denseIndex < dense_.size() && dense_[denseIndex] == entity;+ u32 di = denseIndexOf(entity);+ return di != INVALID_INDEX && dense_[di] == entity;}/**@@ -183,29 +179,21 @@ public:*/T& get(Entity entity) {ES_ASSERT(contains(entity), "Entity does not have component");- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return components_[(*pages_[pageIndex])[offset]];+ return components_[denseIndexOf(entity)];}/** @copydoc get() */const T& get(Entity entity) const {ES_ASSERT(contains(entity), "Entity does not have component");- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return components_[(*pages_[pageIndex])[offset]];+ return components_[denseIndexOf(entity)];}T& getUnchecked(Entity entity) {- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return components_[(*pages_[pageIndex])[offset]];+ return components_[denseIndexOf(entity)];}const T& getUnchecked(Entity entity) const {- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return components_[(*pages_[pageIndex])[offset]];+ return components_[denseIndexOf(entity)];}/**@@ -214,18 +202,16 @@ public:* @return Pointer to the component, or nullptr*/T* tryGet(Entity entity) {- if (!contains(entity)) return nullptr;- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return &components_[(*pages_[pageIndex])[offset]];+ u32 di = denseIndexOf(entity);+ if (di == INVALID_INDEX || dense_[di] != entity) return nullptr;+ return &components_[di];}/** @copydoc tryGet() */const T* tryGet(Entity entity) const {- if (!contains(entity)) return nullptr;- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return &components_[(*pages_[pageIndex])[offset]];+ u32 di = denseIndexOf(entity);+ if (di == INVALID_INDEX || dense_[di] != entity) return nullptr;+ return &components_[di];}// =========================================================================@@ -249,8 +235,9 @@ public:T& emplace(Entity entity, Args&&... args) {ES_ASSERT(!contains(entity), "Entity already has component");- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;+ const u32 idx = entity.index();+ const auto pageIndex = idx / SPARSE_PAGE_SIZE;+ const auto offset = idx % SPARSE_PAGE_SIZE;if (pageIndex >= pages_.size()) {pages_.resize(pageIndex + 1);@@ -258,10 +245,10 @@ public:if (!pages_[pageIndex]) {pages_[pageIndex] = std::make_unique<Page>();- std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_ENTITY);+ std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_INDEX);}- (*pages_[pageIndex])[offset] = static_cast<Entity>(dense_.size());+ (*pages_[pageIndex])[offset] = static_cast<u32>(dense_.size());dense_.push_back(entity);components_.emplace_back(std::forward<Args>(args)...);@@ -279,21 +266,21 @@ public:void remove(Entity entity) override {if (!contains(entity)) return;- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- const auto last = dense_.back();- const auto index = (*pages_[pageIndex])[offset];+ const u32 idx = entity.index();+ const auto pageIndex = idx / SPARSE_PAGE_SIZE;+ const auto offset = idx % SPARSE_PAGE_SIZE;+ const Entity last = dense_.back();+ const u32 denseIdx = (*pages_[pageIndex])[offset];- dense_[index] = last;- components_[index] = std::move(components_.back());+ dense_[denseIdx] = last;+ components_[denseIdx] = std::move(components_.back());- const auto lastPageIndex = last / SPARSE_PAGE_SIZE;- const auto lastOffset = last % SPARSE_PAGE_SIZE;- (*pages_[lastPageIndex])[lastOffset] = index;+ const u32 lastIdx = last.index();+ (*pages_[lastIdx / SPARSE_PAGE_SIZE])[lastIdx % SPARSE_PAGE_SIZE] = denseIdx;dense_.pop_back();components_.pop_back();- (*pages_[pageIndex])[offset] = INVALID_ENTITY;+ (*pages_[pageIndex])[offset] = INVALID_INDEX;}// =========================================================================@@ -324,17 +311,17 @@ public:void rebuildSparse() {pages_.clear();for (usize i = 0; i < dense_.size(); ++i) {- const Entity entity = dense_[i];- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;+ const u32 idx = dense_[i].index();+ const auto pageIndex = idx / SPARSE_PAGE_SIZE;+ const auto offset = idx % SPARSE_PAGE_SIZE;if (pageIndex >= pages_.size()) {pages_.resize(pageIndex + 1);}if (!pages_[pageIndex]) {pages_[pageIndex] = std::make_unique<Page>();- std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_ENTITY);+ std::fill(pages_[pageIndex]->begin(), pages_[pageIndex]->end(), INVALID_INDEX);}- (*pages_[pageIndex])[offset] = static_cast<Entity>(i);+ (*pages_[pageIndex])[offset] = static_cast<u32>(i);}}@@ -391,12 +378,22 @@ public:*/usize indexOf(Entity entity) const {ES_ASSERT(contains(entity), "Entity not in set");- const auto pageIndex = entity / SPARSE_PAGE_SIZE;- const auto offset = entity % SPARSE_PAGE_SIZE;- return (*pages_[pageIndex])[offset];+ return denseIndexOf(entity);}private:+ /**+ * @brief Looks up the dense array index for an entity+ * @return Dense index, or INVALID_INDEX if page not allocated+ */+ u32 denseIndexOf(Entity entity) const {+ const u32 idx = entity.index();+ const auto pageIndex = idx / SPARSE_PAGE_SIZE;+ const auto offset = idx % SPARSE_PAGE_SIZE;+ if (pageIndex >= pages_.size() || !pages_[pageIndex]) return INVALID_INDEX;+ return (*pages_[pageIndex])[offset];+ }+// =========================================================================// Data Members// =========================================================================diff --git a/src/esengine/ecs/System.hpp b/src/esengine/ecs/System.hppindex 1c9625326..20d0a152e 100644--- a/src/esengine/ecs/System.hpp+++ b/src/esengine/ecs/System.hpp@@ -18,6 +18,7 @@// Project includes#include "../core/Types.hpp"+#include "../core/World.hpp"// Standard library#include <algorithm>@@ -41,10 +42,10 @@ class Registry;* @code* class MovementSystem : public System {* public:- * void update(Registry& registry, f32 deltaTime) override {- * registry.each<Transform, Velocity>(- * [deltaTime](Entity e, Transform& t, Velocity& v) {- * t.position += v.linear * deltaTime;+ * void update(World& world) override {+ * world.registry.each<Transform, Velocity>(+ * [&](Entity e, Transform& t, Velocity& v) {+ * t.position += v.linear * world.deltaTime;* });* }* };@@ -69,13 +70,12 @@ public:/*** @brief Called every frame to execute system logic- * @param registry Reference to the ECS registry- * @param deltaTime Time since last frame in seconds+ * @param world The world context (registry, services, deltaTime)** @details Pure virtual - must be overridden. This is where* the main system logic goes.*/- virtual void update(Registry& registry, f32 deltaTime) = 0;+ virtual void update(World& world) = 0;/*** @brief Called once when the system is removed@@ -213,10 +213,10 @@ public:* @details Calls update() on each enabled system in priority order.* Disabled systems are skipped.*/- void update(Registry& registry, f32 deltaTime) {+ void update(World& world) {for (auto& system : systems_) {if (system->isEnabled()) {- system->update(registry, deltaTime);+ system->update(world);}}}diff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hppindex d069f1431..7dc11f27b 100644--- a/src/esengine/ecs/TransformSystem.hpp+++ b/src/esengine/ecs/TransformSystem.hpp@@ -34,9 +34,8 @@ public:(void)registry;}- void update(Registry& registry, f32 deltaTime) override {- (void)deltaTime;- updateDirtyTransforms(registry);+ void update(World& world) override {+ updateDirtyTransforms(world.registry);}private:diff --git a/src/esengine/events/Dispatcher.hpp b/src/esengine/events/Dispatcher.hppindex 7b1dcc24f..010422dbe 100644--- a/src/esengine/events/Dispatcher.hpp+++ b/src/esengine/events/Dispatcher.hpp@@ -65,11 +65,10 @@ public:Dispatcher() = default;~Dispatcher() = default;- Dispatcher(Dispatcher&&) = default;- Dispatcher& operator=(Dispatcher&&) = default;-Dispatcher(const Dispatcher&) = delete;Dispatcher& operator=(const Dispatcher&) = delete;+ Dispatcher(Dispatcher&&) = delete;+ Dispatcher& operator=(Dispatcher&&) = delete;/*** @brief Get a sink for subscribing to an event type@@ -125,9 +124,8 @@ public:*/template<typename Event>void enqueue(const Event& event) {- auto* signal = &assure<Event>();- eventQueue_.push({[signal, event]() {- signal->publish(event);+ eventQueue_.push({[this, event]() {+ trigger(event);}});}diff --git a/src/esengine/platform/input/Input.hpp b/src/esengine/platform/input/Input.hppindex 826e6bf75..7760ac33a 100644--- a/src/esengine/platform/input/Input.hpp+++ b/src/esengine/platform/input/Input.hpp@@ -72,7 +72,7 @@ struct TouchState {* layer feeds events via onTouchEvent() and onKeyEvent().** @code- * Input& input = app.input();+ * Input& input = app.require<Input>();** // In game loop* input.update();diff --git a/src/esengine/resource/Handle.hpp b/src/esengine/resource/Handle.hppindex e9ba29160..fd2783b16 100644--- a/src/esengine/resource/Handle.hpp+++ b/src/esengine/resource/Handle.hpp@@ -19,6 +19,9 @@// Project includes#include "../core/Types.hpp"+// Standard library+#include <functional>+namespace esengine::resource {// =============================================================================@@ -101,6 +104,73 @@ private:IdType id_ = INVALID;};+// =============================================================================+// SharedHandle (RAII wrapper)+// =============================================================================++/**+ * @brief RAII wrapper around Handle that auto-releases on destruction+ *+ * @details Calls a release function when the last SharedHandle copy is+ * destroyed. Use for scoped resource ownership. The underlying+ * Handle can be extracted with get() for hot-path access.+ *+ * @tparam T The resource type+ *+ * @code+ * {+ * auto tex = SharedHandle<Texture>::make(+ * rm.loadTexture("player.png"),+ * [&rm](TextureHandle h) { rm.releaseTexture(h); });+ * // Use tex.get() ...+ * } // auto-released here+ * @endcode+ */+template<typename T>+class SharedHandle {+public:+ using ReleaseFunc = std::function<void(Handle<T>)>;++ SharedHandle() = default;++ /** @brief Creates a SharedHandle that will auto-release */+ static SharedHandle make(Handle<T> handle, ReleaseFunc release) {+ SharedHandle sh;+ if (handle.isValid()) {+ sh.state_ = std::make_shared<State>(handle, std::move(release));+ }+ return sh;+ }++ /** @brief Gets the underlying raw handle (no ownership transfer) */+ Handle<T> get() const { return state_ ? state_->handle : Handle<T>{}; }++ /** @brief Checks if valid */+ bool isValid() const { return state_ && state_->handle.isValid(); }+ explicit operator bool() const { return isValid(); }++ /** @brief Manually release (all copies become invalid) */+ void reset() { state_.reset(); }++private:+ struct State {+ Handle<T> handle;+ ReleaseFunc release;++ State(Handle<T> h, ReleaseFunc r) : handle(h), release(std::move(r)) {}+ ~State() {+ if (handle.isValid() && release) {+ release(handle);+ }+ }++ State(const State&) = delete;+ State& operator=(const State&) = delete;+ };++ Shared<State> state_;+};+} // namespace esengine::resource// =============================================================================@@ -146,6 +216,15 @@ using SpineDataHandle = Handle<esengine::spine::SpineSkeletonData>;/** @brief Handle to a bitmap font resource */using BitmapFontHandle = Handle<esengine::text::BitmapFont>;+/** @brief RAII handle to a shader resource */+using SharedShaderHandle = SharedHandle<esengine::Shader>;++/** @brief RAII handle to a texture resource */+using SharedTextureHandle = SharedHandle<esengine::Texture>;++/** @brief RAII handle to a bitmap font resource */+using SharedBitmapFontHandle = SharedHandle<esengine::text::BitmapFont>;+} // namespace esengine::resource// =============================================================================diff --git a/src/esengine/spine/SpineSystem.hpp b/src/esengine/spine/SpineSystem.hppindex 181408378..96b035baa 100644--- a/src/esengine/spine/SpineSystem.hpp+++ b/src/esengine/spine/SpineSystem.hpp@@ -197,7 +197,7 @@ public:static constexpr i32 EVENT_STRIDE = 4;struct NativeEventRecord {- Entity entity = 0;+ Entity entity;std::string animationName;std::string eventName;std::string stringValue;