Files
esengine/packages/rendering/particle/src/modules/Physics2DCollisionModule.ts

342 lines
9.5 KiB
TypeScript
Raw Normal View History

import type { Particle } from '../Particle';
import type { IParticleModule } from './IParticleModule';
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 失败
2025-12-08 21:10:57 +08:00
// 从 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
*/
export enum Physics2DCollisionBehavior {
/** 销毁粒子 | Kill particle */
Kill = 'kill',
/** 反弹 | Bounce */
Bounce = 'bounce',
/** 停止运动 | Stop movement */
Stop = 'stop'
}
/**
*
* Collision callback data
*/
export interface ParticleCollisionInfo {
/** 粒子引用 | Particle reference */
particle: Particle;
/** 碰撞位置 | Collision point */
point: { x: number; y: number };
/** 碰撞法线 | Collision normal */
normal: { x: number; y: number };
/** 碰撞的实体 ID | Collided entity ID */
entityId: number;
/** 碰撞体句柄 | Collider handle */
colliderHandle: number;
}
/**
* 2D
* 2D Physics collision module
*
* 使 Physics2DService API
* Uses Physics2DService query API to detect particle collisions with scene colliders.
*
* @example
* ```typescript
* // 获取物理服务
* const physicsService = scene.services.resolve(Physics2DService);
*
* // 创建模块
* const collisionModule = new Physics2DCollisionModule();
* collisionModule.setPhysicsQuery(physicsService);
* collisionModule.particleRadius = 4;
* collisionModule.behavior = Physics2DCollisionBehavior.Bounce;
*
* // 添加到粒子系统
* particleSystem.addModule(collisionModule);
*
* // 监听碰撞事件
* collisionModule.onCollision = (info) => {
* console.log('Particle hit entity:', info.entityId);
* };
* ```
*/
export class Physics2DCollisionModule implements IParticleModule {
readonly name = 'Physics2DCollision';
enabled = true;
// ============= 物理查询 | Physics Query =============
/** 物理查询接口 | Physics query interface */
private _physicsQuery: IPhysics2DQuery | null = null;
// ============= 碰撞设置 | Collision Settings =============
/**
*
* Particle collision radius
*
*
*/
particleRadius: number = 4;
/**
*
* Collision behavior
*/
behavior: Physics2DCollisionBehavior = Physics2DCollisionBehavior.Bounce;
/**
*
* Collision layer mask
*
* 0xFFFF
* Default 0xFFFF means collide with all layers
*/
collisionMask: number = 0xFFFF;
/**
* (0-1)
* Bounce factor (0-1)
*
* 1 = 0 =
* 1 = fully elastic, 0 = no bounce
*/
bounceFactor: number = 0.6;
/**
* (0-1)
* Life loss on bounce (0-1)
*/
lifeLossOnBounce: number = 0;
/**
*
* Minimum velocity threshold
*
*
* Kill particle when velocity falls below this (prevents infinite tiny bounces)
*/
minVelocityThreshold: number = 5;
/**
* 使线
* Use raycast instead of overlap detection
*
* 线穿
* Raycast is more accurate and prevents fast particle tunneling, but more expensive
*/
useRaycast: boolean = false;
/**
* N
* Detection frequency (detect every N frames)
*
*
* Increase to improve performance at cost of accuracy
*/
detectionInterval: number = 1;
// ============= 内部状态 | Internal State =============
/** 帧计数器 | Frame counter */
private _frameCounter: number = 0;
/** 需要销毁的粒子 | Particles to kill */
private _particlesToKill: Set<Particle> = new Set();
// ============= 回调 | Callbacks =============
/**
*
* Collision callback
*
*
*/
onCollision: ((info: ParticleCollisionInfo) => void) | null = null;
// ============= 公开方法 | Public Methods =============
/**
*
* Set physics query interface
*
* @param query - Physics2DService| Physics query (usually Physics2DService)
*/
setPhysicsQuery(query: IPhysics2DQuery | null): void {
this._physicsQuery = query;
}
/**
*
* Get particles to kill
*/
getParticlesToKill(): Set<Particle> {
return this._particlesToKill;
}
/**
*
* Clear death flags
*/
clearDeathFlags(): void {
this._particlesToKill.clear();
}
/**
*
* Reset frame counter
*/
resetFrameCounter(): void {
this._frameCounter = 0;
}
// ============= IParticleModule 实现 | IParticleModule Implementation =============
update(p: Particle, dt: number, _normalizedAge: number): void {
if (!this._physicsQuery) return;
// 检测频率控制 | Detection frequency control
this._frameCounter++;
if (this._frameCounter % this.detectionInterval !== 0) {
return;
}
if (this.useRaycast) {
this._updateWithRaycast(p, dt);
} else {
this._updateWithOverlap(p);
}
}
// ============= 私有方法 | Private Methods =============
/**
* 使
* Update using circle overlap detection
*/
private _updateWithOverlap(p: Particle): void {
if (!this._physicsQuery) return;
const result = this._physicsQuery.overlapCircle(
{ x: p.x, y: p.y },
this.particleRadius,
this.collisionMask
);
if (result.entityIds.length > 0) {
// 发生碰撞 | Collision occurred
const entityId = result.entityIds[0];
const colliderHandle = result.colliderHandles[0];
// 估算法线(从粒子速度反向)| Estimate normal (from particle velocity)
const speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy);
const normal = speed > 0.001
? { x: -p.vx / speed, y: -p.vy / speed }
: { x: 0, y: 1 };
this._handleCollision(p, { x: p.x, y: p.y }, normal, entityId, colliderHandle);
}
}
/**
* 使线
* Update using raycast detection
*/
private _updateWithRaycast(p: Particle, dt: number): void {
if (!this._physicsQuery) return;
const speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy);
if (speed < 0.001) return;
// 归一化方向 | Normalize direction
const direction = { x: p.vx / speed, y: p.vy / speed };
const distance = speed * dt + this.particleRadius;
const hit = this._physicsQuery.raycast(
{ x: p.x, y: p.y },
direction,
distance,
this.collisionMask
);
if (hit) {
this._handleCollision(p, hit.point, hit.normal, hit.entityId, hit.colliderHandle);
}
}
/**
*
* Handle collision
*/
private _handleCollision(
p: Particle,
point: { x: number; y: number },
normal: { x: number; y: number },
entityId: number,
colliderHandle: number
): void {
// 触发回调 | Trigger callback
if (this.onCollision) {
this.onCollision({
particle: p,
point,
normal,
entityId,
colliderHandle
});
}
switch (this.behavior) {
case Physics2DCollisionBehavior.Kill:
this._particlesToKill.add(p);
break;
case Physics2DCollisionBehavior.Bounce:
this._applyBounce(p, normal);
break;
case Physics2DCollisionBehavior.Stop:
p.vx = 0;
p.vy = 0;
break;
}
}
/**
*
* Apply bounce effect
*/
private _applyBounce(p: Particle, normal: { x: number; y: number }): void {
// 反射公式: v' = v - 2 * (v · n) * n
// Reflection formula: v' = v - 2 * (v · n) * n
const dot = p.vx * normal.x + p.vy * normal.y;
// 只在粒子朝向表面时反弹 | Only bounce if particle is moving towards surface
if (dot < 0) {
p.vx = (p.vx - 2 * dot * normal.x) * this.bounceFactor;
p.vy = (p.vy - 2 * dot * normal.y) * this.bounceFactor;
// 稍微移开粒子防止重复碰撞 | Move particle slightly away to prevent repeated collision
p.x += normal.x * this.particleRadius * 0.1;
p.y += normal.y * this.particleRadius * 0.1;
}
// 应用生命损失 | Apply life loss
if (this.lifeLossOnBounce > 0) {
p.lifetime *= (1 - this.lifeLossOnBounce);
}
// 检查最小速度 | Check minimum velocity
const speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy);
if (speed < this.minVelocityThreshold) {
this._particlesToKill.add(p);
}
}
}