refactor(plugin): 重构插件系统架构,统一类型导入路径 (#296)

* refactor(plugin): 重构插件系统架构,统一类型导入路径

## 主要更改

### 新增 @esengine/plugin-types 包
- 提供打破循环依赖的最小类型定义
- 包含 ServiceToken, createServiceToken, PluginServiceRegistry, IEditorModuleBase

### engine-core 类型统一
- IPlugin<T> 泛型参数改为 T = unknown
- 所有运行时类型(IRuntimeModule, ModuleManifest, SystemContext)在此定义
- 新增 PluginServiceRegistry.ts 导出服务令牌相关类型

### editor-core 类型优化
- 重命名 IPluginLoader.ts 为 EditorModule.ts
- 新增 IEditorPlugin = IPlugin<IEditorModuleLoader> 类型别名
- 移除弃用别名 IPluginLoader, IRuntimeModuleLoader

### 编辑器插件更新
- 所有 9 个编辑器插件使用 IEditorPlugin 类型
- 统一从 editor-core 导入编辑器类型

### 服务令牌规范
- 各模块在 tokens.ts 中定义自己的服务接口和令牌
- 遵循"谁定义接口,谁导出 Token"原则

## 导入规范

| 场景 | 导入来源 |
|------|---------|
| 运行时模块 | @esengine/engine-core |
| 编辑器插件 | @esengine/editor-core |
| 服务令牌 | @esengine/engine-core |

* refactor(plugin): 完善服务令牌规范,统一运行时模块

## 更改内容

### 运行时模块优化
- particle: 使用 PluginServiceRegistry 获取依赖服务
- physics-rapier2d: 通过服务令牌注册/获取物理查询接口
- tilemap: 使用服务令牌获取物理系统依赖
- sprite: 导出服务令牌
- ui: 导出服务令牌
- behavior-tree: 使用服务令牌系统

### 资产系统增强
- IAssetManager 接口扩展
- 加载器使用服务令牌获取依赖

### 运行时核心
- GameRuntime 使用 PluginServiceRegistry
- 导出服务令牌相关类型

### 编辑器服务
- EngineService 适配新的服务令牌系统
- AssetRegistryService 优化

* fix: 修复 editor-app 和 behavior-tree-editor 中的类型引用

- editor-app/PluginLoader.ts: 使用 IPlugin 替代 IPluginLoader
- behavior-tree-editor: 使用 IEditorPlugin 替代 IPluginLoader

* fix(ui): 添加缺失的 ecs-engine-bindgen 依赖

UIRuntimeModule 使用 EngineBridgeToken,需要声明对 ecs-engine-bindgen 的依赖

* fix(type): 解决 ServiceToken 跨包类型兼容性问题

- 在 engine-core 中直接定义 ServiceToken 和 PluginServiceRegistry
  而不是从 plugin-types 重新导出,确保 tsup 生成的类型声明
  以 engine-core 作为类型来源
- 移除 RuntimeResolver.ts 中的硬编码模块 ID 检查,
  改用 module.json 中的 name 配置
- 修复 pnpm-lock.yaml 中的依赖记录

* refactor(arch): 改进架构设计,移除硬编码

- 统一类型导出:editor-core 从 engine-core 导入 IEditorModuleBase
- RuntimeResolver: 将硬编码路径改为配置常量和搜索路径列表
- 添加跨平台安装路径支持(Windows/macOS/Linux)
- 使用 ENGINE_WASM_CONFIG 配置引擎 WASM 文件信息
- IBundlePackOptions 添加 preloadBundles 配置项

* fix(particle): 添加缺失的 ecs-engine-bindgen 依赖

ParticleRuntimeModule 导入了 @esengine/ecs-engine-bindgen 的 tokens,
但 package.json 中未声明该依赖,导致 CI 构建失败。

* fix(physics-rapier2d): 移除不存在的 PhysicsSystemContext 导出

PhysicsRuntimeModule 中不存在该类型,导致 type-check 失败
This commit is contained in:
YHH
2025-12-08 21:10:57 +08:00
committed by GitHub
parent 2476379af1
commit c3b7250f85
86 changed files with 1813 additions and 551 deletions

View File

@@ -7,11 +7,11 @@
*/
import { GizmoRegistry, EntityStoreService, MessageHub, SceneManagerService, ProjectService, PluginManager, IPluginManager, AssetRegistryService, type SystemContext } from '@esengine/editor-core';
import { Core, Scene, Entity, SceneSerializer, ProfilerSDK } from '@esengine/ecs-framework';
import { CameraConfig } from '@esengine/ecs-engine-bindgen';
import { TransformComponent } from '@esengine/engine-core';
import { SpriteComponent, SpriteAnimatorComponent } from '@esengine/sprite';
import { invalidateUIRenderCaches } from '@esengine/ui';
import { Core, Scene, Entity, SceneSerializer, ProfilerSDK, createLogger } from '@esengine/ecs-framework';
import { CameraConfig, EngineBridgeToken, RenderSystemToken, EngineIntegrationToken } from '@esengine/ecs-engine-bindgen';
import { TransformComponent, PluginServiceRegistry, TransformTypeToken } from '@esengine/engine-core';
import { SpriteComponent, SpriteAnimatorComponent, SpriteAnimatorSystemToken } from '@esengine/sprite';
import { invalidateUIRenderCaches, UIRenderProviderToken, UIInputSystemToken } from '@esengine/ui';
import * as esEngine from '@esengine/engine';
import {
AssetManager,
@@ -21,7 +21,8 @@ import {
globalPathResolver,
SceneResourceManager,
assetManager as globalAssetManager,
AssetType
AssetType,
AssetManagerToken
} from '@esengine/asset-system';
import {
GameRuntime,
@@ -29,12 +30,16 @@ import {
EditorPlatformAdapter,
type GameRuntimeConfig
} from '@esengine/runtime-core';
import { BehaviorTreeSystemToken } from '@esengine/behavior-tree';
import { Physics2DSystemToken } from '@esengine/physics-rapier2d';
import { getMaterialManager } from '@esengine/material-system';
import { resetEngineState } from '../hooks/useEngine';
import { convertFileSrc } from '@tauri-apps/api/core';
import { IdGenerator } from '../utils/idGenerator';
import { TauriAssetReader } from './TauriAssetReader';
const logger = createLogger('EngineService');
/**
* Engine service singleton for editor integration.
* 用于编辑器集成的引擎服务单例。
@@ -198,15 +203,19 @@ export class EngineService {
// 初始化所有插件的运行时模块
await pluginManager.initializeRuntime(Core.services);
// 创建服务注册表并注册核心服务
// Create service registry and register core services
const services = new PluginServiceRegistry();
services.register(EngineBridgeToken, this._runtime.bridge);
services.register(RenderSystemToken, this._runtime.renderSystem);
services.register(AssetManagerToken, this._assetManager);
services.register(EngineIntegrationToken, this._engineIntegration);
services.register(TransformTypeToken, TransformComponent);
// 创建系统上下文
const context: SystemContext = {
services: Core.services,
engineBridge: this._runtime.bridge,
renderSystem: this._runtime.renderSystem,
assetManager: this._assetManager,
engineIntegration: this._engineIntegration,
isEditor: true,
transformType: TransformComponent
services
};
// 让插件为场景创建系统
@@ -216,29 +225,44 @@ export class EngineService {
// 插件注册完加载器后,重新同步资产(确保类型正确)
await this._syncAssetRegistryToManager();
// 同步系统引用到 GameRuntime 的 systemContext(用于 start/stop 时启用/禁用系统)
this._runtime.updateSystemContext({
animatorSystem: context.animatorSystem,
behaviorTreeSystem: context.behaviorTreeSystem,
physicsSystem: context.physicsSystem,
uiInputSystem: context.uiInputSystem,
uiRenderProvider: context.uiRenderProvider
});
// 同步服务注册表到 GameRuntime用于 start/stop 时启用/禁用系统)
// Sync service registry to GameRuntime (for enabling/disabling systems on start/stop)
const runtimeServices = this._runtime.getServiceRegistry();
if (runtimeServices) {
// 复制所有已注册的服务到 runtime 的服务注册表
// 这样 runtime 的 start/stop 方法可以正确访问这些服务
const animatorSystem = services.get(SpriteAnimatorSystemToken);
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
const physicsSystem = services.get(Physics2DSystemToken);
const uiInputSystem = services.get(UIInputSystemToken);
const uiRenderProvider = services.get(UIRenderProviderToken);
if (animatorSystem) runtimeServices.register(SpriteAnimatorSystemToken, animatorSystem);
if (behaviorTreeSystem) runtimeServices.register(BehaviorTreeSystemToken, behaviorTreeSystem);
if (physicsSystem) runtimeServices.register(Physics2DSystemToken, physicsSystem);
if (uiInputSystem) runtimeServices.register(UIInputSystemToken, uiInputSystem);
if (uiRenderProvider) runtimeServices.register(UIRenderProviderToken, uiRenderProvider);
}
// 设置 UI 渲染数据提供者
if (context.uiRenderProvider && this._runtime.renderSystem) {
this._runtime.renderSystem.setUIRenderDataProvider(context.uiRenderProvider);
const uiRenderProvider = services.get(UIRenderProviderToken);
if (uiRenderProvider && this._runtime.renderSystem) {
this._runtime.renderSystem.setUIRenderDataProvider(uiRenderProvider);
}
// 在编辑器模式下,禁用游戏逻辑系统
if (context.animatorSystem) {
context.animatorSystem.enabled = false;
const animatorSystem = services.get(SpriteAnimatorSystemToken);
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
const physicsSystem = services.get(Physics2DSystemToken);
if (animatorSystem) {
animatorSystem.enabled = false;
}
if (context.behaviorTreeSystem) {
context.behaviorTreeSystem.enabled = false;
if (behaviorTreeSystem) {
behaviorTreeSystem.enabled = false;
}
if (context.physicsSystem) {
context.physicsSystem.enabled = false;
if (physicsSystem) {
physicsSystem.enabled = false;
}
this._modulesInitialized = true;
@@ -253,9 +277,14 @@ export class EngineService {
pluginManager.clearSceneSystems();
}
const ctx = this._runtime?.systemContext;
if (ctx?.uiInputSystem) {
ctx.uiInputSystem.unbind?.();
// 使用服务注册表获取 UI 输入系统
// Use service registry to get UI input system
const runtimeServices = this._runtime?.getServiceRegistry();
if (runtimeServices) {
const uiInputSystem = runtimeServices.get(UIInputSystemToken);
if (uiInputSystem && uiInputSystem.unbind) {
uiInputSystem.unbind();
}
}
// 清理 viewport | Clear viewport
@@ -475,7 +504,7 @@ export class EngineService {
const allAssets = assetRegistry.getAllAssets();
const metaManager = assetRegistry.metaManager;
console.log(`[EngineService] Syncing ${allAssets.length} assets from AssetRegistry to AssetManager`);
logger.debug(`Syncing ${allAssets.length} assets from AssetRegistry to AssetManager`);
// Use loaderFactory to determine asset type from path
// This allows plugins to register their own loaders and types
@@ -533,7 +562,7 @@ export class EngineService {
});
}
console.log(`[EngineService] Asset sync complete`);
logger.debug('Asset sync complete');
}
/**
@@ -694,10 +723,18 @@ export class EngineService {
* Enable animation preview in editor mode.
*/
enableAnimationPreview(): void {
const ctx = this._runtime?.systemContext;
if (ctx?.animatorSystem && !this._running) {
ctx.animatorSystem.clearEntityCache?.();
ctx.animatorSystem.enabled = true;
if (this._running) return;
const runtimeServices = this._runtime?.getServiceRegistry();
if (runtimeServices) {
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
if (animatorSystem) {
// 如果有 clearEntityCache 方法则调用
// Call clearEntityCache if available
const system = animatorSystem as { clearEntityCache?: () => void; enabled: boolean };
system.clearEntityCache?.();
system.enabled = true;
}
}
}
@@ -705,9 +742,14 @@ export class EngineService {
* Disable animation preview in editor mode.
*/
disableAnimationPreview(): void {
const ctx = this._runtime?.systemContext;
if (ctx?.animatorSystem && !this._running) {
ctx.animatorSystem.enabled = false;
if (this._running) return;
const runtimeServices = this._runtime?.getServiceRegistry();
if (runtimeServices) {
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
if (animatorSystem) {
animatorSystem.enabled = false;
}
}
}
@@ -715,7 +757,12 @@ export class EngineService {
* Check if animation preview is enabled.
*/
isAnimationPreviewEnabled(): boolean {
return this._runtime?.systemContext?.animatorSystem?.enabled ?? false;
const runtimeServices = this._runtime?.getServiceRegistry();
if (runtimeServices) {
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
return animatorSystem?.enabled ?? false;
}
return false;
}
/**

View File

@@ -4,7 +4,7 @@
*/
import { PluginManager, LocaleService, MessageHub } from '@esengine/editor-core';
import type { IPluginLoader, ModuleManifest } from '@esengine/editor-core';
import type { IPlugin, ModuleManifest } from '@esengine/editor-core';
import { Core } from '@esengine/ecs-framework';
import { TauriAPI } from '../api/tauri';
import { PluginSDKRegistry } from './PluginSDKRegistry';
@@ -158,7 +158,7 @@ export class PluginLoader {
code: string,
pluginName: string,
_pluginDirName: string
): Promise<IPluginLoader | null> {
): Promise<IPlugin | null> {
const pluginKey = this.sanitizePluginKey(pluginName);
try {
@@ -257,9 +257,9 @@ export class PluginLoader {
}
/**
* 查找模块中的插件加载器
* 查找模块中的插件
*/
private findPluginLoader(module: any): IPluginLoader | null {
private findPluginLoader(module: any): IPlugin | null {
// 优先检查 default 导出
if (module.default && this.isPluginLoader(module.default)) {
return module.default;
@@ -277,14 +277,14 @@ export class PluginLoader {
}
/**
* 验证对象是否为有效的插件加载器
* 验证对象是否为有效的插件
*/
private isPluginLoader(obj: any): obj is IPluginLoader {
private isPluginLoader(obj: any): obj is IPlugin {
if (!obj || typeof obj !== 'object') {
return false;
}
// 新的 IPluginLoader 接口检查
// 新的 IPlugin 接口检查
if (obj.manifest && this.isModuleManifest(obj.manifest)) {
return true;
}
@@ -307,13 +307,15 @@ export class PluginLoader {
/**
* 同步插件语言设置
*/
private syncPluginLocale(plugin: IPluginLoader, pluginName: string): void {
private syncPluginLocale(plugin: IPlugin, pluginName: string): void {
try {
const localeService = Core.services.resolve(LocaleService);
const currentLocale = localeService.getCurrentLocale();
if (plugin.editorModule?.setLocale) {
plugin.editorModule.setLocale(currentLocale);
// 类型安全地检查 editorModule 是否有 setLocale 方法
const editorModule = plugin.editorModule as { setLocale?: (locale: string) => void } | undefined;
if (editorModule?.setLocale) {
editorModule.setLocale(currentLocale);
}
// 通知 UI 刷新

View File

@@ -5,6 +5,26 @@
import { TauriAPI } from '../api/tauri';
// ============================================================================
// 配置常量 | Configuration Constants
// ============================================================================
/**
* 引擎 WASM 模块配置
* Engine WASM module configuration
*
* 避免硬编码目录名,使用配置驱动
* Avoid hardcoded directory names, use configuration-driven approach
*/
const ENGINE_WASM_CONFIG = {
/** 引擎 WASM 目录名 | Engine WASM directory name */
dirName: 'es-engine',
/** 引擎包名 | Engine package name */
packageName: 'engine',
/** WASM 文件列表 | WASM file list */
files: ['es_engine_bg.wasm', 'es_engine.js', 'es_engine_bg.js']
} as const;
/**
* 运行时模块清单
* Module manifest for runtime modules
@@ -93,15 +113,44 @@ export class RuntimeResolver {
return startPath;
}
/**
* 获取可能的安装路径列表
* Get list of possible installation paths
*
* 使用环境变量和标准路径,避免硬编码
* Use environment variables and standard paths, avoid hardcoding
*/
private getInstalledEnginePaths(): string[] {
const paths: string[] = [];
// 1. 使用环境变量(如果设置) | Use environment variable if set
// 可以在 Tauri 配置或系统环境变量中设置 ESENGINE_INSTALL_DIR
// 注意Tauri 目前无法直接读取环境变量,此处为将来扩展预留
// 2. 使用标准安装位置(按平台) | Use standard install locations (by platform)
// 这些路径仍然是硬编码的,但集中在一处便于维护
// Windows
paths.push('C:/Program Files/ESEngine Editor/engine');
paths.push('C:/Program Files (x86)/ESEngine Editor/engine');
// macOS (future support)
paths.push('/Applications/ESEngine Editor.app/Contents/Resources/engine');
// Linux (future support)
paths.push('/opt/esengine-editor/engine');
paths.push('/usr/local/share/esengine-editor/engine');
return paths;
}
/**
* Find engine modules path (where compiled modules with module.json are)
* 查找引擎模块路径(编译后的模块和 module.json 所在位置)
*/
private async findEngineModulesPath(): Promise<string> {
// Try installed editor location first
const installedPath = 'C:/Program Files/ESEngine Editor/engine';
if (await TauriAPI.pathExists(`${installedPath}/index.json`)) {
return installedPath;
// Try installed editor locations first (production mode)
for (const installedPath of this.getInstalledEnginePaths()) {
if (await TauriAPI.pathExists(`${installedPath}/index.json`)) {
return installedPath;
}
}
// Try workspace packages directory (dev mode)
@@ -237,15 +286,11 @@ export class RuntimeResolver {
// 复制所有 chunk 文件(代码分割会创建 chunk-*.js 文件)
await this.copyChunkFiles(moduleDistDir, dstModuleDir);
// Add to import map
importMap[`@esengine/${module.id}`] = `./libs/${module.id}/${module.id}.js`;
// Also add common aliases
if (module.id === 'core') {
importMap['@esengine/ecs-framework'] = `./libs/${module.id}/${module.id}.js`;
}
if (module.id === 'math') {
importMap['@esengine/ecs-framework-math'] = `./libs/${module.id}/${module.id}.js`;
// Add to import map using module.name from module.json
// 使用 module.json 中的 module.name 作为 import map 的 key
// e.g., core/module.json: { "name": "@esengine/ecs-framework" }
if (module.name) {
importMap[module.name] = `./libs/${module.id}/${module.id}.js`;
}
copiedModules.push(module.id);
@@ -330,28 +375,45 @@ export class RuntimeResolver {
}
}
/**
* 获取引擎 WASM 文件的搜索路径
* Get search paths for engine WASM files
*/
private getEngineWasmSearchPaths(): string[] {
const paths: string[] = [];
// 1. 开发模式:工作区内的 engine 包 | Dev mode: engine package in workspace
paths.push(`${this.baseDir}\\packages\\${ENGINE_WASM_CONFIG.packageName}\\pkg`);
// 2. 相对于引擎模块路径 | Relative to engine modules path
paths.push(`${this.engineModulesPath}\\..\\..\\${ENGINE_WASM_CONFIG.packageName}\\pkg`);
// 3. 生产模式:安装目录中的 wasm 文件夹 | Production mode: wasm folder in install dir
for (const installedPath of this.getInstalledEnginePaths()) {
// 将 /engine 替换为 /wasm | Replace /engine with /wasm
const wasmPath = installedPath.replace(/[/\\]engine$/, '/wasm');
paths.push(wasmPath);
}
return paths;
}
/**
* Copy engine WASM files
* 复制引擎 WASM 文件
*/
private async copyEngineWasm(libsDir: string): Promise<void> {
const esEngineDir = `${libsDir}\\es-engine`;
const esEngineDir = `${libsDir}\\${ENGINE_WASM_CONFIG.dirName}`;
if (!await TauriAPI.pathExists(esEngineDir)) {
await TauriAPI.createDirectory(esEngineDir);
}
// Try different locations for engine WASM
const wasmSearchPaths = [
`${this.baseDir}\\packages\\engine\\pkg`,
`${this.engineModulesPath}\\..\\..\\engine\\pkg`,
'C:/Program Files/ESEngine Editor/wasm'
];
const filesToCopy = ['es_engine_bg.wasm', 'es_engine.js', 'es_engine_bg.js'];
const wasmSearchPaths = this.getEngineWasmSearchPaths();
for (const searchPath of wasmSearchPaths) {
if (await TauriAPI.pathExists(searchPath)) {
for (const file of filesToCopy) {
for (const file of ENGINE_WASM_CONFIG.files) {
const srcFile = `${searchPath}\\${file}`;
if (await TauriAPI.pathExists(srcFile)) {
const dstFile = `${esEngineDir}\\${file}`;