A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor: migrate 8 singleton services to IoC and eliminate component switch dispatch
esenginee73ec6aea248
diff --git a/docs/plans/architecture-refactoring-roadmap.md b/docs/plans/architecture-refactoring-roadmap.mdnew file mode 100644index 000000000..302160278--- /dev/null+++ b/docs/plans/architecture-refactoring-roadmap.md@@ -0,0 +1,217 @@+# Editor Architecture Refactoring Roadmap++## Current State++EditorContainer IoC 已管理 16 类 token(ComponentSchema、Panel、Gizmo、Menu 等),24 个 plugin 通过 `PluginRegistrar` 注册。但 8 个核心服务仍用 `let instance; export function getXxx()` 单例模式绕过 IoC。++## Phase 1: Service Token 化(Singleton → IoC)++**目标**:将 8 个 singleton 服务迁移到 EditorContainer,统一生命周期管理。++### 依赖关系图++```+GlobalPathResolver ─────────────────────────┐+AssetEventBus ──────────────────────────────┤+AssetDependencyGraph ───────────────────────┤ 无依赖(叶子节点)+ImporterRegistry ───────────────────────────┘+EditorStore ────────────────────────────────── 无依赖+SharedRenderContext ────────────────────────── 无依赖(async init 需要 WASM module)+AssetDatabase ──────────────────────────────── 无依赖(async init 需要 projectDir + fs)+PlayModeService ────────────────────────────── 依赖 EditorStore + SharedRenderContext + AssetDatabase+```++### 迁移顺序(按依赖 + 影响范围排序)++| 批次 | 服务 | 消费者数 | 难度 | 说明 |+|------|------|----------|------|------|+| 1a | AssetEventBus | 3 | 低 | 无依赖,有 reset,消费者少 |+| 1b | AssetDependencyGraph | 3 | 低 | 无依赖,有 reset,消费者少 |+| 1c | ImporterRegistry | 3 | 低 | 无依赖,已在 plugin 中注册 |+| 2a | GlobalPathResolver | 9 | 中 | 无依赖,但消费者多 |+| 2b | EditorStore | 3 | 中 | 构造时创建 5 个内部服务,无 dispose |+| 3 | SharedRenderContext | 5 | 中 | 需要 async init,有完整 dispose |+| 4 | AssetDatabase | 11 | 高 | 消费者最多,需要 async init |+| 5 | PlayModeService | 7 | 高 | 依赖其余 3 个服务,最后迁移 |++### 迁移模式++```typescript+// tokens.ts 新增+export const EDITOR_STORE = new ServiceToken<EditorStore>('EditorStore');+export const SHARED_RENDER_CTX = new ServiceToken<SharedRenderContext>('SharedRenderContext');+// ... 其余 6 个++// plugin 中注册+export const coreServicesPlugin: EditorPlugin = {+ name: 'core-services',+ register(ctx) {+ ctx.registrar.provide(ASSET_EVENT_BUS, 'default', new AssetEventBus());+ ctx.registrar.provide(ASSET_DEP_GRAPH, 'default', new AssetDependencyGraph());+ // ...+ },+};++// 消费端:getAssetEventBus() 内部改为 getEditorContainer().get(ASSET_EVENT_BUS, 'default')+// 保留 getter 函数作为便捷 API,但底层走 IoC+```++### 关键决策++- **保留 getter 函数**:`getEditorStore()` 等不删除,改为内部调用 `getEditorContainer().get()`。这样不破坏现有消费端,但 lifecycle 由 IoC 管理。+- **Dispose 统一**:EditorContainer 增加 `dispose()` 方法,LIFO 顺序清理所有注册的服务(类似 DisposableStore)。+- **AsyncInit 服务**:AssetDatabase 和 SharedRenderContext 需要 async 初始化。Token 注册时只创建实例,`init()` 由 Editor bootstrap 序列显式调用。++---++## Phase 2: 组件类型 Switch → Registry++**目标**:消除 `EditorSceneManager.removeComponentFromEntity()` 的 20+ case switch。++### 现状++| 位置 | 类型 | Cases | 改造价值 |+|------|------|-------|----------|+| `EditorSceneManager.removeComponentFromEntity()` | switch | 8 (Transform, Sprite, BitmapText, UIRect, UIMask, Text, TextInput, SpineAnimation) | 高 — 新组件必须散修改 |+| `ComponentSchemas.getDynamicOverrides()` | switch | 2 (Sprite, Canvas) | 低 — 极少变动 |++### 方案++新增 `COMPONENT_LIFECYCLE` token:++```typescript+interface ComponentLifecycle {+ add?: (world: World, entity: Entity, data: Record<string, unknown>) => void;+ remove?: (world: World, entity: Entity) => void;+ sync?: (world: World, entity: Entity, data: Record<string, unknown>) => void;+}++// tokens.ts+export const COMPONENT_LIFECYCLE = new ServiceToken<ComponentLifecycle>('ComponentLifecycle');++// sprite plugin 中注册+ctx.registrar.provide(COMPONENT_LIFECYCLE, 'Sprite', {+ add: (world, entity, data) => { world.insert(entity, Sprite, data); },+ remove: (world, entity) => { if (world.has(entity, Sprite)) world.remove(entity, Sprite); },+});++// TextInput plugin - 级联删除 Text+ctx.registrar.provide(COMPONENT_LIFECYCLE, 'TextInput', {+ remove: (world, entity) => {+ if (world.has(entity, TextInput)) world.remove(entity, TextInput);+ if (world.has(entity, Text)) world.remove(entity, Text);+ },+});+```++**EditorSceneManager** 改造后:+```typescript+removeComponentFromEntity(entityId: number, componentType: string): void {+ const lifecycle = getEditorContainer().get(COMPONENT_LIFECYCLE, componentType);+ if (lifecycle?.remove) {+ lifecycle.remove(this.world_, entity);+ }+}+```++### getDynamicOverrides 改造++合并到 `COMPONENT_SCHEMA` token 中:给 `ComponentSchema` 接口增加可选的 `editorDefaults?: () => Record<string, unknown>` 字段。++```typescript+// sprite plugin+const SpriteSchema: ComponentSchema = {+ name: 'Sprite',+ defaults: { ... },+ editorDefaults: () => ({+ size: {+ x: getSettingsValue('rendering.defaultSpriteWidth') ?? 100,+ y: getSettingsValue('rendering.defaultSpriteHeight') ?? 100,+ },+ }),+};+```++---++## Phase 3: 清理模块级状态泄漏++**目标**:项目切换时不残留旧状态。++### 问题清单++| 文件 | 状态 | 影响 |+|------|------|------|+| `io/SceneSerializer.ts` | `currentFileHandle` | 切换项目后可能指向旧文件 |+| `settings/SettingsDialog.ts` | `lastActiveSectionId_` | 低影响,UI 偏好 |+| `builder/BuildSettingsDialog.ts` | `activeDialog` | 对话框未关闭时切换 |++### 方案++Phase 1 完成后,这些状态可以挂在 IoC 容器上。容器 `dispose()` 时统一清理。对于仅是 UI 偏好的状态(如 lastActiveSectionId),可以保留模块级变量。++---++## Phase 4: 统一 Registry Query API++**目标**:消除各 Registry 模块(PanelRegistry、MenuRegistry、GizmoRegistry、InspectorRegistry、SettingsRegistry)中重复的 filter/sort 逻辑。++### 现状++每个 Registry 模块都实现了类似的模式:+```typescript+export function getAllXxx(): XxxDescriptor[] {+ return Array.from(getEditorContainer().getAll(XXX_TOKEN).values())+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+}+export function getXxx(id: string): XxxDescriptor | undefined {+ return getEditorContainer().get(XXX_TOKEN, id);+}+```++### 方案++给 EditorContainer 增加泛型查询方法:+```typescript+class EditorContainer {+ getOrdered<V extends { order?: number }>(token: ServiceToken<V>): V[] {+ return Array.from(this.getAll(token).values())+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ }++ filter<V>(token: ServiceToken<V>, pred: (v: V) => boolean): V[] {+ return Array.from(this.getAll(token).values()).filter(pred);+ }+}+```++这样各 Registry 的 `getAllXxx()` 函数可以简化为一行。++---++## 实施优先级++```+Phase 1(Singleton → IoC)+├── Batch 1: AssetEventBus + AssetDependencyGraph + ImporterRegistry [≤3 文件/服务]+├── Batch 2: GlobalPathResolver + EditorStore [中等]+├── Batch 3: SharedRenderContext [中等]+├── Batch 4: AssetDatabase [高影响]+└── Batch 5: PlayModeService [最后]++Phase 2(Switch → Registry)+├── COMPONENT_LIFECYCLE token + plugin 注册 [新 token]+├── 迁移 removeComponentFromEntity [核心改造]+└── 合并 getDynamicOverrides 到 ComponentSchema [小改动]++Phase 3(状态泄漏清理) [依赖 Phase 1]++Phase 4(统一 Registry Query) [独立,可随时做]+```++## 风险与约束++1. **Phase 1 的 getter 兼容层**:保留 `getXxx()` 函数避免大面积改动,但需确保 IoC 容器已初始化才能调用。在 Editor 构造前调用会 throw。+2. **Async init 服务**:AssetDatabase 和 SharedRenderContext 的 init 是异步的,注册到 IoC 时只创建空壳,需要 Editor bootstrap 显式调用 init。+3. **测试影响**:迁移后单测需要 mock EditorContainer 而非直接 mock 单例 getter。+4. **Phase 2 的 SpineAnimation**:destroySpineInstance 有复杂生命周期(C++ 资源释放),需要确保 COMPONENT_LIFECYCLE.remove 能访问 EditorSceneManager 的 spine 管理器。diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 3be71d01b..f0db87df0 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -97,14 +97,8 @@ export class Editor {constructor(container: HTMLElement, options?: EditorOptions) {this.container_ = container;- this.store_ = getEditorStore();this.projectPath_ = options?.projectPath ?? null;- this.panelManager_ = new PanelManager();- this.menuManager_ = new MenuManager();- this.menuManager_.setStore(this.store_);- this.previewManager_ = new PreviewManager(this.projectPath_);-const iocContainer = new EditorContainer();setEditorContainer(iocContainer);@@ -127,6 +121,12 @@ export class Editor {for (const plugin of builtinPlugins) {this.addPlugin(plugin);}++ this.store_ = getEditorStore();+ this.panelManager_ = new PanelManager();+ this.menuManager_ = new MenuManager();+ this.menuManager_.setStore(this.store_);+ this.previewManager_ = new PreviewManager(this.projectPath_);exposeRegistrationAPI();iocContainer.lockBuiltins();diff --git a/editor/src/__tests__/PlayModeService.test.ts b/editor/src/__tests__/PlayModeService.test.tsindex d3ac507a5..24665ed43 100644--- a/editor/src/__tests__/PlayModeService.test.ts+++ b/editor/src/__tests__/PlayModeService.test.ts@@ -90,6 +90,24 @@ vi.mock('../context/EditorContext', () => ({})),}));+const mockContainer = (() => {+ const stores = new Map<any, Map<string, any>>();+ return {+ provide: (token: any, key: string, value: any) => {+ if (!stores.has(token)) stores.set(token, new Map());+ stores.get(token)!.set(key, value);+ },+ get: (token: any, key: string) => stores.get(token)?.get(key),+ has: () => false,+ getAll: () => new Map(),+ };+})();++vi.mock('../container/EditorContainer', () => ({+ getEditorContainer: vi.fn(() => mockContainer),+ setEditorContainer: vi.fn(),+}));+vi.mock('../asset', () => ({getAssetDatabase: vi.fn(() => ({getAllEntries: vi.fn(() => mockDbEntries[Symbol.iterator]()),@@ -97,13 +115,15 @@ vi.mock('../asset', () => ({isUUID: vi.fn(() => false),}));-import { getPlayModeService } from '../services/PlayModeService';+import { getPlayModeService, PlayModeService } from '../services/PlayModeService';+import { PLAY_MODE_SERVICE } from '../container/tokens';describe('PlayModeService — SceneManager integration', () => {let service: ReturnType<typeof getPlayModeService>;beforeEach(() => {vi.clearAllMocks();+ mockContainer.provide(PLAY_MODE_SERVICE, 'default', new PlayModeService());service = getPlayModeService();});diff --git a/editor/src/asset/AssetDatabase.ts b/editor/src/asset/AssetDatabase.tsindex eecfef685..aa214853d 100644--- a/editor/src/asset/AssetDatabase.ts+++ b/editor/src/asset/AssetDatabase.ts@@ -543,17 +543,15 @@ export function getComponentRefFields(componentType: string): string[] | undefin// Singleton// =============================================================================-let instance: AssetDatabase | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { ASSET_DATABASE } from '../container/tokens';export function getAssetDatabase(): AssetDatabase {- if (!instance) {- instance = new AssetDatabase();- }- return instance;+ return getEditorContainer().get(ASSET_DATABASE, 'default')!;}export function resetAssetDatabase(): void {- instance = null;+ // no-op: lifecycle managed by IoC container}// Backward-compatible aliasesdiff --git a/editor/src/asset/AssetDependencyGraph.ts b/editor/src/asset/AssetDependencyGraph.tsindex 257d238ca..931762d50 100644--- a/editor/src/asset/AssetDependencyGraph.ts+++ b/editor/src/asset/AssetDependencyGraph.ts@@ -48,16 +48,16 @@ export class AssetDependencyGraph {}}-let graph: AssetDependencyGraph | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { ASSET_DEP_GRAPH } from '../container/tokens';++const SERVICE_KEY = 'default';export function getDependencyGraph(): AssetDependencyGraph {- if (!graph) {- graph = new AssetDependencyGraph();- }- return graph;+ return getEditorContainer().get(ASSET_DEP_GRAPH, SERVICE_KEY)!;}export function resetDependencyGraph(): void {+ const graph = getEditorContainer().get(ASSET_DEP_GRAPH, SERVICE_KEY);graph?.clear();- graph = null;}diff --git a/editor/src/asset/ImporterRegistry.ts b/editor/src/asset/ImporterRegistry.tsindex 3c445622c..3849db379 100644--- a/editor/src/asset/ImporterRegistry.ts+++ b/editor/src/asset/ImporterRegistry.ts@@ -56,7 +56,7 @@ const defaultImporter: AssetImporter<ImporterData> = {// ImporterRegistry// =============================================================================-class ImporterRegistryImpl {+export class ImporterRegistryImpl {private importers_ = new Map<string, AssetImporter<any>>();private extToType_ = new Map<string, string>();@@ -100,23 +100,28 @@ class ImporterRegistryImpl {}// =============================================================================-// Singleton+// IoC accessor// =============================================================================-let registry: ImporterRegistryImpl | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { IMPORTER_REGISTRY } from '../container/tokens';++const SERVICE_KEY = 'default';export function getImporterRegistry(): ImporterRegistryImpl {- if (!registry) {- registry = new ImporterRegistryImpl();- registry.register(new TextureImporter());- registry.register(new AudioImporter());- registry.register(new SpineImporter());- registry.register(new MaterialImporter());- registry.register(new ShaderImporter());- registry.register(new BitmapFontImporter());- registry.register(new SceneImporter());- registry.register(new PrefabImporter());- registry.register(new TimelineImporter());- }+ return getEditorContainer().get(IMPORTER_REGISTRY, SERVICE_KEY)!;+}++export function createImporterRegistry(): ImporterRegistryImpl {+ const registry = new ImporterRegistryImpl();+ registry.register(new TextureImporter());+ registry.register(new AudioImporter());+ registry.register(new SpineImporter());+ registry.register(new MaterialImporter());+ registry.register(new ShaderImporter());+ registry.register(new BitmapFontImporter());+ registry.register(new SceneImporter());+ registry.register(new PrefabImporter());+ registry.register(new TimelineImporter());return registry;}diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.tsindex 487692af9..9e4214a80 100644--- a/editor/src/asset/index.ts+++ b/editor/src/asset/index.ts@@ -65,12 +65,9 @@ export {} from './ImporterTypes';import { AssetPathResolver } from './AssetPathResolver';--let globalPathResolver: AssetPathResolver | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { GLOBAL_PATH_RESOLVER } from '../container/tokens';export function getGlobalPathResolver(): AssetPathResolver {- if (!globalPathResolver) {- globalPathResolver = new AssetPathResolver();- }- return globalPathResolver;+ return getEditorContainer().get(GLOBAL_PATH_RESOLVER, 'default')!;}diff --git a/editor/src/container/EditorContainer.ts b/editor/src/container/EditorContainer.tsindex 0aab69294..b188838c8 100644--- a/editor/src/container/EditorContainer.ts+++ b/editor/src/container/EditorContainer.ts@@ -57,6 +57,15 @@ export class EditorContainer implements PluginRegistrar {}}+ getOrdered<V extends { order?: number }>(token: ServiceToken<V>): V[] {+ return Array.from(this.getAll(token).values())+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ }++ filter<V>(token: ServiceToken<V>, pred: (v: V) => boolean): V[] {+ return Array.from(this.getAll(token).values()).filter(pred);+ }+clearExtensions(): void {for (const [token, map] of this.stores_) {const builtin = this.builtinKeys_.get(token);diff --git a/editor/src/container/tokens.ts b/editor/src/container/tokens.tsindex 49a191d55..ffbb98639 100644--- a/editor/src/container/tokens.ts+++ b/editor/src/container/tokens.ts@@ -9,6 +9,14 @@ import type { SettingsSectionDescriptor, SettingsGroupDescriptor, SettingsItemDeimport type { ContextMenuContribution } from '../ui/ContextMenuRegistry';import type { InspectorSectionDescriptor, ComponentInspectorDescriptor } from '../panels/inspector/InspectorRegistry';import type { AssetTypeDescriptor } from '../asset/AssetTypeRegistry';+import type { AssetEventBus } from '../events/AssetEventBus';+import type { AssetDependencyGraph } from '../asset/AssetDependencyGraph';+import type { ImporterRegistryImpl } from '../asset/ImporterRegistry';+import type { AssetPathResolver } from '../asset/AssetPathResolver';+import type { EditorStore } from '../store/EditorStore';+import type { SharedRenderContext } from '../renderer/SharedRenderContext';+import type { AssetDatabase } from '../asset/AssetDatabase';+import type { PlayModeService } from '../services/PlayModeService';export const COMPONENT_SCHEMA = new ServiceToken<ComponentSchema>('COMPONENT_SCHEMA');export const PROPERTY_EDITOR = new ServiceToken<PropertyEditorFactory>('PROPERTY_EDITOR');@@ -26,3 +34,16 @@ export const INSPECTOR_SECTION = new ServiceToken<InspectorSectionDescriptor>('Iexport const COMPONENT_INSPECTOR = new ServiceToken<ComponentInspectorDescriptor>('COMPONENT_INSPECTOR');export const ASSET_TYPE = new ServiceToken<AssetTypeDescriptor>('ASSET_TYPE');export const ASSET_EDITOR_TYPE = new ServiceToken<string>('ASSET_EDITOR_TYPE');+export const ASSET_EVENT_BUS = new ServiceToken<AssetEventBus>('ASSET_EVENT_BUS');+export const ASSET_DEP_GRAPH = new ServiceToken<AssetDependencyGraph>('ASSET_DEP_GRAPH');+export const IMPORTER_REGISTRY = new ServiceToken<ImporterRegistryImpl>('IMPORTER_REGISTRY');+export const GLOBAL_PATH_RESOLVER = new ServiceToken<AssetPathResolver>('GLOBAL_PATH_RESOLVER');+export const EDITOR_STORE = new ServiceToken<EditorStore>('EDITOR_STORE');+export const SHARED_RENDER_CTX = new ServiceToken<SharedRenderContext>('SHARED_RENDER_CTX');+export const ASSET_DATABASE = new ServiceToken<AssetDatabase>('ASSET_DATABASE');+export const PLAY_MODE_SERVICE = new ServiceToken<PlayModeService>('PLAY_MODE_SERVICE');++export interface ComponentLifecycle {+ remove(world: any, entity: any, entityId: number): void;+}+export const COMPONENT_LIFECYCLE = new ServiceToken<ComponentLifecycle>('COMPONENT_LIFECYCLE');diff --git a/editor/src/events/AssetEventBus.ts b/editor/src/events/AssetEventBus.tsindex 72cf269f7..18542fa0b 100644--- a/editor/src/events/AssetEventBus.ts+++ b/editor/src/events/AssetEventBus.ts@@ -43,16 +43,16 @@ export class AssetEventBus {}}-let bus: AssetEventBus | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { ASSET_EVENT_BUS } from '../container/tokens';++const SERVICE_KEY = 'default';export function getAssetEventBus(): AssetEventBus {- if (!bus) {- bus = new AssetEventBus();- }- return bus;+ return getEditorContainer().get(ASSET_EVENT_BUS, SERVICE_KEY)!;}export function resetAssetEventBus(): void {+ const bus = getEditorContainer().get(ASSET_EVENT_BUS, SERVICE_KEY);bus?.clear();- bus = null;}diff --git a/editor/src/gizmos/GizmoRegistry.ts b/editor/src/gizmos/GizmoRegistry.tsindex e44c15f4b..47f8adf2b 100644--- a/editor/src/gizmos/GizmoRegistry.ts+++ b/editor/src/gizmos/GizmoRegistry.ts@@ -39,6 +39,5 @@ export function getGizmo(id: string): GizmoDescriptor | undefined {}export function getAllGizmos(): GizmoDescriptor[] {- return Array.from(getEditorContainer().getAll(GIZMO).values())- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(GIZMO);}diff --git a/editor/src/menus/MenuRegistry.ts b/editor/src/menus/MenuRegistry.tsindex 8a986d540..f2444fe07 100644--- a/editor/src/menus/MenuRegistry.ts+++ b/editor/src/menus/MenuRegistry.ts@@ -42,21 +42,16 @@ export function registerStatusbarItem(item: StatusbarItemDescriptor): void {}export function getAllMenus(): MenuDescriptor[] {- return Array.from(getEditorContainer().getAll(MENU).values())- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(MENU);}export function getMenuItems(menuId: string): MenuItemDescriptor[] {- const result: MenuItemDescriptor[] = [];- for (const item of getEditorContainer().getAll(MENU_ITEM).values()) {- if (item.menu === menuId) result.push(item);- }- return result.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(MENU_ITEM)+ .filter(item => item.menu === menuId);}export function getAllStatusbarItems(): StatusbarItemDescriptor[] {- return Array.from(getEditorContainer().getAll(STATUSBAR_ITEM).values())- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(STATUSBAR_ITEM);}export function getMenuItem(id: string): MenuItemDescriptor | undefined {diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.tsindex 2f7dfc316..49bdc8a76 100644--- a/editor/src/panels/PanelRegistry.ts+++ b/editor/src/panels/PanelRegistry.ts@@ -55,8 +55,7 @@ export function getPanel(id: string): PanelDescriptor | undefined {}export function getAllPanels(): PanelDescriptor[] {- return Array.from(getEditorContainer().getAll(PANEL).values())- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(PANEL);}export function getPanelsByPosition(position: PanelPosition): PanelDescriptor[] {diff --git a/editor/src/panels/inspector/InspectorRegistry.ts b/editor/src/panels/inspector/InspectorRegistry.tsindex 609982fcc..5a7395bbd 100644--- a/editor/src/panels/inspector/InspectorRegistry.ts+++ b/editor/src/panels/inspector/InspectorRegistry.ts@@ -50,11 +50,8 @@ export function registerInspectorSection(descriptor: InspectorSectionDescriptor)}export function getInspectorSections(target: 'entity' | 'asset'): InspectorSectionDescriptor[] {- const result: InspectorSectionDescriptor[] = [];- for (const s of getEditorContainer().getAll(INSPECTOR_SECTION).values()) {- if (s.target === target || s.target === 'both') result.push(s);- }- return result.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(INSPECTOR_SECTION)+ .filter(s => s.target === target || s.target === 'both');}export function registerComponentInspector(descriptor: ComponentInspectorDescriptor): void {diff --git a/editor/src/plugins/assetInfra.ts b/editor/src/plugins/assetInfra.tsindex 3f7a214dc..11c5ee68c 100644--- a/editor/src/plugins/assetInfra.ts+++ b/editor/src/plugins/assetInfra.ts@@ -1,9 +1,30 @@import type { EditorPlugin, EditorPluginContext } from './EditorPlugin';import { registerBuiltinAssetTypes } from '../asset/AssetTypeRegistry';+import { AssetEventBus } from '../events/AssetEventBus';+import { AssetDependencyGraph } from '../asset/AssetDependencyGraph';+import { createImporterRegistry } from '../asset/ImporterRegistry';+import { AssetPathResolver } from '../asset/AssetPathResolver';+import { EditorStore } from '../store/EditorStore';+import { SharedRenderContext } from '../renderer/SharedRenderContext';+import { AssetDatabase } from '../asset/AssetDatabase';+import { PlayModeService } from '../services/PlayModeService';+import {+ ASSET_EVENT_BUS, ASSET_DEP_GRAPH, IMPORTER_REGISTRY,+ GLOBAL_PATH_RESOLVER, EDITOR_STORE, SHARED_RENDER_CTX,+ ASSET_DATABASE, PLAY_MODE_SERVICE,+} from '../container/tokens';export const assetInfraPlugin: EditorPlugin = {name: 'asset-infra',register(ctx: EditorPluginContext) {+ ctx.registrar.provide(ASSET_EVENT_BUS, 'default', new AssetEventBus());+ ctx.registrar.provide(ASSET_DEP_GRAPH, 'default', new AssetDependencyGraph());+ ctx.registrar.provide(IMPORTER_REGISTRY, 'default', createImporterRegistry());+ ctx.registrar.provide(GLOBAL_PATH_RESOLVER, 'default', new AssetPathResolver());+ ctx.registrar.provide(EDITOR_STORE, 'default', new EditorStore());+ ctx.registrar.provide(SHARED_RENDER_CTX, 'default', new SharedRenderContext());+ ctx.registrar.provide(ASSET_DATABASE, 'default', new AssetDatabase());+ ctx.registrar.provide(PLAY_MODE_SERVICE, 'default', new PlayModeService());registerBuiltinAssetTypes(ctx.registrar);},};diff --git a/editor/src/plugins/coreComponents.ts b/editor/src/plugins/coreComponents.tsindex c8d9e0cbf..7dd2aeb95 100644--- a/editor/src/plugins/coreComponents.ts+++ b/editor/src/plugins/coreComponents.ts@@ -1,6 +1,7 @@import type { EditorPlugin, EditorPluginContext } from './EditorPlugin';import type { ComponentSchema } from '../schemas/ComponentSchemas';import { COMPONENT_SCHEMA } from '../container/tokens';+import { getSettingsValue } from '../settings/SettingsRegistry';const NameSchema: ComponentSchema = {name: 'Name',@@ -60,6 +61,13 @@ const SceneOwnerSchema: ComponentSchema = {const CanvasSchema: ComponentSchema = {name: 'Canvas',category: 'builtin',+ editorDefaults: () => {+ const ppu = getSettingsValue<number>('rendering.pixelsPerUnit');+ if (ppu != null) {+ return { pixelsPerUnit: ppu };+ }+ return null;+ },properties: [{ name: 'designResolution', type: 'vec2' },{ name: 'pixelsPerUnit', type: 'number', min: 1, step: 1 },diff --git a/editor/src/plugins/importers.ts b/editor/src/plugins/importers.tsindex 5e6e68d65..54b9763ec 100644--- a/editor/src/plugins/importers.ts+++ b/editor/src/plugins/importers.ts@@ -1,10 +1,8 @@import type { EditorPlugin, EditorPluginContext } from './EditorPlugin';-import { getImporterRegistry } from '../asset/ImporterRegistry';export const importersPlugin: EditorPlugin = {name: 'importers',dependencies: ['asset-infra'],register(_ctx: EditorPluginContext) {- getImporterRegistry();},};diff --git a/editor/src/plugins/sprite.ts b/editor/src/plugins/sprite.tsindex 3cb950036..0ffaae342 100644--- a/editor/src/plugins/sprite.ts+++ b/editor/src/plugins/sprite.ts@@ -3,10 +3,19 @@ import type { ComponentSchema } from '../schemas/ComponentSchemas';import { spriteBoundsProvider } from '../bounds/SpriteBoundsProvider';import { COMPONENT_SCHEMA, BOUNDS_PROVIDER } from '../container/tokens';import { LAYER_MIN, LAYER_MAX } from '../schemas/schemaConstants';+import { getSettingsValue } from '../settings/SettingsRegistry';const SpriteSchema: ComponentSchema = {name: 'Sprite',category: 'builtin',+ editorDefaults: () => {+ const w = getSettingsValue<number>('rendering.defaultSpriteWidth');+ const h = getSettingsValue<number>('rendering.defaultSpriteHeight');+ if (w != null || h != null) {+ return { size: { x: w ?? 100, y: h ?? 100 } };+ }+ return null;+ },properties: [{ name: 'texture', type: 'texture' },{ name: 'material', type: 'material-file' },diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.tsindex 7288feeb4..b7424d7de 100644--- a/editor/src/renderer/SharedRenderContext.ts+++ b/editor/src/renderer/SharedRenderContext.ts@@ -412,16 +412,16 @@ export class SharedRenderContext {}}-let sharedInstance: SharedRenderContext | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { SHARED_RENDER_CTX } from '../container/tokens';export function getSharedRenderContext(): SharedRenderContext {- if (!sharedInstance) sharedInstance = new SharedRenderContext();- return sharedInstance;+ return getEditorContainer().get(SHARED_RENDER_CTX, 'default')!;}export function resetSharedRenderContext(): void {- if (sharedInstance) {- sharedInstance.dispose();- sharedInstance = null;+ const instance = getEditorContainer().get(SHARED_RENDER_CTX, 'default');+ if (instance) {+ instance.dispose();}}diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex 289314d19..ad00714f9 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -51,6 +51,8 @@ import { AssetPathResolver } from '../asset/AssetPathResolver';import { getDependencyGraph } from '../asset/AssetDependencyGraph';import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';import { getEditorContext } from '../context/EditorContext';+import { getEditorContainer } from '../container/EditorContainer';+import { COMPONENT_LIFECYCLE, type ComponentLifecycle } from '../container/tokens';import { getPlatformAdapter } from '../platform/PlatformAdapter';import {transformToMatrix4x4,@@ -109,6 +111,33 @@ export class EditorSceneManager {this.assetServer_ = new EditorAssetServer(module, pathResolver);this.postLoadHooks_.set('SpineAnimation', (id, data) => this.syncSpineInstance(id, data));this.postLoadHooks_.set('SpriteAnimator', (id, data) => this.applyAnimFirstFrame(id, data));+ this.registerComponentLifecycles_();+ }++ private registerComponentLifecycles_(): void {+ const container = getEditorContainer();+ const simpleRemove = (comp: any): ComponentLifecycle => ({+ remove: (world, entity) => {+ if (world.has(entity, comp)) world.remove(entity, comp);+ },+ });+ container.provide(COMPONENT_LIFECYCLE, 'Transform', simpleRemove(Transform));+ container.provide(COMPONENT_LIFECYCLE, 'Sprite', simpleRemove(Sprite));+ container.provide(COMPONENT_LIFECYCLE, 'BitmapText', simpleRemove(BitmapText));+ container.provide(COMPONENT_LIFECYCLE, 'UIRect', simpleRemove(UIRect));+ container.provide(COMPONENT_LIFECYCLE, 'UIMask', simpleRemove(UIMask));+ container.provide(COMPONENT_LIFECYCLE, 'Text', simpleRemove(Text));+ container.provide(COMPONENT_LIFECYCLE, 'TextInput', {+ remove: (world, entity) => {+ if (world.has(entity, TextInput)) world.remove(entity, TextInput);+ if (world.has(entity, Text)) world.remove(entity, Text);+ },+ });+ container.provide(COMPONENT_LIFECYCLE, 'SpineAnimation', {+ remove: (_world, _entity, entityId) => {+ this.destroySpineInstance(entityId);+ },+ });}setProjectDir(projectDir: string): void {@@ -403,32 +432,9 @@ export class EditorSceneManager {removeComponentFromEntity(entityId: number, componentType: string): void {const entity = this.entityMap_.get(entityId);if (entity === undefined) return;- switch (componentType) {- case 'Transform':- if (this.world_.has(entity, Transform)) this.world_.remove(entity, Transform);- break;- case 'Sprite':- if (this.world_.has(entity, Sprite)) this.world_.remove(entity, Sprite);- break;- case 'BitmapText':- if (this.world_.has(entity, BitmapText)) this.world_.remove(entity, BitmapText);- break;- case 'UIRect':- if (this.world_.has(entity, UIRect)) this.world_.remove(entity, UIRect);- break;- case 'UIMask':- if (this.world_.has(entity, UIMask)) this.world_.remove(entity, UIMask);- break;- case 'Text':- if (this.world_.has(entity, Text)) this.world_.remove(entity, Text);- break;- case 'TextInput':- if (this.world_.has(entity, TextInput)) this.world_.remove(entity, TextInput);- if (this.world_.has(entity, Text)) this.world_.remove(entity, Text);- break;- case 'SpineAnimation':- this.destroySpineInstance(entityId);- break;+ const lifecycle = getEditorContainer().get(COMPONENT_LIFECYCLE, componentType);+ if (lifecycle) {+ lifecycle.remove(this.world_, entity, entityId);}}diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex a5660c0f9..1e621757d 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -1,6 +1,5 @@import type { PropertyMeta } from '../property/PropertyEditor';import { getComponentDefaults } from 'esengine';-import { getSettingsValue } from '../settings/SettingsRegistry';import { getEditorContainer } from '../container';import { COMPONENT_SCHEMA } from '../container/tokens';@@ -13,6 +12,7 @@ export interface ComponentSchema {removable?: boolean;hidden?: boolean;displayName?: string;+ editorDefaults?: () => Record<string, unknown> | null;}function isVec2(v: unknown): boolean {@@ -134,25 +134,11 @@ const editorInitialOverrides: Record<string, Record<string, unknown>> = {};function getDynamicOverrides(typeName: string): Record<string, unknown> | null {- switch (typeName) {- case 'Sprite': {- const w = getSettingsValue<number>('rendering.defaultSpriteWidth');- const h = getSettingsValue<number>('rendering.defaultSpriteHeight');- if (w != null || h != null) {- return { size: { x: w ?? 100, y: h ?? 100 } };- }- return null;- }- case 'Canvas': {- const ppu = getSettingsValue<number>('rendering.pixelsPerUnit');- if (ppu != null) {- return { pixelsPerUnit: ppu };- }- return null;- }- default:- return null;+ const schema = getEditorContainer().get(COMPONENT_SCHEMA, typeName);+ if (schema?.editorDefaults) {+ return schema.editorDefaults();}+ return null;}export function getInitialComponentData(typeName: string): Record<string, unknown> {diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.tsindex f12dede02..435ac3887 100644--- a/editor/src/services/PlayModeService.ts+++ b/editor/src/services/PlayModeService.ts@@ -42,7 +42,7 @@ export function runtimeToEntityData(re: RuntimeEntityData): EntityData {};}-class PlayModeService {+export class PlayModeService {private state_: PlayState = 'stopped';private selectedEntityId_: number | null = null;private cachedEntities_: RuntimeEntityData[] = [];@@ -391,9 +391,9 @@ class PlayModeService {}}-let instance: PlayModeService | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { PLAY_MODE_SERVICE } from '../container/tokens';export function getPlayModeService(): PlayModeService {- if (!instance) instance = new PlayModeService();- return instance;+ return getEditorContainer().get(PLAY_MODE_SERVICE, 'default')!;}diff --git a/editor/src/settings/SettingsRegistry.ts b/editor/src/settings/SettingsRegistry.tsindex 3a860772b..d171a5084 100644--- a/editor/src/settings/SettingsRegistry.ts+++ b/editor/src/settings/SettingsRegistry.ts@@ -141,32 +141,27 @@ export function onSettingsChange(listener: SettingsChangeListener): () => void {}export function getAllSections(): SettingsSectionDescriptor[] {- return [...getEditorContainer().getAll(SETTINGS_SECTION).values()]- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(SETTINGS_SECTION);}export function getSectionItems(sectionId: string): SettingsItemDescriptor[] {- return [...getEditorContainer().getAll(SETTINGS_ITEM).values()]- .filter(item => item.section === sectionId)- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(SETTINGS_ITEM)+ .filter(item => item.section === sectionId);}export function getSectionGroups(sectionId: string): SettingsGroupDescriptor[] {- return [...getEditorContainer().getAll(SETTINGS_GROUP).values()]- .filter(g => g.section === sectionId)- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(SETTINGS_GROUP)+ .filter(g => g.section === sectionId);}export function getGroupItems(groupId: string): SettingsItemDescriptor[] {- return [...getEditorContainer().getAll(SETTINGS_ITEM).values()]- .filter(item => item.group === groupId)- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(SETTINGS_ITEM)+ .filter(item => item.group === groupId);}export function getUngroupedSectionItems(sectionId: string): SettingsItemDescriptor[] {- return [...getEditorContainer().getAll(SETTINGS_ITEM).values()]- .filter(item => item.section === sectionId && !item.group)- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ return getEditorContainer().getOrdered(SETTINGS_ITEM)+ .filter(item => item.section === sectionId && !item.group);}export function searchSettings(query: string): SettingsItemDescriptor[] {diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 0d343c644..e9000151a 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -702,18 +702,16 @@ export class EditorStore {}// =============================================================================-// Singleton Instance+// IoC accessor// =============================================================================-let editorStore: EditorStore | null = null;+import { getEditorContainer } from '../container/EditorContainer';+import { EDITOR_STORE } from '../container/tokens';export function getEditorStore(): EditorStore {- if (!editorStore) {- editorStore = new EditorStore();- }- return editorStore;+ return getEditorContainer().get(EDITOR_STORE, 'default')!;}export function resetEditorStore(): void {- editorStore = null;+ // no-op: lifecycle managed by IoC container}