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
chore: stop tracking architecture rearch design docs (local-only)
esenginea5e38c7f4054
diff --git a/.gitignore b/.gitignoreindex 6fbf845e0..4fe0d37a2 100644--- a/.gitignore+++ b/.gitignore@@ -86,3 +86,6 @@ design/desktop/src-tauri/toolchain/!desktop/src-tauri/toolchain/.gitkeep__pycache__/++# Architecture rearch design docs — local only, not tracked+docs/REARCH_*.mddiff --git a/docs/REARCH_ANIMATION.md b/docs/REARCH_ANIMATION.mddeleted file mode 100644index f6b888e5f..000000000--- a/docs/REARCH_ANIMATION.md+++ /dev/null@@ -1,159 +0,0 @@-# Estella 动画 / Sequencer 重构 —— 反射写入 · 纯 TS 运行时 · 文档即真源(REARCH_ANIMATION)--> 目标读者:引擎维护者 / AI 协作代理。-> 体例同 `REARCH_SPINE.md` / `REARCH_EDITOR_MODEL.md`:描述**目标架构**与根治路径,而非现状;-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 三路并行只读审计 + 交叉印证)。-> **立项缘由**:设计稿(`design/ue5-animation.html` + `ue5-overview.html#botDock`)里的 **UE Sequencer**-> 从未被搬进编辑器;而引擎那套 timeline runtime 当年是**临时实现**,用户明确"不够最佳现代就连引擎一起重构"。-> 本文把"补一个编辑器面板"升级成"把整条动画求值链收口成一套现代化架构"。-> **决策(用户已定)**:① Timeline 运行时改为**纯 TS**(文档即运行时);② **编辑器优先**交付。-> **执行纪律**:终态删掉 C++ 临时实现与重复,不为兼容保留旧路径;分阶段只为每步可验证。-------## 0. 核心诊断--**真正的分界线不是"动画该不该有编辑器",而是"动画求值该不该和引擎已有的权威反射层合流"。**--引擎**已经有**一套引擎权威的"按字段路径读写任意组件"的反射层(序列化 + Inspector 都在用):-TS 侧 `PTR_LAYOUTS`(组件→字段偏移描述)+ `BuiltinBridge.writePtrField/readPtrField`(按偏移读写 WASM 堆)+-`COMPONENT_META.animatableFields`(引擎权威的可动画字段表,与下文枚举**同源于** `ES_PROPERTY(animatable)`)。--而 timeline 却**另起炉灶**:把可动画目标硬编码成 `AnimTargetField` 枚举 + 一个 ~40 路 `switch`,并且把运行时切成-**C++ 求值 / TS 持文档**两半、靠每帧轮询结果缓冲同步。`AnimTargetField::CustomField` 这条"反射兜底"分支本身-就证明了枚举是多余的——既然兜底能反射,全部都能反射。--**三条事实定调:**-1. **side-effect 本就大多必须过 JS**:音频=WebAudio 纯 JS(`sdk/src/audio/Audio.ts`)、spine=side-module 经 JS 桥- (`sdk/src/spine/ModuleBackend.ts`)、SpriteAnimator=纯 TS(`sdk/src/animation/SpriteAnimator.ts`)。- 也就是说 C++ timeline 里**唯一**非 JS 的工作只剩"属性曲线求值"。-2. **属性求值搬到 TS 几乎零成本**:写入直接走 `writePtrField` 戳 WASM 堆(不经 embind 拷整结构),- authored 序列实例数很少,逐帧求值在 JS 完全可忽略;现有自定义属性分支早就在 TS 求值- (`TimelineRuntime.ts` `setNestedProperty` + `world.set`)证明可行。-3. **批量程序化补间另有归宿**:Tween(`src/esengine/animation/TweenSystem.cpp`)是 C++ 批量快路径,- 服务"成千上万个简单补间";authored Sequencer 序列是"少量、富功能"——两者尺度不同,不必同核。--**结论:属性求值统一到反射写入层;Timeline 运行时纯 TS 化(文档即运行时);Tween 留 C++ 批量快路径,-与 Timeline 共用 easing/keyframe/反射写入。** 这样可消掉一整个 codegen 子系统、一套 C++ 系统、poll 缓冲、-脑裂同步,同时为编辑器换来 **scrub == evaluate-at-T 免费** 的实时预览。-------## 1. 现状病灶(file:line)--### G1:可动画目标硬编码成枚举 + 大 switch(根因)-- `src/esengine/animation/animTargets.generated.hpp` —— `enum AnimTargetField`(`TransformPositionX`…)+- `applyAnimatedValue()` 一个 ~40 路 `switch`,逐字段直接写结构体成员;末路 `CustomField` 空 case(TS 兜底)。-- `src/esengine/animation/animTargets.generated.ts` —— `FIELD_MAP: Record<component, Record<path, enum>>` 镜像。-- 生成器 `tools/eht/generators/anim_target.py` —— **与** `metadata.py`(`COMPONENT_META.animatableFields`)/- `ptr_layout.py`(`PTR_LAYOUTS`)**同源**于 `ES_PROPERTY(animatable)`。即:可动画字段已有引擎权威表,枚举是第二套真源。-- **逐字段语义不可省**:`rotation.z` 欧拉角→四元数 `glm::quat(cos h,0,0,sin h)`、UIRect `anim_override_` 标志等——- 重构不是"删 switch",是"把 switch 改成数据驱动的 `path → writer` 反射表",逐字段语义保留为表项。--### G2:每种轨道一个 binding(刚性)-- `src/esengine/bindings/TimelineBindings.cpp` —— `tl_addPropertyTrack` / `tl_addSpineTrack` / `tl_addAudioTrack` /- `tl_addActivationTrack` / `tl_addSpriteAnimTrack` / `tl_addCustomPropertyTrack`,各自手工 float 打包。- 每加一种轨道都要动 C++ binding + `TimelineUploader.ts` 分支。--### G3:脑裂 + 每帧轮询结果缓冲-- C++ 持运行时 timeline(`TimelineSystem.cpp` / `TimelineData.hpp`),TS 持文档(`TimelineTypes.ts`),- 靠 `TimelineUploader.ts` re-upload 同步——两份真源。-- side-effect 走"结果缓冲轮询":`TimelineBindings.cpp` `tl_getEventCount/getEventType/...` +- `tl_getCustomPropertyCount/...`,TS 端 `TimelineRuntime.ts` `processTimelineEvents()` / `processCustomProperties()`- 每帧循环跨 WASM 边界拉取再 `tl_clearResults()`。(同款 poll 模式 spine 也有,是 WASM 边界产物,非通用范式。)--### G4:没有 scrub 原语、没有创作/序列化-- `TimelineSystem.cpp:388` `evaluateAt()` 只回**裸通道值不应用**;`advance()`(:362)应用但只能按 dt **前进**——- 编辑器拖播放头没有"在任意 T 采样并应用"的干净入口。-- 全栈**没有任何创作 API**(add/remove track、add/move/setInterp keyframe),**没有序列化器**- (`TimelineLoader.ts` 只解析 `.estimeline`,无逆向写盘);`Marker`/`CustomEvent` 是只声明不实现的空桩。--### G5:4 份重复 easing + 两套 keyframe 类型-- `src/esengine/animation/EasingFunctions.hpp`(全集,仅 Tween 用)、`TimelineSystem.cpp:114-124`(内联重复 3 个)、- `src/esengine/particle/ParticleEasing.hpp`(子集)、`sdk/src/camera/CameraDirector.ts` `applyCurve()`(第三套)。-- TS 侧 `sdk/src/animation/Easing.ts` 已是 C++ 全集的 1:1 端口(可直接当统一 TS 源)。-- Timeline 有带切线的 `TimelineKeyframe`(最富),Tween 只有隐式 from/to+easing——无统一 `Keyframe`。--### G6:编辑器完全没有动画面板-- `desktop/src/panels/` 只有 Outliner/Viewport/Details/ContentBrowser/OutputLog/GamePanel;- `DockLayout.tsx` 组件表无 sequencer;设计稿底部停靠 tab「动画 Sequencer」缺席。-------## 2. 目标架构(四层)--每层都**复用**引擎/编辑器已有的权威机制,而非再造。--### L1 —— 统一反射写入层(codegen,C++ + TS 双镜像)-- 由 `ES_PROPERTY(animatable)` 生成一张**数据驱动写入表** `path → writer`,取代 `AnimTargetField` 枚举 + switch + `FIELD_MAP`。- - C++:`ComponentFieldRegistry`(typeId → {name, offset, type, applyFn}),`applyFn` 承载逐字段语义(quat 转换、override 标志)。- - TS:复用既有 `PTR_LAYOUTS` + `writePtrField`,特例字段配套 writer(mirror C++ applyFn)。-- **唯一写入路径**:Tween(C++)、Timeline(TS)、编辑器预览全部经此,与 Inspector/序列化同源。-- 产出:删 `animTargets.generated.{hpp,ts}` 的枚举/switch/FIELD_MAP,改为生成 registry/表。--### L2 —— 统一 easing / keyframe 数学-- C++ `SharedEasing.hpp`(由 `EasingFunctions.hpp` 提升)+ TS `Easing.ts`(已存在端口);删 Timeline 内联、Particle 子集、Camera 第三套(改为委托/共享)。-- 单一 `Keyframe { time, value, interp, inTangent, outTangent }` + `evaluateChannel(channel, t)`;Hermite/Linear/Step/Ease* 各模式集中一处。--### L3 —— Timeline 运行时:纯 TS(文档即运行时)-- `TimelineEvaluator.sample(doc, t, ctx)`:求值属性通道→走 L1 写入;side-effect(audio/spine/spriteAnim/activation/event)- 在 TS 内**边沿检测**(prevT→t)直接调对应 JS 子系统(`audio.playSFX` / `SpineManager.setAnimation` / SpriteAnimator / world.set)。-- forward play 与 scrub **同一入口**(play = 累加 t 后 sample;scrub = 任意 T 直接 sample)→ scrub 免费。-- 删 C++ `TimelineSystem`/`TimelineData`、`tl_add*Track`、poll 缓冲;`TimelinePlugin` 改为驱动 TS evaluator。-- **Tween 留 C++** 批量快路径,apply 改走 L1 的 C++ registry。--### L4 —— 创作层 + Sequencer 面板(编辑器,全新)-- **资产文档会话**(首个,镜像 `EditorSession`/`SceneModel`/`Reconciler`/`SceneCommands`/`SceneStore`/`SceneQuery`/`EditorHistory`):- - `TimelineDocument`(= `.estimeline` JSON,**也就是 L3 的运行时对象**,无独立 upload)。- - `TimelineCommands`(addTrack/removeTrack/mute/addKey/moveKey/deleteKey/setValue/setInterp/setDuration/setFps/setWrap),- 每步经**同一** `EditorHistory`/`TransactionManager` 可撤销。- - 响应式 `TimelineStore` + `TimelineQuery` + `TimelineSerializer`(`TimelineLoader` 的逆)。- - 抽成 `AssetDocumentSession<T>` 基类——瓦片集/瓦片地图编辑器后续复用。-- **`Sequencer.tsx`**:底部停靠 tab(与 Content/Log 并排,`referencePanel:'content', direction:'within'`)+ ActivityBar 入口 +- `editorStore` sequencer 态(当前 clip、播放头 time/frame、选中关键帧、录制)。- 传输条 / 轨道树(实体→组件→属性)/ 时间轴(标尺·帧网格·可拖播放头·关键帧道)/ 摄影表⇄曲线 / 精灵帧条 / 插值弹窗 / 吸附帧 / 录制(自动打帧)。- 复用 Details 的 scrub 手势 + 色板 token;"添加轨道"选择器由 `COMPONENT_META.animatableFields` + 选中实体层级(childPath)驱动。-- **实时预览**:拖播放头/改关键帧 → 在播放头处 `evaluator.sample` 应用到绑定实体 → 视口即刷(scrub 免费的兑现点)。--### 资产格式说明-- **`.estimeline`** = 多轨 Sequencer 文档(property/spine/audio/activation/spriteAnim 轨 + Hermite/Linear/Step/Ease*)——本次 Sequencer 的编辑对象。-- **`.esanim`**(AnimClip 精灵翻页,`AnimClipLoader.ts`)保持独立,作为 Sequencer 底部「精灵帧条」/ SpriteAnim 轨的来源。-- 设计稿把 clip 写成 `Walk.esanim` 是 mockup 笔误;落地以 `.estimeline` 为 Sequencer 文档格式(沿用 loader version "1.1")。-------## 3. 分阶段计划(编辑器优先)--> 每阶段可独立验证、可单独提交。P1–P3 让编辑器先跑起来(建在最小新 TS runtime 上),P4 回收 C++ 临时实现,P5 收尾通用化。--- **P1 —— 端到端可见闭环(证明 seam)**- L3 最小核(仅属性轨)`TimelineEvaluator.sample` + L4 文档会话骨架 + `TimelineSerializer`(读已有 + 写)。- `Sequencer.tsx` 注册进底部停靠 + ActivityBar + store;开 `.estimeline`(Content Browser 双击 / 选中实体的 TimelinePlayer)→ 渲染轨道树 + 关键帧道 + 播放头;- 拖播放头 → `sample` 应用到绑定实体 → 视口实时动。**验收:开真实 `.estimeline` → 见轨道 → 拖播放头角色动起来。**--- **P2 —— 编辑 + 撤销 + 存盘**- `TimelineCommands`(add/move/delete key、setValue、setInterp)经 `EditorHistory` 手势;关键帧拖拽(时间+值)、插值弹窗、吸附帧;- 存盘走 Electron fs(`ProjectStore`);录制态(auto-key:录制中改 Inspector 受跟踪属性 → 在播放头插帧)。**验收:打帧/拖帧/改插值/撤销重做/存盘往返。**--- **P3 —— 轨道创作 + 传输 + 曲线视图**- 添加轨道选择器(`COMPONENT_META.animatableFields` + 实体层级 childPath);静音/独奏、duration/fps/wrap 编辑、分组折叠;- 曲线视图(hermite/bezier 手柄)+ 摄影表⇄曲线切换;编辑态播放循环(rAF 驱动 sample)+ 上/下关键帧 + loop;精灵帧条(AnimFrames / SpriteAnimator)。--- **P4 —— 回收 C++ 临时实现(引擎重构落地)**- side-effect 派发全部并入 TS evaluator(边沿检测)→ 删 C++ `TimelineSystem`/`TimelineData`/`TimelineBindings`(`tl_*`)+ poll 缓冲;- 生成 L1 反射写入表(C+++TS)→ 删 `animTargets` 枚举/switch/FIELD_MAP,Tween 的 C++ apply 改走新 registry;合并 easing(4→1)。- **预期 `esengine.wasm` 体积下降**(同 spine 重构 -503KB 的量级方向)。**验收:全测试绿 + wasm 重建 + 体积对比。**--- **P5 —— 通用化收尾(可选)**- 抽 `AssetDocumentSession<T>` 基类;为 Animator/状态机层(设计稿 `Animator` 组件)预留组合点;瓦片集/瓦片地图编辑器复用同基类。-------## 4. 风险 / 注记-- **堆布局特例**:`writePtrField` 写的是 C++ 堆布局,少数字段 JS 形状与堆布局背离(如 Camera `viewport` vec4 vs JS viewportX/Y/W/H)。- L1 生成器同时知道偏移与打包,特例配套 writer;不可对所有字段裸 poke。-- **rotation.z 语义**:JS Transform 用四元数;动画"rotation.z"按欧拉角需转换——L1 writer 表项承担,TS/C++ 两侧对齐。-- **确定性**:play-realm 本就跑 SDK(TS);TS 定步求值与原 C++ 数值一致即可,无新确定性风险。-- **P4 之前**:P1–P3 期间 C++ 旧 timeline 与新 TS evaluator **并存**(编辑器走新核,运行时旧核暂留),P4 才删旧核,避免中途破坏现有运行时播放。-</content>-</invoke>diff --git a/docs/REARCH_ASSETS.md b/docs/REARCH_ASSETS.mddeleted file mode 100644index c0748aa35..000000000--- a/docs/REARCH_ASSETS.md+++ /dev/null@@ -1,200 +0,0 @@-# REARCH — Unified Asset Pipeline (AssetDatabase)--Status: **design / proposed**. Authoritative plan for the engine's second spine —-**content/assets** — complementing the document/scene spine built in-`REARCH_EDITOR_MODEL.md` (model-authoritative editor) and-`REARCH_SERIALIZATION.md` (JSON-first scenes). It is the foundation the Content-Browser, prefabs (`REARCH_PREFABS.md`, future), materials/fonts/audio in the-editor, hot-reload, and the ship/cook path all sit on.--## 1. Problem: a strong runtime asset system the editor doesn't use--The **runtime** already has a capable asset system — it is not the gap:--- `sdk/src/asset/Assets.ts` loads every type (`loadTexture`/`loadMaterial`/- `loadFont`/`loadAudio`/`loadSpine`/`loadAnimClip`/`loadTilemap`/`loadTimeline`/- `loadPrefab`), with ref-counted caches, hot-reload (`invalidate` / `onInvalidate`),- a pluggable `setAssetRefResolver` / `setAssetRegistry`, and scene-level- `preloadSceneAssets` + `resolveSceneAssetPaths`.-- `sdk/src/asset/AssetRegistry.ts` resolves `@uuid:` → path (`resolveRef` /- `uuidToPath`); `sdk/src/runtimeLoader.ts` abstracts fetching per platform.-- `tools/asset-meta.js` generates per-asset `.meta` sidecars- (`{uuid, version, type, importer}`) for ~all types and can `--emit-manifest`.-- `.esprefab` files + `Assets.loadPrefab` already exist (e.g.- `examples/space-shooter/assets/prefabs/*`).--The gap is **the editor and the project layer**:--- **The editor re-implements a texture-only subset.** `ProjectStore.resolveTextures`- scans `.meta`, loads **only textures** via `estella://`, and writes its own- `uuidToHandle` map — bypassing the engine `Assets`/`AssetRegistry`. Its own- comment: *"material/font refs aren't served yet."* So in the viewport,- materials/fonts/audio/spine/tilemap refs resolve to handle `0` (blank).-- **Three duplicate resolution paths.** `ProjectStore.resolveTextures`,- `SceneLoader.loadTextures`, and the P1 `Reconciler.setAssetResolver` each- collect uuids → load → map to handles independently. They drift.-- **No project-wide AssetDatabase.** `.meta` generation is a one-shot CLI;- `AssetRegistry` is a runtime manifest. Nothing in the editor *lives*: scans the- project, watches for changes, tracks dependencies, and serves one index to the- Content Browser + the registry + the cook.-- **Content Browser is read-only.** `ContentBrowser.tsx` lists/searches/previews- but Import/Add are disabled and tiles are `draggable={false}` — no import, no- drag-assign to inspector fields.-- **No cook/ship step.** `asset-meta.js --emit-manifest` exists, but- `build-tools/cli.js` does not dedupe / transcode / bundle assets per target- (web / wechat / native).-- **Asset-field knowledge is split** across `AssetFieldRegistry` (builtins),- `component.generated.ts`, and `extractSchemas` (user components).--**One root cause:** there is no single project-level **AssetDatabase** that the-editor, the runtime loader, and the cook all read — so the editor improvised a-texture-only slice instead of feeding the engine's existing loader.--## 2. Principle: one AssetDatabase, the content source of truth--Mirror the model-authoritative principle on the **content axis**: a single-**AssetDatabase** owns *what assets exist* (guid / type / importer / dependencies);-the editor, the engine `Assets` loader, and the cook are all **derived consumers**-of it. The editor stops resolving assets itself — it builds an `AssetRegistry`-from the DB, hands it to the engine `Assets` (`setAssetRegistry`), and reuses-`preloadSceneAssets` / `resolveSceneAssetPaths`. `@uuid:` stays the portable ref-in the lossless model; the DB is what turns a `@uuid:` into a live handle, for-**every** type, in editor and runtime alike.--```- ┌────────── AssetDatabase (main process, single index) ─────────┐- Importers ──write│ scan project → .meta {guid, type, importer, deps} │── change events ─┐- (texture/audio/ │ dependency graph guid→[guid]; cooked/preview cache by guid │ │- font/spine/...) │ artifact: .esengine/cache/assets.json (like schemas.json) │ ▼- └────────────────────────────────────────────────────────────────┘ ┌──────────────────┐- │ serve (guid|path) │ registry │ cook │ │ hot-reload │- ▼ ▼ ▼ │ │ Assets.invalidate│- estella:// AssetServer engine Assets.setAssetRegistry build-tools → │ └──────────────────┘- (editor preview + runtime) + preloadSceneAssets + bundles +- resolveSceneAssetPaths assets.manifest- │- ▼- the ONE resolution path: editor + runtime + cook- all turn @uuid: → handle through engine Assets-```--This is the pattern mature engines converge on: Unity's AssetDatabase + import-pipeline + addressables, UE's Asset Registry + Cooker. The **runtime** half-already exists here; this rearch builds the **project/editor** half and unifies-the two.--## 3. Target architecture (6 layers)--1. **AssetDatabase** (main process, alongside `extractSchemas`/`buildScripts`) —- scans the project, reads/writes `.meta` (the git-friendly per-asset truth),- builds the guid↔path index + dependency graph, watches the fs, and emits- `.esengine/cache/assets.json` (the fast index artifact). One IPC surface- (`project:assets*`) to the renderer.-2. **Importers** — per-type, producing import settings + (where needed) a cooked- or preview artifact keyed by guid. Reuse `tools/asset-meta.js`'s extension→type- map and default importer settings as the seed.-3. **AssetServer** — generalize the `estella://` handler (already serves project- files by path) to also serve **by guid** (via the DB index) and to serve the- manifest. One transport for editor preview AND runtime fetch.-4. **Editor↔engine unification** — on project open the editor builds an- `AssetRegistry` from the DB and calls `Assets.setAssetRegistry`; scene load- uses `Assets.preloadSceneAssets` + `resolveSceneAssetPaths`; the P1- `Reconciler` asset resolver delegates to the registry/`Assets` for **all**- types. The three duplicate paths collapse to one. Hot-reload: DB fs-watch →- `Assets.invalidate(guid)` → Reconciler re-projects.-5. **Content workflow** — Content Browser **import** (copy file in + write `.meta`- via the DB), **drag-assign** (drag a guid onto an inspector asset field →- `SceneCommands.setField('@uuid:'+guid)`; model-authoritative, undoable), and- **inspector asset-field controls** per type, resolved from a single asset-field- source. The asset ref edit flows through the same model→Reconciler→Assets path.-6. **Cook / ship** — `build-tools` walks the DB dependency graph from the entry- scene(s), transcodes/compresses/dedupes per target, emits bundles +- `assets.manifest`. The isolated play realm (`REARCH_EDITOR_MODEL` P3) loads the- **same** manifest → `play == ship` for assets too.--## 4. How each problem dissolves (structural, not patched)--| Problem | Why it goes away |-|---|---|-| Editor resolves textures only | The editor feeds the DB's registry to engine `Assets` and reuses `preloadSceneAssets`; every type resolves the way the runtime already loads it. |-| 3 duplicate resolution paths | One path: `@uuid:` → DB registry → `Assets` handle. `ProjectStore.resolveTextures` + `SceneLoader.loadTextures` are deleted; the Reconciler resolver delegates to `Assets`. |-| No project-wide asset index | The AssetDatabase is the live index (scan + watch + deps), the single source the Content Browser, registry, and cook read. |-| Content Browser read-only | Import writes file + `.meta` through the DB; drag-assign emits a model `setField` of the guid. |-| No ship/cook | The cook walks the DB dep graph → per-target bundles + manifest; the play realm loads the same manifest. |-| Asset-field knowledge split | One asset-field source (folded into the DB/schema layer) drives builtin + user components alike. |-| Non-texture assets uneditable in inspector | They resolve now (layer 4) and get per-type controls (layer 5). |--## 5. Phased migration (reuse-heavy, not a rewrite)--- **A1 — Unify the editor onto the engine `Assets`; collapse the 3 paths**- (highest ROI). The editor builds an `AssetRegistry` from `.meta` and uses- `Assets.setAssetRegistry` + `preloadSceneAssets` + `resolveSceneAssetPaths`;- the Reconciler resolver delegates to it. Outcome: **every** asset type resolves- and previews in the viewport; pure wiring over existing engine code.-- **A2 — AssetDatabase service.** Live scan + fs-watch + dependency graph +- `.esengine/cache/assets.json` artifact + `project:assets*` IPC; it becomes the- registry source (replacing the ad-hoc `.meta` scan) and the Content Browser's- data source. Hot-reload wired through `Assets.invalidate`.-- **A3 — Content workflow.** Content Browser import + drag-assign; inspector- asset-field controls for all types; a single asset-field source.-- **A4 — Cook / bundle.** Per-target transcode/dedupe/bundle from the dep graph +- `assets.manifest`, integrated into the build CLI; closes `play == ship` with the- play realm.-- **A5 — Prefabs** (own doc `REARCH_PREFABS.md`): the `.esprefab` format +- `Assets.loadPrefab` exist; the editor authoring — prefab **instance + overrides**- on the model-authoritative `SceneModel` (an override *is* a document delta) — is- the payoff layer this pipeline unlocks.--## 6. A1 — detailed implementation checklist--Goal: one resolution path; all asset types resolve in the editor viewport;-`@uuid:` stays lossless in the model.--**Editor registry from `.meta`**-- On project open, build an `AssetRegistry` from the project's `.meta` files- (reuse `tools/asset-meta.js`'s scan, or `AssetRegistry` + a manifest emitted by- it) and call `EngineHost.getResource(Assets).setAssetRegistry(registry)`.-- Set the `estella://`-based fetch path on `Assets` (the runtime loader) so it- fetches project files through the protocol (it already serves them).--**`ProjectStore.loadCurrentScene`** (replace texture-only resolution)-- Replace `resolveTextures` with `Assets.preloadSceneAssets(raw)` (async, all- types) → `resolveSceneAssetPaths` to produce the resolved scene for- `resetWorldTo`. Keep the **raw** `@uuid:` scene as the model (lossless, P1).-- Delete `mapAssetRefs`/`collectUuids`/`uuidToHandle` from ProjectStore.--**`Reconciler` resolver** (P1 `setAssetResolver`)-- Delegate `@uuid:` → handle to the registry/`Assets` for **all** types (not the- texture-only map). Keep it a **sync** lookup of already-preloaded handles (see- Open decisions: async). For incremental recreate (duplicate/undo) the refs were- preloaded at scene load, so the lookup hits.--**`SceneLoader.loadInto`** — route through `Assets` + the registry (delete its-private `loadTextures`); editor + runtime now share one loader.--**Hot-reload** — DB/file change → `Assets.invalidate(guid)` → Reconciler-re-projects the affected components.--**Tests**-- Load a scene referencing a material/font/spine asset → handles are non-zero →- viewport renders (not blank). Round-trip keeps `@uuid:` in the model.-- Duplicate/undo an entity with an asset ref → the recreated World entity keeps- the resolved asset (no regression vs the P1 texture path).-- One-path assertion: ProjectStore no longer holds a uuid→handle map.--## 7. Open decisions--- **Async loads vs the synchronous Reconciler.** Asset loads are async; the- World projection is sync. Pattern: **preload at the boundary** (scene load,- drag-assign) so projection-time lookups are sync hits. A NEW ref assigned via- the inspector must `await Assets.load*` before/within `setField` so the handle- is ready when the Reconciler projects. (Alternative: project a placeholder- handle, patch on resolve — more complex; defer.)-- **`.meta` (per-asset, git-friendly) vs `assets.json` (fast index).** Keep- `.meta` as the authored truth; the DB derives `assets.json` as a cache (rebuilt- on scan), the same artifact pattern as `schemas.json`/`scripts.mjs`.-- **guid scheme** stays UUID v4 (already established; do not change).-- **DB location** — main process (fs + watch), with an IPC index to the renderer,- consistent with `extractSchemas`/`buildScripts`.-- **Where importers run** — pure-node in main (like `extractSchemas`), so cook is- headless-capable.diff --git a/docs/REARCH_EDITOR_AUTOMATION.md b/docs/REARCH_EDITOR_AUTOMATION.mddeleted file mode 100644index 00daaaf57..000000000--- a/docs/REARCH_EDITOR_AUTOMATION.md+++ /dev/null@@ -1,218 +0,0 @@-# REARCH — Editor Automation & Observation Surface (toward an editor MCP)--## Why--Two needs converge on the same architecture:--1. **Verification is blocked at the pixel surface.** Logic and state can be verified- headlessly today (the Spine 3.8 module load + animate test runs the real- `spine38.wasm` in node and asserts a bone advances). But "does it actually- rasterize on screen" cannot be observed without a human looking at the editor —- the headless test path has no GL context, and an external agent cannot reach the- live Electron renderer. Every render-correctness change ends in a manual smoke- test.-2. **A future editor MCP** wants exactly the same thing: a clean, typed surface an- agent can call to open a project, mutate a scene, drive a frame, and read back- what happened — including the rendered pixels.--The answer to both is one canonical, transport-agnostic **EditorControlSurface**-(command + query + observation), plus the two primitives that make render-verification meaningful and reachable: a deterministic engine **step**, and a-**headless render host** that owns a real WebGL2 context. The MCP server is then a-thin transport adapter over that surface — not a parallel API.--## Diagnosis — the programmatic surface that exists today--| Layer | Where | What it gives | Gap |-|---|---|---|---|-| Mutations | `desktop/src/engine/SceneCommands.ts` | `addEntity` / `deleteEntity` / `duplicateEntity` / `renameEntity` / `setField` / `setEntityXY` / `beginGesture` / `endGesture`; dual-writes World + `SceneModel`; every edit undoable via `EditorHistory` | No `setComponent` (add/remove a whole component), no asset-ref set helper |-| Reads | `desktop/src/engine/SceneQuery.ts` | `worldVersion` / `readSceneTree` / `readEntity` / `readInspector` / `getFieldValue` | — |-| Truth | `desktop/src/engine/SceneModel.ts` | JSON-first `SceneData` (lossless: unknown components, `@uuid:` refs, `visible:false` entities); `serialize()` | — |-| Engine bridge | `desktop/src/engine/EngineHost.ts` (renderer) | owns `module`, **WebGL2 `canvas`**, live `World`; `setRunMode(isPlaying,isPaused)`; `getResource` | Loop is Emscripten rAF (`app.run()`) — **no deterministic `step(dt)`**; capture is whatever frame rAF landed on |-| Picking / transforms | `desktop/src/engine/ViewportController.ts` | `pickEntity` / `getEntityScreenRect` / `getEntityXY` / `canvasToWorld` | — |-| Telemetry | `desktop/src/engine/StatsStore.ts` | `{ fps, entities, cursor }` (sampled, not per-frame) | No draw-call / batch stats; no per-entity render state |-| Asset load | `desktop/src/engine/SceneLoader.ts` | `loadInto(app, sceneUrl, manifestUrl)` — resolves `@uuid:` → texture handles, spawns | — |-| Transport | `desktop/electron/{main,preload}.ts` | pure `ipcMain.handle` + `estella://` protocol | **No local server**; nothing an external process can attach to |-| Headless test | `desktop/tests/**`, `tests/helpers/loadWasm.ts` | constructs `App` + `Registry` in **pure node, no canvas** | **No GL → cannot rasterize → cannot pixel-verify** |--The command/query core is already correct and already unit-tested. What's missing is-(a) a single composed entry point over it, (b) the two render primitives, and-(c) a transport an agent can reach.--## Target architecture--```- Consumers- ─────────- React UI (existing) vitest (logic/state) Agent / editor MCP client- │ │ │- │ direct calls │ direct calls ┌─────▼──────────────┐- │ (renderer) │ (in-proc) │ Editor MCP server │ P2- │ │ │ main process │- │ │ │ Streamable HTTP │ (attach to live editor)- │ │ │ + stdio │ (spawn headless host)- │ │ └─────┬──────────────┘- │ │ │ editor:rpc IPC- ▼ ▼ ▼- ┌──────────────────────────────────────────────────────────────────────────┐- │ EditorControlSurface — the ONE canonical programmatic API (renderer) │ P1- │ │- │ Lifecycle openProject · loadScene · saveScene · setRunMode · step │- │ Commands addEntity · deleteEntity · setComponent · setField · … │ (over SceneCommands)- │ Queries getSceneTree · getEntity · getInspector · getProjectInfo │ (over SceneQuery / SceneModel)- │ Observe captureViewport · getEntityRenderState · getStats · pickAt │ (over canvas/GL + ViewportController)- └──────────────────────────────────────────────────────────────────────────┘- │ │ │- ▼ ▼ ▼- SceneCommands SceneQuery/Model EngineHost (canvas, WebGL2, World, step)-```--### The EditorControlSurface (P1) — one API, four pillars--A new renderer-side module `desktop/src/engine/EditorControlSurface.ts` that **composes-the existing modules** — it adds no new truth, it is the single front door.--- **Lifecycle** — `openProject(root)`, `loadScene(rel)`, `saveScene()`,- `setRunMode({playing,paused})`, and the new **`step(frames, dt)`** (see below).-- **Commands** — pass-throughs to `SceneCommands` plus two small additions the agent- needs that the UI does today by other means: `setComponent(entity, type, data)` /- `removeComponent(entity, type)` (add/remove a whole component), and- `setAssetRef(entity, type, key, uuid)` (set a `@uuid:` ref via `SceneModel`, the way- the inspector's asset picker does). Everything stays undoable.-- **Queries** — pass-throughs to `SceneQuery` + `SceneModel.serialize()` +- `getProjectInfo()` (root, scene list, build/schema-cache status).-- **Observe** — the verification-closing pillar:- - `captureViewport({region?, maxWidth?}) → { png: Uint8Array, w, h }` — read the- WebGL2 framebuffer (`gl.readPixels` into a canvas → PNG, or `canvas.toDataURL`).- The agent literally sees the frame.- - `getEntityRenderState(id) → { worldTransform, screenRect, visible, inFrustum }` —- `ViewportController.getEntityScreenRect` + world transform. Cheap, deterministic,- diff-friendly — often enough to verify without a screenshot.- - `getStats() → { fps, entities, drawCalls?, batches? }` — `StatsStore` plus- draw-call/batch counters surfaced from the renderer (small engine add).- - `pickAt(x, y) → EntityId | null` — `ViewportController.pickEntity`.--The surface is **transport-agnostic**: the same object is called directly by the-React UI, in-process by a test, and (via IPC marshalling) by the MCP server. It is-directly unit-testable in the existing vitest harness.--### Determinism primitive — engine `step(dt)` (already exists)--Render verification is only meaningful if it is reproducible. Today the editor drives-`app.run()` (Emscripten rAF) — a capture reflects whatever frame rAF happened to be on.--**The primitive already exists: `App.tick(delta)` (`sdk/src/app.ts:465`).** `tick` does-the same lazy init `run()` does (SystemRunner, `Time` resource, `finishPlugins_`), then-`flushStartupSystems_()` + `runFrame_(delta)` — exactly one frame, with the supplied-delta, no wall-clock, **no rAF, no `'unwind'`**. `run()` is just that same setup plus a-self-driving `mainLoop` that computes wall-clock delta and `requestAnimationFrame`s-`runFrame_`. So the surface's `step(frames, dt)` is `for … await app.tick(dt)` — and the-headless host simply calls `tick()` N times **instead of** `run()`. **No engine/SDK-change.** Canonical recipe: `loadScene → setRunMode(play) → step(30, 1/60) →-captureViewport → assert`.--The same wall-clock-free drive serves the isolated play realm (REARCH_EDITOR_REALM-R0–R2). Most of the surface (commands, queries, lifecycle, `step` via `tick`) is also-testable in the existing **pure-node vitest** (which already constructs `App` + mocks-`EngineHost`); only `captureViewport` needs the WebGL2 window.--### Render host — where pixels actually rasterize--`captureViewport` needs a real **WebGL2** context. Two hosts provide the surface; pick-per task:--| Host | GL | Use | Notes |-|---|---|---|---|-| **Live editor** (renderer) | real WebGL2 | interactive / MCP-over-HTTP | the running GUI a human also uses |-| **Headless editor** (Electron `BrowserWindow {show:false}` / offscreen) | real WebGL2 (Chromium SwiftShader/ANGLE) | agent verification, CI, MCP-over-stdio | boots the editor with no visible window, drives the surface programmatically |-| pure-node vitest | **none** | logic/state only | keeps verifying World/command correctness; **cannot** pixel-verify |--The decisive choice: **the headless render host is a headless boot of the real editor**,-not a separate `headless-gl` rig. `headless-gl` (`gl` npm) is WebGL1-only — a dead end-for a WebGL2 engine. A `show:false` Electron window gives a real Chromium WebGL2-context, reuses the actual boot path (`createWebApp(..., wasmBaseUrl:'/wasm')`,-`registerContext`), and **doubles as the MCP-over-stdio host**. One host serves both-"my verification driver" and "the editor MCP transport."--## MCP mapping (P2) — tools, resources, transport--Grounded in MCP tool-design practice: dedicated typed tools (not a bash escape hatch)-so the editor can validate, gate, and audit each action; strict JSON schemas-(`additionalProperties:false`, explicit `required`); prescriptive descriptions that-state *when* to call.--- **Commands → MCP tools** (side effects, need gating). `editor_add_entity`,- `editor_delete_entity`, `editor_set_component`, `editor_set_field`,- `editor_load_scene`, `editor_set_run_mode`, `editor_step`.-- **Observations → MCP tools returning image content** — `editor_capture_viewport`- returns an MCP **image content block**, so the agent sees the frame inline.- `editor_get_render_state`, `editor_get_stats`, `editor_pick_at` return JSON.-- **Stable reads → MCP resources** (read-only, addressable, cacheable context, kept- out of the tool list): `editor://scene/tree`, `editor://scene/{entity}/inspector`,- `editor://project`. Parametric reads stay tools.--**Transport: Streamable HTTP as primary, stdio for headless.**-- **Streamable HTTP** — the editor's main process hosts `http://127.0.0.1:<port>/mcp`;- an agent attaches to the **already-running** GUI. Right because the editor is a- long-lived process a human also uses (stdio would force the client to own the editor- as a subprocess).-- **stdio** — for `--headless` boots where the agent spawns the editor (CI, autonomous- verification). Same surface, different framing.--Both bind localhost only and sit behind a **permission policy**:-- `read` — queries + observations always allowed.-- `write` — mutations gated; default off, enabled with `--allow-writes` or a UI toggle,- so an agent cannot silently rewrite the user's project. Transient verification- scenes (load → step → capture, no save) need only `read` + ephemeral mutation, never- `saveScene`.-- Destructive/outward ops (`saveScene` overwrite, `openProject`) always require explicit- opt-in.--The MCP server is `desktop/electron/mcp/` in the main process; it marshals each tool-call to the renderer surface over a new `editor:rpc` IPC channel pair and marshals the-result (PNG bytes → image content) back.--## Phases--- **P1 — EditorControlSurface + `step` + headless render host.**- - `EditorControlSurface.ts` composing the existing modules (commands/queries/observe).- - Engine `app.tick(dt)` manual-step entry; surface `step(frames, dt)`.- - Headless editor boot (`show:false`) that instantiates the surface.- - **Deliverable that closes the current gap:** a verification run that does- `loadScene(spine 3.8 spineboy) → step(30,1/60) → captureViewport → assert the- spine region is non-blank / matches a reference`. This pixel-verifies Spine S1- (and every future render change) **without a human**. P1 is self-contained and- immediately useful even before any MCP exists.-- **P2 — Editor MCP server.**- - `desktop/electron/mcp/` MCP server (official SDK), Streamable HTTP + stdio.- - Tools/resources per the mapping above; `capture_viewport` → image content.- - `editor:rpc` IPC bridge main↔renderer; permission policy (`read` / `write`).- - **Deliverable:** an agent connects to a live or headless editor and drives the- full loop (open project · add a sprite/spine entity · set its asset · step · see- the viewport · read the scene tree).--## Open risks--- ~~**WebGL2 in headless Electron**~~ — **RETIRED.** A `show:false` `BrowserWindow` gives- a usable WebGL2 context with the engine's exact context options, and `gl.readPixels`- returns the expected color. Evidence (de-risk spike, electron 42 on macOS):- `{"ok":true,"version":"WebGL 2.0 (OpenGL ES 3.0 Chromium)","pixel":[255,0,0,255]}`.- (`headless-gl` was never an option — WebGL1 only.) CI/Linux-headless still to confirm- (SwiftShader fallback; `enable-unsafe-swiftshader` already wired in the spike).-- ~~**`step(dt)` vs the Emscripten main loop**~~ — **RETIRED.** `App.tick(delta)` already- exists and shares `runFrame_` with `run()`'s `mainLoop`; the headless host calls- `tick()` instead of `run()`, so there is no rAF loop to co-exist with. No engine change.-- **Capture determinism** — texture upload / async asset load must be settled before- the captured frame; `loadScene` resolves textures before spawn, but verify nothing- uploads lazily on first draw (one warm-up `step` before the asserted capture if so).-- **Pixel comparison** — reference-image diffing needs a tolerance (driver AA, SwiftShader- vs hardware). Prefer structural assertions (region non-blank, bounding box, draw-call- count, `getEntityRenderState`) over exact pixel equality where possible.--## Cross-links--- Determinism/host shares the wall-clock-free drive of REARCH_EDITOR_REALM (R0–R2,- isolated play realm) — build the step primitive once.-- First consumer is the Spine rearch (REARCH_SPINE S1 pixel verification, then S2- pixel-parity vs native 4.2) — the spineboy asset ships for 3.8/4.1/4.2 at the same- example path, ideal for reference-image parity.diff --git a/docs/REARCH_EDITOR_MODEL.md b/docs/REARCH_EDITOR_MODEL.mddeleted file mode 100644index 1a484ec72..000000000--- a/docs/REARCH_EDITOR_MODEL.md+++ /dev/null@@ -1,232 +0,0 @@-# REARCH — Model-Authoritative Editor (unidirectional data flow)--Status: **P1 + P2-core implemented** (2026-06-20); P3 proposed. Authoritative-plan for inverting the editor's data flow from *dual-write* to a single source of-truth with derived projections. This is the natural completion of-`REARCH_SERIALIZATION.md` (JSON-first model) and the prerequisite for-`REARCH_EDITOR_REALM.md` (isolated play).--**P2-core done** — the engine-state singletons are now instance classes wired by-constructor injection (`SceneModelImpl`/`EditorHistoryImpl`/`SceneStoreImpl`/-`ReconcilerImpl`/`SceneCommandsImpl`/`SceneQueryImpl` + `createSelectionStore`).-A new `desktop/src/engine/EditorSession.ts` owns the whole graph as ONE instance;-`EditorControlSurface` is its façade (`EditorControlSurfaceImpl(session)`).-`EditorSession.create()` builds an isolated session (fresh model/history/.../World-projection) for a headless host, the MCP server, or a test — proven by migrating-every wasm test to a per-test session (no shared-singleton `clear()`). The app's-default-session singletons are preserved, so the UI/EngineHost are unchanged.-**Remaining P2 (gradual):** route the UI through `session`/the surface (full H2-closure) and decouple EngineHost from the default-session reconciler — these need-no new design, just mechanical migration; genuine multi-World sessions await the-engine-instancing pillar. RESUME: finish P2 UI-routing **or** start **P3**-(isolated play realm).--**P1 done** — commands mutate the `SceneModel` (by stable source id) only; a new-`desktop/src/engine/Reconciler.ts` projects model→World (the World is now a pure-derived projection); `SceneStore` is a model-change bus (the engine `editorBridge`-is retired as the editor reactivity source); `SceneQuery` reads the model;-selection is source ids self-healing on the model's `entityRemoved`; the-`schemas.json` consumer (`schema.ts`) makes unknown/user components inspectable +-editable; `setRunMode` Stop rebuilds the World from the untouched model (no-snapshot/restore); scene load clears history + selection. 64 desktop vitest pass-(+ `inspector-model.test.ts`, hierarchy/unknown lossless-undo). RESUME: **P2**-(EditorSession instance + EditorControlSurface as its façade), then **P3**-(isolated play realm).--## 1. Problem: dual-write desyncs--Today every mutation **writes the World AND the `SceneModel`** (the JSON-first-truth), kept in sync by `runtimeToSource`/`sourceToRuntime` entity-id maps. The-World is a lossy render projection; the model is the lossless truth. This is-correct in steady state but the binding goes stale on any *wholesale* World-change, and the World capture is lossy on recreate. The consequences (all-observed):--- **Play→Stop model desync.** `EngineHost.setRunMode` does- `serializeScene(world)` then `resetWorldTo(world, snapshot)`; the new runtime- ids are never re-`adopt`ed, so the model maps go dead → post-Stop edits resolve- to `undefined` and silently never reach the model → lost on save.-- **Scene reload leaves stale history/model.** `ProjectStore.loadCurrentScene`- re-`adopt`s a new model but never clears `EditorHistory`/`SceneModel`, so undo- closures reference dead entities from the previous scene.-- **Lossy undo-recreate.** `SceneCommands` captures recreated entities from the- registry-only World (`STRUCTURAL_SKIP = {Parent, Children}`), so delete→undo- drops hierarchy AND unknown/project components from the World projection.-- **Unknown/project components are invisible.** The inspector enumerates the live- engine registry; project code never runs in the editor realm, so user- components (which the loader SKIPs into the model only) can't be inspected or- edited. `schemas.json` was built to fix this but has no consumer.-- **Reads leak into the raw World.** `Details.tsx` reads `EngineHost.world`- directly; the outliner derives hierarchy from World `Parent`. The truth (the- model) is bypassed for reads.--These are **one root cause**: two sources of truth synchronized by convention.--## 2. Principle: unidirectional, model-authoritative--```- ┌──────────── single source of truth ────────────┐- Command ──write│ Document Model (SceneModel) │── change events ─┐- (only writer) │ lossless JSON: entities / components (incl. │ │- │ unknown) / hierarchy / @uuid refs │ │- └─────────────────────────────────────────────────┘ ▼- ▲ │ read ┌────────────────────┐- │ ├──▶ Inspector / Outliner (read MODEL) │ Reconciler │- Undo = model ops ├──▶ Selection (MODEL source ids) │ model → World │- (TransactionManager over the │ │ spawn/set/despawn │- model; lossless by record) └──────────────────────────────────────── │ (known comps; │- │ │ unknown stay model)- └──────────────────────────────────────────────────────────────────└─────────┬──────────┘- ▼- World (pure projection; read only for- camera-derived geometry: pick / gizmo)-```--**Invariant: the World is a pure function of the Model.** Commands mutate the-Model only; a Reconciler projects Model→World. There is no path that writes the-World directly (except the Reconciler), so they cannot diverge.--This is the pattern mature editors converge on: UE (UObject graph is truth, the-world is constructed from it), Unity (serialized objects are truth), Figma /-VS Code (the document is truth; the scene graph / view is derived).--## 3. Target architecture (6 layers)--1. **Document Model** — `SceneModel` upgraded to the sole truth; addressed by- **stable source id**; emits fine-grained change events. Holds unknown- components + `@uuid:` refs + invisible entities verbatim.-2. **Commands + Transactions** — every mutation is a command that edits the- model; `EditorHistory` records **model operations** (not World re-spawns), so- undo restores the full model record → lossless by construction.-3. **Reconciler** — subscribes to model changes; projects to the World- (spawn/despawn/insert/remove/set) for components the engine knows; leaves- unknown components in the model only. Owns the source↔runtime id map; rebuilds- it on a wholesale model load (bulk path = `resetWorldTo(world, model.data)`).-4. **Selectors / Queries** — `SceneQuery`, inspector, outliner read the **Model**.- The Viewport reads the **World** only for camera-derived screen geometry- (pick, gizmo, selection outline) via the engine `CameraView` — that is- rendering, the engine's domain.-5. **EditorSession (single boundary)** — owns {model, history, selection,- reconciler, App/World, handles} as an **instance**; the one API for UI,- headless host, and MCP. `EditorControlSurface` becomes its façade. (Phase 2.)-6. **Isolated Play Realm** — Play runs the scene in an iframe/worker loading the- built `scripts.mjs` + the model's scene data. The editor realm never runs- project code; Stop destroys the realm; the editor model/World are untouched.- `play == ship`. (Phase 3.)--## 4. How each problem dissolves (structural, not patched)--| Problem | Why it cannot happen |-|---|---|-| Play→Stop model desync | Play is isolated (P3); the editor model never participates, so there is no snapshot/restore and no stale map. Until P3, Stop just re-reconciles the World from the untouched model. |-| Scene reload stale history | A scene = a session document; replacing it clears the model + history; the reconciler rebuilds the World + binding. |-| Lossy undo-recreate | Undo replays the **model op**; the model record holds every component + the parent link → reconciler re-projects → lossless. |-| Unknown components invisible | Inspector reads the **model** (+ `schemas.json` for field shapes); unknown components live in the model and are editable, just not projected to the World. |-| `Details` reads raw World | No UI reads the World; it is only read for camera geometry. |-| `EditorControlSurface` bypassed | One `EditorSession` boundary; UI / headless / MCP all go through it. |-| Singletons assume one window | `EditorSession` is an instance → multi-scene / multi-window are natural. |--## 5. Phased migration (reuse-heavy, not a rewrite)--- **P1 — Data-flow inversion** (highest ROI; kills the data-bug class #1–#4 + the- raw-World read leak). Pure editor-side TS, unit-testable, no engine change.-- **P2 — Session scoping.** Collapse the engine-layer singletons into one- `EditorSession` instance; `EditorControlSurface` becomes its façade; the UI- routes through it (closes H2).-- **P3 — Isolated play realm.** Build the `scripts.mjs` / `schemas.json` realm- loader + iframe play; delete `setRunMode`'s snapshot/restore entirely.-- **Cross-cutting (fold in anytime):** SDK type exports (kill shadow-typing),- jsdom interaction tests, error boundaries + failure toasts, command-registry- extension points + persisted keymap, multi-entity transform.--## 6. P1 — detailed implementation checklist--Goal: commands mutate the model (by source id); a Reconciler projects to the-World; reads come from the model; undo records model ops.--**New — `src/engine/Reconciler.ts`**-- Subscribes to model change events; projects each to the World:- - entity added → `world.spawn()` + `SceneModel.bindRuntime(sourceId, runtime)`;- insert each component the registry knows (`getComponent(type)`); skip unknown.- - entity removed → `world.despawn(runtime)`.- - field/component set → `world.set/insert` for known types; no-op for unknown.- - component removed → `world.remove`.- - parent changed → World `Parent` insert/remove.-- Bulk path (load): `resetWorldTo(world, model.current)` → returns entityMap →- `SceneModel.adopt(model, entityMap)` (reuses the engine loader; no per-entity- spawn loop). Used by boot + project load + (until P3) play-stop.-- Owns nothing the model already owns — it drives `SceneModel.bindRuntime`.--**Change — `SceneModel`** (truth + event source)-- Add a change emitter (or reuse `SceneStore` as the bus): emit- `entityAdded(sourceId)`, `entityRemoved(sourceId)`, `componentChanged(sourceId,- type)`, `parentChanged(sourceId)`. Mutations key off **source id** (overloads- that take `runtime` resolve via `sourceFor` and stay for the gizmo path).-- `setField`/`setComponent`/`removeComponent`/`addEntity`/`removeEntityBySource`/- `restoreEntity`/`setParent` already exist — they become the *only* writers and- emit events. `removeEntityBySource` must also scrub the child id from its- parent's `children[]`.--**Change — `SceneCommands`** (single model write, no dual-write)-- `setField` → `SceneModel.setField` (model emits → reconciler projects). Delete- the `applyFieldWrite` World write.-- `addEntity` → `SceneModel.addEntity` (allocate source id, no runtime) → emit →- reconciler spawns + binds. Return the **source id**.-- `deleteEntity` → `SceneModel.removeEntityBySource`; undo = `restoreEntity(full- record)` → reconciler respawns. Delete `captureEntity`/`recreateEntity` (the- lossy World capture).-- `addComponent`/`removeComponent`/`setParent`/`duplicateEntity` → model ops only.-- `beginGesture`/`endGesture` unchanged (still coalesce into one undo step).--**Change — `EditorHistory`** records model ops. `forward`/`reverse` mutate the-model; the reconciler follows via events. (TransactionManager unchanged.)--**Change — `SceneQuery`** reads the Model-- `readSceneTree` from `SceneModel.current.entities` (hierarchy from- `parent`/`children`), not World `Parent`.-- `readInspector`/`readEntity`/`getFieldValue` from the model entity's- `components` (incl. unknown) + field shapes from the registry (builtin) or- `schemas.json` (user). The Viewport's pick/gizmo/`worldToClient` keep reading- the World via `CameraView`.--**New — `schemas.json` consumer** in `schema.ts`-- Load `.esengine/cache/schemas.json` (via the fs IPC bridge) on project open;- merge as a field-shape source for component names absent from the engine- registry. `inspectableComponents` enumerates the **model entity's** component- types, resolving each shape from registry-or-schemas.json. (Closes rearch E1.)--**Change — Selection** references **source ids** (stable, survive recreate);-self-heal on `entityRemoved`. The Viewport resolves source→runtime-(`SceneModel.runtimeFor`) for the gizmo/outline.--**Change — `ProjectStore.loadCurrentScene` / `EngineHost` boot** call-`EditorHistory.clear()` + `SceneModel.clear()` before adopting, and use the-Reconciler's bulk path.--**Delete (eventually):** the engine `editorBridge` as the editor's reactivity-source — the editor now reacts to **model** events, not engine-pushed mutations-(the World is derived). Keep the bridge only if other consumers need it.--**Tests (P1 acceptance):**-- Round-trip stability: load → batch of edits (field/color/angle, add/remove- component, reparent, add/delete/duplicate) → `serialize()` → reload → re-serialize- → assert identical.-- Lossless undo: delete a parented entity carrying an unknown component → undo →- assert the World projection AND the model both have it back, with the parent- link restored.-- Scene reload: open scene B after A, then undo → assert no-op on B's world (no- dead-handle mutation).-- Unknown-component inspector: load a scene with an unknown component + its- `schemas.json` → inspector lists + edits its fields → model round-trips.-- Extend `engine-model-sync.test.ts` / `scene-model.test.ts`.--## 7. Open decisions--- **Selection id space.** Recommend **source ids** (stable). Requires migrating- `selectionStore` + the Viewport's resolve. Alternative (runtime ids) keeps the- current code but re-introduces self-heal-on-respawn complexity.-- **Reconciler granularity.** Per-change incremental for edits; bulk- (`resetWorldTo`) for load. A "dirty set + flush per frame" batcher is a later- optimization, not needed for P1.-- **SceneStore vs a new emitter.** Reuse `SceneStore` as the model-change bus- (it already drives panel reactivity) rather than adding a parallel emitter.diff --git a/docs/REARCH_EDITOR_REALM.md b/docs/REARCH_EDITOR_REALM.mddeleted file mode 100644index d160d1655..000000000--- a/docs/REARCH_EDITOR_REALM.md+++ /dev/null@@ -1,119 +0,0 @@-# Estella 隔离 Play Realm + Schema 即产物 —— 最优编辑器架构的兑现(RC12 §E8 / N6)--> 目标读者:引擎维护者 / 编辑器作者 / AI 协作代理。-> 体例同 `REARCH_ENGINE_INSTANCING.md` / `REARCH_SERIALIZATION.md`:描述目标架构与根治路径。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 三路并行只读审计)。-> **立项缘由**:这是本轮工作的**会话原始目标 E8(动态加载工程脚本)的最优实现**,也是 `RC12_EDITOR_SEAM.md` 最优编辑器架构的兑现点。两条地基腿已就绪——① 引擎实例化(`REARCH_ENGINE_INSTANCING.md`,每 realm 一份 context)+ ② 无损序列化(`REARCH_SERIALIZATION.md`,SceneModel 真相 + 给 realm 喂快照)——本文把它们合拢成"**编辑器主 realm 零执行工程代码**:跑工程靠隔离 play realm(= 出货 runtime),编工程靠 schema 即产物"。-------## 0. 核心诊断:最优架构已解锁,缺的是工程流水线 + realm 外壳--`RC12 §E8` 的原设计是"把工程代码 import 进编辑器 realm"(import-map 共享 esengine 实例),其命门是脆弱的模块同实例。审计确认有更优解,且现在可做:--- **跑工程 = 隔离 play realm**:按 Play 时在独立 realm(各自一份 wasm)里跑**出货 runtime**,加载工程的真实 bundle(含自定义组件/系统),喂当前场景快照 → **play==ship**,且不依赖 import-map 同实例。-- **编工程 = schema 即产物**:从工程构建出一份组件 schema(`schemas.json`),编辑器读它给未知组件建 inspector,**主 realm 不执行任何工程代码** → 崩溃/安全/重载隔离都由"物理"(独立 realm + 纯数据 schema)保证,不靠约定。--**根治原则**(承接 RC 系列):编辑器主 realm 对工程代码**零执行**;隔离由 realm 边界(物理)+ 纯数据 schema 强制,而非 import-map 约定。-------## 1. 已具备、可直接复用(好消息)--- **出货 runtime 核心链**:`sdk/src/runtimeLoader.ts` 的 `initRuntime`(`:581`)/`loadRuntimeScene`(`:470`)是 **provider 抽象**的场景+资产装载,`flushPendingSystems(app)`(`:584`)把工程系统刷入,`app.run()`(`sdk/src/app.ts:481`)跑帧。playable/wechat 都只在外围(wasm 实例化 / 谁建 app / 资产来源)不同,核心共享。**play realm 直接复用这条链,无需改。**-- **工程代码注册机制**:`defineComponent` 写 `AppContext.componentRegistry`(纯 JS,`component.ts:132-150`),`addSystemToSchedule` 只 push 进 `pendingSystems`(只入队不执行,`system.ts:177`),靠 bundle 的 import 副作用触发 + `flushPendingSystems` 注册。-- **schema 可纯 node 提取**:`defineComponent`/`AppContext`/`createComponentDef` **全链纯 JS、零 wasm**(复核 `component.ts:128-150`、`context.ts:53-87`);system 只入队不跑。故 `new AppContext()` → import 工程声明入口 → 读 `getUserComponents()`(`component.ts:237`)→ 序列化 schemas.json,可在纯 node 跑。-- **无损未知组件已留存**:`SceneModel`(`desktop/src/engine/SceneModel.ts`)已无损保留未知组件 `{type,data}`;只缺"字段 schema"这一半。-- **控件推断已是纯数据**:`inferField`(`desktop/src/engine/schema.ts:124`)能从默认值推断 vec2/vec3/color/angle/number/bool/string。-- **现成 runtime-host 范式**:`templates/web/index.html:51-80` 是一个独立 html:`import('esengine.js')` → `createWebApp` → `main(Module)` → swallow `'unwind'`。play realm 的 host 页照抄。-- **快照 = 纯 JSON**:`SceneData`(`scene.ts:45`)结构化克隆安全,`SceneModel.serialize()` 直出,过 postMessage/IPC 干净。-- **CSP 已就绪**:`desktop/index.html:7` 已放行 `worker-src 'self' blob:`、同源(`'self'`)iframe(无 `frame-src` → 落到 `default-src 'self'`,同源 iframe 允许、`estella:` iframe 被挡)。-------## 2. 病灶 / 缺口(file:line)--### G1:工程脚本构建流水线**完全缺失**(E8-1)-- `build-tools/cli.js` 的 `build`(`:25`)只构建引擎 wasm+SDK,**不碰工程 src/**;`examples` 任务(`tasks/examples.js:75`)只把工程目录**原样 zip**(给"导入模板"用),不编译;`check-examples`(`tasks/check-examples.js:91`)只 `tsc --noEmit`。-- esbuild **未作直接依赖**(根/desktop/sdk package.json 均无);唯一声明在 `templates/package.json:14`,其 build 脚本 `npx esbuild src/main.ts --bundle --format=esm`(`templates/package.json:6`)—— **没有 `--external:esengine`**(把 esengine 整个打进),产物去 `build/js/` 而非 `.esengine/cache`,与 E8-1 设想不一致。-- 编辑器侧 `desktop/src` **零 import/eval 工程代码**;`.esengine/` 只有 `workspace.json`(`format.ts:21`),无 `cache`。`schemas.json` 全仓不存在。--### G2:入口约定缺失(声明 vs 启动混在一起)-- `examples/*/src/main.ts` 把"声明"(`import './components'`)和"启动"(顶层 `addSystemToSchedule` + 函数里 `createWebApp`/`run`)混在一起;`components.ts` 单独(只 defineComponent,无启动)。无强制约定,提取器无稳定入口。--### G3:play realm 入口 + host 页缺失-- 出货 runtime 的场景来自打进 bundle / 从文件读(`playableRuntime.ts:33`、`wechatRuntime.ts:202`),**没有"接收编辑器快照"的入口**。无 play.html。--### G4:realm 外壳与通道缺失-- 编辑器引擎跑在**主 renderer 进程**(`EngineHost.ts`),无 iframe/worker 隔离。play/stop 是同进程翻 `playMode`(`EngineHost.setRunMode:144`)。-- `electron/main.ts` 单 `BrowserWindow`,`setWindowOpenHandler` **deny 所有 window.open**(`:82`);`estella://` 绑单一 `projectRoot`(`:103`);preload 桥(`preload.ts:49`)**无 realm 间消息通道**(只有 invoke 请求/响应)。-- 主↔realm 的**快照/控制/观测通道不存在**。--### G5:生产 file:// 的引擎加载 bug(前置)-- `EngineHost.ts:196` `import(\`${location.origin}/wasm/esengine.js\`)` 在 dev(http)可用;生产 `win.loadFile`(`main.ts:91`)→ `location.origin='file://'` → 解析成 `file:///wasm/...`(文件系统根),**找不到 glue**。任何出货 runtime realm 必须先修这个(改相对路径或 `estella://`)。--### G6:inspector 绑定活 World,未知组件不可编辑-- `schema.ts:64` `inspectableComponents` 遍历引擎注册表 + `world.has` 过滤(`:67`);`SceneQuery.readInspector`(`SceneQuery.ts:71`)从 `world.get` 取值。未知组件不进 World → 永远不可见/不可编。-------## 3. 目标架构--### 3.1 工程流水线(主进程 esbuild + 纯 node 提取)-- **工程 bundle**:editor 用 esbuild 把工程入口(`src/main.ts`)bundle 成单 ESM,`external: ['esengine','esengine/*']`,产物入 `.esengine/cache/`(本地、gitignore)。-- **schemas.json**:纯 node 提取步骤——`setDefaultContext(new AppContext())` → import 工程**声明入口** → 读 `getUserComponents()` → 序列化 `{name,isTag,default,colorKeys,assetFields,spineFields,entityFields}` 数组到 `.esengine/cache/schemas.json`。零 wasm、零 system 执行。--### 3.2 隔离 play realm(= 出货 runtime,play==ship)-- 一个**同源 `play.html`** runtime-host 页(照 `templates/web/index.html` 范式),在隔离 realm 里:加载 `/wasm/esengine.js`(各自一份 wasm)+ 经 **import map** 把 `esengine` 指向自己的 SDK + 加载工程 bundle(external esengine → 命中 import map)→ 触发工程 `defineComponent`/`addSystemToSchedule` 副作用 → `initPlayRealmRuntime(快照)` → `app.run()`。`setEditorMode(false)/setPlayMode(true)` = 真出货。-- **`initPlayRealmRuntime(config)`**(SDK 新增):收 `{module, canvas, sceneData, assets}` → `createWebApp` → `initRuntime({scenes:[{name,data:sceneData}],firstScene,provider})` → `app.run()`。几乎是 `initPlayableRuntime` 去掉 base64、场景换单个快照。`initRuntime`/`loadRuntimeScene` **不改**。-- 编辑器 Play:拼快照(`SceneModel` 的**原始 `@uuid:` SceneData**,不是 handle 解析后的)+ 资产 manifest(uuid→url 或 data-url)+ 工程 bundle URL → 送进 realm;Stop 拆掉 realm。替换 `setRunMode` 的同进程 play。--### 3.3 编辑器主 realm:零执行工程代码 + schemas.json 喂 inspector-- inspector 对 **builtin** 组件仍走引擎注册表 + World;对 **user/未知** 组件改从 `schemas.json`(字段定义)+ `SceneModel`(值)合流(`schema.ts` 的 `inspectableComponents`/`componentFields` + `SceneQuery.readInspector`/`getFieldValue`)。未知组件从"无损留存"升级到"可编辑"。写回走已有的 `SceneModel.setField`(对 user 组件只写模型,不写 World)。-------## 4. 需要拍板的岔路--| 岔路 | 选项 | 推荐 |-|---|---|---|-| **realm transport** | (a) 同源 iframe(`play.html`,postMessage) / (b) 第二 BrowserWindow(IPC,进程级隔离) / (c) Web Worker(OffscreenCanvas) | **(a) 同源 iframe** 为主:可 docked 成"Game"面板、realm 隔离、WebGL 直跑、scene+资产+控制全走 postMessage(无需 preload/IPC 改动、play realm 不需 `window.estella`);加一条 `frame-src 'self'` CSP。**(b) BrowserWindow 作升级**:要进程级崩溃隔离时再上(原生复用 preload+estella://、file:// 最干净)。**(c) Worker 否决**:整套 boot/render/input 假设 DOM canvas+window,OffscreenCanvas 改造面大、收益小 |-| **工程 bundle 的 esengine** | external + import map / 打进 bundle | **external + import map**:play.html 注入 import map(`esengine`→自己的 `/sdk` 实例),工程 bundle external esengine。play realm 是独立 realm,一份 esengine 实例,无 RC12 §E8 的"编辑器 realm 同实例"脆弱性 |-| **schema 提取入口** | 约定声明入口(如 `src/components.ts` / manifest `scripts.register`)/ 扫描 defineComponent | **约定 + 强制声明/启动分离**:工程 manifest 加 `scripts.register` 指向纯声明模块(默认 `src/components.ts`);提取器**只 import 声明模块,不 import 启动**(避免顶层 createApp 崩)。examples 顺带迁移成声明/启动分离 |-| **资产送进 realm** | uuid→url manifest(realm 自己经 estella:// 取)/ data-url 内联随快照 | **uuid→url manifest**:realm 经 `estella://`(若 iframe 同源可 fetch)或编辑器代取后传 data-url。注意:快照必须是**原始 `@uuid:`**(handle 是 realm-local 的,`ProjectStore.ts:226`) |-| **file:// 修复(G5)** | 相对路径 / `estella://` / 自定义 app:// | **改相对路径 + 自定义协议兜底**:dev/prod 都可达;这是 realm 与生产打包的共同前置 |-------## 5. 迁移序(分阶段,每段可验证)--### Phase P —— 工程流水线(原始 E8 的地基;纯主进程/node,无 GUI,可单测)-- **P1 工程 bundle(E8-1)**:editor 主进程 esbuild,external esengine,产物入 `.esengine/cache`;IPC `project:buildScripts`。验证:产物含 `from "esengine"`、不内联 esengine(读 metafile 断言)。-- **P2 schemas.json 提取**:纯 node `new AppContext()` → import 声明入口 → 读 `getUserComponents()` → 序列化。验证:对一个含 `defineComponent('Wave',…)` 的工程,schemas.json 含 Wave 字段/默认值;零 wasm。-- **P3 入口约定**:manifest `scripts.register` + examples 迁移成声明/启动分离。验证:提取只 import 声明模块、不触发启动。--### Phase E —— 主 realm 编辑未知组件(接 schemas.json + SceneModel,纯 TS,可单测)-- **E1 inspector 读 schemas.json**:`schema.ts` 对 user/unknown 组件用 schemas.json(字段)+ SceneModel(值);builtin 不变。验证(desktop vitest):open 含未知组件场景 + schemas.json → inspector 列出该组件字段、可编辑、SceneModel 写回、保存无损。--### Phase R —— 隔离 play realm(GUI 重,需跑 Electron 验证)-- **R0 修 file://(G5)**:EngineHost glue 路径改相对/协议。-- **R1 play.html + initPlayRealmRuntime**:SDK 加入口(复用 initRuntime);play.html host 页 + import map。验证:play.html 独立加载 wasm + 一个快照 + 一个工程 bundle 能跑。-- **R2 编辑器 Play → realm**:Play 拼快照+资产 manifest+bundle → iframe;postMessage 控制(play/pause/stop)+ 观测;Stop 拆 realm。替换 `setRunMode` 同进程 play。验证(Electron 冒烟 + 可加 e2e):Play 跑出工程自定义系统(play==ship)、Stop 干净、编辑场景不被 play 污染。-------## 6. 验证机制-- **P1**:bundle metafile 断言(external esengine、无内联);主进程单测。-- **P2**:纯 node 提取单测——含 `defineComponent` 的工程 → schemas.json 字段正确、不含 builtin、零 wasm。-- **E1**:desktop vitest——未知组件场景 + schemas.json → `inspectableComponents` 含该组件、`readInspector` 列字段、`setField` 写 SceneModel、保存无损(接现有 `engine-model-sync` 网)。-- **R**:Electron 冒烟/e2e——Play 跑工程系统、Stop 还原、编辑态不被污染、realm 崩不拖垮编辑器(iframe 内 throw 不杀主 realm)。-- **回归**:SDK 全量 + desktop vitest + editor build 常绿。-------## 7. 与其他条目的关系-- **会话原始目标 E8 的最优落地**:跑工程(play realm = 出货)+ 编工程(schemas.json),取代 RC12 §E8 的 import-map 同实例方案。-- **吃掉两条地基腿**:① 实例化(每 realm 一份 context)+ ② 无损序列化(SceneModel 快照、原始 @uuid:)——本文是它们的汇合点。-- **接 E2**:命令边界复用;user 组件的编辑只写 SceneModel(World 不认),撤销/重做沿用。-- **play==ship**:R2 让 play 走出货 runtime,彻底取代同进程翻 playMode。-- **零 ABI**:纯 SDK/编辑器/构建工具 + esbuild(新依赖);不动组件布局/哈希。diff --git a/docs/REARCH_ENGINE_INSTANCING.md b/docs/REARCH_ENGINE_INSTANCING.mddeleted file mode 100644index 4be26a6a0..000000000--- a/docs/REARCH_ENGINE_INSTANCING.md+++ /dev/null@@ -1,147 +0,0 @@-# Estella 引擎实例化(Engine Instancing)—— 从"单例引擎"到"实例引擎"--> 目标读者:引擎维护者 / 编辑器作者 / AI 协作代理。-> 本文是 `REARCHITECTURE.md` / `REARCH_FRONTIER.md` / `RC12_EDITOR_SEAM.md` 的姊妹篇,体例一致:描述目标架构与根治路径,而非现状。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 三路并行只读审计 + 交叉印证)。-> **立项缘由**:`RC12_EDITOR_SEAM.md` 描述的最优编辑器架构(隔离的 edit / play realm、play==ship)依赖"引擎能干净地承载多个隔离实例"。当前引擎结构上是**单进程、单活动上下文(进程单例)**——这是编辑器接缝脆弱(见本会话修的 headless null-context 崩溃)与"无法隔离 play"的共同根因。本文把它根治。-------## 0. 核心诊断:引擎是"单例引擎",但主模块其实已经实例化了--引擎对外表现为"只有一个活动上下文",但深审发现**真相是分层的**:--1. **主模块的 per-app 状态早已收进 `EstellaContext`**。`EstellaContext`(`src/esengine/core/EstellaContext.{hpp,cpp}`)经 `ServiceRegistry` 拥有 GfxDevice / ResourceManager / RenderContext / StateTracker / RenderFrame / ImmediateDraw / GeometryManager / TransformSystem / UISystem / TweenSystem / (Timeline/Particle/Tilemap/Spine) + `EngineState`(material_cache / viewport / delta / view_proj)。主模块的渲染/资源/动画/瓦片/粒子子系统 `.cpp` **全部无文件级可变全局**——都已被 ServiceRegistry 持有。**主模块在数据结构上已经是 per-instance 的。**--2. **唯一卡住的是"活动上下文"是进程单例**:`g_activeContext`(`bindings/ActiveContext.hpp:13`)被 `initRenderer` 硬写成 `&EngineContext::instance().context()`(`bindings/WebSDKEntry.cpp:217,236`)。`EngineContext::instance()`(`bindings/EngineContext.cpp:6`)是进程唯一 Meyers 单例;`EstellaContext` **没有任何 embind**,JS 无法 `new` 它,也没有 `setActiveContext`(仅 `ActiveContext.hpp:11` 注释提到,无声明/定义)。--3. **真正搬不动的是 physics / spine —— 它们是独立 wasm 模块**。`CMakeLists.txt:450-545`:`spine_module` / `physics_module` 是独立 `add_executable`,各自独立 `.wasm`、**独立线性内存**,与主模块只走扁平 C ABI。它们的 per-app 状态是各自模块里的进程全局(`bindings/PhysicsContext.cpp:3` `PhysicsContext g_ctx`、`bindings/SpineModuleEntry.cpp:149` `SpineContext g_ctx`),**物理上无法 `registerOwned` 进主模块的 EstellaContext**。--> **关键洞察(决定整盘可行性)**:`RC12` 的最优编辑器架构用**隔离的 realm**(iframe / worker,每 realm 各自 instantiate 一份 wasm)。在那个模型里,每个 realm 有**自己的** physics/spine wasm——所以第 3 点这个最难的阻塞**对编辑器架构是天然回避的**。于是本文把工作切成:**Phase 1 主模块实例化(高价值、可做、解锁编辑器)** + **Phase 2 side-module 实例化(仅"单 realm 内多 App 共享一份 wasm"才需要,默认用'每 realm 独立 wasm'回避)**。--**根治原则**(承接 RC 系列):把"进程级活动单例"降级为"显式注入的实例句柄";把每一处"假设单 App / 单 context"的隐式全局收成显式 per-instance;side-module 的隔离用"每 realm 独立 wasm"在架构层回避,而非在 ABI 层强行打补丁。-------## 1. 病灶(file:line)--### I1:活动上下文是进程单例,JS 无法 own / 注入-- `bindings/ActiveContext.hpp:13` `inline EstellaContext* g_activeContext = nullptr;`——进程全局活动指针。-- `bindings/WebSDKEntry.cpp:217,236` `g_activeContext = &legacyCtx().context();`——`initRenderer*` **硬写**成单例的 context,JS 不能控制"活动的是谁"。-- `bindings/EngineContext.cpp:6` `EngineContext::instance()`——进程唯一 Meyers 单例,内含唯一 `EstellaContext context_`。-- `EstellaContext` **零 embind**(全仓 `class_<EstellaContext>` 无命中);`setActiveContext` **不存在**(仅 `ActiveContext.hpp:11` 注释)。-- `bindings/WebSDKEntry.cpp:230`(及 `:195`)`if (g_initialized) return true;`——`g_initialized = ctx().state().initialized`,**第二次 init 静默早退、复用同一单例**:两个 App 共享同一套 GPU 子系统 / viewport / material cache,互相践踏。--### I2:`ctx()` 是 6 份各自为政的定义,回退不对称-`ctx()` 在每个 binding `.cpp` 各自 `static` 重定义,语义不一:-- `WebSDKEntry.cpp:69-77`:`g_activeContext ? activeCtx() : legacyCtx().context()`——**唯一带单例回退**(本会话为 headless 修的)。-- `RendererBindings.cpp:34` / `ImmediateDrawBindings.cpp:23` / `GeometryBindings.cpp:25` / `PostProcessBindings.cpp:23` / `TilemapBindings.cpp:26` / `TimelineBindings.cpp:14`:全是裸 `return activeCtx();`——**无活动上下文即 `*nullptr` 解引用**。-- 后果:迁移到"显式实例上下文"后,任一路径若未先 `setActiveContext`,WebSDKEntry 的 UI/Tween 静默走单例、其余 6 处直接 null deref——同一引擎两种 null 语义,极易漏。约 **97 处 `ctx()` 调用,跨 7 个文件**(全部局限在 `bindings/`,未逃逸到 core/renderer/ecs——迁移面被收束在 bindings 层,这是好消息)。--### I3:没有 per-instance 销毁路径,活动指针会悬垂-- `app.quit()`(`sdk/src/app.ts:527-554`)只做 JS 清理,**从不调 `module.shutdownRenderer()`**;全仓无任何 TS 调用 C++ `shutdownRenderer`(`wasm.ts:78` 仅声明无 caller)。-- 结果:`EstellaContext` **运行中从不被销毁**,`g_activeContext` 从不置空;quit 后再 init 撞 `g_initialized` 早退复用旧单例。-- `~EstellaContext`(`EstellaContext.cpp:74`)会在 `initialized` 时 `shutdown()`,但 JS 走不到(没有 delete 路径);且若 JS `delete` 掉的是当前活动 ctx,`g_activeContext` 变**悬垂**(`shutdownRenderer` 在 `:243` 才置 null,delete 路径绕过它)。--### I4:SDK 侧的"单 App 假设"——module 级单例-- 8+ 个渲染封装模块各持一份 module 级 `let module`:`renderer.ts:33`、`draw.ts`、`geometry.ts`、`material.ts`、`glDebug.ts`、`ui/uiHelpers.ts`、`spine/SpineCppAPI.ts`、`postprocess/PostProcessAPI.ts`、`tilemap/tilemapAPI.ts`。`corePlugin.build` 每次 `initXxxAPI(module)`(`corePlugin.ts:15-25`)**覆盖**前一个 App 的引用 → 这些全局函数只服务"最后连上的 module"。-- JS `AppContext` 懒单例 `defaultContext_`(`context.ts:99`),`world.ts` / `env.ts` / `app.ts:878` 全读 `getDefaultContext()`,多 App 默认串味(注释 `context.ts:90-98` 已自承)。-- SDK `AppContext`(componentRegistry/pendingSystems/editorBridge/playMode)与 C++ `EstellaContext` 是**两套平行、零联动**的"上下文":`setDefaultContext` 绝不触碰 `g_activeContext`,反之亦然。--### I5:side-module(physics / spine)是另一个 wasm 里的进程全局-- `bindings/PhysicsContext.cpp:3` `PhysicsContext g_ctx`(b2WorldId + entityToBody/Shapes/Joint 映射 + buffers);`bindings/SpineModuleEntry.cpp:149` `SpineContext g_ctx`(skeleton/instance 句柄表 + id 计数器 + buffers)。-- 它们 **不 include EstellaContext、不碰 `ctx()`**,是独立 wasm 的独立单例。主引擎做成多实例后,两个 App 实例仍共享**同一个 Box2D world / 同一个 spine 实例表**,互相踩 entityId。-- 最隐蔽:`bindings/PhysicsModuleEntry.cpp:58` box2d `b2Body_SetUserData` 存的是**裸 entityId、不带 world/app 标识**,多 world 且 entityId 重号时回调无法区分归属。-------## 2. 目标架构:实例引擎(EstellaContext 一等实例)--### 2.1 主模块(Phase 1 —— 高价值、可做)--1. **EstellaContext 成为 JS 可 `new` 的 embind 类**(照抄 `Registry` 的机制 `WebBindings.generated.cpp:1176-1178`):- ```cpp- class_<EstellaContext>("EstellaContext")- .constructor<>()- .function("init", &EstellaContext::init) // init(glHandle) -> bool- .function("shutdown", &EstellaContext::shutdown)- .function("isInitialized", &EstellaContext::isInitialized);- function("setActiveContext", +[](EstellaContext& c){- g_activeContext = &c;- }, allow_raw_pointers());- ```- `EstellaContext` 已满足前提:默认构造、`init(int)`、`shutdown()`、析构自动 shutdown、拷贝已 delete(引用语义,embind 友好)。--2. **JS App own 一个 cppContext**:`createWebApp`(`sdk/src/app.ts:850`)新增 `const cppContext = new module.EstellaContext()`,App 持有它(类似现持 `module_`)。用 `cppContext.init(glHandle)` + `module.setActiveContext(cppContext)` 取代 `module.initRendererWithContext(...)` 的硬绑单例(`app.ts:856-860`)。`Registry` 与 context 解耦(Registry 只作 `renderFrame` 参数),**无需绑进 context**;真正要保证的是"渲染/ tick 前活动的是本 App 的 context"——多 App 交替时每帧 `setActiveContext(app.cppContext)`。--3. **退役进程单例**:`g_activeContext` 保留(它就是"当前活动实例"开关,本就该 module 级);但赋值改为**只由 `setActiveContext` 注入**,删掉 `WebSDKEntry.cpp:217,236` 的硬写。`EngineContext::instance()` 单例与 `g_initialized` 早退退役。--4. **统一 `ctx()` 为单一定义、单一语义**:把 6 份 file-local `ctx()` 收成一处共享定义(如 `ActiveContext.hpp` 里 `activeCtx()` 直接带"显式注入优先、否则 fatal/清晰诊断"),消除"WebSDKEntry 走回退、其余 null deref"的不对称。headless 工具走"显式创建一个未 init 的 EstellaContext 并 setActive",而不是隐式回退单例。--5. **per-instance 销毁闭环**:JS `cppContext.delete()` → `~EstellaContext` → `shutdown()`;并在 shutdown/析构里 `if (g_activeContext == this) g_activeContext = nullptr;` 防悬垂。`app.quit()` 串上 `cppContext.delete()`(补 I3 缺口)。--6. **SDK 收口单 App 假设**:渲染封装的 module 级 `let module`(I4)改为"按 App/context 实例持有"(API 从 module 级函数挂到 App/context 实例上);`createWebApp` 内 `setDefaultContext(new AppContext())`(或把 `AppContext` 直接挂到 `App` 上、移除 `defaultContext_`),让 JS 软状态也 per-App。--### 2.2 side-module(Phase 2 —— 默认回避,按需才做)--physics/spine 的 `g_ctx` 在另一个 wasm,三选一:-- **(a) 编进主模块**:把 physics/spine 源文件并入主 wasm,`g_ctx` 即可搬进 EstellaContext。代价:主 wasm 变大、box2d/spine 链接进主模块、放弃 side-module 拆分。-- **(b) 句柄表化 ABI**:side-module 内把 `g_ctx` 改成 `worldId/appId → Context` 句柄表,每个 EstellaContext 持一个 handle,所有 `physics_*`/`spine_*` 调用带 handle。代价:C ABI 大改 + box2d user-data 要加 world 标识。-- **(c) 每实例一份 side-module wasm**:每个 App/realm 各 `instantiate` 一份 physics.wasm / spine.wasm(`PhysicsModuleLoader.ts` 已是工厂式)。代价:每实例多一份 wasm 内存。--> **推荐:(c),并在编辑器层用"每 realm 独立 wasm"自然落地**。编辑器的隔离 edit/play realm 本就各自一份 wasm,physics/spine 随之天然隔离——**Phase 2 在编辑器架构下基本不需要单独做**。只有当出现"单一 realm 内多个 App 共享一份 wasm 且都用物理/spine"的真实需求,才评估 (a)/(b)。-------## 3. 拍板(已决,2026-06)--贯穿性前提决定了所有选型:**最优编辑器架构用隔离 realm(edit / play 各一个 iframe/worker,各自 instantiate 一份 wasm),即"每 realm 一份 wasm、一个 App"**。这把"单 realm 内多 App 共享一份 wasm"这个最难的场景整个消掉——side-module 全局与 SDK module 级单例都靠 realm 边界天然隔离,无需在 ABI/SDK 层强行打补丁。--| 岔路 | 已拍板 | 理由 |-|---|---|---|-| **side-module 隔离** | **(c) 每 realm 独立 wasm**,靠 realm 架构自动落地、本期零改动 | (a) 编进主模块否决:砸微信/playable 体积预算(`REARCH_FRONTIER §0.1`)+ 砸 spine 多版本;(b) 句柄表化延后:只为"单 realm 多 App 用物理",而该需求不存在 |-| **EngineContext 单例** | **降级为"未设时的惰性默认 fallback",去掉特权硬绑**(删 `WebSDKEntry.cpp:217/236` 的硬写 + `g_initialized` 早退) | 不激进删;真正的 App 走显式 `new EstellaContext()`,单例只兜底 headless/测试,不再强绑所有 App |-| **ctx() 统一** | **单一共享定义**:`activeCtx() = 显式注入优先,否则惰性默认` | 消除 6 份 file-local 定义的不对称回退(I2),是迁移正确性的硬前提 |-| **setActiveContext 时机** | **context 创建时设一次,不每帧切**(保留切换能力) | 一个 realm 一个 context,活动上下文 realm 内不变 → N3 更简单 |-| **生命周期所有权** | **JS own,显式 `.delete()`**(照抄 `Registry`);shutdown/析构防 `g_activeContext` 悬垂 | 与 `new module.Registry()` 同构,最小心智负担 |-| **SDK module 级单例 / 多-App 收口(原 N5)** | **延后**:realm 隔离(每 realm 独立 JS context)让 `let module`×8 与 `defaultContext_` 天然各自一份 | 仅"单 realm 内多 App"才需要,而 realm 架构每 realm 一个 App |--### 已知的一处"务实 > 纯粹"-`setActiveContext` 是一个"当前上下文"全局(OpenGL `makeCurrent` 一类的可变全局——正是 RC 系列反对的环境全局反模式)。**接受它**,因为 realm 架构让它退化成"每 realm 设一次、永不切换"的事实常量,可变全局的真正危险(中途被切、另一路径读错)在"设一次"下不出现。最纯粹的"每 binding 显式传 context 句柄"要穿过 ~97 处 binding + 整个 JS SDK,为的是 realm 已给到的隔离——收益重复、成本巨大,故不选。这是少数"工程对、非教科书最纯"的点,明记在此。-------## 4. 迁移序--### Phase 1 —— 主模块实例化(本期交付;可拆、每步可验证、全程构建常绿、零 ABI)-- **N1(纯加法、解锁一切)**:给 `EstellaContext` 加 embind(newable + `init`/`shutdown`/`isInitialized`)+ 自由函数 `setActiveContext`/`createEngineContext`。`wasm.ts`/`wasm.generated.ts` 增类型。**不改任何现有路径**,只是让 JS 能 new/设活动。验证:单测 `new module.EstellaContext()` → `setActiveContext` → UI layout 走到该实例(而非单例)。-- **N2(统一 ctx)**:6 份 file-local `ctx()` 收成单一定义、单一语义(`activeCtx() = g_activeContext ? *g_activeContext : 惰性默认`);消除不对称回退(I2)。验证:headless 与 rendered 两路都不 null deref;require/tryGet 行为表一致。-- **N3(已选 lean,已做)**:teardown 接进生命周期——`app.quit()` 调 `module.shutdownRenderer()`(补 I3:此前 quit 只清 JS 态、丢 module 引用,EstellaContext 从不 shutdown,GPU 子系统 + WebGL context 泄漏,再 init 复用陈旧单例)。`shutdownRenderer` 已对 null `g_activeContext` 安全(headless no-op)。- - **修正**:原稿说"删 `g_initialized` 早退"——**不对,保留它**。早退是正确的幂等守卫(已 init 别重复 init;EstellaContext::init 自身也有同样守卫)。真正的 bug 是缺 shutdown:补上 teardown 后,create→quit(→shutdown→initialized=false)→create 自然干净重 init,早退不再误触。- - **N3-full(已选延后)**:`createWebApp` `new` 自己的 cppContext + `setActiveContext`、退役 `initRenderer` 硬绑单例——最"先进"但要处理 canvas 创建路 + 4 个 runtime boot 入口(编辑器/wechat/playable/standalone),无运行时测试兜底。realm 架构(每 realm 一 App 一 context)下无额外收益,故延后至真出现"单 realm 内多 context"需求,或随编辑器 realm 消费者(N6)一起做。- - 验证:SDK 2170(含 `shutdownRenderer` headless 安全断言);完整 render→quit→render 循环需 GL/编辑器环境,随 N6 消费者验证。-- **N4(销毁闭环,部分随 N3)**:app.quit 串接已做(上)。剩余:N1 显式 context 的 `delete()` 若删的是当前活动 context,`g_activeContext` 会悬垂——当前靠 JS 纪律(delete 前 `setActiveContext(null)`,N1 测试已示范);结构化守卫(embind delete 钩子)留待 N6 编辑器 realm 消费者落地时一并做(那时才有真实的"建/销/重建"调用方)。--### 延后 / 被 realm 架构吃掉(非本期)-- **~~N5 多-App 收口~~**:退役单例的"特权"在 N3 已做;剩下的"SDK module 级 `let module`×8 + `defaultContext_` 改 per-App"**仅"单 realm 内多 App"才需要**——realm 架构每 realm 一个 App、一份 JS context,天然隔离,故延后(出现真实需求再做)。-- **~~Phase 2 side-module 实例化~~**:physics/spine 的 `g_ctx` 靠"每 realm 独立 wasm"隔离(选型 (c)),本期零改动;仅"单 realm 多 world 都用物理"才评估句柄表化 (b)。--### 编辑器层(接 RC12,独立条目)-- **N6**:编辑器隔离 realm(edit / play 各一份 wasm 实例)落地——吃掉 side-module 隔离、接通 `RC12` 的 play==ship。属 `RC12_EDITOR_SEAM.md` 的范畴,以 Phase 1 为前置。-------## 5. 验证机制-- **N1**:`new module.EstellaContext()`+`init`+`setActiveContext` 后,`require<UISystem>()`/几何绘制命中该实例(而非单例)。-- **N3/N5**:**双 App 隔离测试**——两个 App 各自 `new EstellaContext`,分别 spawn 不同实体、渲染到不同 canvas,断言:各自 Registry 实体数独立、material_cache/viewport 独立、互不串味。-- **N4**:`for (create→init→quit→delete) ×N` 后 C++ 端 service 计数归零、无 WebGL context 泄漏、`g_activeContext` 不悬垂。-- **回归**:现有 SDK 2166 测试 + editor typecheck/build 全绿(单 App 路径行为不变)。-- **门禁**:双 App 隔离测试进 CI(native 或 headless wasm)。-------## 6. 与其他条目的关系-- **解锁 `RC12_EDITOR_SEAM.md` 的最优架构**:隔离 edit/play realm、play==ship 都要求"引擎可干净多实例 + 干净销毁/重建"——N1–N5 是其前置。-- **承接本会话的 headless-context 修复**:`ctx()` 的单例回退(`WebSDKEntry.cpp:76`)是 N2 的临时形态;N2 把它转正为统一语义。-- **与 E2(编辑器 World 写边界)正交**:E2 收编辑器侧写门,本文收引擎侧实例边界,互补。-- **不与 RC1(ABI 单源)冲突**:实例化不动组件布局/哈希,零 ABI 变更(embind 加法)。diff --git a/docs/REARCH_FOUNDATION_CONSOLIDATION.md b/docs/REARCH_FOUNDATION_CONSOLIDATION.mddeleted file mode 100644index 83d8dfbd0..000000000--- a/docs/REARCH_FOUNDATION_CONSOLIDATION.md+++ /dev/null@@ -1,168 +0,0 @@-# Estella 地基收口(Foundation Consolidation)— RC6 前置--> 目标读者:引擎维护者 / AI 协作代理。-> 本文是 `REARCHITECTURE.md` 的续篇,体例一致。**执行上先于 [`REARCH_RC6_ASSETS.md`](./REARCH_RC6_ASSETS.md)**——在叠加资产管线(能力层)之前,先把地基收成"统一、简洁、无半成品"。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 全仓审计)。--## 0. 核心诊断:RC1–RC5 之后,地基仍有四处未收口--RC1–RC5 坍缩了五个正确性根因,但留下四处"半成品 / 未统一 / 已死却仍拖累每个文件"的地基债。它们都是同一组原则的延伸——**单一通道、单一真相、减法优先**:--1. **平台差异散落为内联 `#ifdef`**:`ES_PLATFORM_WEB / #else` 双臂遍布 ResourceManager / Texture / Log / Engine / PathResolver。仓库已 web-only(native 平台层删于 `d9a08d87`,CI web-only `c9b476e4`),native 既不出货也不被测试,却仍以双臂形式污染业务逻辑。-2. **SDK 五套 WASM 桥接写法**:RC5 的"统一 WasmBridge"未做;且 abort 守卫只覆盖主模块。-3. **状态半 per-App**:Tween/Audio/Scene 已资源化,Camera/SpriteAnimator/PostProcess/Timeline + 六个 core 模块仍是进程级全局。-4. **文档漂移**:`ARCHITECTURE.md` 描述的类已在 RC5 删除。--**决议(已拍板,2026-06 修订并落地)**:~~native 保留但隔离~~ → **塌成 web-only(删 native)**。审计推翻了"保留 native"的前提:native C++ 引擎**零出货消费者**——web / 微信 / 桌面(Tauri 内嵌 wasm webview)全跑 wasm 构建;CI 只编 Emscripten(`build.yml`),native C++ 引擎从不进 CI。于是"隔离 + CI 门禁守护 native"是在为一条没人跑的路加机器;最优雅/统一的是**靠删除收敛**(与 RC2"靠删除而非改造"同精神)。详见下方 F1 落地记录。-------## F1:平台差异 → 单一平台后端接缝(保留 native,隔离之)--### 病灶-- **内联 `#ifdef` 双臂遍地**:`ResourceManager.cpp:14-19/37-40/54-57/72-76/125-152/541-586`(ShaderLoader + 热重载 + stbi 全套)、`Texture.cpp:19-21/124-160`(`stbi_load`)、`Log.hpp:26-28` + `Log.cpp:22-24/61-63/70-72/80-82`(sink mutex)、`Engine.cpp:23-28/37-39/45-46`(Win/Mac/Linux 平台名)、`PathResolver.cpp:110-168/180-185`(OS 路径分支)。-- **孤儿死代码**:`LoaderJobQueue.cpp`(`std::thread` 线程池)——web 不编译,**native 下也从无调用**;`AsyncHandle`(`resource/AsyncHandle.hpp:67-151`)同样无引用。**含义:C++ 侧"异步加载"目前是虚的**,RC6 的流式不能建在其上。-- **合法但应单点化的平台选择**:`OpenGLHeaders.hpp:18-30`(GL 头按平台 include)、`CMakeLists.txt:326`(glfw/glad/OpenGL 仅 native 分支链接)。--### 目标架构(web-only 收口)-平台概念坍缩成**单一真相 = web**:删掉所有 `#ifndef ES_PLATFORM_WEB` native 臂与多臂 OS 分支,业务逻辑零双臂 `#ifdef`。保留的仅两类:① binding 边界文件的诚实单臂 `#ifdef ES_PLATFORM_WEB` 封套(标记 emscripten-only 代码,非业务污染);② `Engine::getPlatformName` 的 WeChat/Web **运行时**变体(`ES_PLATFORM_WXGAME`,是 web 内的真实分支,非 native)。--### F1 — ✅ 已落地(web-only 收口,分支 `rearch/f1-web-only` → master `5ac53d91`)-五个原子批次,约 **1700 行 native 代码删除**:-- **B1**(`5a24370d`):删死代码孤儿 `LoaderJobQueue`(std::thread 池)+ `AsyncHandle<T>`——全仓零引用,C++ 侧异步加载本是虚的。RC6 流式真要异步时**重建 web-first `IAsyncLoader`**(JS Promise/主线程),不复活 native 线程池。-- **B2**(`37481fcf`):`Log` sink mutex 删除(web 单线程,唯一其它 mutex 用户是被删的 `HotReloadManager`)。-- **B3**(`1e3b5110`):`ResourceManager`/`Texture` 塌成 web-only——删 `loadShaderFile`/`loadEngineShader`/`reloadShader`(native `ShaderFileLoader`+热重载)、`Texture::createFromFile`(stbi)、`loadTexture`/`loadBitmapFont` 的 native 臂;删 TU `stb_image_impl`/`HotReloadManager`/`ShaderLoader`。web 经 JS 解码 + `createTexture`/`registerExternalTexture` 上传,无 C++ 文件解码路径。-- **B4**(`eb0a990e`):`Engine`/`PathResolver`/`OpenGLHeaders`/`GLDevice` 多臂 OS 分支 → web/GLES3 单一真相。-- **B5**(`5ac53d91`):删 native 构建配置——CMake native 分支(`find_package(OpenGL)`/glfw/glad/OpenGL/nlohmann/`ES_PLATFORM_NATIVE`/`ES_SOURCE_DIR`)、`ESEngineConfig` OS/native/scripting 宏、third_party glfw/glad。`esengine` 无条件是 Emscripten 目标。--**验证**:本机 MSVC 编译并运行 `tests/renderer/test_texture_fb`(直吃改过的 `Texture.cpp`)全绿——证明 ① 纹理仍正确走 GfxDevice,② **header-only / MockGfxDevice 原生验证能力在收口后依然可用**(不 link `esengine`,任意 C++20 工具链可跑)。`Log.cpp`/`PathResolver.cpp` 亦 MSVC 编译通过。Emscripten 全量构建经 CI `build.yml` 守门。--> **遗留(可选 cosmetic)**:binding 边界仍有约 18 处单臂 `#ifdef ES_PLATFORM_WEB` 封套(含 2 个 EHT 生成文件)+ `Script.hpp` 的 `#ifdef ES_SCRIPTING_ENABLED`(宏现已永不定义)。皆为已激活的 web 代码(删之为行为 no-op),属诚实 emscripten 接缝标记,非业务污染——留待后续统一清扫或随 EHT 模板调整。-------## F2(keystone):五套桥接 → 单一 `WasmBridge` 基类 + 守卫下沉--### 病灶-- 桥接写法 5+ 套,各自实现 loader / ready / 错误 / 缺绑定策略:- - 类式:`BuiltinBridge`(`sdk/src/ecs/BuiltinBridge.ts:299`)- - 全局单例 init/shutdown ×6:`postprocess/PostProcessAPI.ts:9`、`geometry.ts:43`、`draw.ts:23`、`material.ts:98`、`glDebug.ts:8`、`renderer.ts:31`- - 子系统接口 ×3:physics 直传参(`physics/PhysicsSystem.ts:79`)、spine(`spine/SpineCppAPI.ts:4`)、tilemap(`tilemap/tilemapAPI.ts:102`)- - 其它:timeline 全局模块(`timeline/TimelineControl.ts:4`)、uiHelpers 模块+注册表对(`ui/uiHelpers.ts:83-84`)-- **abort 守卫只装在 `BuiltinBridge`**(`BuiltinBridge.ts:331`,包装在 `resolveAndCache_` 473-485)。physics/spine/timeline 的 WASM 调用**全程无守卫**(`PhysicsSystem.ts:79+`、`TimelinePlugin.ts:138+`、spine `SpineController`)——模块 abort 后继续调尸体,正是 RC3 要消灭的失败模式。--### 目标架构-- **单一 `WasmBridge` 基类**:一个 loader、一个 ready promise、一条缺绑定策略、一条错误路径。六个全局模块单例 + 三套子系统接口 + timeline/uiHelpers 全部继承它。-- **守卫下沉**:基类在唯一收口处统一"调用前 `throwIfModuleAborted` + 调用中 abort 则致命重抛"(把 `BuiltinBridge` 已验证的 `resolveAndCache_` 模式提升到基类)。所有子系统**自动**获得 abort 安全,无需各自补。-- F2 一步同时解决"统一"与"基础安全"两件事。--> 这是 keystone:它既是 RC5 SDK 尾巴的收口,也是 RC3 abort 覆盖的补全,还是 F3 的载体(基类持 per-App 模块引用)。--### 实现 — ✅ 已落地(commit `ac390f7d`,分支 `rearch/f2-wasm-bridge`)-- **`WasmBridge<M>`(`sdk/src/WasmBridge.ts`)**:`connect(module, healthModule?)` 装 abort 守卫并返回**同型守卫代理**——函数调用经 `throwIfModuleAborted` 前置 + 调用中 abort 则致命重抛;`HEAP*`、`_malloc/_free` 透传(让 `withScratch` 的 finally 在 abort 后仍能释放,不掩盖原错)。守卫包装按属性惰性缓存,稳态开销仅一次 proxy get + Map 查找。`healthModule` 参数支持"调用面与 abort 权威模块分离"(spine side module:守 `api`、health=`raw`)。-- **`CoreApiBridge`(`sdk/src/CoreApiBridge.ts`)**:label 走构造参数的共享子类,用于主模块各 facet——renderer/draw/material/geometry/postprocess/glDebug + tilemap + timeline + uiHelpers。-- **`PhysicsBridge` / `SpineCoreBridge` / `SpineModuleBridge`**:physics + spine 两个 surface(主模块 `spine_*` 与版本化 side module)。-- **迁移方式**:每个子系统在其 init/connect 接缝处把存储的 module 引用替换为 `bridge.module`,**数百个调用点零改动**继承守卫。-- **覆盖**:abort 守卫从"仅主模块经 BuiltinBridge"扩展到 physics / spine / tilemap / timeline / ui / 六个 core facet **全覆盖**——补全 RC3 空洞。-- **验证**:29 个新测试(wasm-bridge 12 / spine-bridge 7 / core-bridge 4 / timeline-tilemap-ui 6);typecheck 通过;全量 SDK 套件 **2052 通过 / 0 失败**。-- **`ResourceManager` 闭环 — ✅**:embind RM 对象经 `WasmBridge`(health=主模块)守卫,`initResourceManager(rm, module)` 接缝路由;测试路径(无 module)保持 raw 向后兼容。至此 SDK 全部 WASM 调用面均经守卫。`Camera` 的 module 触点归 F3。-------## F3:半 per-App → 全子系统 per-App 资源--### 病灶-- 已正确(per-App 资源):`Tween`(`animation/Tween.ts:217`)、`Audio`(`audio/Audio.ts:279`)、`Scene`(`sceneManager.ts:662`)。-- 仍进程级全局:Camera 池(`camera/CameraPlugin.ts:36`,永不重置)+ 缓存 app(`camera/Camera.ts:7`);SpriteAnimator clip 注册表 + 事件监听(`animation/SpriteAnimator.ts:43/65-66`,跨 App 泄漏);PostProcess 注册表(`postprocess/PostProcessStack.ts:27`,手动 swap);Timeline 模块(`timeline/TimelineControl.ts:4`);六个 core 模块全局(geometry/draw/material/glDebug/renderer + uiHelpers)。-- 后果:多 App / 编辑器反复 F5 预览时**状态串味、资源泄漏**。--### 目标架构-- 所有子系统运行时状态改为 **per-App/per-World 资源**(`defineResource`),与 Tween/Audio/Scene 对齐。-- **搭 F2 的车**:模块引用由 `WasmBridge` 基类按 App 持有;子系统状态挂 App 资源。App 销毁 = 状态随之回收,无需手动 reset/swap。--### 执行计划(已拍板:**完整 per-App,接受公共 API 变更**,支持多 App 同时运行)-**模式**:每个子系统的状态收进一个 per-App API 对象(构造时持 `app`),经 `defineResource` 注册,用户 `app.getResource(X)` 取用——与 `Tween`/`Audio`/`Scene` 完全一致;进程级全局 + 全局自由函数随之退役。--**待迁清单与公共 API 影响**:-| 子系统 | 现状全局 | 目标 | 公共 API 变更 | 牵连 |-|---|---|---|---|---|-| **Camera** | `app_`、`CameraUtils`(`Camera.ts:7/23`)、`cameraInfoPool_`(`CameraPlugin.ts:36`) | `Camera` 资源(API 对象持 app)+ 池移入实例 | `CameraUtils.x()` → `app.getResource(Camera).x()` | **无内部调用方**,最干净 |-| **PostProcess** | `activeRegistry`/stacks(`PostProcessStack.ts:27`)、手动 `setPostProcessRegistry` | per-App 注册表资源 | 退役手动 swap | 中等 |-| **Timeline** | `handles_` 全局(`TimelineControl.ts:3`,且与 plugin 实例的 `handles_` 重复) | handles 收进 per-App 资源 | `TimelineControl.play(entity)` → app 作用域 | 去重 |-| **SpriteAnimator** | `clipRegistry`、`globalAnimEventListeners`(`SpriteAnimator.ts:43/66`) | `SpriteAnimation` 资源持 clips/listeners | `registerAnimClip(clip)` → 资源方法 | **牵连 LoadContext**:`AnimClipAssetLoader`/`runtimeLoader` 在资产加载期注册 clip,需把目标 app 的 clip 资源带进加载上下文 |--**子岔路(需在 B4 前拍板)**:模块绑定单例(geometry/draw/material/renderer/glDebug/postprocess module/tilemap/timeline/uiHelpers,F2 已收进 `CoreApiBridge`)持有的是 **wasm 模块**。若多 App **各自独立 wasm 模块**,这些单例(last-init-wins)也须 per-App——量很大;若多 App **共享同一模块**,它们是 per-module 而非 per-App,按 teardown 重置即可。取决于 `createWebApp(module)` 的实际用法。--**批次顺序(每批独立验证、保持常绿)**:-1. **B1 Camera** — ✅ 已落地(`95f74041`):`CameraView` 资源 + per-App scratch 池。-2. **B2a Timeline** — ✅ 已落地(`06e0268e`):`Timeline` 资源,消除全局 handles 串味。-3. **B2b PostProcess** — ✅ 已落地(`1e27c712`/`a1f421b0`/`90b8cfdc`/`60937741`):拆 god-object(Stack 数据 / Api 类 / effects 工厂)→ per-App `defineResource` + **管线依赖注入**(后处理成为可插拔渲染阶段,pipeline 不再硬依赖全局)+ 删 `sync.ts` 重复路径。两个 App 后处理状态完全隔离。-4. **B3 SpriteAnimator** — ✅ 已落地(`c983106d`/`635d80a1`):clip 注册表 + 帧事件监听器收进 per-App `SpriteAnimation` 资源;clip 注册按 app 路由(资产加载经 `ctx.getSpriteAnimation()` 惰性解析,仿 `getAudio`;运行时加载经 `app.getResource`);`gotoFrame/gotoLabel` 转方法。两个 App 不再共享 clips/监听器。-5. **B4 模块绑定单例** — ✅ 关闭(已拍板:**单模块运行时**)。模块绑定单例(geometry/draw/material/renderer/glDebug/postprocess-module/tilemap/uiHelpers/timeline-module)持有的是 wasm 模块;`corePlugin.build` 每次建 App 都重新 `initXxxAPI(module)`,单模块运行时(WeChat 一游戏一模块;编辑器 F5 顺序销毁重建)下本就正确。仅"多 App 同时各带独立模块"才需 per-App,该场景不适用,故无需改动。--> **F3 完成**:游戏状态子系统(Camera / Timeline / PostProcess / SpriteAnimator)全部 per-App 隔离;模块绑定单例在单模块运行时下正确,无需改。--### B2b PostProcess —— 拆 god-object,后处理成为可插拔渲染阶段-**病灶**:`PostProcess`(`postprocess/PostProcessAPI.ts`)是四合一全局单例——混 ① wasm 调用 ② 状态(`stacks`/`cameraBindings`/`screenStack`)③ 着色器工厂 ④ 管线编排(`_applyForCamera`/`_applyScreenStack` 等)。叠加三处结构病:`renderPipeline.ts:9` 反向 `import` 全局并在热路径调 `PostProcess._*`(管线硬依赖全局);状态散落 4+ 份全局(`activeRegistry`、`screenStack`、`sync.ts` 与 `volumeSystem.ts` 各一套 `volumeStacks/volumeShaders`);`PostProcessStack` 构造即自注册全局 `activeRegistry`(`:56`)。`sync.ts` 与 `volumeSystem.ts` 是两套重复的 volume→stack。--**目标架构(分层 + 依赖注入 + 可插拔)**:-| 层 | 职责 | 归属 |-|---|---|---|-| `PostProcessDevice` | 薄 wasm 命令包装(`postprocess_*`),沿用 F2 守卫 | 模块级(共享,与 Renderer/Draw 同级;模块本身归 B4) |-| `PostProcessStack` | 纯数据(passes+uniforms+dirty),去全局自注册 | 谁持有谁拥有 |-| `PostProcessState` | per-App 资源:`stacks`/`cameraBindings`/`screenStack` + create/bind/unbind/setScreenStack | `defineResource` |-| `PostProcessRenderer` | 编排:应用 stack 到相机/屏幕(读 State + 调 Device) | per-App,**注入 RenderPipeline** |-| `postProcessEffects` | `createBlur/...` 纯着色器工厂 | 无状态模块 |--- **依赖反转**:`RenderPipeline` 不再 import 全局,改持**可选** `postProcess_: PostProcessRenderer | null`(默认 null = 无后处理、零开销);`PostProcessPlugin.build` 注入。后处理成为**可插拔渲染阶段**。-- **单一 volume→stack**:删 `sync.ts` 重复路径,保留 ECS 组件驱动的 `volumeSystem`,经 `Res(PostProcessState)` 取状态。--**子批次(build-green)**:-1. **B2b-1** 数据净化:`PostProcessStack` 去全局自注册;`activeRegistry` → `PostProcessState` 类(暂单例,纯搬迁,无行为变化)。-2. **B2b-2** 拆 `PostProcessDevice` + `postProcessEffects`,god-object 瘦身。-3. **B2b-3** `PostProcessRenderer` + RenderPipeline 可选注入 + 插件注入;删管线对全局 `PostProcess` 的 import。-4. **B2b-4** `PostProcessState` 转 per-App 资源;`volumeSystem` 经 `Res` 取状态;删 `sync.ts`。--> 可行性:`RenderPipeline` 已 per-App(`app.setPipeline`,webAppFactory),DI 成立;`sync.ts` 是可删的重复路径。-------## F4:文档漂移 → 与代码对齐--### 病灶-- `ARCHITECTURE.md` 仍描述 RC5 已删除的 `Renderer`(静态 API)、`RenderCommand`、`BatchRenderer2D`;SparseSet/Entity 布局写的是旧版(实际分页 + 20-bit index+generation,见 `Registry.hpp:552`)。--### 目标架构-- 重写 `ARCHITECTURE.md` 的渲染与 ECS 段,与 RC1–RC5 后的真实类(`GfxDevice`/`RenderFrame`/`DrawList`/分页 `SparseSet`)对齐。文档亦受"单一真相"约束。-------## 一处已澄清的好消息(无需动作)-- **JS→C++ 边界在 release 下安全**:`Registry::valid()`(`Registry.hpp:197-201`)是纯运行时布尔检查,**非** `ES_ASSERT`;生成的 embind 包装器每个入口 `if (!r.valid(entity) || !r.has<>()) return`(`WebBindings.generated.cpp:1196`)。RC1 codegen 已把守卫生成进去。仅 `emplace/get` 的 **C++ 内部**调用还靠 `ES_ASSERT`(`Registry.hpp:243/262/305`),属可信引擎代码,风险面远小于原文档担心。**RC3 的"release 剥离校验"项可降级关闭。**-------## 执行顺序(全程保持构建常绿,每批可独立验证)--1. **F2 — 单一 `WasmBridge` 基类 + 守卫下沉**(无依赖、价值最高,先做)。逐子系统迁移:core 六模块 → physics → spine → tilemap → timeline → uiHelpers。每迁一个,typecheck + 该子系统测试守门。-2. **F3 — 全 per-App 资源化**(搭 F2)。每子系统:全局单例 → `defineResource`;补"双 App 互不串味"测试。-3. **F1 — 平台后端接缝**(保留 native,隔离):先 `IImageDecoder`/`IAsyncLoader`/`IHotReload` 抽接口,把 `#ifdef` 业务臂迁进 per-platform impl;`PathResolver`/`Engine` 拆 TU;`Log` mutex 去 `#ifdef`;**接通 `LoaderJobQueue`(消灭孤儿,为 RC6 备好 native 异步)**;CMake 把 `ES_BUILD_NATIVE` 接进 CI 编译门禁。-4. **F4 — 重写 `ARCHITECTURE.md`**(可并行,随时做)。-5. → 然后进 **RC6 资产管线**。--> 依赖:F2 是 keystone(F3 搭其车,RC6 的桥接靠它);F1 的 `IAsyncLoader` 接通是 RC6 流式的前置;F4 无依赖。-------## 验证机制-- **F2**:单一基类的 loader/ready/error 单测;abort 注入测试覆盖 physics/spine/timeline(模块标死后调用即致命重抛,不再调尸体)。-- **F3**:每子系统"创建两个 App → 各自改状态 → 互不可见 → 销毁其一另一无残留"测试。-- **F1**:`ES_BUILD_NATIVE` + `ES_BUILD_WEB` 双目标 CI 编译;接口实现切换的行为对拍(web no-op vs native 实现);`LoaderJobQueue` 接通后的 native 异步加载冒烟测试。-- **F4**:人工复核 + 关键类名 grep 一致性(文档提到的类必须在代码中存在)。--## 需要拍板的岔路-| 岔路 | 选项 A | 选项 B(推荐) |-|---|---|---|-| **native CI 力度** | 仅本地偶测(会 bit-rot) | **CI 编译门禁**(隔离才不白做;这是"保留 native"决议的硬前提) |-| **`LoaderJobQueue` 时机** | 留到 RC6 再接 | **F1 即接通**(顺手消灭孤儿,RC6 直接有 native 异步底座) |-| **core 六模块 per-App** | 维持进程级(编辑器预览串味) | **随 F3 一并资源化**(多 App 干净,编辑器 F5 无残留) |diff --git a/docs/REARCH_FRONTIER.md b/docs/REARCH_FRONTIER.mddeleted file mode 100644index 040e93d8f..000000000--- a/docs/REARCH_FRONTIER.md+++ /dev/null@@ -1,186 +0,0 @@-# Estella 能力前沿现代化方案(Capability Frontier Re-architecture)--> 目标读者:引擎维护者 / AI 协作代理。-> 本文是 `REARCHITECTURE.md` 的**续篇**,体例一致:描述目标架构与根治路径,而非现状。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 全仓只读审计,4 路并行 + 交叉印证)。-> **与 RC1–RC6 的区别**:-> - RC1–RC5 根治**正确性根因**(多源真相、可绕过抽象、存储/身份/错误模型)。-> - RC6 根治**资产/平台能力错配**(压缩纹理、内容寻址、显存预算、分包流式)。-> - 本文(RC7–RC11)根治**能力前沿错配**:引擎在 RC1–RC6 后将"功能正确、地基干净",但其**性能上限、渲染后端、数据驱动深度、编辑器协议、联网能力**仍停在"能跑"而非"最先进"。这不是 bug,是**未建立的能力**——区别于 RC1–RC5 的"已建立但有缺陷"。-------## 0. 核心诊断:一条横切约束 + 一片能力空白--### 0.1 横切约束(决定所有排序):主战场是微信小游戏 + playable--构建目标以 `wechat` / `playable` 为一等公民(`build-tools/build.config.js:21-128`)。这条现实约束**否决了"按技术新潮排序"**:--- **WebGPU**:微信小游戏端支持不普及 → 必须 WebGL2 回退共存,不能 all-in。-- **wasm threads(`-pthread`/SharedArrayBuffer)**:微信环境 SAB 受限、需 COOP/COEP 头 → 需双构建分叉,不能作为默认。-- **Wasm SIMD(`-msimd128`)**:旧机型/旧 WebView 支持不全 → 需 no-SIMD 回退构建。--**原则**:凡涉及 web-only 前沿特性者,一律设计为 **web 优先 + 微信回退共存**;keystone 优先选那些"在 WebGL2 / 单线程基线下就有收益"的改造,让前沿特性成为纯加法的升级层,而非主线依赖。--### 0.2 能力空白:RC1–RC6 未触及的五个维度--| 维度 | RC1–RC6 状态 | 本文 |-|---|---|---|-| 渲染后端 | 纯 WebGL2,零 WebGPU;管线命令式、无 render graph、无实例化 | **RC7** |-| ECS 执行性能 | 调度信息齐备但单线程串行、零 SIMD(主模块)、math 纯标量 | **RC8** |-| 数据驱动 / 反射深度 | 反射刻意停在 ABI 层,富元数据从未存活到 TS | **RC9** |-| 编辑器 ↔ 运行时协议 | 无版本化协议,进程内 mutate 单例;热重载全量丢状态 | **RC10** |-| 网络复制 / 多人 | 概念完全为零 | **RC11** |--**根治原则**:每条主线先找到**在基线下就有收益的 keystone**,把前沿特性挂成它之上的加法层;凡半成品已在仓者(实例化粒子、变体系统、prefab 迁移框架)优先**激活而非新建**。-------## RC7:渲染后端现代化--### 病灶-- **后端纯 WebGL2/GLES3,零 WebGPU**:全 7 套构建配置写死 `-sUSE_WEBGL2=1 -sFULL_ES3=1`(`cmake/Emscripten.cmake`,各档)。`GfxDevice.hpp:4` 注释口头提到 "WebGPU/Vulkan" 但**仅 `GLDevice` 一个实现**(`GLDevice.hpp:29`)。-- **实例化是死代码**:`GfxDevice::drawElementsInstanced`(`GfxDevice.hpp:249`)、`vertexAttribDivisor`(`:236`)已实现于 `GLDevice` 但**零调用者**;`PARTICLE_INSTANCE_VERTEX/FRAGMENT` 实例化 shader(`Shader.hpp:310-358`)写好却**零引用**。粒子实走 CPU 逐粒子展开 4 顶点 + sin/cos 旋转(`ParticlePlugin.cpp:82-149`),WASM 单线程下每帧重建整个顶点流。-- **多纹理批能力闲置**:`DrawCommand` 支持 8 纹理槽(`DrawCommand.hpp:14`),`DrawList::execute` 已能多槽绑定,但提交侧只填 `texture_count=1`(`RenderFrameSubmit.cpp:49`、`ParticlePlugin.cpp:159`)——**不同纹理立即断批**。-- **GfxDevice 抽象层级过低**:接口是 "一个方法 = 一次 glXxx" 的瘦封装(`GfxDevice.hpp:37` 自述 1:1)。WebGL 概念漏满签名——VAO(`:220-236`)、散装 `glUniform*`(`:170-188`)、immediate-bind(`:204-213`)、GLSL 源码直传(`:153-155`)、裸 `u32` 资源句柄、WebGL-only 枚举(`pixelStorei`/`setUnpackFlipY`,`:290/298`)。这些在 WebGPU 里**无对应物**,故现状下无法新增 `WebGPUDevice : public GfxDevice`。-- **无 render graph / 无 MRT**:管线命令式 collect→sort→merge→flush(`RenderFrame.cpp`);`RenderStage` 仅 4 固定档(`RenderStage.hpp`),非可声明 pass 图;后处理是线性 ping-pong FBO 链(`PostProcessPipeline.hpp:230-231`),全仓 `drawBuffers`/`COLOR_ATTACHMENT1` 零命中。-- **shader 变体系统闲置 + 来源分裂**:`#pragma variant` 解析存在(`ShaderParser.cpp:194-225`)但 8 个 `.esshader` 一个没用,运行期变化全靠 uber-shader 的 uniform int 分支(`ui.esshader:24-26`);GLSL 两套来源(`.esshader` 文件 + `Shader.hpp`/`PostProcessPipeline.cpp:24-48` 内联字符串);存在 ES1.0/ES3.0 混用与 `EXT_MESH_*` 老语法残留(`Shader.hpp:242-272`)。--> **亮点(不动)**:排序/合并做得扎实——`DrawCommand::buildSortKey` 把 stage/layer/shader/blend/texture/depth 打成 u64(`DrawCommand.hpp:45-69`),`DrawList::finalize` 相邻连续 index 合并为单次大 `drawElements`(`DrawList.cpp:18-58`);`TransientBufferPool` 按 `LayoutId` 分 VBO 解决 baseVertex 截断;collect 阶段经 `RenderTypePlugin` 接口**已后端无关**——GL 泄漏集中在 `DrawList::execute` 与资源类,边界清晰。--### 目标架构-1. **激活实例化(纯加法,半成品已在仓)**:`DrawCommand` 加 `instance_count` 字段 + instanced 分支;`ParticlePlugin` 改走 per-instance 数据流(pos/size/rotation/color/uv),4 顶点 quad + divisor,接上已写好的 `PARTICLE_INSTANCE` shader。带宽降 ~75%,CPU 顶点重建开销大降。-2. **多纹理批合并**:`BatchVertex` 加 texIndex/texLayer 通道;`DrawList::finalize` 合并放宽到多槽;batch fragment shader 改 `sampler2DArray`(GLES3 核心,零扩展)。多图集/字体场景 draw call 显著下降。-3. **抬升 GfxDevice 抽象(keystone)**:把 §病灶列的 GL 泄漏收敛为后端无关模型——`PipelineState`(shader + 顶点布局 + blend/depth/stencil 不可变对象)、`BindGroup`(资源集合)、命令编码、UBO 替代散装 uniform、类型化资源句柄。**主重写点是 `DrawList::execute`(`DrawList.cpp:60-131`)**;collect 阶段不动。**在纯 WebGL2 下先落地即有收益(UBO 减少 uniform 调用)。**-4. **WebGPU 后端(加法层,依赖 3)**:抽象抬升后新增 `WebGPUDevice : public GfxDevice` + GLSL→WGSL 翻译(Tint/naga,或把 `.esshader` 作者语言迁 WGSL);微信保留 WebGL2 回退(双后端架构天然容纳)。解锁 compute shader(粒子/裁剪 GPU 化)。-5. **后处理 → 小型 render graph + MRT**:pass 链改声明式(输入/输出资源 + 依赖),调度器分配/复用 transient FBO;`Framebuffer` 加多 color attachment(GLES3 核心 `drawBuffers`)。-6. **shader 变体系统 + 单一来源**:扩 `ShaderParser` 支持 feature-keyword permutation(编译期 `#define` 注入 + 变体缓存);内联 GLSL 收编进 `.esshader`;统一升 `#version 300 es`,删 ES1.0 回退与 `PARTICLE_INSTANCE` 之外的死 shader。--> keystone = 第 3 步:它是 WebGPU(4)、UBO、未来任何后端的唯一前置,且基线下先落地就有收益。第 1/2/6 步与之正交,可先行。-------## RC8:ECS 执行性能--### 病灶-- **两套 ECS 并存**:C++ 核心是存储层(每组件一个分页 `SparseSet<T>`,`SPARSE_PAGE_SIZE=4096`,`SparseSet.hpp:149`);SDK 里另有一套**完整 Bevy 式 TS 用户态 ECS**(schedule/query/command-buffer/change-detection),是游戏逻辑实际编写与调度处(`app.ts:689-809`)。-- **调度器有信息却不并行**:系统已声明读写集(`Mut` = 写、`Query`/`Res` = 读,`system.ts:52-60`),`sortSystems()` 做拓扑排序 + 环检测(`app.ts:689-767`),但执行是单 for 循环串行 `await`(`app.ts:803`)——**只排序、不做冲突分析、零并行**。-- **零多线程**:全仓 `std::thread`/`pthread`/`SharedArrayBuffer`/`Atomics` 零命中;link flags 无 `-pthread`/`-sUSE_PTHREADS`(`Emscripten.cmake` 全档单线程)。-- **SIMD 仅物理侧**:`-msimd128` 只在 Box2D side-module(`Emscripten.cmake:368-378`),主模块/渲染/spine 不开;`src/` 无 `<wasm_simd128.h>`/`v128_t`。-- **math 纯标量**:`Math.hpp:20-28` 只设 `GLM_FORCE_RADIANS` 等,**无任何 `GLM_FORCE_SSE*/NEON/SIMD/DEFAULT_ALIGNED`** → GLM 走标量默认实现;TransformSystem 的 mat4 乘法逐分量标量。-- **C++ 侧延迟很初级**:`View::each` 用整池 `std::vector` 快照拷贝容忍迭代内增删(`View.hpp:273-274`)——每帧每查询一次堆分配;延迟逻辑散落(`TweenSystem.cpp:72` 手搓 pending、`Signal.hpp` pendingAdds),无统一 command buffer 抽象。--> **亮点(不动)**:SDK 侧 command buffer(`commands.ts`,系统结束自动 flush)、变更检测(`ChangeTracker.ts` 按 tick)、`RemovedQuery`、`SystemSet`/`runIf` 已是相当现代的特性集。--### 目标架构-1. **SIMD math(低风险独立,keystone-low)**:`Math.hpp` 开 GLM SIMD 后端 + `GLM_FORCE_DEFAULT_ALIGNED_GENTYPES`;主模块 + 渲染热路径加 `-msimd128`(物理侧已验证可用);微信出 no-SIMD 回退构建。**关键 caveat**:开对齐会改组件 struct 布局,而零拷贝靠 `ptrLayouts.generated.ts` 固定偏移——必须重新生成偏移表,**RC1 的 ABI hash 握手 + `static_assert(offsetof)` 正是这个改动的安全网**(改错即启动拒绝/编译失败)。-2. **自动并行调度**:用已声明的读写集构建系统冲突图,把拓扑序升级为"按组件读写冲突分组并行批次"(Bevy 式)。**先在单线程上做冲突分析 + 确定性验证**(拿到收益且为并行铺路);真并行作为加法层依赖第 4 步。-3. **C++ 统一 command buffer**:把散落的延迟逻辑收敛为单一 deferred 抽象,消除 `View::each` 每帧快照分配,并为并发结构变更提供单一安全入口;语义对齐 SDK `CommandsInstance`。-4. **wasm threads 工作线程池(加法层,受平台约束)**:`Emscripten.cmake` 加 `-pthread -sUSE_PTHREADS -sPROXY_TO_PTHREAD -sSHARED_MEMORY`,解锁数据并行(变换层级、粒子);微信因 SAB 受限走双构建。**高风险,排在最后。**--> **存储模型已拍板**:**不上 archetype**(会推翻 RC2 的"单一 SparseSet"统一计划 + 破坏 `ptrLayouts` 稳定指针契约)。如需固定组合的连续遍历,做 EnTT owning-group(增量维护交集连续布局,与 RC2 兼容),不做全量 archetype 重构。-------## RC9:数据驱动 / 反射深化--### 病灶-- **反射刻意停在 ABI 层**:`ES_COMPONENT`/`ES_PROPERTY` 是**空宏**(`Reflection.hpp:35,56`),反射靠 EHT 正则解析(`tools/eht/parser.py`)。注解白名单仅 5 个(asset/animatable/anim_override/entity_ref/readonly,`parser.py:102`)。-- **富编辑器元数据全缺**:无 range/step/slider、无 tooltip、无 DisplayName、无真分组(category 退化为组件名)、无 hidden、无网络复制标记。-- **富元数据从未存活到 TS(关键)**:C++ 侧生成了 `editor_getComponentSchema` JSON(`editor_api.py`),但**TS 侧零消费**;`component.generated.ts` 的 `COMPONENT_META` 只带值 + 轻量标签(defaults/assetFields/entityFields/colorFields/animatableFields),全文件无 min/max/step/tooltip/label/category。-- **scene 迁移无框架**:prefab 迁移是**真·版本化、幂等**的(`prefab/migrate.ts`,`PREFAB_FORMAT_VERSION`,加载自动应用)——很好;但 scene 迁移是散落硬编码命令式特例(`scene.ts:156-179,267-282`),`version:'1.0'` 字段**写了从不读分支**(死字段),无"格式版本过新即拒绝"守卫。-- **TS 用户组件是二等公民**:`animatableFields` 恒空、colorKeys 靠 `detectColorKeys` 启发式(`component.ts:236-249`),元数据形状与 C++ builtin 不同构。--> **亮点(不动)**:prefab 的 8 种 override / 嵌套 / 变体 / diff / 校验是 **Unity 级**;资产引用 = 稳定 UUID GUID(`.meta` 旁挂、改名不破引用、`AssetRegistry` 双 map);ABI 三重握手(组件方法存在性 + 自报组件表 + layout hash,`BuiltinBridge.ts:385-438`)。弱点集中在 **scene 格式本身**(冗长美化 JSON、无二进制、无 delta)。--### 目标架构-1. **富元数据单一权威源(keystone)**:给 `ES_PROPERTY` 扩注解词汇(`range=`/`step=`/`tooltip=`/`label=`/`category=`/`hidden`/`replicated`/`skip_serialize`),在 `parser.py` 透传,从 `MetadataGenerator` 发到 TS `COMPONENT_META`(而非只进 C++ 的 `editor_getComponentSchema`)。**一处注解,三处受益**:带约束的精修 inspector + 声明式序列化策略 + 网络复制声明(RC11 前置)。-2. **序列化版本迁移框架**:把 `prefab/migrate.ts` 的版本化幂等模式提升为通用框架套到 scene;让 serializer 写真版本号、loader 按版本分支、加"版本过新即拒绝"守卫。-3. **TS 用户组件与 builtin 同构**:`defineComponent` 扩为 schema-builder(字段级 `f.float({min,max}).tooltip()`),让纯 TS 组件进同一 inspector/序列化/复制管线,元数据形状与 EHT 产出对齐。--> keystone = 第 1 步:它是 RC9 第 3 步、RC10 inspector、RC11 复制声明的共同杠杆。`ES_PROPERTY` 当前是空宏,扩它是纯加法。-------## RC10:编辑器 ↔ 运行时协议--### 病灶-- **无版本化、类型化协议**:编辑器与运行时同 JS realm,靠**直接 mutate 共享单例** `AppContext.editorBridge`(`context.ts:56`)+ 观察者回调(`EditorBridge`,`context.ts:18-38`)接入,无握手、无信封、无版本戳;`postMessage`/`rpc`/`jsonrpc` 全仓零命中。-- **同步是隐式文件布局契约**:`syncToDesktop` 纯 `fs.cp` 拷贝(`build-tools/tasks/sync.js:7-44`),无 manifest、无版本戳;唯一"类型化"部分是 bundle 里的 `.d.ts`。-- **热重载全量丢状态**:`PreviewPlugin.reloadScene()`(`preview/PreviewPlugin.ts:191-201`)= `SceneManager.switchTo('__preview__')` 整场景拆毁重建、重 fetch JSON、重载所有资产,**不保留任何实体/组件状态**;`runtimeLoader.ts` 是一次性加载器,无增量路径。SSE 服务器不在本仓(仅见客户端 `EventSource` 连 `/sse-reload`)。--### 目标架构-1. **版本化命令/事件契约**:把隐式接缝(`EditorBridge`、`inputRouter.setEditorHandler`、`transaction.ts`、SSE)收敛为显式 `attachEditor(version, bridge)` 握手 + editor→runtime 编辑命令 schema(复用 `commands.ts` 命令类型)+ runtime→editor 变更事件信封;同步产物打协议版本戳。为未来 out-of-process / 远程编辑铺路。-2. **状态保留热重载 / 场景 live-patch**:借 `prefab/diff.ts:49` 的 diff 思路做 scene-diff → 增量 apply(insert/remove/setField),保留运行时状态;World 已有 `ChangeTracker` + ECS 重映射(`scene.ts:132-150`)可复用。调参体验从"重载丢状态"升级到"改字段立即生效"。--> 注:编辑器源码在仓外,改契约需跨仓协调——这是 RC10 的主要约束,故契约设计须先行、向后兼容。-------## RC11:网络复制 / 多人--### 病灶-- **复制层完全为零**:"replication" 概念全仓不存在;`net/GameSocket.ts` 仅有 socket 传输,无权威/插值/relevancy/RPC。--### 目标架构-- **从反射生成复制层(复用 RC9 + 已有 ptr 布局)**:基于 RC9 第 1 步的 `replicated`/`authority` 注解,从 EHT 生成 per-component 增量序列化器——**复用 `ptrLayouts.generated.ts`(本身已是紧凑二进制表示)做 binary diff**,与 RC9 第 2 步的 binary delta 序列化共享底层;运行时补权威/插值/relevancy。-- **战略定位**:工作量最大;若产品路线图含多人则为战略缺口,否则暂缓。其杠杆点在于"反射注解 + ptr 布局"已铺好底座,不必从零造轮子。-------## 附:工具链小改进(非引擎架构,顺手)--- **收敛 8 套重复 flag 集合**:`Emscripten.cmake` 各 target 手工重复 link flags 易漂移 → 抽公共基集 + 差异叠加(`es_emscripten_flags()` 或 `list(APPEND)`),逐 target 验证产物字节级一致。低风险纯重构。-- **EHT 去正则**:`parser.py` 正则解析 C++ 头对模板/宏脆弱 → 迁 libclang AST(保留 Python,只换解析内核)。-- **wasm-split 懒加载**:对主 `esengine.wasm` 用 profile-guided `wasm-split`,把编辑器专用/post-process/tilemap 冷代码切二级模块,首屏只下主块;`ES_ENABLE_*` 特性开关天然是切分边界。微信/playable 首包体积 KPI。-- **CMake generator 换 Ninja**(emsdk 已自带)。--## 尊重的既定取舍(不改)--经独立复核,以下决定正确,**本文不建议改动**:-- `-fno-exceptions` + 显式状态码(保留,省体积/速度)。-- Memory64(2D 引擎用不上 4GB 上限,纯 ~10-20% 性能/体积税)。-- archetype(不如 owning-group,且冲突 RC2)。-------## 执行顺序(按"微信/playable 主战场 + ROI"排,全程保持构建常绿,每批可独立验证)--| 档位 | 批次 | 依据 |-|---|---|---|-| **立即(独立 / 低风险 / 见效快)** | RC7-1 实例化粒子、RC7-2 多纹理批、RC8-1 SIMD math、RC7-6 shader 死代码清理+统一来源、RC9-2 scene 迁移框架、工具链 flag 收敛 | 均不依赖大重构;微信端立竿见影;半成品已在仓者优先激活 |-| **keystone(解锁后续)** | RC7-3 GfxDevice 抽象抬升、RC9-1 富反射元数据单一源 | 两个总闸门,WebGL2/基线下即有收益,各自解锁一整条上层 |-| **中长期(依赖前置 + 平台权衡)** | RC7-4 WebGPU、RC8-2/4 自动并行 + wasm threads、RC11 网络复制、RC10-2 状态保留热重载、RC10-1 规范化协议 | 依赖 keystone 或受微信平台约束需回退共存 |--> 依赖序:RC7-3 是 RC7-4 的唯一前置;RC9-1 是 RC9-3 / RC10 inspector / RC11 复制声明的共同前置;RC8-2 的真并行依赖 RC8-4;RC11 依赖 RC9-1 + RC9-2。-> 核心判断:**先吃 RC7-1/7-2/8-1 三个低垂果实(天级、纯加法、微信直接受益),同时把 RC7-3 与 RC9-1 两个 keystone 立项。WebGPU 性感但不插队。**-------## 验证机制(与 RC1 keystone 同精神:机制即根治成立的证明)--- **RC7 渲染**:实例化前后**逐像素回归**(同场景渲染结果一致,仅 draw call/带宽下降);GfxDevice 抽象抬升用既有 `MockGfxDevice` harness 守护接口契约;多纹理批的合并正确性用 draw call 计数断言。-- **RC8 SIMD/并行**:SIMD math 用标量/向量化**逐 bit 对拍**关键变换;自动并行的冲突图用"同冲突集系统永不并行"断言 + 确定性回放测试;`ptrLayouts` 重生成后由 ABI hash 握手 + `static_assert(offsetof)` 守门。-- **RC9 反射**:富元数据**端到端往返**(注解 → `COMPONENT_META` → inspector 渲染);scene 迁移框架的幂等性 + "版本过新即拒绝" 测试(仿 `prefab/migrate.ts`)。-- **RC10 协议**:`attachEditor` 版本协商测试;scene live-patch 的 diff→apply 与全量重载结果一致性对拍。-- **RC11 网络**:复制序列化往返(编码→解码逐字段一致);权威/插值确定性测试。-------## 需要拍板的架构岔路--| 岔路 | 选项 A | 选项 B(推荐) |-|---|---|---|-| **渲染后端路线** | 直接上 WebGPU 双后端 | **先抬升 GfxDevice 抽象(RC7-3),WebGL2 下落地 UBO/PSO 收益;WebGPU 作为其后的加法层** |-| **并行执行后端** | 立即引入 wasm threads | **先做单线程冲突分析 + 确定性(RC8-2),threads 作为受平台约束的加法层(RC8-4)** |-| **固定组合查询优化** | 全量 archetype 重构 | **EnTT owning-group(增量交集连续布局,兼容 RC2 单一 SparseSet)** |-| **scene 格式** | 维持美化 JSON | **保留 JSON 为可读源 + 加版本迁移框架(RC9-2);二进制/delta 作为发布期可选编码** |-| **RC11 启动时机** | 与 RC9 并行立即做 | **待产品确认多人路线后启动;底座(RC9-1 注解 + ptr 布局)先于其就位** |-------## 实现进度(living status)--- **RC9-2(scene 序列化版本迁移框架):✅ 已落地(2026-06-19)**,作为编辑器 play 态隔离(`RC12_EDITOR_SEAM.md` E4-3)的前置先行:`scene.ts` 新增版本化、幂等、非变异的 `migrateSceneData`(读版本 + 过新即拒绝 + 盖版本),散落硬编码迁移收编,`loadSceneData` 不再变异输入,并以组件 codec 注册表解除 scene↔tilemap 耦合。全 SDK 套件 2161 passed。详见 RC12 living status。-- **其余 RC7–RC11:📋 已立项(设计文档)**,尚未开始执行。-- 建议首个执行批次:RC7-1(实例化粒子,半成品已在仓,纯加法,验证成本低)作为切入点,同步启动 RC7-3 / RC9-1 两个 keystone 的详细根治方案文档。diff --git a/docs/REARCH_GUI.md b/docs/REARCH_GUI.mddeleted file mode 100644index b32afabd4..000000000--- a/docs/REARCH_GUI.md+++ /dev/null@@ -1,249 +0,0 @@-# REARCH_GUI:运行时 GUI clean-sheet 重写(ECS 原生现代框架)--> 对象是**运行时 GUI 系统** `sdk/src/ui`(~54 TS 文件 ~7k LOC,TS side-module 覆于 C++ wasm 引擎之上),**不是**编辑器(那是 `desktop/`,见 `REARCH_EDITOR_*`)。->-> **定位变更(2026-06-22)**:作者本人确认该 GUI 是早期**临时**实现,允许**推倒重写**。因此本文从"小心缝合两代、像素一致增量"改为 **clean-sheet 重写**:沿用引擎已是 SOTA 的底座(ECS + Yoga + 序列化 + 编辑器 + 渲染管线),把 TS 逻辑层**重建为一套统一的现代 UI 框架**,补齐缺失的现代层(MSDF 文本 / 样式系统 / 响应式绑定 / 正经事件传播 / 声明式组合 / 动画整合),最后**删除全部遗留 plugin**。->-> **对象模型决策:A — ECS 原生**(已定)。UI = 实体 + 组件。否决 B(并行 VisualElement 树 / UI-Toolkit 式)与 C(渐进改造)。理由见 §1.5。-------## 0. 横切约束(决定排序,不可绕过)--与 `REARCH_RENDER.md` 同一主战场:**微信小游戏 + playable**,WebGL2 一等公民,**无 DOM 保证**(WeChat 无 DOM)。由此:--- **DOM 依赖须可回退**:遗留 `TextInputPlugin` 用隐藏 `<textarea>`(`TextInputPlugin.ts:66`),`TextRenderer` 用 `platformCreateCanvas`。重写后文本/输入走 platform 抽象,不得硬依赖浏览器 DOM。-- **C++ 管热循环、TS 管策略**:布局(Yoga)、命中测试、渲染排序、UIRenderer→draw collect、字形图集 在 C++;TS 负责样式解析、事件分发、行为 FSM、虚拟化、绑定、声明式组合。-- **接 render-rearch**:UI 渲染并入 `REARCH_RENDER` 的 `DrawList`/批次/PipelineState,**不再每文本实体一张 Canvas2D 纹理**。-- **接 animation-rearch**:UI 过渡/状态动画走 `REARCH_ANIMATION` 的统一缓动/求值器,不自造 lerp。-- **重写 ≠ 全停摆**:strangler-fig 迁移——新模块与遗留并存,逐层把 examples/widgets 切到新模块,达成 parity 后再删遗留。公共 barrel `index.ts` 在可行处保持稳定,破坏性变更集中在一次。-------## 1. 现状评估--### 1.1 底座:沿用(已是对的,重写不碰)-| 子系统 | 状态 | 证据 |-|---|---|---|-| 作者化模型 | ✅ 正解 | UI = 实体 + builtin 组件,随 `.esscene`/prefab 序列化(`scene.ts`/`sceneManager.ts`);编辑器直接当实体编辑。无需单独 UI 文档格式 |-| 布局求解器 | ✅ SOTA | C++ `ecs/UILayoutSystem.cpp` 直接用 **Yoga**(`toYGFlexDirection`/`YGJustify*`,`:130-157`),flex/wrap/justify/align/anchor 单趟 `uiLayout_update`。与 Unity UI Toolkit/RN 同款 |-| ECS 组件存储 | ✅ | builtin 组件存于 C++ registry,经 codegen 镜像到 TS;reset-proof、可序列化 |-| 渲染收集 | ✅ 可接 | UIRenderer→draw 在 C++ `renderer/plugins/UIElementPlugin.cpp`;并入 render-rearch DrawList 即可 |--### 1.2 可借鉴的好点子(重写时在干净模型里重建,而非原样保留)-- 虚拟化:`collection/`(ListView+ViewPool+LayoutProvider+DataSource)——思路对(实体池回收 + 可见区间裁剪 + 变更通知),重建进统一模型。-- 事件总线:`core/events.ts`(实体级+全局订阅、冒泡、再入保护)——重写为正经 capture→target→bubble 传播引擎。--### 1.3 病灶(为什么重写而非修补)-1. **两代架构并存 / 职责劈两半**:组件 schema 在 `core/`/`layout/`/`behavior/`,驱动它们的 system 却在 ~11 个遗留扁平 plugin(`UIInteractionPlugin`/`DragPlugin`/`FocusPlugin`/`ImagePlugin`/`TextPlugin`/`TextInputPlugin`/`ScrollViewPlugin`/`SafeAreaPlugin`/`UIRenderOrderPlugin`/`UIMaskPlugin`/`UILayoutPlugin`);新 `behavior/systems.ts` 又叠一层。`index.ts:269` 起整段 `// Legacy plugins / resources still in ui/` 自供状。-2. **~13 个 plugin 手写排序**:`uiPlugins.ts` 12 项 + `systemLabels.ts` 字符串常量 + 各处 `runAfter`/`runBefore` 拼出隐式管线,无单一事实源。-3. **滚动双实现**:遗留 `ScrollView`(Transform + 惯性/弹性物理)vs 新 `collection/scroll-container`(纯状态)。-4. **文本双实现 + 最不先进**:C++ `BitmapText`+`text/BitmapFont.cpp`(.fnt 图集、批渲染、快,但位图字体)vs TS `Text`+`TextRenderer.ts`(Canvas2D 整串栅格化→**每实体一张 GPU 纹理**→慢、无 SDF;富文本/系统字体)。UI 主用慢路径;`TextInputPlugin` 又复制一套。-5. **缺响应式绑定**(全命令式 `setValue`)、**主题未整合**(`UITheme` 孤立 resource,widget 收裸 color)、**动画自造轮子**(`StateVisualsApplySystem` 私有颜色/缩放 lerp)。--### 1.4 C++ 侧体量-`ecs/UILayoutSystem.cpp`(434,Yoga)· `text/BitmapFont.cpp`(242)· `renderer/plugins/TextPlugin.cpp`(164)· `renderer/plugins/UIElementPlugin.cpp`(121)· `ecs/UISystem.cpp`(64)。C++ 已拥有 ECS 存储 + Yoga 布局 + 命中测试 + 渲染排序 + UIRenderer draw collect + 位图字形图集基建。--### 1.5 对象模型决策:A(ECS 原生)-| | A. ECS 原生(选定) | B. 并行保留树(UI Toolkit 式) | C. 渐进改造 |-|---|---|---|---|-| 元素 | 实体 + 组件 | 独立 VisualElement 树 + USS/UXML | 维持 |-| 布局 | 复用 C++ Yoga | 自带(也 Yoga) | 现状 |-| 序列化/编辑器 | **白嫖** | 另造 UI 文档 + 编辑器集成 | 现状 |-| 渲染 | 接 render-rearch DrawList | 自渲染再桥接 | 现状 |-| 工量 | 重写 TS 逻辑层 | 造平行对象模型(最大) | 最小但不够先进 |--**选 A**:引擎从底到顶 ECS,作者化已是"UI=实体进场景",Yoga 已绑 ECS 组件,编辑器已能编辑实体。Bevy 即 A。Unity 另搞 UI Toolkit(B)是为治其 GameObject-per-element 旧债 + 编辑器特殊需求——我们**无此历史包袱**,A 能白嫖全部引擎投资,B 要把序列化/编辑器/布局重造。A 的短板(组合啰嗦/无绑定/无样式)用加层补齐,无须换对象模型。-------## 2. 目标架构(clean-sheet)--### 2.1 原则-**一套 ECS 原生保留模式 UI 框架:每个关注点一个负责人(schema 与其 system 同模块),整套一条显式有序管线(单个 `UIPlugin`),C++ 管热循环、TS 管策略,渲染接 render-rearch、动画接 animation-rearch。**--### 2.2 类型地基(先于组件,根因修复)--旧组件难看的根因不是设计者偷懒,而是 **builtin 序列化只支持扁平字段**(详见 §2.6):`StateVisuals` 被迫拆成 8-slot 32 字段、尺寸要 `width:f32,widthUnit:u8` 这样拆。先把地基立起来,组件才能写得现代:--| 地基类型 | 形状 | 取代的反模式 |-|---|---|---|-| `Dimension` | `{ value: f32, unit: Px\|Percent\|Auto }` | `size`/`offset`/`min/max`/`widthPercent` 四套尺寸表达 + `-1` sentinel |-| `Edges<T>` | `{ left, top, right, bottom }`(T=Dimension 或标量) | `Padding` vs `Vec4 sliceBorder` vs 4 个 bool 三套"四条边" |-| `AssetRef` | 资产引用 + 资产元数据(texture/font/material) | 裸 `number` handle、`fontFamily:'Arial'` 字符串、不一致的 assetFields |-| `Visibility` | `{ display: Visible\|Hidden\|None }`(共享引擎概念) | 散落在 UIRenderer/Image/UIMask/Interactable 的 `enabled` 重载 |-| **全枚举化** | `ES_ENUM enum class : u8` | 该用枚举处的 `number`/`bool`(见 §2.2 词汇表注) |-| **transient 标记** | 组件/字段不进 `.esscene` | `justPressed`/`DragState`/`previous`/`isFocused`/`dirty` 等帧态被序列化 |--> 这些需要 codegen 支持任意 POD 嵌套结构(`Dimension`)与结构数组(`VisualStates.states[]`)—— 那是 §2.6 的根因修复,排在组件落地之前。--### 2.2′ 统一组件词汇表(一套到底,消灭 legacy/new 双轨)--布局主模型 = **CSS/Flex(决策 2026-06-22)**:`UINode` 是 CSS 盒,anchor/offset/pivot 降级为可选 `UIAnchors`(见 §1.5)。--| 层 | 组件 | 角色 | 取代 / 修法 |-|---|---|---|---|-| **布局** | `UINode` | CSS 盒:`position`/`width/height/min/max`(Dimension)/`inset`/`flex*`/`alignSelf`/`margin`(Edges) | UIRect + FlexItem(合一,去锚点为主) |-| | `UIAnchors` | 可选:RectTransform 锚点/pivot(给需要的人) | UIRect 锚点部分(降级为可选) |-| | `UILayout` | 容器布局意图:`mode: Flex\|Grid` + flex/真 grid 模板(Yoga 解算) | FlexContainer + GridLayout(合一) |-| | `UISafeArea` | 安全区内缩 → 喂布局 | SafeArea(4 bool → EdgeFlags) |-| **视觉** | `UIVisual` | 背景:`kind: None\|Color\|Texture\|NineSlice\|Tiled\|Filled` + AssetRef + 单一 fill 词汇 + `sliceBorder:Edges` | **UIRenderer + Image 合一**;删 render/image.ts 延迟拷贝 |-| | `UIText` | 文本内容 + `parseMode`(纯/富) → SDF 字形 run | core/text.ts Text 的内容部分 |-| | `TextStyle` | 字体(AssetRef)/字号/`fontWeight`/`fontStyle`/color/stroke/shadow(可继承可主题化) | Text 的样式部分(拆出);bold/italic→枚举 |-| | `UIMask` | 裁剪 | 同名,`maskTexture`→AssetRef |-| | `Visibility` | 显隐(共享) | 抽出散落 enabled |-| **交互** | `Interactable` | 命中门控:`pickingMode: Ignore\|Pass\|Block` | blockRaycast+raycastTarget 合并 |-| | `PointerState` | 帧态:hover/press + 指针位置/按键/touch(**transient**) | UIInteraction(清理 + 不序列化) |-| | `VisualStates` | 变长 `states[]{name,color?,sprite?,scale?}` + `Transition{duration,easing}`(过渡走动画运行时) | **StateMachine + StateVisuals 合一**,去 8-slot/反射/私有 lerp |-| | `Focusable` | `tabIndex`(单一事实源 = FocusManager) | 删 isFocused |-| | `Draggable` / `DragState` | 拖拽配置:`axis` + `constraint:Rect?` / 帧态(**transient**) | lockX/Y→axis;DragState 不序列化 |-| **Widget/数据** | `Button/Toggle/Slider/ProgressBar/Dropdown/Dialog` | 组件 + 驱动 system(value→geometry 归 system) | widget factory(从手改 anchor 升级) |-| | `TextField` | 文本输入(组合 UIText/TextStyle,走 SDF) | legacy TextInput(去重复排版 + 序列化帧态) |-| | `UIScroll` | 滚动组件,前置 collection/ScrollContainer | legacy ScrollView(双实现收一) |-| | `ThemeTokens` | 语义 token:颜色角色 + spacing/typography scale | UITheme(去 per-widget 上帝对象,接入 widget) |--> 词汇表注(全枚举化,消灭裸 number/bool):`pickingMode`、`fontWeight`/`fontStyle`、Draggable `axis`、`fillDirection`(单一权威,替 FillMethod/FillOrigin/字符串三套)、`UIVisual.kind`、`UILayout.mode`、`UIMask.mode`、SafeArea `EdgeFlags`。`collection/*`(虚拟化 ListView/ViewPool/DataSource)与事件总线 `core/events.ts` 保留,仅统一 axis/direction 词汇。--### 2.3 模块结构(schema 与 system 同处,单一负责人)-```-sdk/src/ui/- core/ UINode · UIStyle · 事件传播引擎 · UIPlugin(单管线装配)- layout/ Flex/Grid + 唯一 Yoga 驱动 system + SafeArea- text/ UIText + MSDF 字形图集 + 富文本布局(复用 RichText 解析)- render/ UIImage · UIRenderer 构建 · 渲染排序 · DrawList 接入- input/ Interactable/UIInteraction + 命中测试 + 事件分发 + Focusable + Draggable + 其 system- behavior/ StateMachine/StateVisuals + FSM system(动画整合) + widget 驱动- style/ stylesheet/主题 token + 级联解析器- binding/ 响应式 observable→字段- collection/ 虚拟化(ListView/ViewPool)+ 唯一 ScrollView(并入遗留物理)- widgets/ 声明式 widget builder- index.ts 公共 barrel-```--### 2.4 单管线(一个 UIPlugin,固定有序)-```-PreUpdate : SafeArea → StyleResolve → Layout(Yoga) → HitTest-Update : EventDispatch(capture→target→bubble) → Behavior(FSM/Drag/Focus)- → BindingApply → Content(UIText/UIImage 构建)-PostUpdate: ScrollView → RenderOrder → Render(DrawList)-```-排序在 `UIPlugin` 内单处定义,替代 12 plugin 各自的 `runAfter`/`runBefore` + `systemLabels` 散落常量。--### 2.5 现代层(干净新建)-1. **MSDF 字形图集文本(头号 keystone)**:单一 SDF 路径——C++ 管图集(离线/运行时 MSDF 生成)+ 批量字形 quad(并入 render-rearch DrawList,与 sprite 同批);TS 管富文本解析/布局喂字形序列。**任意缩放清晰、字形级批合并(告别每实体一纹理)、系统字体+富文本+emoji 统一**,一举退役 `BitmapText`-only 与 Canvas2D-每实体两条路。`TextInput` 复用同一渲染路径,只加光标/选区/IME。-2. **样式系统(USS 式级联 token)**:stylesheet/主题资产 → 解析为 `UIStyle`(级联 + 状态变体)。widget 与作者化 UI 读主题,取代裸色 + 孤立 UITheme。-3. **响应式绑定**:observable/signal → 组件字段。声明式数据驱动,删命令式 `setValue` 样板。-4. **事件传播引擎**:capture→target→bubble 三相,单一引擎(替代现"发射者手动走父链")。-5. **声明式组合 API**:builder/JSX 式描述 UI,内部 spawn 实体树。DX 对标 UI Toolkit,但产物是 ECS 实体(保住序列化/编辑器)。-6. **动画整合**:状态过渡/transition 委托 animation-rearch 运行时。-------## 2.6 序列化约束与 codegen 根因修复(决策 2026-06-22)--builtin 组件经 **EHT codegen**(`tools/eht/`,正则扫 `ES_COMPONENT`/`ES_PROPERTY` → 生成 embind 绑定 + TS 镜像 + ptr 快路径)镜像并序列化进 `.esscene`(JSON,经 embind `getComp` 取字段)。当前能力矩阵:--| 字段形状 | 可序列化? | 机制 / 限制 |-|---|---|---|-| 标量 / vec2/3/4/quat / color / 枚举(u8) / handle / Entity / string | ✅ | 类型表 + embind |-| `Padding` 嵌套结构 | ✅(唯一硬编码) | `CUSTOM_STRUCT_TYPES` 单例 |-| `vector<Entity>` | ✅(唯一硬编码) | `VECTOR_TYPES` 单例 |-| **任意 POD 嵌套结构**(`Dimension`/`Edges`) | ❌ | 需改 4-5 张 Python 表 + 正则解析嵌套花括号 |-| **结构数组**(`vector<StateEntry>`) | ❌ | 无 element-struct marshaller;ptr 无法定尺寸 |-| `glm::mat4` / `std::function` / map / variant | ❌ | `SKIP_TYPES` |--证据见 `tools/eht/type_system.py`(`CUSTOM_STRUCT_TYPES`/`VECTOR_TYPES`/`CPP_TO_TS`)、`tools/eht/generators/ptr_layout.py`(size/align)、`tools/eht/generators/embind.py`(`value_object`)、`tools/eht/field_utils.py`、`tools/eht/parser.py`(`RE_PROPERTY`)。--**这是旧组件难看的根因**:`StateVisuals` 的 8-slot 32 字段、尺寸的 `f32+u8` 拆分,都是被这个矩阵逼出来的——不是设计取舍。--**决策(选 B,根因修复,非扁平化 stopgap)**:泛化 EHT codegen,使其支持-1. **任意小 POD 嵌套结构**(把写死的 `Padding` 改为可注册集合)→ `Dimension`/`Edges` 成一等字段;**F1**。-2. **结构数组 `vector<struct>`**(element-struct marshaller + 真成员解析)→ `VisualStates.states[]` 等;**F5**(较重,排在文本/视觉之后)。--原则:**纯增量**——只新增类型支持,不改现有扁平字段处理;以"重新生成后现有 `*.generated.*` 逐字节一致 + 全套测试绿"证明零回归。收益是**引擎级**:此后任意组件(不止 UI)都能用干净的嵌套/数组字段。--**布局主模型 = CSS/Flex**:`UILayoutSystem.cpp` 当前 RectTransform-primary(手写锚点数学,Yoga 仅用于 flex 容器子节点)。改为整棵 UI 子树**单趟 Yoga**(`YGNodeStyleSetPosition`/`*Percent`/`*Auto` + position type 已原生支持),`Dimension` 按 unit 派发 `Set*`/`Set*Percent`/`Set*Auto`,锚点数学降为 `UIAnchors` fallback;hit-test/render-order/draw 读 `computed_size_`/`pivot` 输出不变。约 150-250 LOC 单文件;**F3**。--**编辑器**:Inspector 由字段元数据自动生成(`desktop/src/engine/schema.ts inferField` + `panels/Details.tsx`),扁平字段零工作量自动出现;新形状(Dimension/Edges)需在 `inferField` + Details 加控件(随 F1 一并)。-------## 3. 分阶段落地(rewrite 序:建新 → 迁移 → 删遗留)--> **历史(已完成,新 F 序取代旧 P 序)**:旧 **P0**(layout/input/render 概念模块化 + shim)与旧 **P1**(动态 SDF 字形图集文本:`Text` 单一 SDF 渲染、退役 Canvas2D-每实体、富文本/多行/对齐/换行/CJK/UIRect 定位/z-order 全像素验证)**均已完成并推送**。详见 §7 与 `memory/gui-rearch.md`。下表是组件模型重构的新主线(2026-06-22 起):--| 阶段 | 内容 | 产出/判据 |-|---|---|---|-| **F0 规范** | 本文 §2.2/§2.6 + 记忆锁定:CSS/Flex 词汇表 + codegen 根因修复 + transient + 单 UIPlugin + 注释金标准 | 单一事实源 |-| **F1 codegen 根因** | 泛化 EHT 支持任意 POD 嵌套结构(Padding 单例→可注册集) + 编辑器控件 | 现有 `*.generated.*` 重生逐字节一致 + 全套绿;Dimension/Edges 可作 builtin 字段 |-| **F2 地基类型** | Dimension/Edges/AssetRef/Visibility/枚举 + transient 机制 | 地基可用,测试绿 |-| **F3 UINode + 布局** | UINode(CSS 盒)+ UIAnchors(可选)+ UILayoutSystem.cpp 单趟 Yoga 重写 | 布局像素验证;锚点降级为 fallback |-| **F4 视觉/文本组件** | UIVisual(并 UIRenderer+Image)+ Visibility 抽出 + UIText/TextStyle 拆分 + UILayout(并 Flex+Grid)+ UISafeArea | 删延迟拷贝;像素验证 |-| **F5 结构数组 + 状态** | 泛化 codegen vector<struct> + VisualStates(并 StateMachine+StateVisuals,变长 states[],过渡走动画) | 退役 8-slot/反射/私有 lerp |-| **F6 交互 + 单管线** | Interactable/PointerState/Focusable/Draggable 重做 + 合 12 plugin 为单 UIPlugin + SystemSets + 删 shim/字符串排序 + index.ts 收敛 | 单一现代 barrel(破坏性 API 集中此);测试重写后绿 |-| **F7 主题/绑定/widget** | ThemeTokens + 响应式绑定 + widget 组件化(value→geometry 归 system)+ UIScroll 统一、删 legacy ScrollView | 去裸色/去 setValue 样板 |-| **F8 文本收尾** | SDF 描边/阴影(text.esshader 专用管线)+ TextField(取代 TextInput,走 SDF)+ 退役 Canvas2D TextRenderer/BitmapText | 文本栈单一化 |--> 每阶段:`build -t web`(改 C++/shader/codegen 时)+ `cd sdk && npx vitest run` + `npx tsc --noEmit` + 触及渲染处像素验证(electron headless)。破坏性公共 API 变更集中在 **F6** 一次。-------## 4. 迁移与删除(strangler-fig)--- 新模块在 `sdk/src/ui/` 内逐层立起,与遗留并存;`uiPlugins.ts` 渐次把遗留 plugin 换成新 `UIPlugin` 的子系统。-- 每层达成 parity(对应 UI 测试 + examples 跑通)后删对应遗留文件。-- 破坏性公共 API 变更集中到 P4 一次,`index.ts` 收敛为单一现代 barrel。-- C++ 侧:Yoga 布局/命中/排序保留;新增 MSDF 图集(P1)替代 BitmapFont-only;`UIElementPlugin.cpp` 渲染并入 render-rearch DrawList。-------## 5. 验证基建--- **回归护栏**:现有 ~25 个 UI 测试(`sdk/tests/ui-*.test.ts`,含 `ui-plugins`/`ui-systems`/`ui-behavior`/`scrollview`/`ui-components`/`uiLayout`/`RichText*` 等)。重写保持行为处,测试须持续绿;契约变更处同步更新测试。-- **像素验证**:补 UI headless fixture,逐帧 diff(对齐 render-rearch 的 `verify:render:*` 范式)。P1 文本重点测同字号/缩放清晰度 + draw call 数(字形批合并应显著降 draw call,类比 RC7-2 sprite 4→3)。-- **对外回归基线**:`examples/ui-layout|ui-interaction|ui-controls` 三例。------------## 7. P1 详细落地:统一动态 SDF 字形图集文本(微信+web+CJK)--### 7.1 约束反推的决策-主战场微信=中文受众 → **海量动态 CJK 文本**(玩家名/聊天/描述,数千字形)。由此:-- **运行时动态字形图集**(不是离线 MSDF 全集):CJK 全集 MSDF 纹理爆炸,不可行。按需用 **Canvas2D 栅格化**任意字形(web 与微信都可用且**现有 TS 文本路径已在用 `getImageData`→`createTexture` 且微信能跑**,已去风险),打包进共享图集 + 缓存。覆盖任意字体 + CJK + emoji。-- **从栅格 alpha 生成单通道 SDF**(可行的"MSDF 级"方案):真 MSDF 需矢量轮廓(opentype 解析,运行时 CJK 不现实)。改用 **C++/WASM 距离变换(8SSEDT)** 从 Canvas2D 的 alpha 算 SDF → 任意缩放清晰;SDF 还**廉价+清晰地给描边/阴影/发光**(比现 Canvas2D 更好,顺带覆盖 UI Text 的 stroke/shadow)。(可选未来:Latin 离线真 MSDF。)-- **复用 C++ 批量字形 quad 路径**(`TextPlugin.collect`→`emitQuad`→`DrawList`)+ RC7-6 shader 变体系统加 **SDF 变体**(`batch.esshader` `#pragma feature SDF`)。不新建管线。-- 简单文本走 C++ 布局(现有 `TextPlugin` UTF-8+kerning+align),富文本走 TS(复用 `RichTextLayout`,后置子阶段)。--### 7.2 新增基元-1. **`Texture::updateSubRegion`**(C++)+ binding + TS `ResourceManager.updateTextureSubregion` —— 子区域上传单字形(`GfxDevice.texSubImage2D` 已支持,Texture 仅缺封装)。-2. **C++ SDF 距离变换**(8SSEDT):`sdfFromAlpha(alpha,w,h,range)→u8` binding;TS 传栅格 alpha 取 SDF。-3. **TS `GlyphAtlas` 管理器**:shelf/skyline 装箱 + 字形缓存(键=font/size-bucket/codepoint/style);miss→Canvas2D 栅格→C++ SDF→装箱→子上传→把字形 metrics 注册进 C++ DynamicFont。-4. **C++ `DynamicFont`**:把 `BitmapFont` 泛化为运行时可加字形(id,x,y,w,h,offsets,advance)+ isSDF + pxRange。--### 7.3 管线接入(决策:TS 中心,方案 B —— 实现期定)-两种接法:**A C++ 中心**(C++ TextPlugin 读组件 + DynamicFont,需逐字形 binding + 在 C++/TS 两处重复 metrics);**B TS 中心**(TS 已有 GlyphAtlas 持全 metrics → TS 布局 + 生成字形 quad → 经一个通用 `submitTextBatch` 提交,C++ 只批渲染)。**选 B**:复用已验证的 spine TS-提交模式、单一 metrics 事实源(DRY)、无 DynamicFont/无逐字形 binding、富文本天然在 TS。-- C++ `RenderFrame::submitTextBatch`(仿 `submitSpineBatch`,但走 `batchProgram({"SDF"})` + RenderType::Text;非门控)+ `renderer_submitTextBatch` binding + TS `ui/text/submit.ts`(HEAPU8 字节拷贝,因该 wasm 仅导出 HEAPU8)。-- TS **文本系统**(pre-flush 回调):扫可见文本实体 → glyph-prepare(GlyphAtlas 备字形,限量/帧)→ 布局 → 生成 quad → `submitTextBatch`。--### 7.4 组件统一-- **`UIText`**(并 BitmapText + `core/text.ts` Text):text/font/fontSize/color/align/wrap + outlineColor/Width + shadowColor/Offset/Blur + richText(flag)。替换两者。--### 7.5 子阶段(每步 build wasm + 验证)-- **P1.0** 图集子区域基元(`Texture::updateSubRegion` + binding + TS 封装)。-- **P1.1** GlyphAtlas 管理器 + SDF 生成(C++ 8SSEDT binding + TS 栅格/装箱/缓存)。-- **P1.2** SDF shader 变体(median/smoothstep + pxRange + outline/shadow uniforms)。-- **P1.3** TS 中心(方案 B):①`submitTextBatch` 提交基元(C+++binding+TS,DONE)→ ②真 `CanvasGlyphRasterizer`+`EngineAtlasPageStore` 接 GlyphAtlas → ③ TS 文本系统(pre-flush:glyph-prepare+布局+生成 quad+提交)→ 端到端清晰批量 CJK 文本;headless 渲染验 draw call↓ + 清晰度。-- **P1.4** 富文本(TS 布局 runs)+ SDF 描边/阴影;`core/text.ts` Text→`UIText`;退役 Canvas2D-每实体路径。-- **P1.5** TextInput 接新路径(光标/选区/IME overlay)。-- **P1.6** 退役 BitmapText(debug overlay 迁移或保留);shim 统一 P4 删。--### 7.6 微信保险-- getImageData 复用现成路径,但**真机 WeChat build 验证后**再依赖;SDF 太重时回退**纯 alpha 图集**(仍批渲染)。图集页预算 1024²/2048²,溢出多页;CJK 工作集(可见字形)而非全集。--构建:`node build-tools/cli.js build -t web`(按 hpp/cpp/h/esshader 源 hash 缓存,增量较快)。emcc 5.0.6 在 `~/.emsdk`。-------> 状态(2026-06-22):方向 **A(ECS 原生 clean rewrite)**,布局主模型 **CSS/Flex**。旧 **P0**(概念模块化)+ 旧 **P1**(SDF 字形文本,全像素验证)**已完成推送**。组件模型重构主线改用 **F0–F8**(§3):**F0 规范已写入本文 §2.2/§2.6**,下一步 **F1**(泛化 EHT codegen 支持 POD 嵌套结构)。记忆见 `memory/gui-rearch.md`。diff --git a/docs/REARCH_IMPLEMENTATION_AUDIT.md b/docs/REARCH_IMPLEMENTATION_AUDIT.mddeleted file mode 100644index a31e73a1f..000000000--- a/docs/REARCH_IMPLEMENTATION_AUDIT.md+++ /dev/null@@ -1,169 +0,0 @@-# Estella 实现质量债审计(Implementation Quality Audit)--> 目标读者:引擎维护者 / AI 协作代理。-> **与 RC 文档的区别**:`REARCHITECTURE.md`(RC1–RC5)、`FOUNDATION_CONSOLIDATION`、`RC6_ASSETS`、`REARCH_FRONTIER.md`(RC7–RC11)描述的是**主动识别的根因**与**新能力规划**;本文是对**已实现、正在运行的代码**的一次全面质量体检——找出"能跑、但实现得糙 / 有裂缝 / 有空腔 / 该重构"的债。-> 方法:2026-06 四路并行只读审计(设计 / 完成度 / 性能 / 健壮性)+ 逐条行号核实 + 误报剔除。-> **重要免责**:A 类多为审计**推断**的缺陷(已核实行号与逻辑,但**未运行复现**)。执行时应**先写复现/回归测试确认,再修**,不可凭本文盲改。-> 已排除 RC1–RC11 全部已修复 / 已规划项,下列均为**其之外**的剩余债。-------## 0. 核心诊断:三类债 + 一个放大器 + 一条贯穿线--### 放大器(根因级):`ES_ASSERT` 在 release/WASM 下编译为空操作-`core/Log.hpp:316` —— `ES_ASSERT` 在生产构建展开为 `((void)0)`。后果:所有"靠 assert 兜底"的边界 / 成员资格 / 大小 / 溢出检查,在**出货版本里全部消失**,坠入未检查的 fall-through。开发期 assert 拦住的,生产期就是 OOB 读 / abort / 静默损坏。**A 类多项的严重度由此抬高。**--> 系统性修复建议:把"必须始终生效"的边界检查从 `ES_ASSERT` 剥离为独立的、release 也保留的运行时守卫(与 RC3 "边界校验始终开启" 同精神,但 RC3 只覆盖了 JS→C++ 的 embind 入口,**引擎内部调用点未覆盖**)。--### 一条贯穿性能债的线:有机制却没接上用-难的(SIMD / 并行 / 批合并)已在 RC7–RC8 规划;本审计发现的性能债集中在另一类——**dirty / 缓存 / 复用机制已存在,却没被调用**:`rebuildIfDirty()` 不调而走无条件 `rebuild`、`Shader::uniformCache_` 被绕过、`sort_entries_` 间接排序却又物化深拷贝、wasm 真值源之外又维护一份 JS Set。多为低-中风险、改动局部、收益直接。--### 一类最危险的债:功能静默缺失(不是死代码,是"以为有其实没有")-比死代码更危险——代码看似实现了某功能,但**从未接到运行路径**,用户/上层以为它在工作:活地图无碰撞体、UI 行为层不 tick、微信音量控制 no-op、material 缓存失效 no-op。见 B2。-------## A. 正确性裂缝(会崩溃 / 内存损坏 / 资源泄漏)--### A-Critical(确定的 abort / OOB / UAF,优先堵)--| # | 位置 | 缺陷 | 触发 | 后果 | 修复 |-|---|---|---|---|---|---|-| A1 | `core/Log.hpp:244` | `std::stoi` 解析浮点格式精度,`-fno-exceptions` 下抛即 abort | 格式串以 `f` 结尾含 `.` 但精度段非数字/空,如 `"{:.f}"` | **整个 WASM 模块挂死** | 改 `std::from_chars`,失败跳过精度 |-| A2 | `renderer/Texture.cpp:166-174` | `setDataRaw` 把 `sizeBytes` `(void)` 丢弃,按全尺寸 `texSubImage2D` | 调用方传入小于 `w*h*bpp` 的 buffer | **越界读 WASM 线性内存** | 运行时校验 `sizeBytes`,不足早退 |-| A3 | `bindings/SpineModuleEntry.cpp:589,631+` | `currentBatch` 裸指针指入 `meshBatches` vector,后续 `emplace_back` 扩容搬迁后继续写 | 任意 ≥2 batch 的骨骼 | **use-after-free 写 / 堆破坏** | 改存 `batchIndex` 整型,用时重解析;或预 `reserve` |-| A4 | `bindings/SpineModuleEntry.cpp:184,193` | `spSkeletonBinary/Json_create` 返回 null 未检查即解引用 | spine-c 分配失败 / 损坏数据 | null 解引用 UB | 解引用前判空,失败返回 -1 |-| A5 | `text/BitmapFont.cpp:133,156` | `createLabelAtlas` 整数除零(`charWidth==0` 或 `texWidth<charWidth`) | 数据驱动的图集描述 | **WASM trap,模块 abort** | `cols==0 \|\| charWidth==0` 早退 |-| A6 | `ecs/SparseSet.hpp:193`、`ecs/Registry.hpp` `get<T>` | release 下唯一守卫 `ES_ASSERT(contains)` 消失,`denseIndexOf` 返回 `0xFFFFFFFF` 被当下标 | 对不持有组件的实体 `get<T>`(`UILayoutSystem.cpp:72` 等 `get<UIRect>(parent)`) | **无界 OOB 读 → 静默损坏/崩溃**(引擎内最大 OOB 源) | `get` 走 release 也生效的范围检查;热路径用 `tryGet` |--### A-High(生命周期 / 泄漏 / 静默损坏)--- **A7 重入 `destroy` 计数下溢 + 索引双回收** `ecs/Registry.hpp:137-167`:`onDestroy` 内递归 destroy 同实体,内外层各 `--entity_count_`(usize 下溢)+ 同 idx 两次入 `recycled_` → 未来 create 发出别名 entity。修:回调前先标失效。-- **A8 `View<T>::each` 单组件特化不快照** `ecs/View.hpp:421-437`:持 `pool_->entities()` 引用,回调内 emplace 扩容即悬垂 / remove swap-pop 漏访。多组件版有快照,单版没有,**行为不一致**。修:单版同样快照 + 复检。-- **A9 层级递归无深度/环守卫** `TransformSystem.hpp`(`destroyWithChildren:223`/`isDescendantOf:151`/`getRoot:214`)、`UITree::buildDFS`:裸 `emplace<Parent>` 可造环 → 无限递归 / 栈溢出 trap。修:深度上限 + visited 集。-- **A10 `ResourceManager` 所有 create* 裸解引用 `*device_`** `resource/ResourceManager.cpp:63,127,274`:init 前 / shutdown 后调用 → null 解引用或 UAF。修:`!initialized_` 早退,shutdown 置 `device_=nullptr`。-- **A11 Spine 资源生命周期**:`texture_handles_` 按去重后 handle id 作 key → 共享条目被提前/双重释放(`SpineResourceManager.cpp`);`loadJson/loadBinary` 成功但 `pool_.get==null` 时局部 atlas 析构却仍缓存 → 渲染时 UAF。-- **A12 `ParticleSystem` 注册捕获 `this` 的 onDestroy 永不移除** `particle/ParticleSystem.cpp:12-17`:系统先于 Registry 析构后回调悬垂 this。修:析构 `removeOnDestroy`。-- **A13 Physics 关节生命周期** `bindings/PhysicsJoints.cpp:35,144`:`entityToJoint[B]` 单端 key → 同 B 再建关节旧句柄泄漏;destroy body A 留悬垂 map 条目。-- **A14 Tilemap 越界 / 截断**:`setChunkTiles` 源索引用未裁剪 `width`(`TilemapSystem.cpp:92`)OOB 读;`convertGid` 双重截断把大 gid 静默映射成错 tile(`TiledMapLoader.cpp:114`);Tiled 有符号 count 未检查(`:197`)负转 u32 巨大 → bad_alloc/OOB。-- **A15 渲染器错误契约形同虚设** `Texture.cpp:131`:`initialize()` 恒返回 true,失败路径死代码,OOM 时返回包裹 id 0 的"有效"纹理(静默黑屏);`createFromExternalId` 析构无条件 `deleteTexture`(外部所有者也删 → 双删);`CustomGeometry::init` 空 layout `stride_==0` 除零。-- **A16 TS:WASM 实例化失败吞掉** `wechatRuntime.ts:89`、`spine/SpineModuleLoader.ts:190`:`.catch` 只 log 不调 `successCallback` → **工厂 Promise 永久挂起**,该路径所有调用挂死。修:透传 rejection + 超时。-- **A17 TS:超时纹理仍上传 → 每次慢加载泄漏 VRAM** `asset/AsyncCache.ts:41`:超时置 `aborted` 但底层继续跑、返回已注册 GL 的纹理被丢弃无人释放。修:`onAbandon` 处置器 / AbortController。-- **A18 TS:Scene `load/unload` 无回滚** `sceneManager.ts:280-391`:load 失败留 `status==='loading'` 尸体,重试解引用 undefined → **场景永久无法重载**;`unload` 的 `config.cleanup` 无 try/catch,抛出则后续 teardown 全跳过 → entity/system/纹理泄漏。-- **A19 TS:Physics/Spine Plugin 无 `cleanup()`** :native 模块 shutdown 是死代码,`world.onDespawn` 监听注册不移除 → re-init 留陈旧监听。-- **A20 TS:`createTexture()!` 上下文丢失崩 + 错误路径 GL 泄漏** `TextureLoader.ts:188`、`compressed.ts:168`:`!` 断言 null;upload 抛出则纹理不删。-- **A21 TS:Audio 多处** :`Audio.ts:98` 快速换 BGM 不 stop 旧 handle → 永放泄漏;`AudioPool.ts:52` release 不 disconnect → 音频图累积。--### A-Medium(规模相关 / 静默别名,择要)-- `ResourcePool`/`Registry` 的 index+generation 打包静默溢出(>2^20 条目或槽复用 4096 次后 handle 别名);`clear()` 把 generation 重置为 0 → reinit 后旧 handle 与新资源别名误判 `valid()`。-- `PhysicsContext.cpp:24` entity 0 存为 `void*(0)` 被当"无 userdata" → entity 0 碰撞/射线静默丢弃(修:存 `id+1`)。-- Box2D create 返回值从不校验、多边形/链顶点无上界校验(bad_alloc abort);`getEventRecord(i32)` 无界索引 OOB。--> 已核实为**非问题**(避免误修):`TilemapRenderPlugin.cpp:177` 在 `const auto&` 上写 `dirty` 是有意的 `mutable` 渲染缓存(`ChunkData::dirty` 声明 mutable + collect 非 const),**不是 const 违规**;Texture/Buffer/Shader 的 move 语义干净、shader 编译失败路径正确清理、Framebuffer 完整性检查在位。-------## B. 空腔(死代码 + 半成品)--### B1:可直接删的死代码(低风险,缩小地基面积)--**C++ 整块死岛**(无 embind 暴露,删除干净):-- `platform/` 抽象岛:`Platform`/`WebPlatform`(`Platform::create` 零调用 → 从不构造,20 虚函数全死)、`Input` 类、`PathResolver` 全套、`FileSystem` 16 个方法死 15(仅 `readBinaryFile` 被 `SpineExtension.cpp:27` 用,保留)。宣传的热重载/文件监视从未实现。-- `resource/` 死面:可插拔 loader 子系统(`ResourceLoader.hpp` + `LoaderRegistry.hpp` + `ResourceManager::registerLoader/getLoader/...` + `loaderRegistry_`,无任何子类)、`Resource.hpp`(零 include)、GUID 纹理缓存(`loadTextureByGUID/...` + `guidToTexture_`)、VBO/IBO 工厂、`ResourceStats`、`SharedHandle` + 三别名。-- `core/Engine.hpp`+`.cpp` 整个 `Engine`/`EngineVersion`(编译但从不实例化,仅文档引用)、`Types.hpp:263` `Result<T,E>`、`RuntimeConfig` 热重载残留、`Math.hpp` 死函数(`lookAt`/`eulerToQuat`/`quatToEuler` 等,quat 在 TS 侧做)。--**渲染死项**:6 个死 `.esshader`(axis/color/gizmo/grid/sprite/ui,运行时只用 batch+shape)+ 对应 `ShaderEmbeds.generated.hpp` 条目、`Shader.hpp` 的 `EXT_MESH_*` ES1.0 遗留、`renderer/TextureSlotAllocator.hpp` 整文件、`RenderContext` stats 链、一组零调用 getter(`Framebuffer::getSpecification`、`RenderTarget::getSize`、`TransientBufferPool::vboId` + 永不产出的 `LayoutId::MatSprite`)、`GfxEnums.hpp` 死枚举值。--**ECS / 动画死项**:5 个未用 tag 组件(`Common.hpp` `Active/Visible/Static/MainEntity/Folder`)、`Script.hpp` 整文件 + ScriptComponent 集群(TS 用自己的 ScriptStorage)、`Registry::restore/sort<T>`、`View::getAll`、`Glyph::page`(write-only)、`TweenData::group_id`。--**~28 个死 embind 绑定**(JS 零调用,仅 `wasm.ts` 声明):`renderFrame`/`renderFrameWithMatrix`(旧整体入口)、6 个空 `renderer_submitXxx` stub、12 个 Tiled object-group 绑定(`tiled_getObjectGroupCount/...`,TS 走纯 JS `parseTmjJson`)+ 连带 C++ `TiledObjectInfo` 结构、postprocess 6 个、resource refcount getter、UI patch/dirty/anim-override 一组、`physics_hasBody/hasJoint`。**删前确认 clip/stencil 8 个不是给外部 embedder 的公开 API。**--**Python / Node / CMake 死项**:`type_system.py` 的 `needs_wrapper` 被同名第二定义**整个遮蔽**(第一个永不执行)+ `is_glm/is_custom_struct` 零调用;Node 死导出(`buildAllWasm`/`buildSdkDirect`/`syncWasmOnly`/logger spinner 全套/`hash.js` 部分/`errorHelp BuildError`);`Emscripten.cmake:149` `es_apply_emscripten_settings()` 死簇(导出的 `_es_app_init` 无定义,pre-SDK 遗留);孤儿且**损坏**的 `tools/bundle-playable.js`(CommonJS require 但 root 是 ESM,一跑就崩);`tools/pack_bitmap_font.py` 零 wiring。--**整目录决策项**:`src/esengine/events/` 仅被 `tests/events/test_events.cpp` 消费,引擎/SDK/示例零集成(含纯死的 `ScopedConnection`、`Signal` 非 void 特化 ~115 行)。**若不打算发布事件系统,整目录是删除候选。**--### B2:功能静默缺失(必须**接线或明确移除**——需产品决策)--| # | 位置 | 现象 | 影响 |-|---|---|---|---|-| **B2-1** | `tilemap/tiledLoader.ts` `generateTileCollision:544` / `collisionMerge.ts` | 只被测试调用;生产路径 `parseTmjJson→tilemapPlugin` 上传 tile 但**不生成任何 collider** | **活的瓦片地图静默无碰撞**(正确性) |-| **B2-2** | `ui/plugin.ts:25` `uiBehaviorPlugin` | barrel 导出但不在 `uiPlugins.ts` 的 11 插件中 → 任何 `createWebApp` 应用里**整个 Layer-2 UI 行为层(ListView/StateMachine/滚轮)永不 tick** | 整层功能死 |-| **B2-3** | `platform/wechat/WeChatAudioBackend.ts:95` | `mixer` 返回 null(Web 返真 AudioMixer) | 微信平台 `setMusicVolume/SFXVolume/UIVolume/master` **静默 no-op** |-| **B2-4** | C++ MaterialCache 链 | `getMaterialDataWithUniforms` 零调用 = 唯一写 `material_cache` 者 → `EngineState::material_cache` 永空 | TS 侧 `invalidateMaterialCache/clearMaterialCache`(`material.ts:200-281`)沦为**对永空 map 的 no-op** |-| **B2-5** | `resource/ShaderParser` `remapCompilerLog`/`assembleStageEx` | 完整的错误行号重映射功能从未接入编译错误路径(活的 `assembleStage` 丢弃 `headerLineCount`) | shader 报错行号不准(最高价值"待接线"项) |-| **B2-6** | `PostProcess volumeSystem.ts:91` | 只激活 `isGlobal` 体积(硬编码 factor:1),非全局体积取出即丢 | 空间体积混合运行时全死 |-| **B2-7** | Timeline `MarkerTrack` / `CustomEventTrack` | TimelineLoader 解析但 Uploader 无 upload case | "timeline 触发游戏事件"未完成,静默丢弃 |-| **B2-8** | `core/Log.hpp` sink 子系统 | `addSink/removeSink` 零调用,`sinks_` 恒空,`notifySinks()` 每条日志空转 | 日志无法重定向 |--其它半成品:Spine asset-loader controller 路径从未武装(`setSpineController` 无人调用,`getSkeletonHandle` 恒 -1)、`uiBehavior` 的 `uiFlexLayout_update` 空 stub、prefab diff 无法发 `entity_removed`、audio `priority`(voice-stealing 搭架未实现)。--### B3:配置 / 构建死项与不一致-- **`build.config.js:15-19` optimization 只覆盖 15 个 wasm 目标中的 3 个**,其余 12 个(含本应 `-Oz` 的 `physics-playable`)静默拿默认 `-O2`。**发布意外优化级别。**-- 优化级别**三处规定且互相冲突**:`build.config.js`(编译 -O2/-Oz)vs `Emscripten.cmake`(链接硬编码 -O3)vs `wasm.js:144`(wasm-opt)——无单一真源。-- `CMakeLists.txt:224` `GENERATED_EDITOR_API` 缺于 eht custom_command 的 OUTPUT/DEPENDS(潜在增量构建陈旧);toolchain CLI `--no-strip/--no-archive`/`--debug` 被忽略/中和;`tasks/sdk.js` SDK 文件列表声明两次会漂移;`field_utils.py VEC*_SUBS` 与 `anim_target.py` 重复。-------## C. 性能债(热路径低效)--### C-Critical:每帧整体重算,有现成 dirty 机制却被绕过-- **C1 UI 布局树每帧无条件全量重建** `ecs/UILayoutSystem.cpp:421` → `UITree.hpp:28`:`layoutUpdate` 每帧 `tree.rebuild()` 重走整棵 Canvas 层级,**而 `rebuildIfDirty()` + `structure_dirty_` 已存在、JS 导出已接好**(`WebSDKEntry.cpp:550`),紧随的 `unifiedLayoutPass` 本身已 dirty 门控、被白白浪费。修:改调 `rebuildIfDirty`(近一行)。风险中:先审所有 add/remove/reparent 是否都 mark dirty。-- **C2 `UITree::indexOf` O(n) 被 `markDirty` 沿祖先链反复调** `UITree.hpp:65`:单次 markDirty O(depth×n),批量 mark 退化每帧 O(nodes²)。修:rebuild 时建 `Entity→index` 表,O(1)。-- **C3 UI render-order 每帧全量 DFS 重算** `UIRenderOrderSystem.hpp:38`:无 dirty 门控,结构不变也算同样的值。修:复用 C1 的 structure-dirty 信号。--### C-High-- **C4 DrawList 每帧整表深拷贝排序缓冲** `DrawList.cpp:35-40`:每帧堆分配全量 `std::vector<DrawCommand>`(~96B/条 ×数千)+ 乱序深拷贝每条 + 释放旧。`sort_entries_` 间接排序本为避免物化,这里又物化了。修:`sorted` 提升为常驻 scratch 或就地按序合并。-- **C5 每帧字符串查 uniform location** `DrawList.cpp:70`:draw 循环里 `getUniformLocation(shader, "u_projection")` 字符串键查找 + 跨界,且 `u_projection` 整帧恒定却每次 shader 切换重 set;`Shader::uniformCache_` 被绕过。修:每 program 缓存 location,每帧 set 一次。-- **C6 粒子 `forEachAlive` 扫满池容量 + `std::function` 间接调用** `particle/Particle.cpp:55`:容量 10000/存活 50 仍跑 10000 次。修:packed swap-remove 迭代 `[0,alive)` + 模板函子。风险中(现用索引算术,需协同改)。-- **C7 SpineController 每帧每批拷贝两个 typed array + 对象字面量** `spine/SpineController.ts:224-271`:`new Float32Array(vertices)` + `new Uint16Array(indices)` 每实例每批每帧 → 动画 Spine 主 GC 源。修:池化 scratch / 直接暴露 heap view 上传。-- **C8 BuiltinBridge 冗余 JS `Set<Entity>` 镜像** `ecs/BuiltinBridge.ts:303`:每内置组件成员关系在 C++ 和 JS Set 各一份;`deleteFromEntitySets` 每次 despawn O(组件类型数) 全扫。**约束:query 规划器的 smallest-set 收窄依赖它的 `.size`,不能直接删**。修:让 delete 只动该实体实际所在的 set。--### C-Medium / 快速 win(一行 / 低风险类)-- **M2 `packColor` 在 4 顶点循环内重复算** `SpritePlugin.cpp:138`、`UIElementPlugin.cpp:140`:提到循环外,**一行、零风险**(nine-slice/text 路径已正确提外,基础四边形漏了)。-- 文本 collect 每帧走 3 遍字符串 + 逐字符 hash(`TextPlugin.cpp:71,90,121`,`measureText` 已返回宽度可复用);`TimelineRuntime.ts:185` per-property 循环内 `.filter` O(n²) + 每帧数组;`PhysicsSystem.ts:410` 每帧 4 数组 + 每事件字面量 + 空资源对象;UI behavior 模板字符串键 slot 查找 + 每帧 Color/scale 字面量;`world.ts` 多处(空查询不缓存、每帧重建 depIds、`getComponentTypes` 线性扫 + `has()` 风暴);`ChangeTracker` 连 `isEmpty` 都分配数组;`L2 RenderFrameSubmit.cpp:86` Spine 索引重映射每批堆分配。--> 已核实为**干净**(无需动):`TransformSystem`(正确 dirty 跳过干净子树)、`StateTracker`(模范去重 early-return)、`TransientBufferPool`(缓冲复用非每帧重建)、`QueryCache` hit 路径零分配、`ptrAccessors`(写预分配 out + 每实体重读 HEAP 是 `ALLOW_MEMORY_GROWTH` 下的**必要**正确性)。-------## D. 结构债(设计层,大重构)--### D-High-- **D1 entity/handle 位打包逻辑三处独立复制**:`core/Types.hpp:128`(Entity 20+12 位)、`resource/Handle.hpp:52`(逐字复制)、`ecs/Entity.hpp:5`(FFI 64-bit 第三套)。扩世界容量要三处同步改,漏改即句柄碰撞。修:抽 `PackedId<INDEX_BITS,GEN_BITS>` 模板委托。**非 TypeId 排除项**(那是类型身份,这是实例索引+代际)。-- **D2 `ResourceManager` 五类资源样板各一套 + Texture 独挂 GUID 层** `resource/ResourceManager.hpp:131-357`:违反 SRP,四套独立 pool 的 find/add/release 重复,Texture 释放耦合元数据/GUID。修:`TypedResourcePool<T>` 模板 + `TextureMetadataRegistry` 下沉。**RC6 资产管线会建在其上,先收口收益大。**-- **D3 `world.ts` 770 行 god class + 组件操作双路由**:实体生命周期 + 层级 + builtin/script 路由 + 查询缓存全塞一类,`isBuiltinComponent` 分支在 insert/set/get/has/remove/tryGet 出现 14+ 次。修:拆 `EntityManager`/`HierarchyManager`/`ComponentDispatcher`/`QueryEngine`。-- **D4 SceneManager / App 两套实体销毁路径** `sceneManager.ts:356` vs `app.ts:539`:销毁/卸载决策分散两处,SceneManager 本应只管配置却直接操纵 world。修:抽 `SceneOrchestrator` 统一实体生命周期。-- **D5 UI 三 plugin 各自重造 Entity→资源缓存 + 清理循环** `TextPlugin.ts:31`、`ImagePlugin.ts:22`、`TextInputPlugin.ts:49`:同模式三份,驱逐策略不一致;`TextRenderer.ts:47` 文本缓存无上界(长时游戏 OOM)。修:抽 `EntityResourceCache<T>`(acquire/release + valid 驱逐 + LRU 上界)。--### D-Medium(择要)-- 四边形索引绕序两套不一致(4 plugin `{0,1,2,2,3,0}` vs ParticlePlugin `{0,1,2,0,2,3}`)+ QUAD 常量 5 处复制 → 抽 `QuadPrimitive.hpp`。-- Registry 手搓重入守卫(`firing_destroy_` + dead 标志)与 `events/Signal.hpp` 成熟的 `publishing_` + RAII Connection 重复 → Registry 复用 Signal。-- WASM `_malloc`/HEAP 视图/`ptr>>2` 散在 draw/geometry/material 各自管理 + `PTR_LAYOUTS` 误入公共导出 → 抽 `WasmScratch`,内部化布局。-- `RenderFrame` 编排过载(10+ 不相干成员,clip 与 ClipState 双层维护,stencil 内部结构体泄漏进接口);`BuiltinBridge` 五职责混杂;`UISystem` 公有可变成员破坏封装;C++ 缺字符串工具层(trim 双实现)。-------## 执行优先级(建议分档,全程保持构建常绿、每项独立验证)--| 档 | 内容 | 理由 |-|---|---|---|-| **1. 堵裂缝(先做)** | A1/A2/A5(单点消除确定 abort/OOB)→ A6/A7/A8/A9(ECS 核心 OOB/UAF/下溢,`ES_ASSERT` strip 暴露面最广)→ A3/A4/A11/A12(Spine/Particle UAF)→ A16/A17/A18(TS 挂死/泄漏/场景 wedge) | 真 bug,独立、多为小改动,**每项先写回归测试**。建议同时做"边界检查 release 生效"的系统性修复 |-| **2. 删死代码(低风险)** | B1:platform/ 死岛、resource/ 死面整块删;6 死 shader、Engine、Script.hpp、~28 死绑定、Python/Node 死项 | 缩小地基面积,让后续重构更清晰,零行为变化 |-| **3. 决策半成品(需拍板)** | B2:Tilemap 碰撞、UI 行为层、微信 audio mixer、MaterialCache 链、ShaderParser 报错重映射——逐个"接线 or 移除" | 功能静默缺失,**产品决策**:要这功能就接线,不要就删(别留半成品) |-| **4. 性能快速 win** | C1(一行 rebuildIfDirty)、M2(一行 packColor)、C5(缓存 uniform location)、C2/C4 → C6/C7 | 低风险、改动局部、收益直接;"有机制没用上"类 |-| **5. 大重构立项** | D1(位打包统一,RC6 前)、D2(ResourceManager 模板化,RC6 前)→ D3/D4(World/Scene 拆分)→ D5(UI 缓存) | 影响演进,工作量大,作为新 RC 排期 |-------## 验证机制-- **A 类**:每个缺陷**先写复现/回归测试**(触发条件 → 期望不崩/不泄漏),红→绿后再清单标记修复。优先用 header-only / MockGfxDevice harness(RC1–RC6 已验证可本机原生编译验证)覆盖 ECS/资源/渲染内部。-- **B1 删除**:删后全量构建 + 全测试套件常绿(零行为变化即证明确为死代码);embind 删除额外 grep `wasm.ts` 确认无声明残留。-- **B2 接线**:接线项补"功能确实运行"的集成测试(活地图有 collider、UI 行为层 tick、微信 audio mixer 真改音量)。-- **C 类**:性能项配 before/after 计数断言(draw call 数、每帧分配数、迭代次数),避免回归。-- **D 类**:大重构每批保持外部行为不变,用既有测试套件 + 新增结构测试守门。-------## 实现进度(living status)-- 📋 全部已立项,未开始执行。-- 建议首批:A1/A2/A5(确定 abort/OOB,最小改动最高确定性)+ B1 的 platform/resource 死岛删除(低风险、立即缩小面积)。diff --git a/docs/REARCH_PHYSICS.md b/docs/REARCH_PHYSICS.mddeleted file mode 100644index 490ae0602..000000000--- a/docs/REARCH_PHYSICS.md+++ /dev/null@@ -1,128 +0,0 @@-# Physics Architecture — Audit & Rearchitecture--**Status (2026-06-21):** audit complete; **P1–P3 DONE**, **P4 partial** (the safe query-`ppu` fix landed; the perf opts that need live profiling/render verification are deferred).-P1 = FixedUpdate determinism + render interpolation; P2 = unified reconciler (runtime-collider/joint/enabled mutability); P3 = contact hit events + world-toggle config surface.-Physics core = **Box2D 3.2.0** (the v3 rewrite) in a side wasm module (`third_party/box2d`,-C++ bindings `src/esengine/bindings/Physics*.cpp`), wrapped by the TS SDK-(`sdk/src/physics/*`).--## Verdict--**The engine choice is state-of-the-art (Box2D v3.2 = the SOTA 2D physics, a peer of-Rapier2D). The integration has modern foundations but three real gaps keep it below-top-tier (Bevy+rapier / Unity DOTS Physics).** No engine swap is warranted — the work is-in the integration layer.--### Already modern — do not churn--- v3 C-handle API (`b2WorldId`/`b2BodyId`/`b2ShapeId`/`b2JointId`); no v2 pointers.-- Buffered event model: `b2World_GetContactEvents` / `b2World_GetSensorEvents` — the v2- `b2ContactListener` pattern is fully absent.-- Frame-based joint defs (`base.localFrameA/B`) for all five joints; v3 motion locks- (not v2 `fixedRotation`); per-body `isBullet` continuous.-- Sub-stepping wired (`b2World_Step(dt, subStepCount)`, default 4 substeps).-- Native broadphase queries (`CastRay`/`OverlapShape`/`CastShape`/`OverlapAABB`) — no- manual AABB walking.-- **Batched transform read-back** through a shared HEAP buffer- `[u32 entity, f32 x, y, angle]` + a single `registry_batchSyncPhysicsTransforms`- apply — the #1 thing wasm physics bridges get wrong, done right here.-- Data-only ECS components keyed by entity id (no wasm handles in components —- Bevy/DOTS-correct); generation-safe handles (`b2*_IsValid`); clean lifecycle/teardown;- `playModeOnly` gating; entity↔body via `b2Body_SetUserData`.--## The three gaps that matter (ranked)--1. **Determinism defect.** Physics steps in `Schedule.PostUpdate` on a *variable* wall-clock- `time.delta`, not on the fixed-step schedule. There are two accumulators: a dead TS one- (`app.ts:581-592` `FixedUpdate` — zero SDK registrations) and the live C++ one- (`PhysicsModuleEntry.cpp:106-117`). Substep *count* per frame varies with framerate- (144 Hz vs 60 Hz) → not frame/replay-deterministic.-2. **No render interpolation (the "looks naive" tell).** The C++ accumulator remainder is- trapped; no prev+current pose, no lerp. Default physics 30 Hz vs a 60/144 Hz display →- visible stutter.-3. **Colliders / joints / `RigidBody.enabled` are create-only.** Shapes are built once- (`PhysicsSystem.ts:555`); editing a collider at runtime does nothing (no- change-detection, no shape rebuild). Blocks the editor's live-edit story.--### Secondary gaps--- Ignores `b2World_GetBodyEvents` (moved-only read-back) — re-reads every dynamic body,- including sleeping ones, each frame.-- No contact *hit* events (`enableHitEvents` / `hitEventThreshold` unused) — no impact speed.-- Chatty *writeback* (per-body `_physics_setBodyTransform` / `updateBodyProperties`); only- the read-back is batched.-- Identity leaks: joints keyed by `entityB` (silent overwrite, `PhysicsJoints.cpp:35`);- chain `b2ChainId` discarded (`PhysicsShapes.cpp:174`).-- World toggles hardcoded to `b2DefaultWorldDef()` (sleeping / continuous / restitution- threshold / warm-starting / max linear speed not surfaced) — **overlaps the deferred- physics project-settings work** (the settings UI needs these knobs to exist).-- Query `ppu` defaulted to 100 per-call instead of the live `Canvas.pixelsPerUnit`- (silent wrong-scale footgun, `Physics.ts:145`).-- `enableContactEvents = true` on every shape; single-threaded (`workerCount` unused — fine- for the wasm target today).--## Phased plan--- **P1 — FixedUpdate determinism + render interpolation (together).** Highest correctness +- visible-quality win. SDK-only (no wasm rebuild). See below.-- **P2 — runtime collider/joint/`enabled` mutability (DONE).** A unified declarative- reconciler replaces the ad-hoc imperative loop: Box2D is a reconciled cache of each- entity's component structure, kept in sync with minimal *in-place* Box2D v3 ops that- preserve simulation state — never destroy-and-rebuild the body. Two new C++ primitives:- `physics_setBodyEnabled` (`b2Body_Enable/Disable` — toggles `RigidBody.enabled` keeping- shapes/velocity/joints) and `physics_clearShapes` (`b2DestroyShape` over the body's- shapes, so colliders rebuild in place with the body — and its velocity/pose/contacts —- intact). The reconciler (`PhysicsSystem.ts`) drives them off uniform `isChangedSince`- dirty checks across RigidBody + every collider (`colliderSignature`) + every joint- (`jointChangedOrGone`): body create/destroy/enable-disable/props; shapes rebuilt on- collider set/field change; joints destroyed+recreated on change/removal. **Build note:**- the physics wasm was rebuilt with emscripten 5.0.6 — required dropping the now-removed- `-sRELOCATABLE=1` flag (`cmake/Emscripten.cmake`; `-sSIDE_MODULE=2` already implies it).- Chain colliders aren't runtime-rebuilt (their `b2ChainId` isn't tracked — static geometry).-- **P3 — contact hit events + world-toggle config surface (DONE).** New C++:- `physics_setWorldConfig(enableSleep, enableContinuous, restitutionThreshold,- maxLinearSpeed)` (`b2World_EnableSleeping/EnableContinuous/SetRestitutionThreshold/- SetMaximumLinearSpeed`) — surfaced through `PhysicsPluginConfig` (the knobs the deferred- physics project-settings needs). Contact **hit events**: `enableHitEvents` on every shape- + a `hitEventBuffer` drained from `b2ContactEvents.hitEvents` in `physics_collectEvents`- (`physics_getHitEventCount/Buffer`), surfaced as `PhysicsEvents.collisionHits`- (`CollisionHitEvent{entityA,entityB,point,normal,approachSpeed}`) for impact-strength- gameplay. The **`b2World_GetBodyEvents` moved-only readback moved to P4** — it's a perf- optimization that interacts with the P1 interpolation snapshots, so it's grouped with the- other perf items rather than risked here.-- **P4 — partial.** **DONE: query `ppu` from the live Canvas** — `Physics` queries- (`raycast`/`overlap*`/`shapeCast*`) defaulted `ppu = 100` (a silent wrong-scale footgun);- they now default to a live `ppu_` that `PhysicsSystem` pushes from the Canvas each step- (SDK-only, no wasm rebuild). **DEFERRED (perf / completeness, need live profiling +- render verification this environment can't do):** `b2World_GetBodyEvents` moved-only- readback (interacts with the P1 interpolation snapshots — a body must snap on- `fellAsleep` to avoid a sub-step rest offset); batched writeback (mirror the batched- readback for kinematic/prop writes — marginal, few kinematic bodies); chain-collider- runtime rebuild (track `b2ChainId` so `clearShapes` covers chains — chains are static- level geometry, rarely rebuilt); the `entityToJoint`-keyed-by-`entityB` overwrite is a- non-issue under the one-joint-per-entity invariant.--## P1 — design (SDK-only)--The engine already has a correct fixed-step accumulator (`app.ts:581-592`,-`fixedTimestep_ = 1/60`); after the fixed loop, `fixedAccumulator_` is the interpolation-remainder. P1 puts physics on that seam and interpolates the render pose — no C++ change.--1. **Expose the seam on `Time`.** Add `fixedDelta` (= `fixedTimestep_`) and `fixedAlpha`- (= `fixedAccumulator_ / fixedTimestep_`, 0..1, set after the fixed loop) to the `Time`- resource, plus an `app.getFixedTimestep()` getter.-2. **Align cadences.** The physics fixed timestep is set to the engine's- (`getFixedTimestep()`) so one `FixedUpdate` tick = exactly one `b2World_Step`, and- `fixedAlpha` is the true fraction within a single physics step.-3. **Step in `FixedUpdate`.** A step system (`Schedule.FixedUpdate`, `playModeOnly`)- reconciles bodies, pushes pending writes, `_physics_step(fixedDelta)` (one C++ step),- collects events, then captures pose snapshots: `prev = last cur`, `cur = read-back`.-4. **Interpolate in `PostUpdate`.** A sync system lerps `prev → cur` by `Time.fixedAlpha`- (linear x/y, shortest-arc angle) into a buffer applied via the existing batched- `registry_batchSyncPhysicsTransforms` (+ the parented-body path). New bodies seed- `prev = cur` (no first-frame smear); teleports snap.--**Result:** framerate-independent substep count (deterministic) + smooth render at any-display rate. Lands the integration layer at "modern" to match the SOTA core.diff --git a/docs/REARCH_PREFABS.md b/docs/REARCH_PREFABS.mddeleted file mode 100644index 9d4325ece..000000000--- a/docs/REARCH_PREFABS.md+++ /dev/null@@ -1,195 +0,0 @@-# REARCH — Prefabs (model-authoritative instances over the engine's prefab module)--Status: **design / proposed**. The payoff layer of the model-authoritative editor-(`REARCH_EDITOR_MODEL.md`) sitting on the asset pipeline (`REARCH_ASSETS.md`).-**Key fact: the engine already implements the entire prefab DATA system** — this-doc wires the editor onto it and closes the one scene-format gap. Not a rewrite.--## 1. What the engine already provides (the big reuse)--`sdk/src/prefab/` is a complete, tested prefab data layer:--- **`PrefabData`** (`.esprefab`): `{ version, name, rootEntityId, entities:- PrefabEntityData[], basePrefab?, overrides? }`. Entities use a stable string- `prefabEntityId`, carry `components/parent/children/visible/metadata?` and an- optional `nestedPrefab`. `basePrefab` gives **variants** (inherit + override).-- **`flattenPrefab(prefab, overrides, ctx)` → `{ entities: ProcessedEntity[],- rootId }`** — EXPANDS a prefab + its overrides (+ nested + variants) into flat- entities, allocating runtime ids while preserving each `prefabEntityId`.-- **`diffAgainstSource(source, instance, opts)` → `{ overrides, untracked,- orphanedSourceIds }`** — COLLAPSES an instance subtree back to a minimal- `PrefabOverride[]` (float-epsilon aware, ignore-lists, etc.).-- **`PrefabOverride`** covers everything: `property`, `component_added`,- `component_replaced`, `component_removed`, `name`, `visibility`,- `metadata_set`, `metadata_removed`.-- Plus `migratePrefabData`, `bucketOverridesByEntity`, `validateOverrides`,- `cloneComponentData`, `preloadNestedPrefabs`, and the runtime- `instantiatePrefab(world, prefab, {overrides, parent, assets})` /- `PrefabServer.instantiate(path)`.--So **expand / collapse / overrides / nesting / variants are DONE**. The architecture-below is the natural one *because the engine already speaks it.*--## 2. Problem: the editor doesn't use it, and scenes can't persist instances--- **No editor prefab workflow.** No "instantiate prefab" command, no editing a- prefab instance, no open-`.esprefab`-as-document, no override UI. The asset- pipeline (`REARCH_ASSETS.md` A2/A4) already indexes `.esprefab` + tracks its- deps, but nothing instantiates one into a scene.-- **The scene format can't persist a prefab instance.** `SceneData` entities are- `{ id, name, parent, children, components, visible? }`; `loadSceneData`- (`sdk/src/scene.ts`) has **no prefab handling**. Prefabs can only be- instantiated programmatically (`PrefabServer.instantiate`), never authored into- a saved scene with overrides. So there's no `play == ship` for prefab content.--## 3. Principle: instance = a document delta in the FILE, expanded entities in the MODEL--A prefab instance is, **in the scene file, a minimal delta** — `{ prefab: @uuid,-overrides }` — and, **in the open model, the fully-expanded real entities**.-**Load expands** (the engine's `flattenPrefab`); **save collapses** (the engine's-`diffAgainstSource`). The model-authoritative spine *is* the prefab editing engine.--```-.esprefab asset (PrefabData; @uuid-addressed; A2 dep graph already tracks it)- │ load: flattenPrefab(asset, overrides) → ProcessedEntity[] → SceneModel entities- │ (real source ids; each tagged with its prefabEntityId + instance root)- ▼-SceneModel (ordinary entities — Reconciler / SceneQuery / selection / commands /- undo all operate UNCHANGED; prefab-ness is inert tag metadata)- │ save: group instance subtree → diffAgainstSource(asset, subtree) → overrides- ▼-scene file: { id, prefab:@uuid, parent, overrides:[…] } — minimal, propagatable-```--**The core decision — expand-in-model, not keep-collapsed.** The alternative-(store one `{prefab,overrides}` record and expand only at read/projection time)-forces a *second* addressing scheme (instanceRoot + prefabEntityId) through-SceneQuery / Reconciler / selection / commands — a parallel system fighting the-clean single-source-id model. Expand-in-model keeps **one** entity model and-**one** addressing scheme; prefab-ness becomes metadata + a load/save transform.-This is what Unity does internally (instances are real objects + a modification-list; the file stores the delta) and is the cleanest fit for our spine.--### 3.1 A `{prefab, overrides}` delta is NOT enough — structural edits--`PrefabOverride` covers `property` / `component_*` / `name` / `visibility` /-`metadata_*` — but it has **no `entity_added` / `entity_removed`**. By design,-`diffAgainstSource` returns *structural* instance edits separately:--- a child entity **added** to the instance → `untracked: ProcessedEntity[]`-- a prefab child **deleted** in the instance → `orphanedSourceIds: PrefabEntityId[]`--(`sdk/src/prefab/diff.ts`: *"Does NOT yet emit entity_removed overrides … →-`orphanedSourceIds`"*.) So a pure `{prefab, overrides}` entry persists property/-component edits losslessly but **silently loses structural instance edits**.--The complete scene instance entry is therefore:--```-{ id, prefab: @uuid, parent,- overrides: PrefabOverride[], // diffAgainstSource().overrides- added: SceneEntity[], // .untracked — entities added under the instance- removed: PrefabEntityId[] } // .orphanedSourceIds — prefab children deleted here-```--On load: `flattenPrefab(asset, overrides)` → minus `removed` → plus `added`. On-save: write all three buckets from `diffAgainstSource`. This is the modern-Unity-model (added objects + removed components/objects are stored alongside the-modification list). The earlier "minimal delta" framing was incomplete — structural-fidelity requires these buckets (or, the restrictive alternative, disallow-structural edits on instances until the user "unpacks").--## 4. Target architecture (mapped to our components)--1. **Prefab asset** = `.esprefab` (`PrefabData`), already an `@uuid` asset. **Editing- a prefab = open it as a document in the SAME editor** (it's just entities) —- zero new authoring UI.-2. **Scene-format gap (the one engine change).** A `SceneData` entity may carry- `{ prefab: <ref>, overrides: PrefabOverride[] }` (the instance root). `loadSceneData`- detects it, loads the prefab asset, calls `flattenPrefab`, and spawns the- subtree. This is a small, clean completion of the existing prefab module — and- gives `play == ship` for prefab scenes (the runtime loads the same delta).-3. **Editor load — expand.** `ProjectStore.loadCurrentScene` (which already owns- asset access) expands each prefab-instance entry via `flattenPrefab` into- SceneModel entities with fresh source ids, tagging each with its- `prefabEntityId` + the instance-root source id (in `entity.metadata`, the field- the engine designed to survive round-trips). Then `Reconciler.adopt` as usual.-4. **Editor save — collapse.** `serializeCurrent` groups each instance subtree (by- the instance-root tag), maps it to `ProcessedEntity[]`, and calls- `diffAgainstSource(prefabAsset, subtree)` → overrides → writes a single- `{ id, prefab, parent, overrides }` entry; non-prefab entities serialize normally.-5. **Instantiate command.** Drag a `.esprefab` from the Content Browser into the- scene → `SceneCommands.instantiatePrefab(ref, parent)` → `flattenPrefab` → add- the tagged entities to the model (ordinary `addEntity` sequence) → the- Reconciler spawns them. Undoable — and it reuses the recursive-delete subtree- path already built.-6. **Overrides are free.** Any ordinary edit inside an instance (setField /- addComponent / reparent / rename / visibility) is captured at save by- `diffAgainstSource`. No per-edit override bookkeeping.-7. **Nesting + variants are free** — `flattenPrefab`/`diffAgainstSource` already- handle `nestedPrefab` + `basePrefab`; the A2 dep graph already records nested- prefab refs.-8. **Propagation.** On a prefab-asset change (the asset DB watch, `REARCH_ASSETS.md`- A2c), re-expand the open scene's instances of that prefab: re-`flattenPrefab`- with the instance's current overrides, preserving them. Closed scenes pick up- the new prefab on next load.--The Reconciler, SceneQuery, selection, commands, and undo need **no changes** —-they see ordinary entities. Only the load/save boundary (ProjectStore) and one-new command know prefabs exist.--## 5. How each goal is met (reuse-first)--| Goal | How |-|---|---|-| Expand / collapse / overrides | The engine's `flattenPrefab` / `diffAgainstSource` / `PrefabOverride` — reused verbatim. |-| Compact, portable scene files | Instances persist as a delta — `{ prefab:@uuid, overrides, added, removed }` (§3.1) — not the expanded subtree. |-| Edit instances naturally | Expanded entities are ordinary model entities — the whole editor works unchanged. |-| `play == ship` | Both editor + runtime expand the same delta via `flattenPrefab` (needs the §4.2 loader gap). |-| Nesting + variants | Already in the prefab module. |-| Prefab authoring UI | Open `.esprefab` as a scene document — reuses the editor. |-| Asset integration | Prefab = `@uuid` asset; A2 dep graph + A4 cook already include prefabs. |--## 6. Phased plan--- **PF1 — scene-format + `loadSceneData` prefab-instance support** (the one engine- change; `sdk/src/scene.ts`, reusing `sdk/src/prefab/flatten`). A scene entity may- be `{ prefab, overrides }`; load expands it. Unit-testable in node. Unblocks- `play == ship` for prefab scenes.-- **PF2 — editor instantiate + load-expand + save-collapse** on the SceneModel:- `SceneCommands.instantiatePrefab`, ProjectStore expand-on-load / collapse-on-save- via `flattenPrefab` / `diffAgainstSource`, persisting all three buckets- (`overrides` + `added` + `removed`, §3.1), instance-tag metadata. Drag-from-- Content-Browser to instantiate. **Ship the round-trip safety test FIRST** (see §7).-- **PF3 — override UX**: highlight overridden fields in the Inspector (diff vs the- prefab), Revert-override, Apply-instance-to-prefab (writes the asset),- open-`.esprefab`-as-document, and propagation on asset change (A2c).--Prereq: PF2/3 need the asset DB (A2, done) to read prefab assets for-expand/diff; PF1 needs the prefab module (done).--## 7. Open decisions--- **Round-trip is the safety net (REQUIRED, do first).** Save persists via- `diffAgainstSource`, so a diff/flatten gap = silent data loss. Before wiring- save, land a test asserting `expand(collapse(instance)) === instance` for a- scene of instances exercising every override type + structural `added`/`removed`- (§3.1). The engine module is well-covered (`sdk/tests/prefab*.test.ts`, ~82),- but the editor's collapse→file→expand round trip is new and must be pinned.-- **Structural instance edits** are handled by the three-bucket entry (§3.1) —- decided, not open; the only sub-choice is allow-now vs. require-unpack-first.-- **Delta-in-scene (optimal) vs baked-in-scene (no engine change).** §4.2 (delta +- `loadSceneData` expansion) is optimal — minimal files, propagation, `play==ship`- — but touches `sdk/src/scene.ts`. A no-engine-change fallback BAKES the expanded- subtree into the scene with `entity.metadata` prefab tags (the runtime ignores- metadata; the editor re-expands on propagation): larger files, fully editor-side.- **Recommend delta** — it's the right architecture and the prefab module makes the- loader change small; the sdk touch is a legitimate engine completion.-- **source id ↔ `prefabEntityId` mapping.** The editor allocates scene source ids- on expand and stores the origin `prefabEntityId` (+ instance-root id) in- `entity.metadata`; `diffAgainstSource` matches by `prefabEntityId` at save.-- **Propagation timing.** Re-expand open instances eagerly on the asset DB change- event (A2c), preserving overrides; vs. lazy on next load only. Eager is the- better UX once A2c lands.-- **Variants in the editor** — `basePrefab` works at the data layer; surfacing- "create variant" in the UI is a PF3+ nicety, not required for PF1/2.diff --git a/docs/REARCH_RC6_ASSETS.md b/docs/REARCH_RC6_ASSETS.mddeleted file mode 100644index 4844168a7..000000000--- a/docs/REARCH_RC6_ASSETS.md+++ /dev/null@@ -1,131 +0,0 @@-# Estella RC6:资产管线根治方案(Asset Pipeline Re-architecture)--> 目标读者:引擎维护者 / AI 协作代理。-> 本文是 `REARCHITECTURE.md` 的**续篇**,体例一致:描述目标架构与根治路径,而非现状。-> 现状审计见各小节"病灶"引用的 `file:line`。-> 与 RC1–RC5 的区别:RC1–RC5 根治的是**正确性根因**(多源真相、可绕过抽象);RC6 根治的是**能力与平台错配**——资产管线是按"桌面整包载入"假设建的,与微信小游戏"主/分包体积上限 + 远程 CDN + 受限显存 + 单核解码"的现实不匹配。--> 注:`REARCHITECTURE.md` 的"实现进度"段已滞后——RC5(渲染唯一路径 / GfxDevice 唯一入口 / u16→u32)实际已落地(见 `338caff2` single GL boundary + CI guard、PR #44–#47)。RC6 在 RC5 的 `GfxDevice` 唯一入口之上扩展,**纯加法**,不回退既有路径。-------## 0. 核心诊断:管线为"桌面整包"而建,与移动端三大约束错配--对资产路径的深度审计后,几乎所有"包体过大 / 显存吃紧 / 加载慢 / 无法热更"的症状都可归到**四个结构性缺口**,每个对应一处"为桌面假设、未为微信/移动端建立"的能力:--1. **纹理永远是未压缩 RGBA8**:上传路径硬编码 `gl.RGBA/UNSIGNED_BYTE`,`GfxDevice` 根本没有压缩纹理入口。一张 2048² 图集常驻 **16MB 显存**,移动端 GPU 内存上限分分钟打爆。-2. **身份不是内容寻址**:path / UUID / GUID 三套并存,但**没有内容哈希**——无法去重、无法做不可变 CDN 缓存、改一个文件不会自动产生新缓存键。-3. **资源只进不出**:引用计数存在,但**无预算、无 LRU、无驱逐**。长时运行的游戏显存单调增长。-4. **打包是静态意图,无运行时分包/流式**:有 `AddressableManifest` 和 `wechatPackInclude` 标志,但**没有运行时按需下载/卸载**——进不去微信主包体积,也下载不下来远程资源。--**根治原则**:把"显存上限"靠 **GPU 压缩纹理**打住;把"缓存与去重"靠**内容寻址**坐实;把"内存只增"靠**预算 + LRU**收口;把"包体积上限"靠**运行时分包/流式 + CDN**绕开。四者共享同一条新管线,互为前提。--止血式"删几张图、改改尺寸"不在本方案范围——只要管线还假设"未压缩、整包、永驻",同类问题会无限再生。-------## 缺口 1(keystone):纹理无 GPU 压缩 → 压缩纹理成为默认上传格式--### 病灶-- `GfxPixelFormat` 只有 `RGB8 / RGBA8 / DepthComponent24 / Depth24Stencil8`(`renderer/GfxEnums.hpp:76-81`)——**无任何压缩格式**。-- `GfxDevice` 只有 `texImage2D`(`renderer/GfxDevice.hpp:262`),**没有 `compressedTexImage2D`**。grep 全仓 `KTX/Basis/ASTC/ETC2/S3TC/compressedTexImage2D` 在引擎代码中**零命中**(命中项全是 glm/yoga/生成绑定的噪音)。-- Web 上传路径**硬编码** `gl.texImage2D(..., gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)`(`sdk/src/asset/loaders/TextureLoader.ts:161`),无格式选择。-- 后果:下载是 PNG/JPG(线上有压缩),但**解码后在显存里一律是未压缩 RGBA8**。移动端显存是硬约束,这是当前栈最痛的一处。--### 目标架构-1. **`GfxDevice` 加压缩纹理通道**(纯加法):新增 `compressedTexImage2D(textureId, w, h, GfxCompressedFormat, data, byteLen)`,以及一个**能力查询** `bool supportsCompressedFormat(GfxCompressedFormat)`(复用现有 `getString/getInt` 诊断入口的模式,`GfxDevice.hpp:325-328`)。-2. **`GfxPixelFormat`/新 `GfxCompressedFormat` 扩**:`ETC2_RGBA8`、`ASTC_4x4`、`S3TC_DXT5` 等。**基线 = ETC2/EAC**(WebGL2 规范核心保证,无需扩展——只要 WebGL2 可用就有;iOS 高性能模式仍需实测,与你们既有 WebGL2 依赖同一风险面),**升级 = ASTC**(查 `WEBGL_compressed_texture_astc`,iOS A8+ / 多数新 Android 可用)。-3. **导入期编码为 KTX2 容器**(UASTC 或 ETC1S supercompression),运行时用 **Basis Universal transcoder** 按设备能力转码到目标 GPU 格式。-4. **`TextureLoader` 压缩优先 + 优雅回退**:能力探测 → 有压缩走 `compressedTexImage2D`,无则回退现有 RGBA8 路径(`TextureLoader.ts:139-204` 保留为 fallback)。**老资产零改动仍能跑。**--> 这一步是 keystone:显存 4–8× 下降是其他三个缺口(预算/驱逐才有意义、分包才装得下、CDN 才划算)的前提。-------## 缺口 2:身份非内容寻址 → 内容哈希作为物理身份--### 病灶-- 三套身份并存且无哈希:`ResourcePool` 按路径缓存(`pathToId_`,`resource/ResourcePool.hpp:285`);`ResourceManager` 按 GUID 缓存(`guidToTexture_`,`resource/ResourceManager.cpp:319-332`);SDK 用 RFC4122 UUID(`@uuid:` 引用,`sdk/src/asset/AssetRegistry.ts:19-77`)。-- **无内容哈希**:同一张图在两个路径下 = 两份 GPU 资源(无去重);改文件不改 URL(CDN 缓存失效靠手动)。--### 目标架构-- **双身份分层**:`UUID` = 逻辑身份(场景/prefab 里引用,文件改名不破引用,沿用 `AssetRegistry`);**`contentHash`(xxh3 或 BLAKE3)= 物理身份**,导入期对编码后字节计算,产物按 `<hash>.ktx2` 命名。-- **manifest 串起来**:`AddressableManifest`(`sdk/src/asset/AddressableManifest.ts:24-27`)扩为 `UUID → contentHash → URL`。-- **运行时缓存键统一为 contentHash**:把 `pathToId_` / `guidToTexture_` 收敛到单一 `hash → 资源` 表 → 天然去重;**不可变缓存**(内容变 = 新 hash = 新 URL,CDN 可设永久缓存,无失效问题)。-------## 缺口 3:资源只进不出 → 显存预算 + LRU 驱逐--### 病灶-- 引用计数存在(`ResourcePool.hpp:88-233`:`refCount`、`addRef`、`release`),但 `refCount==0` **立即释放**,**无 LRU、无预算、无后台驱逐**——资产要么被持有、要么被销毁,没有"缓存层"。整张管线无任何内存上限概念。--### 目标架构-- **三态生命周期**:`持有(refCount>0)` → `可驱逐(refCount==0 但留在 LRU)` → `驱逐`。`release` 到 0 时**不立即销毁**,进 LRU 候选。-- **显存预算**:`ResourceManager` 持有一个字节预算(按设备显存分级设定);超预算时按 LRU 驱逐最久未用的可驱逐资源。-- **可重载**:因为有 `contentHash → URL` + 既有 `AsyncHandle`(`resource/AsyncHandle.hpp:67-151`),被驱逐的资源再次需要时可异步重载——驱逐是安全的。-------## 缺口 4:静态打包无运行时分包/流式 → 运行时 bundle 加载器 + 微信分包映射--### 病灶-- 有静态打包**意图**:`AddressableManifest` 的 `groups`/`bundleMode`(`AddressableManifest.ts:18-27`)、按资产类型的 `wechatPackInclude` 标志(`sdk/src/assetTypes.ts:20-40`)。-- 但**无运行时下载/卸载**:没有按 group 拉取分包、没有 CDN 重定向层、没有流式协议、没有动态分包切换(审计结论:AddressableManifest 仅声明,无运行时 loader 消费它)。-- Web 资产经 `HttpBackend` 逐个 fetch(`sdk/src/asset/Backend.ts:14-49`);字体靠构建期 `--embed-file` 塞进 wasm(`cmake/Emscripten.cmake:38`)——这两条都不是"分包/流式"。--### 目标架构-- **运行时 bundle 加载器**:把 `AddressableManifest` 接成 loader——按 group/bundle **按需下载、缓存、卸载**,与缺口 3 的 LRU 联动。-- **微信分包映射**(见下节专述):`bundleMode` + `wechatPackInclude` 驱动构建期生成微信 `subpackages` 配置;运行时用 `wx.loadSubpackage` 按需加载;大资产走远程 CDN + 本地文件系统缓存。-------## 微信小游戏分包映射(平台落地)--| 层级 | 放什么 | 机制 |-|---|---|---|-| **主包** | 引擎 wasm(+ Basis transcoder side module)、启动场景必需资产 | `wechatPackInclude:true` 的 materials/prefabs/tilemaps(`assetTypes.ts:26-40`) |-| **分包** | 按 `AddressableManifest` 的 group 切分的关卡/模块资产 | 构建期生成 `subpackages` 字段;运行时 `wx.loadSubpackage({name})` 按需 |-| **远程资源(CDN)** | 大纹理图集、音频——`wechatPackInclude:false` 的类型 | CDN 下载 + `wx.getFileSystemManager().saveFile` 本地缓存;**内容寻址 `<hash>.ktx2` 命名 → 缓存可设永久**(缺口 2 的直接红利) |--- **体积账**:主包靠"压缩纹理(缺口 1)+ 只装必需资产"压到上限内;其余靠分包 + 远程,正面解决主包/总包体积约束。-- **Basis transcoder 落位**:编成**独立 side module**(你们已有 side module 机制,physics/spine 都是——`CMakeLists.txt:470-589`),按需加载,不撑主包。-------## 执行顺序(全程保持构建常绿,每批可独立验证)--1. **Batch A — `GfxDevice` 压缩纹理入口 + 能力查询 — ✅ 已落地**(分支 `rearch/rc6a-compressed-tex`,`df6c7366`):`GfxCompressedFormat`(ETC2/EAC core 基线 + ASTC/S3TC 扩展层)、`compressedTexImage2D`(扩展单一 GPU 通道,非绕过)、`supportsCompressedFormat`(ETC2 报 core,ASTC/S3TC 经 `glGetStringi` GLES3 正确探测扩展);`GLDevice` 实现 `glCompressedTexImage2D` + 压缩格式 GL token fallback 定义。`MockGfxDevice` 记录压缩上传 + 可调 `compressedSupported` 试 fallback 分支;`test_compressed_format` 断言"支持走压缩、不支持回退 RGBA8"的决策(Batch C 的 TextureLoader 将照此)。**纯加法,无压缩资产时零行为变化。** 本机 MSVC 验证通过 + 既有 harness 仍绿;Emscripten 全量构建经 CI 守门。-2. **Batch B — 导入期 KTX2 编码 + 内容哈希命名 + manifest 扩展 — 🟡 仓侧已落地**(`8ac4f78d`):消费端就绪——`.ktx2` 注册为 binary texture 资产(`assetTypes`,`image/ktx2`,`wechatPackInclude:false`);`AddressableManifestAsset` 加 `contentHash`(xxh3 物理身份 → 去重 + 不可变 `<hash>.<ext>` 永久缓存 URL)与 `compressedFormats`。**离线编码器(PNG→KTX2 + 算 hash)在编辑器资产管线侧(非本仓)**;backend 路径→hash 重写依赖 catalog + 真实 hash 资产,留后。-3. **Batch C — 运行时 Basis transcoder + `TextureLoader` 压缩优先/回退 — ✅ 已落地**(`9c1e549c`/`f72f280c`/`109a504f`/`22b2a151`):- - **C1 架构**:`sdk/src/asset/compressed.ts` —— KTX2 检测、WebGL 能力探测(ASTC>ETC2>S3TC,`getExtension` 同时探测+启用)、`BasisTranscoder` 注入接缝、**JS-direct `compressedTexImage2D` 上传 + RGBA8 回退**(镜像既有 PNG 路径,扩展名加 `.ktx2`)、`loadCompressedTexture` 编排。10 测试。- - **C3 transcoder 模块**:`basis_universal` vendor 成 submodule(pin `1aab02b`);`BasisModuleEntry.cpp` —— `ktx2_transcoder` 的 C API(open/size/transcode/close,稳定整型格式契约);CMake `basis_module`(`ES_ENABLE_BASIS`,仅编 `transcoder/basisu_transcoder.cpp`,`KTX2=1`/`ZSTD=0`)+ Emscripten 模块 flags(MODULARIZE,`ESBasisModule`,仿 spine)+ build.config/cli。**CI 确认编译+链接通过**(`✓ WASM basis: Build complete`;`-fno-exceptions/-rtti` 兼容)。- - **C3 运行时**:`basisTranscoder.ts` —— `BasisTranscoderImpl` 堆内 marshalling(仿 physics)实现 C1 接缝;`createBasisTranscoder(factory)` 供 app 注入 `TextureLoader.setTranscoder`(沿用 physics/spine 的"app 提供 factory"约定)。7 测试。- - **待接线**:app 级 `textureLoader.setTranscoder(await createBasisTranscoder(ESBasisModule))` + 提供 `ESBasisModule` factory;`basis.wasm` 的 wasm-opt 优化(当前 CI 报 wasm-opt 跳过,模块仍可用,属体积优化跟进)。-4. **Batch D — 内容寻址缓存键**:`pathToId_`/`guidToTexture_` 收敛到 `contentHash`;去重生效。-5. **Batch E — LRU + 显存预算驱逐**:三态生命周期 + 重载。-6. **Batch F — 运行时 bundle/分包加载器 + 微信 `wx.loadSubpackage` / CDN 缓存映射**。--> 依赖序:A 是 keystone(其余都建立在压缩格式之上);B→C→D 是同一条编码/身份链;E 依赖 D(缓存键统一才能安全驱逐重载);F 依赖 D+E(按内容寻址下载、按预算卸载)。-------## 验证机制(与 RC1 keystone 同精神:机制即根治成立的证明)--- **压缩纹理**:离线编码产物字节级往返测试(解码 KTX2 → 与源像素比对,PSNR 阈值守门);`GfxDevice` 能力探测用 **MockGfxDevice** harness 单测(沿用 RC5 的验证套路)。-- **内容哈希**:幂等性测试(同输入 → 同 hash);去重测试(两路径同内容 → 一份 GPU 资源、一个缓存条目)。-- **预算/驱逐**:单测模拟超预算 → 驱逐最久未用 → 再次请求触发重载且结果正确;refCount>0 的资源**永不**被驱逐。-- **分包**:`AddressableManifest` → 微信 `subpackages` 配置的快照测试;构建期分包划分与 `wechatPackInclude` 标志一致性断言。-- **回退路径**:无压缩能力的模拟设备走 RGBA8,与 Batch A 之前行为逐像素一致。-------## 需要拍板的架构岔路--| 岔路 | 选项 A | 选项 B(推荐) |-|---|---|---|-| **KTX2 supercompression** | 全量 UASTC(高质量、体积大) | **按 label 选**:sprite/UI 用 ETC1S(体积优先),法线/高频纹理用 UASTC(质量优先) |-| **Basis transcoder 位置** | 编进主模块(简单,撑主包) | **独立 side module**(按需加载,主包瘦,沿用既有 side module 机制) |-| **内容哈希算法** | BLAKE3(强抗碰撞,略重) | **xxh3**(构建期算,速度快,资产去重/缓存键场景足够) |-| **驱逐策略** | 维持纯 refCount 立即释放 | **refCount + LRU + 预算**三态(refCount==0 才进 LRU 候选) |-| **远程资源缓存** | 每次启动重下 | **`wx.getFileSystemManager` 本地缓存 + 内容寻址永久缓存键** |diff --git a/docs/REARCH_RENDER.md b/docs/REARCH_RENDER.mddeleted file mode 100644index 5fd6044ff..000000000--- a/docs/REARCH_RENDER.md+++ /dev/null@@ -1,193 +0,0 @@-# REARCH_RENDER:渲染后端现代化(RC7-3 keystone 落地)--> 本文是 `REARCH_FRONTIER.md §RC7` 的展开落地文档,聚焦 **keystone(抬升 `GfxDevice` 抽象)** 及其降险前置(提交路径统一)。-> 目标:把渲染管线从"WebGL2 命令式、GL 概念漏满签名、提交路径碎片化"收敛为 **后端无关的 PipelineState / BindGroup / UBO / 类型化句柄模型**,使 WebGPU 成为纯加法层,且在纯 WebGL2 基线下先落地即有收益。-------## 0. 横切约束(决定排序,不可绕过)--主战场是 **微信小游戏 + playable**(`build-tools/build.config.js`),WebGL2 是一等公民。由此:--- **WebGPU 不普及 → 必须 WebGL2 回退共存**,不能 all-in;WebGPU 只能是 keystone 之后的纯加法后端。-- **keystone 选取原则**:必须在 **纯 WebGL2 / 单线程基线下先有收益**(UBO 减少 uniform 调用、PSO 消灭每帧字符串查表),而不是为了未来后端才付的成本。-- 凡 web-only 前沿特性(WebGPU、threads、SIMD)一律设计为 **web 优先 + 微信回退**,做加法层而非主线依赖。-------## 1. 现状评估:已最优的部分(**不要动**)--| 子系统 | 状态 | 证据 |-|---|---|---|-| 排序 / 合批 | ✅ 扎实 | `DrawCommand::buildSortKey` 把 stage/layer/shader/blend/texture/depth 打成 u64(`DrawCommand.hpp:45-69`);`DrawList::finalize` 把相邻连续 index 合并为单次大 `drawElements`(`DrawList.cpp:18-58`) |-| 瞬时缓冲 | ✅ 合理 | `TransientBufferPool` 按 `LayoutId` 分 VBO/EBO/VAO,规避 `baseVertex` 截断(设计注释 `TransientBufferPool.hpp:20-28`) |-| 资源生命周期 | ✅ 现代 | Buffer/Texture/Shader/Framebuffer 均 RAII(移动语义 + `owns_` 防双删,`Texture.hpp:124-274`) |-| 状态去冗余 | ✅ 有 | `StateTracker` cache-and-compare,消除冗余 GL 状态切换(`StateTracker.cpp`) |-| 设备抽象边界 | ✅ 清晰 | `GfxDevice` 已是抽象接口;**collect 阶段经 `RenderTypePlugin` 已后端无关**——GL 泄漏集中在 `DrawList::execute` 与资源类,边界干净 |--> 结论:这不是重写,是**收敛**。collect 侧不动,主重写点只有 `DrawList::execute` + 资源类。-------## 2. 病灶(真正缺口,按"是否阻塞后端"分层)--### A. `GfxDevice` 抽象层级过低 —— **阻塞 WebGPU 的根因**-接口自述"一个方法 = 一次 glXxx"(`GfxDevice.hpp:37`)。WebGL 概念漏满签名,这些在 WebGPU **无对应物**:-- VAO 系列:`createVertexArray/bindVertexArray/enableVertexAttrib/vertexAttribPointer`(`GfxDevice.hpp:219-236`)-- 散装 uniform:`getUniformLocation` + `setUniform1i/1f/2f/3f/4f/Mat3/Mat4`(`GfxDevice.hpp:163-188`)-- immediate-bind:`bindVertexBuffer/bindIndexBuffer/bindTexture`(`GfxDevice.hpp:134/204-207`)-- GLSL 源码直传:`createProgram(vertexSrc, fragmentSrc, ...)`(`GfxDevice.hpp:153`)-- 裸 `u32` 资源句柄(全接口)、WebGL-only:`pixelStorei/setUnpackFlipY`(`GfxDevice.hpp:290/298`)--因此现状下**无法新增 `WebGPUDevice : public GfxDevice`**——只有 `GLDevice` 一个实现(`GLDevice.hpp:29`)。--### B. 热路径绕开 uniform 缓存-`DrawList::execute` 每次切 shader 直接 `device.getUniformLocation(cmd.shader_id, "u_projection")` 字符串查表(`DrawList.cpp:71`),**绕开了已存在的 `Shader::uniformCache_`**(`Shader.hpp:224`,`Shader.cpp:179-189` 确实在用,但热路径不走 Shader 类)。对应审计 C5。`ImmediateDraw.cpp:111` 同病。--### C. UBO 完全缺失 —— 散装 uniform-`GfxBufferTarget` 只有 `{Vertex, Index}`(`GfxEnums.hpp`),全仓零 UBO GL 调用。每帧每 shader 切换都重设 `u_projection`,全靠散装 `setUniformMat4`。--### D. 提交路径碎片化("统一"那一面)-- 5 个 batch 插件(Sprite/UIElement/Text/Particle/Tilemap)各自复制 `emitQuad`/`rotatePoint`/`buildDrawCommand`(约 200 行重复 + 3 处不一致)。-- **ParticlePlugin index winding `{0,1,2,0,2,3}` 与其它 `{0,1,2,2,3,0}` 不一致**(`ParticlePlugin.cpp:14`)。-- Spine 走 **TS pre-flush 回调**(`SpinePlugin.ts`)而非插件 `collect()`——GPU 侧已归一(同 `LayoutId::Batch` + `DrawList`),但 CPU 提交侧是独立路径。-- ImmediateDraw 自持一套 `TransientBufferPool` + `batch_shader_id_`,与 RenderFrame 平行。-- UI/Text/Tilemap blend mode 硬编码 `Normal`,Sprite/Particle 从组件取——不一致。--### E. material cache 死路径-`getMaterialDataWithUniforms` **零调用者**,`material_cache` 仅此处写(`WebSDKEntry.cpp:107-177`);TS 侧 `invalidateMaterialCache/clearMaterialCache` 沦为对永空 map 的 no-op(审计 B2-4 已确认)。**可删**,且当前没有真正的"材质 = 管线 + 资源绑定"模型。--### F. 死基建(半成品已在仓,留给正交快赢)-- `drawElementsInstanced`(`GfxDevice.hpp:249`)、`vertexAttribDivisor`(`:236`)实现于 GLDevice 但**零调用者**。-- `PARTICLE_INSTANCE_VERTEX/FRAGMENT` 实例化 shader 写好却**零引用**(`Shader.hpp:310-358`);粒子实走 CPU 逐粒子展开(`ParticlePlugin.cpp:82-149`)。-- `DrawCommand` 支持 8 纹理槽(`DrawCommand.hpp:14`),提交侧只填 `texture_count=1`——不同纹理立即断批。-------## 3. 目标架构--### 3.1 核心模型(后端无关)--```-PipelineState ── 不可变对象:program + 顶点布局(VAO 配方) + blend/depth/stencil/cull-BindGroup ── 资源集合:纹理槽[ ] + UBO 绑定[ ]-FrameUBO ── per-frame 常量(首发只装 u_projection: mat4)-TypedHandle<T> ── PipelineHandle / BufferHandle / TextureHandle / BindGroupHandle,取代裸 u32-```--`GfxDevice` 新接口形态(草图,命令编码而非 1:1 glXxx):--```cpp-// 创建期(一次性)-PipelineHandle createPipeline(const PipelineDesc&); // shader+layout+blend/depth/stencil 一次绑定-BufferHandle createBuffer(BufferKind, ...); // BufferKind 加 Uniform-BindGroupHandle createBindGroup(const BindGroupDesc&); // 纹理+UBO 资源集--// 提交期(DrawList::execute 重写为以下三步)-void setPipeline(PipelineHandle); // 取代 useProgram + 顶点格式 + blend/depth/stencil 散装设置-void setBindGroup(u32 slot, BindGroupHandle); // 取代散装 bindTexture + setUniform*-void draw(const DrawParams&); // drawElements / drawElementsInstanced 统一入口-```--WebGL2 后端把 PipelineState 映射为 VAO 配方 + 缓存的 program/blend 状态;UBO 映射为 `glBindBufferBase`。WebGPU 后端则天然 1:1。--### 3.2 关键洞察:batch 路径的 FrameUBO 极小--batch 路径(Sprite/Text/Particle/Tilemap/Spine/UIElement)**已把 transform 烘焙进顶点**,每帧只需 `u_projection`(mat4)+ 每批 `u_texture`。所以:--- **FrameUBO 首发只一个 `mat4 u_projection`**,全帧 bind 一次,**彻底消灭** `DrawList::execute` 每次切 shader 的 `getUniformLocation + setUniformMat4`(病灶 B/C 同时解决)。-- batch / shape shader 改用 `layout(std140, binding=0) uniform Frame { mat4 u_projection; };`(GLES3 核心,零扩展)。-- 后处理的 `u_resolution`/`u_sceneTexture` 后续并入或单列,不影响首发。--### 3.3 边界不变 —— 纯 C++ 重构--TS/WASM 边界对 uniform 布局**不透明**:`renderer_begin(viewProjPtr, target)` 仍传矩阵指针,C++ 内部读 HEAP → 填 FrameUBO。`postprocess_setUniformFloat/Vec4(passName, name, ...)` 仍字符串派发,C++ 内部映射。**无任何导出函数签名变更,TS 侧零改动**(material cache 死函数可顺手删)。--### 3.4 WebGPU 作为加法层(keystone 之后)--抽象抬升后新增 `WebGPUDevice : public GfxDevice` + GLSL→WGSL(Tint/naga,或 `.esshader` 作者语言迁 WGSL);微信保留 WebGL2 回退(双后端架构天然容纳)。解锁 compute shader(粒子/裁剪 GPU 化)。**不插队**。-------## 4. 分阶段落地--> 原则:纯加法优先;旧路径保留到迁移完成;每阶段可独立验证、独立提交、独立回滚。--### P0 — 提交路径统一(降险前置,不依赖 keystone)-- 抽 `BatchPlugin` 基类,收编 5 插件的 `emitQuad`/`rotatePoint`/`buildDrawCommand`/winding 常量。-- Spine 提交收进同一 helper(CPU 侧归一;GPU 侧本已统一)。-- 修 ParticlePlugin winding;统一 blend mode 取值口径。-- 修热路径 uniform-cache 旁路(`DrawList.cpp:71` / `ImmediateDraw.cpp:111` 改走缓存 location)。-- **价值**:keystone 重写 `execute` 时需适配的提交面从 6 条降到 1 条。-- **验证**:`tests/renderer/*` + 像素快照不变;draw call 数不变。--### P1 — GfxDevice 加 UBO 能力 + FrameUBO(纯加法,已据证据修正)-- `GfxBufferTarget` 加 `Uniform`;GfxDevice 加 `createBuffer(Uniform)` + `bindUniformBufferBase(point, buffer)` + `getUniformBlockIndex(program, name)` + `uniformBlockBinding(program, idx, point)`(GLDevice 实现 `glBindBufferBase`/`glGetUniformBlockIndex`/`glUniformBlockBinding`)。WebGL2/GLSL ES 3.00 **无 in-shader `binding=` 限定符**,绑定点必须 host 侧 `glUniformBlockBinding` 设。-- `FrameConstants`(std140)首发只 `mat4 u_projection`(64B,单 mat4 无对齐坑);**一个持久 UBO**,init 创建、`RenderFrame::begin` 每帧 `bufferSubData` 更新一次、绑定点 0 全帧 bind 一次(不走 TransientBufferPool——那是 per-draw 几何流)。-- 活的 shader 只有 **batch + shape** 两个(其余 6 个 .esshader + 内联 EXT_MESH/PARTICLE_INSTANCE 全死,证据见审计/探查)→ 迁移面极小。**注意:batch.esshader 是 GLSL ES 1.00**(`attribute`/`varying`/`texture2D`/`gl_FragColor`),UBO 需 ES 3.00 → batch 必须先升 `#version 300 es`(已有 ES3.00 参照:`Shader.hpp` 的 `BATCH_VERTEX/FRAGMENT` 内联);shape 已是 ES 3.00。这步并入 RC7-6 的 shader 版本统一。-- **旧散装 `u_projection` 路径保留**给 custom-geometry/material(`GeometryBindings::draw_mesh` 用散装 `u_projection`+`u_model` 在用户 shader 上)——P1 纯加法、不破这些路径。-- **价值(修正)**:纯 WebGL2 的 per-frame uniform 节省 **可忽略**(实测路径每帧仅 1–3 次 `setUniformMat4`,按 shader 切换 gate,非 per-draw——原"显著下降"的说法不成立)。P1 的真实价值是 **(a) 最低风险地落地 UBO/bind 机制**(std140 + host 侧 block-binding + ES 版本升级,孤立可逐像素验证,避免与 P2 的 execute 重写纠缠)、**(b) 前向兼容 P2**(UBO 即 BindGroup 的首个非纹理资源,P1 写的 UBO API 被 P2 复用、非废弃)、**(c) WebGPU 前置形态**(WebGPU 无散装 uniform,全是 UBO/bind group)。-- **验证**:headless `verify:render` 四场景逐像素不变(同 P0);FrameCapture 对比 draw call 数不变。--### P2 — PipelineState keystone 主体(DONE,实况记录)-分两 checkpoint 落地:-- **P2a(纯加法)**:`PipelineState.hpp`(`PipelineDesc` = program+vertexLayout+blend+depth+`GfxStencilMode`+cull → 缓存为不可变 `PipelineHandle`);`GfxDevice` 增 `createPipeline`/`setPipeline`/`setStencilReference`/`invalidatePipelineCache`;GLDevice 用 desc 表 + **句柄比较去冗余**(同 pipeline 跳过整组状态应用)实现,stencil 序列镜像旧 StateTracker。`LayoutId` 移到 `GfxEnums.hpp`(叶子头)破除 include 环。-- **P2b(状态归属收敛)**:**重写 `DrawList::execute`** — 每个合并命令解析出 PipelineDesc → `setPipeline` + 动态 scissor/stencilRef/纹理 + draw(一条路径,**删掉 `customDraw` 特例**,shape 变普通 pipeline:program=shape、layout=Shape)。**退役 `StateTracker`**(删 `.hpp/.cpp` + 单测):GPU 状态归属收归 GLDevice,`pipeline-skip` 替代了它对昂贵 program/blend/stencil 的去冗余,per-draw 动态状态直接应用(sort+merge 已粗粒度分组,几无冗余)。`ImmediateDraw` 迁到单一 pipeline + `setPipeline`;`RenderFrame`/`EstellaContext` 去掉 StateTracker 注入;`invalidatePipelineCache` 在 flush/replay/imm-begin 阶段首调用(防外部直接改 program 后 stale)。删了 RenderFrame 无调用者的 stencil 透传 API。-- **决策**:不采用"双缓存 + 每阶段 resync"的折中(那是补丁)——单一状态归属是最佳架构。`DrawCommand`/`buildSortKey`/`canMergeWith` **保持不变**(现有 key 已按 shader+blend+state+texture 分组 = pipeline 一致的批;execute 在 draw 时解析 handle,用 1-entry memo 跳过排序后连续相同 desc 的查找)。`depthWrite` 保持 on(test off),匹配旧 2D 状态以保像素一致。-- **价值**:单一后端无关命令编码层,`WebGPUDevice` 可作为 `GfxDevice` 子类插入;状态归属单一、无双缓存。-- **验证**:emscripten web 构建链接通过;headless `verify:render` 四场景(含 ui-layout 的 stencil 遮罩)像素与 P0/P1 基线**逐项完全一致**;渲染器单测编译通过。--### P3 — 加法层(独立排期,依赖 P2)-- `WebGPUDevice` 后端 + GLSL→WGSL;微信保 WebGL2 双后端(RC7-4)。-- 后处理 → 小型 render graph + MRT(声明式 pass 图 + transient FBO 复用,`Framebuffer` 加多 color attachment)(RC7-5)。-- shader 变体系统 + 单一来源:扩 `ShaderParser` 支持 feature-keyword permutation;内联 GLSL 收编进 `.esshader`;统一升 `#version 300 es`,删死 shader(RC7-6 / 审计 B1)。--### 正交快赢(任意阶段并行,**不依赖 keystone**,微信直接受益)-- **RC7-1 粒子实例化**:接已写好的 `PARTICLE_INSTANCE` shader + `drawElementsInstanced`/`vertexAttribDivisor`;`DrawCommand` 加 `instance_count`;带宽降 ~75%(病灶 F)。-- **RC7-2 多纹理批合并**:`BatchVertex` 加 texIndex 通道;batch fragment 改 `sampler2DArray`(GLES3 核心);`DrawList::finalize` 合并放宽到多槽。-------## 5. Blast radius(精确清单)--| 动 | 不动 |-|---|---|-| `renderer/GfxDevice.hpp`(加 UBO/PSO/BindGroup 接口) | `renderer/RenderFrame.cpp` collect 流程 |-| `renderer/GLDevice.{hpp,cpp}`(实现新接口) | `renderer/DrawCommand.hpp` 排序键 / 合并逻辑 |-| `renderer/DrawList.cpp:60-131`(execute 重写) | `renderer/TransientBufferPool.*`(按 LayoutId 分流) |-| `renderer/Shader.{hpp,cpp}`(uniform→UBO/反射) | `renderer/StateTracker.*` 去冗余(被 PSO 内化但保留) |-| `renderer/ImmediateDraw.cpp`(迁 PSO/UBO) | `renderer/RenderTypePlugin.hpp` collect 接口 |-| `renderer/PostProcessPipeline.cpp`(迁 PSO/UBO) | `bindings/*` 导出签名(边界不变) |-| `renderer/plugins/*`(P0 收编进 BatchPlugin) | `sdk/src/*` TS 渲染层(边界不变) |-| `renderer/GfxEnums.hpp`(加 Uniform target) | |-| 删 `bindings/MaterialCache.hpp` 死路径 | |-------## 6. 验证方案--- **单元**:`tests/renderer/*`(`MockGfxDevice.hpp` 已有,可断言命令序列)。-- **像素一致性**:`FrameCapture` / `renderer_captureNextFrame` 快照逐阶段对比,保证零回归。-- **性能**:FrameCapture 已记录 draw call(`DrawList.cpp:111-126`);P1 后对比 uniform 调用数,P2 后对比 draw call 合并率。-- **编辑器端到端**:`verify:render:spine` 等脚本 + 编辑器 viewport 实测。-------## 7. 风险与回滚--- 每阶段**纯加法优先**:新路径与旧路径并存,验证通过后才删旧路径。-- P0/P1/P2 **可独立提交回滚**;P3 与正交快赢互不阻塞。-- 唯一较大重写是 `DrawList::execute`(约 70 行),blast radius 受控(collect 侧不动)。-------## 8. 进度--| 阶段 | 状态 |-|---|---|-| 方案文档 | ✅ 本文 |-| P0 提交路径统一 | ✅ DONE(commit e23b1ff5 / 675777a3) |-| P1 FrameConstants UBO + batch ES3.00 | ✅ DONE(commit d80619e7) |-| P2 PipelineState keystone(P2a 抽象 + P2b 状态收敛) | ✅ DONE(P2a commit 1b1bc9c3;P2b 待提交) |-| P3 WebGPU / render graph / shader 变体 | ⬜ OPEN(加法层,依赖 P2) |-| 正交快赢 RC7-1/7-2 | ⬜ OPEN(可并行,不依赖 keystone) |diff --git a/docs/REARCH_SERIALIZATION.md b/docs/REARCH_SERIALIZATION.mddeleted file mode 100644index 12a51ccc9..000000000--- a/docs/REARCH_SERIALIZATION.md+++ /dev/null@@ -1,117 +0,0 @@-# Estella 无损序列化 / 数据模型(Lossless Serialization)--> 目标读者:引擎维护者 / 编辑器作者 / AI 协作代理。-> 体例同 `REARCHITECTURE.md` / `REARCH_ENGINE_INSTANCING.md`:描述目标架构与根治路径,而非现状。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 两路并行只读审计 + 交叉印证)。-> **立项缘由**:这是 `RC12_EDITOR_SEAM.md` 最优编辑器架构的**第二条腿**(第一条是 `REARCH_ENGINE_INSTANCING.md`)。当前"无损保存"做不到——编辑器用 `lossy` 标志**拒绝覆盖保存**(`desktop/src/project/ProjectStore.ts:278`),这是症状;根因是序列化结构性有损。它也是 play==ship、prefab、play 快照的共同地基。-------## 0. 核心诊断:live world 是 SceneData 的有损投影--往返链:`load (JSON→world) → 编辑 world → save (world→JSON)`。根因是 **world 装不下 SceneData 的全部信息**,于是"从 world 读回"永远吐不全:--1. **load 丢信息**:未知组件直接丢弃;已知组件的未知字段被过滤;`visible:false` 实体根本不 spawn。-2. **world 降精度**:builtin 数值字段以 **f32** 存(指针布局),double 写入即截断。-3. **save 只能吐 world 里剩下的**:且 asset 字段输出**裸 handle 数字**而非 `@uuid:`(`serializeScene` 无反向映射)。-4. **编辑器症状**:`lossy` 标志 + 拒绝覆盖保存;且连 Save-As 也救不了未知组件——它们在 load 投影时就从 world 消失。--> **命门**:只要"保存从 world 读回",无损就需要无穷多 passthrough/反向补丁去对抗信息丢失,且**未知组件里的 entity 引用无法被 SDK 重映射**(SDK 不认识其 entityFields)。**两路审计独立同结论:JSON-first 让真相从不进入 world,无损是免费的、结构性的**——这正是"结构强制 > 约定"在序列化上的落地。-------## 1. 病灶(file:line)--### S1:未知组件被丢弃,且 world 之后再也拿不回-- load:`loadComponent` 里 `getComponent(type)` 未注册 → `warn + return`,组件**完全丢弃**(`sdk/src/scene.ts:396-400`)。-- serialize:world 根本不持有未知组件;`getComponentTypes` 只枚举已注册(`world.ts:562-590`),`getComponent` 再过滤一次(`scene.ts:485-486`)。-- 编辑器:`unknownComponentTypes(raw)` 在 **原始 JSON** 上检测并设 `lossy`(`ProjectStore.ts:44,166,177`),但检测完 `resetWorldTo` 即丢(`:176`);`save()` 用 lossy 拒绝覆盖(`:278`),Save-As 无守卫(`:289`)却同样丢——**lossy 标志只能阻止保存,救不回数据**。--### S2:已知组件的未知字段被过滤-- builtin insert:`if (!(k in defaults)) continue`(`sdk/src/ecs/BuiltinBridge.ts:524-526`)。-- builtin set:`world.set` 同样删未知键(`sdk/src/world.ts:356-361`)。-- script:`component.create` flat 分支 `{...defaults, ...data}` **意外保留**顶层未知 scalar,但嵌套/keyInfo 分支不保留(`sdk/src/component.ts:101-121`)——**不一致**。--### S3:builtin 数值 f32 截断-- 指针快路 `readPtrField`/`fillPtrField` 读写 `f32[idx]`(`BuiltinBridge.ts:105,142,545,565`);double 写入被截断。script 组件全 JS 对象、double 保真。往返多次收敛(首次截断后不再漂移),但与原始 double 源值有一次性偏差。--### S4:`visible:false` 实体 load→save 后永久消失-- load:`visible===false` 整 entity **不 spawn**(`scene.ts:295,303`)→ world 里不存在。-- serialize:`serializeScene` **从不输出 `visible` 字段**(`scene.ts:499-512`)→ 所有保存的 entity 默认 visible=true。--### S5:asset 引用往返 lossy,且靠编辑器私有补丁-- 盘上格式 `@uuid:`(`sdk/src/asset/AssetRegistry.ts:19`)。load 把 `@uuid:`→ 运行时 handle **原地改写** `comp.data[field]`(`sdk/src/asset/Assets.ts:478,487,504,509`),**不留反向映射**。-- `serializeScene` 输出**裸 handle 数字**(`scene.ts:487`);SDK **无 handle→uuid 反向**(全仓 grep 确认)。-- 还原靠编辑器私有 `restoreAssetRefs` + `handleToUuid` map(`ProjectStore.ts:241-255,224`),且**只覆盖 texture**——material/font/audio 即便是 handle 也写出裸数字(无意义的运行时值)。`枚举`层 `getComponentAssetFields` 覆盖全类型(`scene.ts:101`),但 map 只被 texture 填充。--### S6:textureMetadata(九宫格 sliceBorder)不输出-- load 应用到 ResourceManager(`scene.ts:380-390`),serialize 输出对象**没有 textureMetadata 字段**(`scene.ts:508-512`)。--### S7:编辑器真相 = live world(确认链)-- 编辑写 world:`SceneCommands` 全走 `mutableWorld()` + `world.set/insert/spawn/despawn`(`SceneCommands.ts:86,168,207,225,263`),无 JSON 写。-- 保存从 world 读回:`serializeCurrent` → `serializeScene(world)`(`ProjectStore.ts:234,237`)。-- load 单向投影:`loadCurrentScene` → `resetWorldTo(world,data)`(`:176`),原始 JSON 投影后丢弃。-- inspector 也读 world(`SceneQuery.ts:33,77,89`);`InspectorFieldType` 无 asset 类型(`types.ts`)——asset 字段当前只读穿透。--### 影响面(serializeScene/resetWorldTo 消费方)-- `serializeScene`:EngineHost play 快照(`EngineHost.ts:151`,纯内存往返、最隐蔽地丢东西)、编辑器保存(`ProjectStore.ts:237`)、SDK re-export(`core-content.ts:74`)。-- `resetWorldTo`:play Stop 恢复(`EngineHost.ts:154`)、编辑器 load(`ProjectStore.ts:176`)。-- prefab 实例化复用 scene load 下游(`prefab.ts:101`)→ **同病**;但 prefab 已有 `PrefabEntityData.metadata` 无损通道(`prefab/types.ts:38`)可作范式。-------## 2. 目标架构:JSON-first 数据模型(编辑器真相 = SceneData,world = 渲染预览)--1. **SceneData JSON 是编辑器唯一真相**。load 后**保留**这份数据模型(不再投影即弃)。未知组件、未知字段、material/font/audio 的 `@uuid:`、任意扩展字段——全部原样留在数据模型里,**从不经过 world**,故从不丢失。-2. **world 降级为只读渲染预览**:从数据模型**投影**而来;编辑不直接改 world 当真相。-3. **编辑经命令改数据模型**(承接 E2 的命令边界):`SceneCommands` 的每个写操作改的是数据模型,再**增量同步**到 world 预览(见岔路)。inspector / `SceneQuery` 读数据模型(更简单——直接读 data,不用 `world.get`)。-4. **保存 = 序列化数据模型**(`JSON.stringify` 级别):**无损是免费的**。`lossy` 标志、passthrough、`restoreAssetRefs` 私补**全部消失**。-5. **play 快照取数据模型**(而非 `serializeScene(world)`):play/stop 无损 + 对齐 play==ship。-6. **稳定的 editor entity id**:数据模型自持稳定 id(不依赖 world spawn 顺序);投影时建 `jsonId → 预览 runtime entity` 映射(复用 `remapEntityFields` 的 id→id 机制,`scene.ts:131`,方向反转)。-7. **引擎侧(次要 / 防御)**:把 handle→`@uuid:` 反向映射下沉 SDK(`Assets` 在 `resolveSceneAssetPaths` 处已同时握有 ref+handle,只是写完就扔——`Assets.ts:487`),让任何 world→JSON 导出也可移植;并可选地给引擎加未知组件 passthrough 作非编辑器消费者的防御纵深。JSON-first 下编辑器**不依赖**这些,但它们让 `serializeScene` 本身不再有损。-------## 3. 需要拍板的岔路--| 岔路 | 选项 | 推荐 |-|---|---|---|-| **真相模型** | JSON-first(真相=JSON,world=预览) / world-round-trip + passthrough(真相=world,未知物塞 sidecar) | **JSON-first**:无损 by construction;passthrough 路是与信息丢失打的无尽补丁战(sidecar↔entity 对位脆、未知组件的 entity 引用无法重映射、asset 反向仍要补),且 lossy 是约定非结构 |-| **JSON→world 预览同步** | (a) 单一真相 + 增量投影(差分 patch world) / (b) 双写(命令同时改 JSON + world) | **(a) 增量投影**为目标(单真相、无双态分歧风险);**(b) 双写可作过渡**(复用 E2 命令、落地快),但有 JSON/world 分歧风险,需收敛到 (a) |-| **asset 反向映射** | 下沉 SDK(serializeScene 直出 @uuid:) / 维持编辑器私补 | **下沉 SDK**:`Assets` load 时建 `handle→ref` 反向 map,serialize 经注入回调换 ref;删 `restoreAssetRefs`。注意 handle 复用需在 release 处清 map |-| **builtin f32 精度** | 接受 + 文档化(编辑器按 f32 显示) / 关键字段改 double | **接受 + 文档化**:JSON-first 下数据模型存 double 原值,world 只是 f32 预览;保存写数据模型的 double,故**保存值无 f32 损失**(只有预览是 f32) —— 这是 JSON-first 顺带白赚的精度修复 |-| **与 E2 的关系** | —— | E2 的"单一写门 + 自动 undo"命令边界**整体保留**;JSON-first 只是把命令的 `apply` 目标从 world 换成数据模型(+预览投影)。E2 不白做 |--### 一处要认的代价-JSON-first 是**编辑器核心的较大改造**:`SceneCommands`(~13 个写方法 + undo 闭包)改道到数据模型、`SceneQuery`/inspector 改读数据模型、新增"JSON→world 增量投影"层、稳定 id 分配器。但每一处都更简单(纯数据操作),且换来**无损这一结构性属性 + play==ship + 精度修复**,是一次性可控工程量,而非长期补丁债。-------## 4. 迁移序(可拆、每步可验证)--- **L0(引擎侧,独立可先做,低风险)**:asset 反向映射下沉 SDK(`Assets` 建 `handle→ref`,`serializeScene` 加 `refResolver` 注入)。即便不上 JSON-first,也立刻让 `serializeScene` 不再丢 material/font 的 uuid;编辑器删 `restoreAssetRefs` 私补。验证:含 texture/material/font 引用的场景 world→JSON 往返,asset 字段为 `@uuid:` 而非裸数字。-- **L1(数据模型持有,已做)**:`SceneModel` 在 load 后保留完整 SceneData 为真相(未知组件/字段/visible/`@uuid:`)+ 模型⇄运行时 id 映射(取自 `resetWorldTo` 的返回 map)。`ProjectStore.loadCurrentScene` adopt。-- **~~L2(独立增量投影层)~~ → 被双写吸收**:没有单独的投影层;改为 **L3 的命令双写**(命令在改 world 的同时改模型)。world 仍是预览,模型仍是单一保存真相;省掉一个组件,代价是命令需维护两侧(由测试钉住一致性)。后续若要"模型为唯一真相、world 纯派生"再上独立投影。-- **L3(命令双写,已做)**:`SceneCommands` 的写原语(`applyFieldWrite`)与生命周期命令(add/delete/duplicate/rename)在改 world 的同时改 `SceneModel`(字段按 runtime,生命周期按稳定 source id 跟随 undo/redo recreate)。承接 E2 边界,undo/redo 闭包经同一原语自动同步。-- **L4(无损保存,已做)**:`ProjectStore.serializeCurrent` = `SceneModel.serialize()`(深拷贝模型,无损);`save` 删 lossy 拒绝逻辑;`serializeScene(world)` + `restoreAssetRefs` + 死的 `handleToUuid` 已移除。验证:golden——adopt 含未知组件场景 → 编辑/增删 → 序列化保留未知组件 + 反映编辑 + delete-undo 不丢未知组件。-- **L5(play 快照取数据模型,待做)**:`EngineHost.setRunMode` 快照数据模型而非 `serializeScene(world)`;Stop 恢复。接 play==ship。-- **(可选)L6**:引擎给非编辑器消费者加未知组件 passthrough(防御纵深);prefab 借 `metadata` 范式同样无损。--> **现状(L1+L3+L4 已落地)**:编辑器**已能无损保存**——开含未知组件的场景、编辑已知字段/增删实体、覆盖保存,未知组件/字段/`@uuid:` 原样保留。`lossy` 拒绝保存已退役。`engine-model-sync.test.ts` 钉住。剩 L5(play 快照)是 play==ship 的收尾。-------## 5. 验证机制-- **golden 往返测试(核心,进 CI)**:`load(fixture) → save → deepEqual(原 fixture)`,fixture **必须含**:未知组件、已知组件的未知字段、`visible:false` 实体、texture+material+font `@uuid:` 引用、textureMetadata、需要 double 精度的字段。当前 `sdk/tests/scene.test.ts` **没有**这类字节级 golden(只有 migrate/codec/unknown-warn),是首要补的。-- **L0**:asset 往返断言(@uuid: 保真,全类型)。-- **L4**:`lossy` 标志删除后,含未知组件的场景可覆盖保存且无损。-- **回归**:SDK 全量 + editor build;E2 命令/undo 行为不变。-------## 6. 与其他条目的关系-- **第二条腿**:与 `REARCH_ENGINE_INSTANCING.md` 并列,共同支撑 `RC12` 最优编辑器架构(隔离 realm + 无损 + play==ship)。-- **接 E2**:命令边界(单一写门 + 自动 undo)整体复用,只换 apply 目标。-- **解锁 play==ship**:L5 让 play 快照走数据模型,Stop 无损还原。-- **prefab 同病同药**:prefab 实例化共享 scene load 下游(`prefab.ts:101`),其 `metadata` 通道是 passthrough 范式。-- **零 ABI**:纯 SDK/编辑器 + 序列化格式版本化(`SCENE_FORMAT_VERSION` 机制已成熟,`scene.ts:186,208`),不动组件布局/哈希。diff --git a/docs/REARCH_SPINE.md b/docs/REARCH_SPINE.mddeleted file mode 100644index 97e2ee10c..000000000--- a/docs/REARCH_SPINE.md+++ /dev/null@@ -1,116 +0,0 @@-# Estella Spine 子系统重构 —— 单实现 · 全 side-module · 真多版本(REARCH_SPINE)--> 目标读者:引擎维护者 / AI 协作代理。-> 体例同 `REARCH_EDITOR_REALM.md` / `REARCH_ENGINE_INSTANCING.md`:描述**目标架构**与根治路径,而非现状。-> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 四路并行只读审计 + 交叉印证)。-> **立项缘由**:Spine 当前是**双运行时**架构,而这套复杂度是"一个**真需求(运行时多版本)** 被**半成品 + 重复**地实现了"。真需求确凿——很多用户**只有 3.8 的导出产物、没有 `.spine` 源文件**,导入期转换走不通,运行时必须能跑多版本。但当前实现是**最贵的那种**:一个版本(4.2)进引擎、其余流放 side-module、整条流水线手抄两遍。**本文把它收口成:所有版本对称的 side-module + 单一实现。**-> **执行纪律(用户明确):终态删掉原生重复,不为兼容保留旧路径**;分阶段只为每步可验证。-------## 0. 核心诊断--**真正的分界线不是"C++ vs JS",是"引擎链接单元 vs side-module"。** 一个 wasm 只能静态链接**一份** spine-cpp(不同大版本符号/ABI 冲突)。4.2 拿到"引擎内"特权位**纯属偶然**(谁是当前版本谁就进引擎);所谓"JS 路径"里**没有一行动画跑在 JS**——那 ~1000 行 TS(`SpineManager`/`ModuleBackend`/`SpineController`/`SpineModuleLoader`)全是为了从 JS 调用 sibling wasm 模块的胶水。--**三条事实定调:**-1. **多版本是真需求**(用户只有旧版导出产物),不能删。-2. **side-module 全平台可加载**(已验证):web 用 `blob`+`import()`、微信用 `WXWebAssembly.instantiate(path)`(`platform/wechat/wasm.ts`,需基础库 ≥2.13)、playable 内联;`wechatRuntime.ts:189` 已在按版本加载 `spine_${tag}.wasm`。**平台不否决全 side-module。**-3. 把 4.2 移出核心 → **不用 spine 的游戏核心更小**(spine-cpp ~278KB 不再人人付),用 spine 的按需加载,和 physics 现状一致(pay-for-use)。--**结论:全 side-module + 单实现是最优。** 没有任何一条站得住"4.2 必须留引擎内"——spine-c 4.2 与 spine-cpp 4.2 功能对等;跨堆 memcpy 已零分配、微秒级可忽略;平台已封装。-------## 1. 现状病灶(file:line)--### G1:整条流水线被实现两遍(根因)-- **side-module 路径**:`bindings/SpineModuleEntry.cpp`(~1080 行,`#ifdef ES_SPINE_38/41` 按版本分叉),自带 skeleton/atlas/animation/mesh 提取/event/IK/constraint 一整套,用 **spine-c**(纯 C)。-- **原生路径**:`spine/SpineSystem.cpp`(380)+ `renderer/plugins/SpinePlugin.cpp`(290,collect/emitRegion/emitMesh)+ `spine/SpineResourceManager.cpp`(200),用 **spine-cpp**(C++)。-- 二者**不共享代码/类型/所有权规则,连 spine 运行时风味都不同**。网格提取各 ~180 行近乎雷同。加一个 spine 功能要改 ~5 处(raw 声明、wrapped API、`wrapSpineModule`、controller、backend、manager)。--### G2:多版本是半成品,从没接通-- 构建声明了 `spine42`/`spine41`/`spine38` 三个 side-module 目标(`CMakeLists.txt:446-503`,同一 `SpineModuleEntry.cpp` 对不同 spine-c 源),但**磁盘上只有 `spine42.*`**——`spine38.*`/`spine41.*` 全仓不存在。-- **web 侧 `SpineWasmProvider` 没有任何具体实现**(`SpineModuleLoader.ts` 只声明接口;`webAppFactory.ts:38` 是可选注入点,无人注入)→ 这就是"3.8 用户跑不起来"的直接原因。微信侧 `wechatRuntime.ts:189` 半接通。--### G3:两条路渲染不一致(潜在正确性 bug)-- 原生 `SpinePlugin.cpp:179-202` 有真 `SkeletonClipping clipper_`;side-module `SpineModuleEntry.cpp:556` **静默跳过 clipping attachment**。**用同一资产两条路渲染结果不同**——重复直接孕育的 bug。--### G4:资源所有权(真正还 OPEN 的 bug)-- **共享 skeletonData 的 UAF**:`SpineResourceManager.cpp:99-102` `load()` 命中缓存**不 `addRef`**,而 `SpineSystem.cpp:134-145` `reloadAssets` 按实体逐个 `release` → 第一个 release 就把多个实体共享的 `SpineSkeletonData` 释放,其余实体的 `::spine::Skeleton` 仍指向已释放的 `skeletonData`(`SpineSystem.cpp:69`)。-- **纹理 refcount 泄漏/释放不对称**:`SpineResourceManager.cpp:43` 把 page key 编码成去重后的 `handle.id()+1`;多页/共享页图集下,`loadTexture` 按路径去重使两页拿到同一 handle/key → `texture_handles_` 只剩一条、refcount 加了两次,`unload` 只释放一次 → 泄漏。-- 现成的 RAII `SharedHandle`(`resource/Handle.hpp:132-175`)**已存在但 Spine 没用**。-- side-module 的 `g_ctx`(`SpineModuleEntry.cpp:149`)是**全局裸 map、零 RAII**,正确性全靠每条错误路径手动 dispose。--### G5:三层透传塔 + spine 内部细节泄漏进 TS-- `SpineManager`(363)→`ModuleBackend`(238)→`SpineController`(417),每层只重新解析 handle 再转发,~20 个方法逐层重复。-- TS 知道它不该知道的 spine 内部:二进制 varint 版本头解析(`SpineManager.ts:326-362`)、顶点 stride `*8*4` / 索引 `*2`(`SpineController.ts:252`)、事件 stride=4 与 `typeNum===5`(`SpineController.ts:325` 与 `SpinePlugin.ts:173` 重复)。版本串 `'3.8'|'4.1'|'4.2'` 在三个文件重声明。-- **潜在双提交**:`SpinePlugin.ts` `setSpineManager`(61-70)与 `build`(124-130)各注册一次 `submitMeshes` preFlush,拷贝粘贴雷同。--### G6:side-module 路径的跨堆拷贝(已零分配,保留为统一成本)-- spine 堆 → core 堆 的 `HEAPU8.set`(`ModuleBackend.ts:205-216`),已是零分配 scratch arena。原生 4.2 直写 transient buffer 无此拷贝。统一后 4.2 也付此拷贝——**微秒级,可接受**。-------## 2. 目标架构(A:单实现 · 全 side-module)--1. **所有版本对称**:每个版本 = `spine{NN}.wasm` side-module,全部由**同一份** `SpineModuleEntry.cpp` 对不同 spine-c 源编译。引擎核心**零原生 spine**(spine-cpp 移出链接)。-2. **单 `SpineRuntime` 接口**(TS):`load(skeleton,atlas)→instance`、`update(dt)`、`produceMeshBatches()`、`collectEvents()`、constraint/IK/slot 等;**一个实现**(side-module 后端)。`SpineManager` 只管 实体→版本→backend 路由 + 网格/事件 fan-out。**删 `SpineCpp` dual path 与所有 fallback**。-3. **删原生路径**:`SpineSystem.cpp`、`renderer/plugins/SpinePlugin.cpp`、`SpineResourceManager.cpp`、`spine_*`/`spine_native_*` embind(`WebSDKEntry.cpp`/`RendererBindings.cpp`)、`needsReload`/`spine_setNeedsReload` 握手、双 tick。-4. **把统一路径提质到原生水平**:把 `SpinePlugin.cpp` 的 clipping 移植进 `SpineModuleEntry.cpp`;保留零分配 scratch 提交;网格/事件做到与原生 4.2 逐像素 parity。-5. **资源所有权根治**:`SpineModuleEntry.cpp` 的 `g_ctx` 改 RAII(move-only `Skeleton`/`Instance` 类型,析构即 dispose,`reset()`=`.clear()`);骨架数据按"路径+scale"做真正的 dedup + refcount(命中即 addRef);纹理按 `AtlasPage*` 而非去重 handle 做 key。-6. **TS 收口**:三层塔压成两角色(thin per-runtime `SpineBackend` + 一个 `SpineManager`);把 varint 版本嗅探、顶点/事件 stride、事件码推回 wasm 边界(`spine_detectVersion`/`spine_describeVertexFormat` 导出),TS 只碰不透明 handle + 字节数。修双提交。-------## 3. 需要拍板的岔路(已定)--| 岔路 | 选项 | 决定 |-|---|---|---|-| 多版本怎么给 | 格式转换器(3.8→4.2) / 各版本官方 spine-c side-module | **side-module**:转换器脆弱、非官方、易错;官方运行时稳 |-| 4.2 放哪 | 留引擎内(零拷贝,但强制双实现) / 全 side-module | **全 side-module**:单实现 + pay-for-use,跨堆拷贝可忽略 |-| 版本选择时机 | 构建期单版本 / 运行时多版本 | **运行时**:真需求(用户混装不同版本资产,且无源不能重导) |-| 终态是否保留原生 4.2 | 保留作快路径 / 删除 | **删除**(用户明确:不为兼容失去最优架构) |-------## 4. 迁移序(分阶段,每段可验证;**终态删原生,不留兼容残桩**)--### S1 —— 先接通多版本(解用户痛点,低风险,不碰 4.2 原生)-实现 web `SpineWasmProvider`(对照 `wechatRuntime` 的微信版)+ 实际构建/出货 `spine38`/`spine41` side-module + `webAppFactory` 默认注入 provider + `SpineManager` 真正加载。**验证:一个真实 3.8 资产能加载 + 动画 + 事件**(web 与微信各一)。此阶段 4.2 暂留原生——仅过渡。--### S2 —— `SpineModuleEntry` 提质到原生水平 ✅ DONE(见 `REARCH_SPINE_S2.md`)-把 `SpinePlugin.cpp` 的 `SkeletonClipping` 移植进 `SpineModuleEntry.cpp`;统一网格提取。-- **路由现实修正(查证):4.2 在配置了 provider 的 web/编辑器里早已走 side-module**(`webAppFactory.ts` 注入 `WebSpineWasmProvider` + `createSpineFactories` 无条件含 4.2 → `SpineManager.loadEntity` 不回退原生)。原生 4.2 仅无-provider 配置才触发。这是 S1 副作用,并暴露 G3 为 **live bug**(side-module 跳过 clipping → 带 clipping 的 4.2 资产在编辑器一直错误地不裁剪)。S2 修复之。-- **验证改为更优:确定性 node clip 不变量**(`spine-clip.integration.test.ts`)替代"对原生像素对拍"——既然原生已非生产路径且自身漏 PMA / 漏 region 裁剪,对齐它不是正确目标;移植的是 spine 官方 `spSkeletonClipping`(三版 API 一致),用几何不变量(裁剪改变网格 + clipped ⊆ unclipped + 严格缩小)验证接线正确。RED→GREEN 走通,spine 套件 28 绿 / 全量 2245 绿。Electron 像素视觉 smoke 留作后续 live-check。-- 副产:spine41 出货(S1 残留补齐),3.8/4.1/4.2 三版齐全。--### S3 —— 4.2 切到 side-module + **删原生** ✅ DONE-所有版本走同一 side-module backend;删 `SpineSystem`/原生 `SpinePlugin`/`SpineResourceManager`/`SpineExtension`/`SpineCpp` embind+TS/`needsReload` 握手/原生 tick;spine-cpp 移出核心链接。`SpineManager` 删原生回退(无 factory 即加载失败 = pay-for-use)。**保留**:`SpineAnimation` 组件(ABI 不变,骨架句柄字段变 vestigial)、渲染器 spine pass、`renderer_submitSpineBatch/ByEntity`(side-module 提交网格路径)。-- **结果(已验证)**:核心 `esengine.wasm` **1,460,160 → 957,156 字节(-503KB)**;embind 确认 `renderer_submitSpineBatch` 在、`spine_native_*` 没了;`verify:render` 引擎 boot+渲染 PASS;side-module clipping 仍绿(spine-clip gate);2240 SDK 测试 + sdk/desktop tsc 绿。-- **未 headless 验证**:编辑器里 spine 实时渲染(SceneLoader 仍未接 spine = S1 编辑器残留;但 side-module 网格路径 node 已证 + 提交 binding 在 + 引擎渲染正常 → 路径完整)。微信/playable 运行时(需各自配 spine module;3.8/4.1 本就如此)。--### S4 —— 资源所有权 RAII 根治-`g_ctx` move-only RAII + 骨架数据 dedup/refcount(命中 addRef)+ 纹理按 page key。**验证:ASAN 下多实体共享同一骨架 reload/despawn 无 UAF;多页图集 load/unload refcount 对称。**--### S5(收尾)—— TS 层收口-三层塔压两角色;spine 内部细节(varint/stride/事件码)推回 wasm 导出;修双提交;删冗余类型面。**验证:desktop/sdk 套件常绿;加一个 spine 集成测试。**--> 删 `third_party/spine-runtimes-3.8|4.1` 的**未用第三方源树**(~290MB)作为独立清理项,在对应版本 side-module 改用精简后或 S3 后进行。-------## 5. 验证机制(机制即根治成立的证明)-- **渲染 parity(最关键)**:原生 4.2 与 side-module 4.2 同场景**关键帧逐像素对拍**(S2 门槛);clipping 资产两路一致。-- **多版本**:3.8 / 4.1 / 4.2 各一个真实资产能加载 + 播放 + 触发事件。-- **三平台**:web(blob)/ 微信(WXWebAssembly)/ playable(内联)各跑通同一 spine 资产。-- **体积**:核心 `esengine.wasm` 减小 ~278KB;不含 spine 的 example 产物不再含 spine 代码(metafile/符号断言)。-- **所有权**:ASAN——多实体共享骨架 + reload/despawn 交错;多页/共享页图集 load/unload 对称。-- **回归**:SDK 全量 + desktop vitest + 全量 wasm 构建常绿。-------## 6. 与其他条目的关系 / 既定取舍-- **吃掉重复**:S3 后只剩 `SpineModuleEntry.cpp` 一套实现;G1/G3(渲染分歧)随之消失。-- **接 RAII 连接**:与刚落地的 `Registry::onDestroyScoped`(RAII 订阅)同精神——所有权由 RAII 强制,不靠手动。-- **接 pay-for-use**:spine-cpp 移出核心,呼应 wasm-split / 按需加载方向。-- **零 ABI 影响**:不改组件布局/哈希;`SpineAnimation` 组件字段不变(仍 `skeletonPath`/`atlasPath`/...,无 version 字段——版本运行时嗅探)。diff --git a/docs/REARCH_SPINE_S2.md b/docs/REARCH_SPINE_S2.mddeleted file mode 100644index e4809c2eb..000000000--- a/docs/REARCH_SPINE_S2.md+++ /dev/null@@ -1,82 +0,0 @@-# Estella Spine S2 —— side-module 提质到原生水平 + parity 验证(REARCH_SPINE_S2)--> 承接 `REARCH_SPINE.md` 的迁移序。S1(多版本接通:spine38/42 出货 + web provider + 编辑器接线 + 3.8 headless 验证)已完成。-> 本文是 **S2** 的可执行计划:把原生 `SpinePlugin.cpp` 的 clipping 移植进 side-module,并用 **逐三角网格 parity** 证明 side-module 4.2 == 原生 4.2 —— 这是 S3 安全删原生的前置门槛。-> 执行纪律(用户已拍板):四个开放决策全部取最优解(见 §2),终态删原生不留兼容桩。-------## 0. 验证目标(= S3 删原生的前置门槛)--S2 改动面 = **把 clipping 移进 side-module + 统一 mesh/event 提取**。验证必须证明:--> 同一个 4.2 资产、同一动画时刻,**side-module 4.2 的逐三角网格输出 == 原生 4.2**;带 clipping 的资产两路裁剪结果一致。--只有它成立,S3 才能"盲删"原生而不回归现有渲染。--## 1. 四条已查证事实(决定计划成本)--| # | 事实 | file:line | 影响 |-|---|---|---|---|-| A | 版本路由在 **TS**(4.2→原生,3.8/4.1→module) | `SpineManager.loadEntity` / `SpinePlugin.ts:104-107` | **force-route 纯 TS**,不重建 wasm |-| B | side-module 网格数据 **JS 可读** | `SpineController.forEachMeshBatch` → `getMeshBatchData` | side-module 4.2 网格 node 内可取 |-| C | 原生网格**只写进 C++ `DrawList`** | `SpinePlugin::emitBatch` | 要对比须给原生加临时取数 hook(S3 删) |-| D | `spineboy-pro` / `tank-pro` 跨 3.8/4.1/4.2 都在且含 clipping | `third_party/spine-runtimes-*/examples/*/export` | 一资产覆盖总 parity + clipping |--## 2. 路由现实(已查证,推翻蓝图前提)+ 简化后的验证--**关键事实:4.2 在编辑器/web 里已经走 side-module,不走原生。** `webAppFactory.ts:51-53` —— 给了 `wasmBaseUrl` 就注入 `WebSpineWasmProvider`;`createSpineFactories`(`SpineModuleLoader.ts:173`)**无条件含 4.2**;故 `SpineManager.loadEntity` line 65 的 `!factories_.has('4.2')` 为假,4.2 落到 module backend。编辑器 `EngineHost` 用 `createWebApp(module,{wasmBaseUrl:'/wasm'})` → **4.2=side-module**。原生 4.2 仅在无 provider 配置才触发。--**这是 S1 的副作用**(接通 3.8/4.1 provider 时把 4.2 一并切了),且暴露一个 **live bug**:side-module 跳过 clipping(`SpineModuleEntry.cpp:556`)→ 带 clipping 的 4.2 资产(tank)在编辑器**正在错误地不裁剪渲染**。**S2 修这个现存回归**,不只是为 S3 铺路。--**次要约束:原生 spine 路径 GL 耦合**(`SpineResourceManager.cpp:30` 用 GL 纹理 `getWidth/getHeight` 填 page 尺寸,不读 .atlas 文本)→ 纯 node 取不到原生网格。但既然原生已非 4.2 生产路径,**不再需要对齐原生**。--简化后的验证(不需 force-route、不需原生像素 parity、不需 capture hook):--1. **主门槛(确定性 · node · 无 GL)= side-module clipping 正确性**:`spine-clip.integration.test.ts` 直接驱动 spine42 controller 加载 tank-4.2,提取裁剪网格,断言 clip 多边形包含性 + clip-on vs clip-off 网格不同。**移植的是 spine 官方 `spSkeletonClipping`(side-module spine-c 自带),与原生调 spine-cpp `SkeletonClipping` 同一算法 → 移植=接线** → 不变量 + 视觉 smoke 足以验证接线正确。-2. **辅门槛(ship 视觉 · Electron)= 自参照 before/after**:编辑器/realm 渲 tank-4.2(side-module 路径),S2 后 clipping 可见。无需原生对比。-3. **资产 = spineboy-pro(总网格回归)+ tank-pro(clipping 专项)**,跨版本都在,均非 PMA。node 测试用 stub page 纹理(.atlas 真实尺寸 + 假 glId)使 attachment emit。-4. **顺手补 spine41 出货**(S1 残留)。--## 3. 脚手架(全部 S3 删除)--- **a. force-route(纯 TS)**:`SpineManager` test-only `forceModuleVersions: Set<string>`,命中则 4.2 也走 module backend(load 已在盘的 `spine42`)。-- **c1. node clip 不变量测试**:`sdk/tests/spine-clip.integration.test.ts`,扩展 `spine38-load.integration.test.ts` 的 node 加载模式 —— spine42 side-module 加载 tank-4.2,t∈{0,0.2,0.5,1.0} 提取网格,断言 clip 包含性 + 关裁剪对照越界。-- **c2. Electron 像素 parity 驱动**:复用 headless Electron + loopback http-static 模式(`headless-verify.mjs` 模板),经 `runtimeLoader`(已接 spine)渲 native-4.2 一帧 → force-route 重渲 side-4.2 一帧 → 像素 diff。-- **d. 资产**:spineboy-pro + tank-pro(4.2)入测试/服务可达路径。--> 不再需要原生 C++ capture hook —— GL 约束下像素 parity 用原生正常渲染,node 不变量用 side-module(无 GL)。--## 4. Pass 判据--- 逐三角:worldVertex/uv/color `epsilon ≤ 1e-4`;index 完全一致。-- 批次数 / 纹理页 / blend mode 一致。-- clipping 资产:裁剪后三角数与原生一致,且 < 未裁剪时(证明确实裁了,排除"两路都没裁"的假绿)。-- 多关键帧时刻都过(动画推进,不只静态 t=0)。--## 5. 验证序 = TDD red→green--1. 搭 a/b/c/d 脚手架,**先不改 clipping 逻辑**。-2. 跑 parity:总网格 region/mesh **PASS**;clipping 资产(tank)**FAIL**(side-module 不裁,三角多于原生)→ red,证明测试有效。-3. 移植 `SkeletonClipping` 进 `SpineModuleEntry.cpp`(= S2 主体),重建 spine wasm。-4. 同一测试转 **GREEN** = S2 完成的客观证明。--## 6. 完成状态(DONE)--**S2 核心 = clipping 移植 + 确定性验证,已完成并验证。**--实现(`src/esengine/bindings/SpineModuleEntry.cpp`):-- `SpineContext` 加 `spSkeletonClipping* clipper`(惰性创建,reset 释放)+ `clippingEnabled` 开关。-- `extractMeshBatches` 的 drawOrder 循环接入 spine 官方裁剪:clipping attachment → `clipStart`;每个 region/mesh 经新 `emitClippedTriangles`(`isClipping()` 时 `clipTriangles` → 用 `clippedVertices/clippedUVs/clippedTriangles` 发射,否则原样);每个非 clip slot 后 `clipEnd(slot)`,循环末 `clipEnd2`。**region 也裁**(修了 native 只裁 mesh 的 bug)。-- 新导出 `spine_setClippingEnabled(int)`(默认开;让测试对比 clip-on/off,亦为 perf 开关)。-- 三版 spine-c 的 `spSkeletonClipping` API 完全一致 → 零 `#ifdef`。spine38/41/42 全部重建出货(**spine41 = S1 残留一并补齐**)。--验证(`sdk/tests/spine-clip.integration.test.ts`,2 用例):-- node 直驱 spine42 加载 tank-4.2 + stub page 纹理 + 显式挂 smoke-glow,提取 clip-on/off 网格。-- 断言:clip 改变了网格(376 vs 344 tri)+ clipped bbox ⊆ unclipped + 严格缩小(smoke maxY 1495→950,被裁回坦克车身多边形内)。-- **RED→GREEN 全程走通**(移植前 clip-on==clip-off 失败 → 移植后通过)。-- 回归:spine 套件 28 绿;全量 SDK **2245 绿**;SDK + desktop tsc 干净。--**剩余(非阻塞)**:Electron 像素视觉 smoke(把 spine 接进 verify:render 或 play realm 渲 tank-4.2,肉眼确认裁剪)—— 渲染管线(submitMeshes→GL)S2 没动,风险低,作为后续 live-check。`spine_setClippingEnabled` 是 S3 可选清理项(留作 perf 开关亦可)。--> **顺带确认的 live bug(见 §2):4.2 在编辑器里早已走 side-module**,S2 此前缺失 clipping → 带 clipping 的 4.2 资产在编辑器一直错误地不裁剪渲染。S2 修复了它。diff --git a/docs/REARCH_TILEMAP.md b/docs/REARCH_TILEMAP.mddeleted file mode 100644index c153a48b3..000000000--- a/docs/REARCH_TILEMAP.md+++ /dev/null@@ -1,122 +0,0 @@-# Tilemap — Architecture & Rearchitecture--**Status (2026-06-23):** **COMPLETE — T0–T4 done + pushed.** T1 = runtime tile collision for-the asset-driven `Tilemap{source}` path (closed the "B2-1" debt); T2 = Tileset editor +-`.estileset`; T3 = the Tilemap painter (model-authoritative `paintTiles` + viewport painting +-palette + Create-Tilemap); T4 = native-path runtime collision (painted `TilemapLayer` →-colliders from its `.estileset`'s collidable tiles, carried out-of-band) + physics auto-gate.-Tilemap runtime = a C++ side concern (`src/esengine/tilemap/TilemapSystem.cpp` chunk store +-`renderer/plugins/TilemapRenderPlugin.cpp`), driven by the SDK (`sdk/src/tilemap/*`). Optional-polish remains (per-tile polygon/iso collision, bucket fill, re-bake, terrain/autotile).--## Verdict--The **runtime is solid** — a real C++ chunked/infinite tilemap with animations, parallax,-orthogonal/isometric/staggered grids, and out-of-band chunk (de)serialization into the-scene file. Two gaps keep it below a shippable 2D-tilemap workflow:--1. **Runtime tilemaps have ZERO physics collision.** `generateTileCollision` (greedy-merge- collidable tiles → static `BoxCollider` entities) exists but is wired ONLY into the- non-runtime `loadTiledMap` (tests). The production `Tilemap{source}` →- `TilemapAssetLoader` → `TilemapSyncSystem` path never generates colliders, and the- loader even drops `collisionTileIds`/`orientation`/`tileAnimations`/`tileProperties` at- the cache boundary (`TilemapAssetLoader` builds a partial `LoadedTilemapSource`).-2. **No editor authoring.** Tiles can only come from an external Tiled `.tmj`/`.tmx`. There- is no in-editor tileset/tilemap editor, though the design mockups (`ue5-tilemap.html`,- `ue5-tileset.html`) call for them.--## Already modern — do not churn--- C++ chunked + infinite layers, per-tile animation, parallax, grid orientations.-- Out-of-band chunk codec: `TilemapLayer` chunks serialize into the `.esscene` via a- registered scene-component codec (`tilemapPlugin.build` → `registerSceneComponentCodec`)- — heavy tile blobs ride alongside the entity losslessly.-- The asset path: `.tmj`/`.tmx` → `parseTmjJson` → `registerTilemapSource` cache →- `TilemapSyncSystem` builds synthetic C++ layers (no ECS-entity-per-tile bloat).-- The collision algorithm: `mergeCollisionTiles` (greedy maximal-rectangle merge) →- one static `BoxCollider` body per merged rect (coalesced, Box2D-friendly).--## Authoring model decision (the keystone)--**The Unity/Godot consensus, adapted to this engine's editor-first / model-authoritative-core** — *not* the UE-Paper2D standalone-tilemap-asset model (an earlier draft of this doc-leaned that way; on review it fights the engine's grain). Three axes, each resolved to the-optimum for *this* engine:--1. **Tileset = `.estileset` reusable asset** (universal across Unity/Godot/UE). The single- source of truth for how a tile looks (atlas slicing) AND behaves. Richer than a- collision boolean — per-tile collision **shapes**, animation, properties, with an- extensible slot for terrain/autotile rules:- ```jsonc- {- "version": "1", "texture": "@uuid:…",- "tileWidth": 16, "tileHeight": 16, "columns": 8, "margin": 0, "spacing": 0,- "tiles": { // sparse — only tiles carrying metadata- "5": { "collision": { "type": "box" }, "animation": [{ "tile": 5, "durationMs": 100 }] },- "12": { "collision": { "type": "polygon", "points": [[0,0],[16,0],[16,8]] } } // a slope- }- }- ```- Edited in the **Tileset editor** (an `AssetDocument` subclass — `.estileset` IS a file).-2. **Tilemap data = scene-embedded first-class `TilemapLayer` entities** (Unity component /- Godot node), NOT a standalone asset. Why this beats the standalone-asset model here:- (a) painting becomes ordinary **scene editing** through SceneCommands/Reconciler — the- same model-authoritative pipeline as the rest of the editor; (b) each layer is a real- entity (selectable / transformable / parentable / z-orderable), vs the `Tilemap{source}`- synthetic-layer black box; (c) no redundant new format. Tiles persist via the existing- out-of-band chunk codec; undo via a tile-region command diff (T3 decides model-field vs- command-diff). The `Tilemap{source}` component (Tiled `.tmj` import + a *future optional*- standalone `.estilemap` for cross-scene reuse) stays as the SECONDARY import path.-3. **Collision authority = the tileset** (Godot model). Colliders are derived at runtime- from `(placed tiles) × (tileset collision shapes)`: boxes greedy-merged (T1), custom- polygons emitted per-tile (later). Change the `.estileset` → every map updates. T1's- Tiled-property collision stays for the import path; both converge on- `generateLayerCollision`. **C++ stays render-only** — `.estileset` resolution (texture- handle + collision shapes) happens in the SDK plugin (engine's C++-mechanics /- SDK-assets split).--## Phases--- **T0 — this doc.**-- **T1 — runtime collision for `Tilemap{source}` (closes B2-1).** Carry the dropped- metadata (`collisionTileIds` + `orientation`/`tileAnimations`/`tileProperties`) into the- `LoadedTilemapSource` cache; generate + lifecycle-manage tile colliders in- `TilemapSyncSystem`, gated `playModeOnly` (colliders are runtime artifacts — never in the- edit world, never serialized; despawned on stop / tilemap removal). Extract a generic- `generateLayerCollision(world, tiles, w, h, tileW, tileH, ids, originX, originY)` from the- Tiled-typed `generateTileCollision` (DRY). SDK-only, no wasm rebuild. Verify in vitest- (collider entities spawn at correct world rects + halfExtents; despawn on stop).- *Caveat:* tile colliders need the physics module loaded — `sceneUsesPhysics` content-scan- can't see runtime-spawned colliders, so a collision tilemap needs `features.physics` (or- another physics body in the scene). Folded into T4's tileset-collision flow.-- **T2 — Tileset editor + `.estileset`.** SDK format (`tilesetAsset.ts`: `TilesetAsset`- type + `parseTileset`/`serializeTileset` + version, exported via the tilemap barrel) +- `AssetDocument<TilesetAsset>` + Tileset panel (texture grid overlay, tileW/H/margin/- spacing controls, click/drag to toggle per-tile collision) + Content-Browser open +- Create-Tileset-from-texture + asset-type registration. The palette + collision authority.-- **T3 — Tilemap painter (scene-embedded `TilemapLayer`).** Paint into first-class- `TilemapLayer` entities through SceneCommands/Reconciler (model-authoritative), with a- selected `.estileset` as the brush palette: layer list, brush/fill/erase/rect/bucket/- eyedropper, live in the viewport (no separate preview mirror needed — it's the real- scene). Decide tile-data home (model-field chunks vs command-diff undo). Create-Tilemap- spawns a `TilemapLayer` entity referencing an `.estileset`.-- **T4 — Unify native-path collision + physics enablement.** Resolve the referenced- `.estileset`'s collision shapes for scene `TilemapLayer` entities → `generateLayerCollision`- (boxes) + per-tile polygons; make a tilemap carrying collidable tiles signal- `sceneUsesPhysics` (closes the T1 caveat: runtime-spawned colliders are invisible to the- content-scan gate). See [[estella-physics-audit]] / [[subsystem-observability]].-- **Later (extensible, not now):** standalone `.estilemap` asset for cross-scene reuse;- terrain/autotile (wang/rule tiles) in `.estileset`; one-way platforms + physics layers.--## Key files--- SDK runtime: `sdk/src/tilemap/{tilemapPlugin,tiledLoader,collisionMerge,tilesetCache,- tilemapAPI,components}.ts`; loader `sdk/src/asset/loaders/TilemapAssetLoader.ts`.-- C++: `src/esengine/tilemap/TilemapSystem.{hpp,cpp}`,- `src/esengine/renderer/plugins/TilemapRenderPlugin.cpp`,- `src/esengine/ecs/components/TilemapLayer.hpp`, `bindings/TilemapBindings.cpp`.-- Editor pattern to copy (the Sequencer asset-document recipe):- `desktop/src/document/AssetDocument.ts`, `desktop/src/timeline/{TimelineDocument,- TimelineCommands,openClip}.ts`, `desktop/src/panels/Sequencer.tsx`,- `desktop/src/engine/TimelinePreview.ts`, `desktop/src/layout/DockLayout.tsx`,- `desktop/src/project/assetMeta.ts`, `desktop/src/components/icons.tsx`.