Skip to content

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.

docs(arch): rewrite ARCHITECTURE.md to match post-RC5 reality (F4)

yhh81ecbd70ff9c
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 60a3aa008..aa42cc0d3 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,259 +1,231 @@
# ESEngine Architecture
-This document describes the architecture and design decisions of the ESEngine game engine.
+This document describes the architecture and design decisions of the Estella /
+ESEngine 2D game engine. It is **descriptive of the current code**. For the
+*target* architecture, the root-cause rationale behind the current design, and
+the forward roadmap, see the architecture-of-record companions:
-## Overview
-
-ESEngine is designed as a lightweight, modular game engine targeting WebAssembly and WeChat MiniGames. The architecture prioritizes:
-
-1. **Performance**: Cache-friendly data structures, minimal allocations
-2. **Simplicity**: Clean APIs, minimal dependencies
-3. **Portability**: Abstract platform differences behind interfaces
-
-## Core Modules
-
-### Core (`src/esengine/core/`)
-
-The foundation of the engine.
+- [`REARCHITECTURE.md`](./REARCHITECTURE.md) — root-cause re-architecture (RC1–RC6, F1–F4).
+- `REARCH_2D_PARITY.md` — 2D feature-parity / modernization roadmap (local, gitignored).
-- **Types.hpp**: Basic type definitions (u32, f32, Entity, etc.)
-- **Log.hpp/cpp**: Logging system with levels (Trace, Debug, Info, Warn, Error, Fatal)
-- **Engine.hpp/cpp**: Engine singleton, version info, platform queries
-- **Application.hpp/cpp**: Base application class with lifecycle hooks
-
-### ECS (`src/esengine/ecs/`)
-
-Entity-Component-System architecture inspired by EnTT.
+## Overview
-```
-┌─────────────────────────────────────────────────────────────┐
-│ Registry │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Entity Management │ │
-│ │ - create() / destroy() │ │
-│ │ - valid() / entityCount() │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Component Pools (SparseSet<T>) │ │
-│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │
-│ │ │ Transform │ │ Sprite │ │ Velocity │ ... │ │
-│ │ └───────────┘ └───────────┘ └───────────┘ │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Views (Query System) │ │
-│ │ - view<Transform, Sprite>() → View<T...> │ │
-│ └─────────────────────────────────────────────────────┘ │
-└─────────────────────────────────────────────────────────────┘
-```
+Estella is a 2D game engine with a **TypeScript SDK** driven by a
+**C++/WebAssembly** backend. It targets web browsers and WeChat MiniGames and
+ships with an Electron-based visual editor.
-#### SparseSet
+The architecture rests on two non-negotiable principles (see `REARCHITECTURE.md`):
-The core data structure for component storage, providing O(1) operations:
+1. **Single source of truth** — a given fact (memory layout, type id, enum value)
+ is defined once. Cross-boundary layout is generated by EHT and enforced with
+ compile-time `static_assert` + a runtime ABI-hash handshake; drift is a build
+ or startup failure, never silent corruption.
+2. **One channel per abstraction** — `GfxDevice` for the GPU, a single
+ `SparseSet` for component storage, `WasmBridge` for the WASM boundary,
+ per-App resources for subsystem state. Bypassing an abstraction should fail to
+ compile or fail a CI guard.
-```cpp
-template<typename T>
-class SparseSet {
- std::vector<Entity> sparse_; // Entity → Dense index
- std::vector<Entity> dense_; // Dense index → Entity
- std::vector<T> components_; // Component data (cache-friendly)
-};
```
-
-Benefits:
-- O(1) add, remove, lookup
-- Cache-friendly iteration (dense arrays)
-- Swap-and-pop deletion (no holes)
-
-#### View System
-
-Views provide filtered iteration over entities with specific components:
-
-```cpp
-auto view = registry.view<Transform, Velocity>();
-for (auto entity : view) {
- auto& t = view.get<Transform>(entity);
- auto& v = view.get<Velocity>(entity);
- t.position += v.linear * deltaTime;
-}
+┌────────────────────────────────────────────────────────────────────┐
+│ TypeScript SDK (sdk/src) │
+│ App · World · Schedule · Plugins · Query/Commands/Res/Events │
+│ rendering submit · physics · spine · tilemap · ui · audio · scene │
+└───────────────┬──────────────────────────────────────────────────────┘
+ │ WasmBridge (single boundary; EHT-generated layout/ABI)
+┌───────────────▼──────────────────────────────────────────────────────┐
+│ C++ / WebAssembly (src/esengine) │
+│ Registry (SparseSet) · RenderFrame → GfxDevice · ResourceManager │
+│ particle · tilemap · text · animation · platform │
+└────────────────────────────────────────────────────────────────────┘
```
-### Renderer (`src/esengine/renderer/`)
-
-WebGL-based rendering system.
+## Core Modules (`src/esengine/`)
-```
-┌─────────────────────────────────────────────────────────────┐
-│ Renderer │
-│ ┌─────────────────┐ ┌─────────────────┐ │
-│ │ RenderCommand │ │ Shader │ │
-│ │ (Low-level GL) │ │ (GLSL Program) │ │
-│ └─────────────────┘ └─────────────────┘ │
-│ ┌─────────────────┐ ┌─────────────────┐ │
-│ │ Buffer │ │ Texture │ │
-│ │ (VBO/EBO/VAO) │ │ (2D Images) │ │
-│ └─────────────────┘ └─────────────────┘ │
-└─────────────────────────────────────────────────────────────┘
-```
+### Core (`core/`)
-Key classes:
-- **Renderer**: High-level static API for rendering
-- **RenderCommand**: Low-level OpenGL operations
-- **Shader**: GLSL shader compilation and uniforms
-- **Buffer**: Vertex/Index buffers with layout specification
-- **Texture**: 2D texture loading and binding
+- **Types.hpp** — base types (`u32`, `f32`, `Entity`), and the **domain-scoped
+ TypeId** system. Instead of one global `getTypeId<T>()` counter shared across
+ unrelated concerns, each domain (`ComponentDomain`, `EventDomain`,
+ `ServiceDomain`, `ResourceDomain`) has its own dense, 0-based sequence
+ (`Types.hpp:189-219`). Component ids stay dense, so they index the `pools_`
+ vector and the per-entity component bitmask without waste or overflow (RC4).
+- **Log.hpp** — leveled logging. Note: `ES_ASSERT` compiles out in release;
+ boundary validation that must always run does **not** rely on it (RC3).
+- **PackedId.hpp** — entity index/generation packing.
+- **Engine / Application** — engine singleton, version, lifecycle hooks.
-### Platform (`src/esengine/platform/`)
+### ECS (`ecs/`)
-Platform abstraction layer.
+Entity-Component-System inspired by EnTT, with a **single** storage core (RC2).
```
-┌─────────────────────────────────────────────────────────────┐
-│ Platform Interface │
-│ - initialize() / shutdown() │
-│ - pollEvents() / swapBuffers() │
-│ - getTime() / getDeltaTime() │
-│ - Touch/Key/Resize callbacks │
-└─────────────────────────────────────────────────────────────┘
- │
- ▼
-┌─────────────────────────────────────────────────────────────┐
-│ WebPlatform │
-│ - Emscripten/WebGL context │
-│ - HTML5 event handling │
-│ - Canvas management │
-└─────────────────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────────────────┐
+│ Registry │
+│ Entity management: create() / destroy() / valid() │
+│ Component pools: one SparseSet<T> per component type │
+│ Single destroy path: mask-driven, no parallel storages │
+└──────────────────────────────────────────────────────────────┘
```
-## Data Flow
-
-### Frame Loop
-
-```
-┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
-│ Events │ → │ Update │ → │ Render │ → │ Swap │
-│ (Input) │ │ (Systems) │ │ (Draw) │ │ (Present) │
-└───────────┘ └───────────┘ └───────────┘ └───────────┘
- │ │ │ │
- ▼ ▼ ▼ ▼
- Input Registry Renderer Platform
- System .each<>() .submit() .swapBuffers()
-```
+#### SparseSet — the one storage core
-### Component Access Patterns
+There is exactly one component-storage implementation. The earlier parallel
+`DynamicComponentPool` / `SchemaComponentPool` were dead/near-dead code and were
+deleted (RC2); JS zero-copy access already read the typed pool's pointer
+directly.
```cpp
-// Pattern 1: Direct access (when you know the entity)
-auto& transform = registry.get<Transform>(entity);
-
-// Pattern 2: View iteration (for batch processing)
-registry.view<Transform, Velocity>().each([](auto& t, auto& v) {
- t.position += v.linear;
-});
-
-// Pattern 3: Conditional access
-if (auto* health = registry.tryGet<Health>(entity)) {
- health->value -= damage;
-}
-```
-
-## Memory Layout
-
-### Entity IDs
+class SparseSetBase {
+ virtual u32 version() const = 0; // pointer-staleness generation
+};
-```
-Entity = uint32_t
-┌────────────────────────────────────┐
-│ 32-bit ID │
-│ (0 to 4,294,967,294) │
-│ INVALID_ENTITY = 4,294,967,295 │
-└────────────────────────────────────┘
+template<typename T>
+class SparseSet : public SparseSetBase {
+ std::vector<Entity> sparse_; // Entity → dense index (paged)
+ std::vector<Entity> dense_; // dense index → Entity
+ std::vector<T> components_; // contiguous component data
+ u32 version_; // bumped on realloc/relocate
+ u32 version() const override { return version_; } // SparseSet.hpp:370
+};
```
-### Component Storage
-
-```
-SparseSet<Transform>:
-sparse_: [2, -, 0, -, 1, ...] (Entity → Index)
-dense_: [E2, E4, E0] (Index → Entity)
-components_: [T2, T4, T0] (Actual data, contiguous)
-```
+- O(1) add / remove / lookup; cache-friendly dense iteration; swap-and-pop delete.
+- `version()` (`SparseSet.hpp:97,370`) is the **single source** for pointer
+ invalidation: it increments whenever the component buffer reallocates
+ (emplace growth) or relocates (remove swap-pop, sort/rebuild). It is the guard
+ any caller that *caches* a cross-boundary pointer must re-check.
+
+#### Views / Queries
+
+`registry.view<A, B>()` iterates entities holding all requested components,
+filtered via the per-entity component mask. The SDK exposes this as
+`Query(...)` with `Mut`, change-detection, and resource/event parameters.
+
+### Renderer (`renderer/`)
+
+WebGL2-based, compiled to WASM. There is **one rendering path** (RC5): the legacy
+`Renderer` / `BatchRenderer2D` classes were removed. Everything goes through
+`RenderFrame`, and **all** GPU access goes through `GfxDevice`.
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ RenderFrame (per-frame orchestration, frustum cull, stats) │
+│ │ collects RenderItems via typed RenderTypePlugins: │
+│ │ BatchPlugin · SpritePlugin · ParticlePlugin · │
+│ │ ShapePlugin · TextPlugin · TilemapRenderPlugin · │
+│ │ UIElementPlugin │
+│ ▼ │
+│ DrawList (sort + coalesce; multi-texture batch; u32 index) │
+│ ▼ │
+│ GfxDevice (the only GPU entry point) │
+│ └── GLDevice : public GfxDevice (the one concrete impl) │
+│ Shader · Texture · Buffer/VAO · Framebuffer · CustomGeometry │
+│ all take GfxDevice&; no raw gl* outside GLDevice (CI-guarded)│
+└──────────────────────────────────────────────────────────────┘
+```
+
+Key facts:
+- **`GfxDevice`** (`GfxDevice.hpp:48`) is an abstract device that owns its
+ pipeline state; `GLDevice` (`GLDevice.hpp:33`) is the single concrete backend.
+ A CI guard rejects raw `gl*` calls outside `GLDevice.cpp` so the abstraction
+ stays the only channel. A `MockGfxDevice` harness exercises it headlessly.
+- **`DrawList`** sorts and coalesces draw commands, merging up to 8 textures per
+ call; indices are **u32** (no >65535 vertex wraparound).
+- **`RenderFrame`** owns transient buffers (`TransientBufferPool`), frustum
+ culling, render-to-texture (`RenderTarget`), masking (`RenderFrameMask`:
+ scissor + stencil), optional post-processing (`PostProcessPipeline`,
+ ping-pong FBOs), material UBOs (`MaterialStore`), and 2D lighting
+ (`LightStore` / `LightConstants`, up to 16 dynamic lights with a Lit2D shader
+ domain). `ImmediateDraw` provides debug/shape primitives on the same buffers.
+
+### Resource pipeline (`resource/`)
+
+- **ResourceManager / ResourcePool** — reference-counted GPU resources with a
+ three-state lifecycle (Held → Evictable → Evicted). An intrusive LRU list plus
+ a byte budget (`setTextureBudget`) evicts the oldest unreferenced entries when
+ resident bytes exceed the budget. (The budget/stats are not yet surfaced to the
+ SDK — see `REARCH_2D_PARITY.md` T1.)
+
+### Other C++ subsystems
+
+`particle/` (CPU simulation, GPU-instanced rendering), `tilemap/`, `text/`
+(SDF/glyph), `animation/`, `data/`, `math/` (glm-backed), `platform/`.
+
+## SDK / WASM boundary (`sdk/src/`)
+
+The SDK is the authored surface: `defineComponent`, `defineSystem`, `Query`,
+`Commands`, `Res`, events, `Schedule`, and `Plugin`-based composition (`App`).
+Subsystems (asset, physics, spine, tilemap, ui, audio, scene, prefab, camera,
+particle, postprocess, timeline, net) are plugins.
+
+- **One WASM boundary**: `WasmBridge<M>` (`sdk/src/WasmBridge.ts:57`) is the
+ single base class — one loader, one ready promise, one missing-binding policy,
+ one error path, with an abort guard. `CoreApiBridge`, `PhysicsBridge`, and
+ `SpineModuleBridge` all extend it (F2). The five ad-hoc bridge styles described
+ in `REARCHITECTURE.md` have been consolidated here.
+- **Generated layout, no hand mirrors**: EHT (`tools/eht`) generates embind,
+ pointer accessors, the TS component layout, cross-boundary enums, and the ABI
+ layout hash. C++ carries `static_assert(offsetof==N)` for every component
+ field; the bridge compares the ABI hash on `connect()` and refuses to start on
+ mismatch (RC1).
+- **Lifecycle/error model**: `-fno-exceptions` in C++ + explicit status at the
+ boundary + a fatal `onAbort` death flag (`moduleHealth.ts`); transient
+ `_malloc` is RAII-scoped via `withScratch()` (RC3).
+- **Per-App state (F3)**: Camera (`CameraView`), Timeline, PostProcess, and
+ SpriteAnimator are per-App/per-World resources, so isolated realms (e.g. the
+ editor's play realm) never alias process-global state.
## Platform Integration
-### Web/Emscripten
-
```
-JavaScript C++ (WASM)
- │ │
- │ es_init(w, h) │
- ├────────────────────────────►│
- │ │
- │ requestAnimationFrame │
- │◄────────────────────────────┤
- │ │
- │ es_update(dt) │
- ├────────────────────────────►│
- │ es_render() │
- ├────────────────────────────►│
- │ │
+JavaScript (SDK) C++ (WASM)
+ es_init(w, h) ───────────────►
+ requestAnimationFrame ◄────────
+ update(dt) ──────────────────► World.systems → Registry
+ render() ────────────────────► RenderFrame → GfxDevice
```
-### WeChat MiniGame
-
-The engine uses a compatibility layer (`weapp-adapter.js`) to provide browser-like APIs in the WeChat environment.
+- **Web/Emscripten** — WebGL2 context, HTML5 events, canvas management.
+- **WeChat MiniGame** — a platform adapter (`sdk/src/platform/wechat`) wraps
+ `wx.*` APIs (`WXWebAssembly`, sync file I/O, storage, a dedicated audio
+ backend) behind the same `PlatformAdapter` interface used by web.
-## Extension Points
+## Scene Management (SDK)
-1. **Custom Components**: Any struct can be a component
-2. **Custom Systems**: Inherit from `System` or use free functions
-3. **Custom Shaders**: Pass GLSL source to `Shader::create()`
-4. **Platform Adaptation**: Implement `Platform` interface
+`SceneManager` is a resource over the single ECS World. Scenes share one World;
+entities are tagged with `SceneOwner` to track ownership. The render path filters
+cameras and draw callbacks by active scene; scene systems are gated to run only
+when their scene is `running`. `sceneManagerPlugin` runs the transition update
+each frame. Prefabs expand to tagged entities on load and collapse on save, using
+the same expand/collapse core in the SDK as the editor.
## Performance Considerations
-1. **Component Iteration**: Views iterate only entities with all required components
-2. **Memory Locality**: Components stored contiguously in SparseSet
-3. **Minimal Allocations**: Entity recycling, pool-based allocation
-4. **Batch Rendering**: BatchRenderer2D for efficient sprite rendering
-
-## Scene Management
-
-The SDK provides a first-class scene management system built on top of ECS resources.
-
-### Architecture
+1. **Component iteration** — views touch only matching entities; dense arrays.
+2. **Memory locality** — components stored contiguously in `SparseSet`.
+3. **Batching** — `DrawList` sorts + coalesces; multi-texture per draw; u32 index.
+4. **Minimal allocations** — entity recycling, transient buffer pools, RAII scratch.
+5. **Eviction** — `ResourcePool` LRU + byte budget bounds VRAM.
-```
-┌─────────────────────────────────────────────────────────────┐
-│ SceneManager (Resource) │
-│ ┌──────────────────────────────────────────────────────┐ │
-│ │ Scene Registry │ │
-│ │ configs_: Map<string, SceneConfig> │ │
-│ └──────────────────────────────────────────────────────┘ │
-│ ┌──────────────────────────────────────────────────────┐ │
-│ │ Active Scenes │ │
-│ │ scenes_: Map<string, SceneInstance> │ │
-│ │ activeScene_ / additiveScenes_ │ │
-│ └──────────────────────────────────────────────────────┘ │
-│ ┌──────────────────────────────────────────────────────┐ │
-│ │ Lifecycle: load → running → paused/sleeping → unload │ │
-│ └──────────────────────────────────────────────────────┘ │
-└─────────────────────────────────────────────────────────────┘
-```
-
-### Key Design Decisions
-
-- **Single World**: All scenes share one ECS World. Entities are tagged with `SceneOwner` component to track ownership.
-- **Camera Filtering**: The render system filters cameras by `SceneOwner`, only rendering cameras belonging to active scenes.
-- **Draw Callback Scoping**: Custom draw callbacks are associated with scene names and filtered during render.
-- **System Scoping**: Scene systems are wrapped to only execute when their scene status is 'running'.
-- **Automatic Plugin**: `sceneManagerPlugin` is included in `createWebApp()` and runs a transition update system each frame.
-
-## Future Improvements
+## Extension Points
-- [ ] Component groups for cache optimization
-- [x] Event/signal system
-- [x] Audio system
-- [x] Scene serialization
-- [x] Physics integration
-- [x] UI system
-- [x] Scene management
+1. **Custom components** — any registered struct (`ES_COMPONENT`/`ES_PROPERTY`).
+2. **Custom systems / plugins** — `defineSystem` + `App.addPlugin`.
+3. **Custom shaders / materials** — GLSL with reflected `#pragma param` UBO layout.
+4. **Custom render types** — implement a `RenderTypePlugin`.
+5. **Platform adaptation** — implement `PlatformAdapter`.
+
+## Status / Future Improvements
+
+Landed root-cause work: RC1 (keystone — generated layout + ABI handshake),
+RC2 (single storage core), RC4 (domain TypeIds), RC5 (single render path +
+`GfxDevice` + u32 index), F2 (single `WasmBridge`), F3 (per-App resources).
+
+In progress / planned (see `REARCHITECTURE.md` and `REARCH_2D_PARITY.md`):
+- [ ] RC3 remainder — always-on C++ boundary validation; per-subsystem abort guards.
+- [ ] F1 — isolate (keep) the native platform backend; F4 — this rewrite.
+- [ ] RC6 / T1 — asset delivery: WeChat subpackages, on-demand loading, auto
+ atlas, import-time texture compression, SDK-exposed VRAM budget.
+- [ ] T2 — animation state machines / blend trees; native 2D skeletal rig.
+- [ ] T3 — 2D shadows + normal maps; richer post-processing; GPU particles.
+- [ ] T4 — SDK math library; one-way platforms; hex tilemaps; i18n; netcode.
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index b3c5cc7d3..ddbba165a 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -162,9 +162,12 @@
见 [`REARCH_FOUNDATION_CONSOLIDATION.md`](./REARCH_FOUNDATION_CONSOLIDATION.md):
- **F2 单一 `WasmBridge` 基类 + abort 守卫下沉(keystone)— ✅ 已落地**(`ac390f7d` + RM 闭环 `41bea17a`,五套桥接全部收敛,abort 守卫全子系统覆盖)。
- **F3 全 per-App 资源 — ✅ 已落地**(分支 `rearch/f3-per-app`):Camera(`CameraView`)、Timeline(`Timeline`)、PostProcess(拆 god-object + 管线注入 + 删 sync.ts)、SpriteAnimator(`SpriteAnimation`)全部 per-App;模块绑定单例在单模块运行时下无需改(B4 关闭)。
-- F1 平台后端接缝(**保留 native 但隔离**,已拍板)、F4 重写 `ARCHITECTURE.md` — ⏳ 待做。
+- **F4 重写 `ARCHITECTURE.md` — ✅ 已落地**:`docs/ARCHITECTURE.md` 重写为当前现实(`RenderFrame`+`GfxDevice`/`GLDevice` 单一 GPU 边界、单一 `SparseSet`+`version()`、按域 TypeId、per-App 资源 + `WasmBridge` 基类、`ResourcePool` LRU/预算),删除对已删除的 `Renderer`/`BatchRenderer2D` 的描述。
+- F1 平台后端接缝(**保留 native 但隔离**,已拍板)— ⏳ 待做。
执行先于 RC6。
+> **能力对标路线**:RC1–RC5 修正确性、F/RC6 修地基与平台错配之外,"能力缺口对标"(交付管线 / 内容创作闭环 / 渲染深度 / 完整度)的优先级与执行顺序见 [`REARCH_2D_PARITY.md`](./REARCH_2D_PARITY.md)(本地 gitignore)。
+
### RC6 资产管线 — 📋 已立项(设计文档)
见 [`REARCH_RC6_ASSETS.md`](./REARCH_RC6_ASSETS.md):面向微信/移动端的资产管线根治——GPU 压缩纹理(keystone)、内容寻址身份、显存预算 + LRU 驱逐、运行时分包/流式 + 微信分包映射。属"能力/平台错配"根治,区别于 RC1–RC5 的"正确性根因"。