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

@@ -42,6 +42,7 @@
"@esengine/ecs-framework": "workspace:*",
"@esengine/ecs-framework-math": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/ecs-engine-bindgen": "workspace:*",
"@esengine/physics-rapier2d": "workspace:*",
"@esengine/build-config": "workspace:*",
"rimraf": "^5.0.5",

View File

@@ -62,8 +62,23 @@ export interface Particle {
/** 初始透明度 | Initial alpha */
startAlpha: number;
// ============= 模块运行时状态 | Module Runtime State =============
// 这些字段由各模块在运行时设置 | These fields are set by modules at runtime
/** 初始速度XVelocityOverLifetimeModule 使用)| Initial velocity X (used by VelocityOverLifetimeModule) */
startVx?: number;
/** 初始速度YVelocityOverLifetimeModule 使用)| Initial velocity Y (used by VelocityOverLifetimeModule) */
startVy?: number;
/** 动画帧索引TextureSheetAnimationModule 使用)| Animation frame index (used by TextureSheetAnimationModule) */
_animFrame?: number;
/** 动画图块列数TextureSheetAnimationModule 使用)| Animation tiles X (used by TextureSheetAnimationModule) */
_animTilesX?: number;
/** 动画图块行数TextureSheetAnimationModule 使用)| Animation tiles Y (used by TextureSheetAnimationModule) */
_animTilesY?: number;
/** 自定义数据槽 | Custom data slot */
userData?: any;
userData?: unknown;
}
/**

View File

@@ -1,60 +1,19 @@
import type { ComponentRegistry as ComponentRegistryType, IScene } from '@esengine/ecs-framework';
import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
import { assetManager as globalAssetManager, type AssetManager } from '@esengine/asset-system';
import { TransformTypeToken } from '@esengine/engine-core';
import { AssetManagerToken } from '@esengine/asset-system';
import { RenderSystemToken, EngineBridgeToken, EngineIntegrationToken } from '@esengine/ecs-engine-bindgen';
import { Physics2DQueryToken } from '@esengine/physics-rapier2d';
import { assetManager as globalAssetManager } from '@esengine/asset-system';
import { ParticleSystemComponent } from './ParticleSystemComponent';
import { ParticleUpdateSystem } from './systems/ParticleSystem';
import { ParticleLoader, ParticleAssetType } from './loaders/ParticleLoader';
import type { IPhysics2DQuery } from './modules/Physics2DCollisionModule';
import { ParticleUpdateSystemToken } from './tokens';
export type { SystemContext, ModuleManifest, IRuntimeModule as IRuntimeModuleLoader, IPlugin as IPluginLoader };
export type { SystemContext, ModuleManifest, IRuntimeModule, IPlugin };
/**
* 引擎桥接接口(用于直接加载纹理)
* Engine bridge interface (for direct texture loading)
*/
export interface IEngineBridge {
loadTexture(id: number, url: string): Promise<void>;
}
/**
* 引擎集成接口(用于加载纹理)
* Engine integration interface (for loading textures)
*/
export interface IEngineIntegration {
loadTextureForComponent(texturePath: string): Promise<number>;
}
/**
* 粒子系统上下文
* Particle system context
*/
export interface ParticleSystemContext extends SystemContext {
particleUpdateSystem?: ParticleUpdateSystem;
/** Transform 组件类型 | Transform component type */
transformType?: new (...args: any[]) => any;
/** 渲染系统(用于注册渲染数据提供者)| Render system (for registering render data provider) */
renderSystem?: {
addRenderDataProvider(provider: any): void;
removeRenderDataProvider(provider: any): void;
};
/** 引擎集成(用于加载纹理)| Engine integration (for loading textures) */
engineIntegration?: IEngineIntegration;
/** 引擎桥接(用于直接加载纹理)| Engine bridge (for direct texture loading) */
engineBridge?: IEngineBridge;
/** 资产管理器(用于注册加载器)| Asset manager (for registering loaders) */
assetManager?: AssetManager;
/**
* 2D 物理查询接口(可选)
* 2D Physics query interface (optional)
*
* 如果提供,将自动注入到使用 Physics2DCollisionModule 的粒子系统中。
* 通常传入 Physics2DService 实例。
*
* If provided, will be auto-injected into particle systems using Physics2DCollisionModule.
* Typically pass a Physics2DService instance.
*/
physics2DQuery?: IPhysics2DQuery;
}
// 重新导出 tokens | Re-export tokens
export { ParticleUpdateSystemToken } from './tokens';
class ParticleRuntimeModule implements IRuntimeModule {
private _updateSystem: ParticleUpdateSystem | null = null;
@@ -65,7 +24,13 @@ class ParticleRuntimeModule implements IRuntimeModule {
}
createSystems(scene: IScene, context: SystemContext): void {
const particleContext = context as ParticleSystemContext;
// 从服务注册表获取依赖 | Get dependencies from service registry
const assetManager = context.services.get(AssetManagerToken);
const transformType = context.services.get(TransformTypeToken);
const engineIntegration = context.services.get(EngineIntegrationToken);
const engineBridge = context.services.get(EngineBridgeToken);
const physics2DQuery = context.services.get(Physics2DQueryToken);
const renderSystem = context.services.get(RenderSystemToken);
// 注册粒子资产加载器到上下文的 assetManager 和全局单例
// Register particle asset loader to context assetManager AND global singleton
@@ -73,13 +38,13 @@ class ParticleRuntimeModule implements IRuntimeModule {
const loader = new ParticleLoader();
// Register to context's assetManager (used by GameRuntime)
if (particleContext.assetManager) {
particleContext.assetManager.registerLoader(ParticleAssetType as any, loader);
if (assetManager) {
assetManager.registerLoader(ParticleAssetType, loader);
}
// Also register to global singleton (used by ParticleSystemComponent.loadAsset)
// 同时注册到全局单例ParticleSystemComponent.loadAsset 使用的是全局单例)
globalAssetManager.registerLoader(ParticleAssetType as any, loader);
globalAssetManager.registerLoader(ParticleAssetType, loader);
this._loaderRegistered = true;
console.log('[ParticleRuntimeModule] Registered ParticleLoader to both context and global assetManager');
@@ -88,32 +53,34 @@ class ParticleRuntimeModule implements IRuntimeModule {
this._updateSystem = new ParticleUpdateSystem();
// 设置 Transform 组件类型 | Set Transform component type
if (particleContext.transformType) {
this._updateSystem.setTransformType(particleContext.transformType);
if (transformType) {
this._updateSystem.setTransformType(transformType);
}
// 设置引擎集成(用于加载纹理)| Set engine integration (for loading textures)
if (particleContext.engineIntegration) {
this._updateSystem.setEngineIntegration(particleContext.engineIntegration);
if (engineIntegration) {
this._updateSystem.setEngineIntegration(engineIntegration);
}
// 设置引擎桥接(用于加载默认纹理)| Set engine bridge (for loading default texture)
if (particleContext.engineBridge) {
this._updateSystem.setEngineBridge(particleContext.engineBridge);
if (engineBridge) {
this._updateSystem.setEngineBridge(engineBridge);
}
// 设置 2D 物理查询(用于粒子与场景碰撞)| Set 2D physics query (for particle-scene collision)
if (particleContext.physics2DQuery) {
this._updateSystem.setPhysics2DQuery(particleContext.physics2DQuery);
if (physics2DQuery) {
this._updateSystem.setPhysics2DQuery(physics2DQuery);
}
scene.addSystem(this._updateSystem);
particleContext.particleUpdateSystem = this._updateSystem;
// 注册粒子更新系统到服务注册表 | Register particle update system to service registry
context.services.register(ParticleUpdateSystemToken, this._updateSystem);
// 注册渲染数据提供者 | Register render data provider
if (particleContext.renderSystem) {
if (renderSystem) {
const renderDataProvider = this._updateSystem.getRenderDataProvider();
particleContext.renderSystem.addRenderDataProvider(renderDataProvider);
renderSystem.addRenderDataProvider(renderDataProvider);
}
}

View File

@@ -91,4 +91,6 @@ export {
// Plugin
export { ParticleRuntimeModule, ParticlePlugin } from './ParticleRuntimeModule';
export type { ParticleSystemContext } from './ParticleRuntimeModule';
// Service tokens | 服务令牌
export { ParticleUpdateSystemToken } from './tokens';

View File

@@ -227,6 +227,9 @@ export class ParticleLoader implements IAssetLoader<IParticleAsset> {
* Dispose loaded asset
*/
dispose(asset: IParticleAsset): void {
(asset as any).modules = null;
// 清理模块引用 | Clean up module references
if (asset.modules) {
asset.modules.length = 0;
}
}
}

View File

@@ -201,11 +201,11 @@ export class CollisionModule implements IParticleModule {
}
// 更新存储的初始速度(如果有速度曲线模块)| Update stored initial velocity
if ('startVx' in p && normalX !== 0) {
(p as any).startVx = -((p as any).startVx) * this.bounceFactor;
if (p.startVx !== undefined && normalX !== 0) {
p.startVx = -(p.startVx) * this.bounceFactor;
}
if ('startVy' in p && normalY !== 0) {
(p as any).startVy = -((p as any).startVy) * this.bounceFactor;
if (p.startVy !== undefined && normalY !== 0) {
p.startVy = -(p.startVy) * this.bounceFactor;
}
// 应用生命损失 | Apply life loss

View File

@@ -1,6 +1,14 @@
import type { Particle } from '../Particle';
import type { IParticleModule } from './IParticleModule';
// 从 physics-rapier2d 导入共享接口
// Import shared interface from physics-rapier2d
import type { IPhysics2DQuery } from '@esengine/physics-rapier2d';
// 重新导出以保持向后兼容
// Re-export for backward compatibility
export type { IPhysics2DQuery };
/**
* 物理碰撞行为
* Physics collision behavior
@@ -14,53 +22,6 @@ export enum Physics2DCollisionBehavior {
Stop = 'stop'
}
/**
* 物理查询接口
* Physics query interface
*
* 抽象物理服务查询,避免直接依赖 physics-rapier2d 包
* Abstract physics service query to avoid direct dependency on physics-rapier2d
*/
export interface IPhysics2DQuery {
/**
* 圆形重叠检测
* Circle overlap detection
*
* @param center - 圆心位置 | Center position
* @param radius - 半径 | Radius
* @param collisionMask - 碰撞掩码 | Collision mask
* @returns 重叠结果 | Overlap result
*/
overlapCircle(
center: { x: number; y: number },
radius: number,
collisionMask?: number
): { entityIds: number[]; colliderHandles: number[] };
/**
* 射线检测
* Raycast detection
*
* @param origin - 起点 | Origin
* @param direction - 方向(归一化)| Direction (normalized)
* @param maxDistance - 最大距离 | Max distance
* @param collisionMask - 碰撞掩码 | Collision mask
* @returns 射线结果或 null | Raycast result or null
*/
raycast(
origin: { x: number; y: number },
direction: { x: number; y: number },
maxDistance: number,
collisionMask?: number
): {
entityId: number;
point: { x: number; y: number };
normal: { x: number; y: number };
distance: number;
colliderHandle: number;
} | null;
}
/**
* 碰撞回调数据
* Collision callback data

View File

@@ -219,14 +219,10 @@ export class TextureSheetAnimationModule implements IParticleModule {
const u1 = u0 + uWidth;
const v1 = v0 + vHeight;
// 存储 UV 到粒子的自定义属性
// Store UV in particle's custom properties
// 这里我们使用粒子的 startR/startG/startB 不太合适,需要扩展 Particle
// 暂时通过覆盖 rotation 的高位来存储帧索引(临时方案)
// Temporary: store frame index in a way that can be read by renderer
// The actual UV calculation will be done in the render data provider
(p as any)._animFrame = frameIndex;
(p as any)._animTilesX = this.tilesX;
(p as any)._animTilesY = this.tilesY;
// 存储动画帧信息到粒子 | Store animation frame info to particle
// 渲染数据提供者会使用这些值计算实际的 UV | Render data provider will use these to calculate actual UVs
p._animFrame = frameIndex;
p._animTilesX = this.tilesX;
p._animTilesY = this.tilesY;
}
}

View File

@@ -78,13 +78,13 @@ export class VelocityOverLifetimeModule implements IParticleModule {
// 应用速度乘数到当前速度 | Apply multiplier to current velocity
// 我们需要存储初始速度来正确应用曲线 | We need to store initial velocity to properly apply curve
if (!('startVx' in p)) {
(p as any).startVx = p.vx;
(p as any).startVy = p.vy;
if (p.startVx === undefined) {
p.startVx = p.vx;
p.startVy = p.vy;
}
const startVx = (p as any).startVx;
const startVy = (p as any).startVy;
const startVx = p.startVx!;
const startVy = p.startVy!;
// 应用曲线乘数 | Apply curve multiplier
p.vx = startVx * multiplier;
@@ -96,8 +96,8 @@ export class VelocityOverLifetimeModule implements IParticleModule {
p.vx *= dragFactor;
p.vy *= dragFactor;
// 更新存储的起始速度以反映阻力 | Update stored start velocity to reflect drag
(p as any).startVx *= dragFactor;
(p as any).startVy *= dragFactor;
p.startVx = startVx * dragFactor;
p.startVy = startVy * dragFactor;
}
// 附加速度 | Additional velocity

View File

@@ -1,7 +1,7 @@
import { EntitySystem, Matcher, ECSSystem, Time, Entity } from '@esengine/ecs-framework';
import { EntitySystem, Matcher, ECSSystem, Time, Entity, type Component, type ComponentType } from '@esengine/ecs-framework';
import type { IEngineIntegration, IEngineBridge } from '@esengine/ecs-engine-bindgen';
import { ParticleSystemComponent } from '../ParticleSystemComponent';
import { ParticleRenderDataProvider } from '../rendering/ParticleRenderDataProvider';
import type { IEngineIntegration, IEngineBridge } from '../ParticleRuntimeModule';
import { Physics2DCollisionModule, type IPhysics2DQuery } from '../modules/Physics2DCollisionModule';
/**
@@ -66,7 +66,8 @@ interface ITransformComponent {
*/
@ECSSystem('ParticleUpdate', { updateOrder: 100 })
export class ParticleUpdateSystem extends EntitySystem {
private _transformType: (new (...args: any[]) => ITransformComponent) | null = null;
/** Transform 组件类型(运行时注入)| Transform component type (injected at runtime) */
private _transformType: ComponentType<Component & ITransformComponent> | null = null;
private _renderDataProvider: ParticleRenderDataProvider;
private _engineIntegration: IEngineIntegration | null = null;
private _engineBridge: IEngineBridge | null = null;
@@ -91,7 +92,7 @@ export class ParticleUpdateSystem extends EntitySystem {
*
* @param transformType - Transform component class | Transform 组件类
*/
setTransformType(transformType: new (...args: any[]) => ITransformComponent): void {
setTransformType(transformType: ComponentType<Component & ITransformComponent>): void {
this._transformType = transformType;
}
@@ -150,7 +151,7 @@ export class ParticleUpdateSystem extends EntitySystem {
// 获取 Transform 位置、旋转、缩放 | Get Transform position, rotation, scale
if (this._transformType) {
transform = entity.getComponent(this._transformType as any) as ITransformComponent | null;
transform = entity.getComponent(this._transformType);
if (transform) {
const pos = transform.worldPosition ?? transform.position;
worldX = pos.x;
@@ -239,7 +240,7 @@ export class ParticleUpdateSystem extends EntitySystem {
// 尝试获取 Transform如果没有则使用默认位置 | Try to get Transform, use default position if not available
let transform: ITransformComponent | null = null;
if (this._transformType) {
transform = entity.getComponent(this._transformType as any) as ITransformComponent | null;
transform = entity.getComponent(this._transformType);
}
// 即使没有 Transform也要注册粒子系统使用原点位置 | Register particle system even without Transform (use origin position)
if (transform) {

View File

@@ -0,0 +1,20 @@
/**
* 粒子模块服务令牌
* Particle module service tokens
*
* 定义粒子模块导出的服务令牌。
* Defines service tokens exported by particle module.
*/
import { createServiceToken } from '@esengine/engine-core';
import type { ParticleUpdateSystem } from './systems/ParticleSystem';
// ============================================================================
// 粒子模块导出的令牌 | Tokens exported by particle module
// ============================================================================
/**
* 粒子更新系统令牌
* Particle update system token
*/
export const ParticleUpdateSystemToken = createServiceToken<ParticleUpdateSystem>('particleUpdateSystem');