Files
esengine/packages/core/src/ECS/Systems/EntitySystem.ts

681 lines
20 KiB
TypeScript
Raw Normal View History

import { Entity } from '../Entity';
import { PerformanceMonitor } from '../../Utils/PerformanceMonitor';
import { Matcher } from '../Utils/Matcher';
import type { Scene } from '../Scene';
2025-06-30 20:43:11 +08:00
import type { ISystemBase } from '../../Types';
import type { QuerySystem } from '../Core/QuerySystem';
import { getSystemInstanceTypeName } from '../Decorators';
import type { EventListenerConfig, TypeSafeEventSystem, EventHandler } from '../Core/EventSystem';
/**
*
*/
interface EventListenerRecord {
eventSystem: TypeSafeEventSystem;
eventType: string;
handler: EventHandler;
listenerRef: string;
}
/**
*
*
* ECS架构中的逻辑处理单元
*
*
* @example
* ```typescript
* class MovementSystem extends EntitySystem {
* constructor() {
* super(Transform, Velocity);
* }
*
* protected process(entities: Entity[]): void {
* for (const entity of entities) {
* const transform = entity.getComponent(Transform);
* const velocity = entity.getComponent(Velocity);
* transform.position.add(velocity.value);
* }
* }
* }
* ```
*/
export abstract class EntitySystem implements ISystemBase {
private _updateOrder: number = 0;
private _enabled: boolean = true;
private _performanceMonitor = PerformanceMonitor.instance;
private _systemName: string;
private _initialized: boolean = false;
private _matcher: Matcher;
private _trackedEntities: Set<Entity> = new Set();
private _eventListeners: EventListenerRecord[] = [];
private _frameEntities: Entity[] | null = null;
private _cachedEntities: Entity[] | null = null;
/**
*
*/
public get entities(): readonly Entity[] {
// 如果在update周期内优先使用_frameEntities
if (this._frameEntities !== null) {
return this._frameEntities;
}
// 否则使用持久缓存
if (this._cachedEntities === null) {
this._cachedEntities = this.queryEntities();
}
return this._cachedEntities;
}
/**
*
*/
public get updateOrder(): number {
return this._updateOrder;
}
public set updateOrder(value: number) {
this.setUpdateOrder(value);
}
/**
*
*/
public get enabled(): boolean {
return this._enabled;
}
/**
*
*/
public set enabled(value: boolean) {
this._enabled = value;
}
/**
*
*/
public get systemName(): string {
return this._systemName;
}
constructor(matcher?: Matcher) {
this._matcher = matcher ? matcher : Matcher.empty();
this._systemName = getSystemInstanceTypeName(this);
}
private _scene: Scene | null = null;
/**
*
*/
public get scene(): Scene | null {
return this._scene;
}
public set scene(value: Scene | null) {
this._scene = value;
}
/**
*
*/
public get matcher(): Matcher {
return this._matcher;
}
/**
*
* @param order
*/
public setUpdateOrder(order: number): void {
this._updateOrder = order;
if (this.scene && this.scene.entityProcessors) {
this.scene.entityProcessors.setDirty();
}
}
/**
*
*
* 使
*/
public initialize(): void {
// 防止重复初始化
if (this._initialized) {
return;
}
this._initialized = true;
// 框架内部初始化:触发一次实体查询,以便正确跟踪现有实体
if (this.scene) {
// 清理缓存确保初始化时重新查询
this._cachedEntities = null;
this.queryEntities();
}
// 调用用户可重写的初始化方法
this.onInitialize();
}
/**
*
*
*
*/
protected onInitialize(): void {
// 子类可以重写此方法进行初始化
}
/**
* 使
* Scene中的实体发生变化时调用
*/
public clearEntityCache(): void {
this._cachedEntities = null;
}
/**
*
*
* 便
*/
public reset(): void {
2025-09-24 18:14:22 +08:00
this.scene = null;
this._initialized = false;
this._trackedEntities.clear();
this._cachedEntities = null;
this._frameEntities = null;
// 清理所有事件监听器
this.cleanupEventListeners();
// 调用用户可重写的销毁方法
this.onDestroy();
}
/**
*
*/
private queryEntities(): Entity[] {
if (!this.scene?.querySystem || !this._matcher) {
return [];
}
const condition = this._matcher.getCondition();
const querySystem = this.scene.querySystem;
let currentEntities: Entity[] = [];
// 空条件返回所有实体
if (this._matcher.isEmpty()) {
currentEntities = querySystem.getAllEntities();
} else if (this.isSingleCondition(condition)) {
// 单一条件优化查询
currentEntities = this.executeSingleConditionQuery(condition, querySystem);
} else {
// 复合查询
currentEntities = this.executeComplexQuery(condition, querySystem);
}
// 检查实体变化并触发回调
this.updateEntityTracking(currentEntities);
return currentEntities;
}
/**
*
*/
private isSingleCondition(condition: any): boolean {
const conditionCount =
(condition.all.length > 0 ? 1 : 0) +
(condition.any.length > 0 ? 1 : 0) +
(condition.none.length > 0 ? 1 : 0) +
(condition.tag !== undefined ? 1 : 0) +
(condition.name !== undefined ? 1 : 0) +
(condition.component !== undefined ? 1 : 0);
return conditionCount === 1;
}
/**
*
*/
private executeSingleConditionQuery(condition: any, querySystem: any): Entity[] {
// 按标签查询
if (condition.tag !== undefined) {
return querySystem.queryByTag(condition.tag).entities;
}
// 按名称查询
if (condition.name !== undefined) {
return querySystem.queryByName(condition.name).entities;
}
// 单组件查询
if (condition.component !== undefined) {
return querySystem.queryByComponent(condition.component).entities;
}
// 基础组件查询
if (condition.all.length > 0 && condition.any.length === 0 && condition.none.length === 0) {
return querySystem.queryAll(...condition.all).entities;
}
if (condition.all.length === 0 && condition.any.length > 0 && condition.none.length === 0) {
return querySystem.queryAny(...condition.any).entities;
}
if (condition.all.length === 0 && condition.any.length === 0 && condition.none.length > 0) {
return querySystem.queryNone(...condition.none).entities;
}
return [];
}
/**
*
*/
private executeComplexQueryWithIdSets(condition: any, querySystem: QuerySystem): Entity[] {
let resultIds: Set<number> | null = null;
// 1. 应用标签条件作为基础集合
if (condition.tag !== undefined) {
const tagResult = querySystem.queryByTag(condition.tag);
resultIds = this.extractEntityIds(tagResult.entities);
}
// 2. 应用名称条件 (交集)
if (condition.name !== undefined) {
const nameIds = this.extractEntityIds(querySystem.queryByName(condition.name).entities);
resultIds = resultIds ? this.intersectIdSets(resultIds, nameIds) : nameIds;
}
// 3. 应用单组件条件 (交集)
if (condition.component !== undefined) {
const componentIds = this.extractEntityIds(querySystem.queryByComponent(condition.component).entities);
resultIds = resultIds ? this.intersectIdSets(resultIds, componentIds) : componentIds;
}
// 4. 应用all条件 (交集)
if (condition.all.length > 0) {
const allIds = this.extractEntityIds(querySystem.queryAll(...condition.all).entities);
resultIds = resultIds ? this.intersectIdSets(resultIds, allIds) : allIds;
}
// 5. 应用any条件 (交集)
if (condition.any.length > 0) {
const anyIds = this.extractEntityIds(querySystem.queryAny(...condition.any).entities);
resultIds = resultIds ? this.intersectIdSets(resultIds, anyIds) : anyIds;
}
// 6. 应用none条件 (差集)
if (condition.none.length > 0) {
if (!resultIds) {
resultIds = this.extractEntityIds(querySystem.getAllEntities());
}
const noneResult = querySystem.queryAny(...condition.none);
const noneIds = this.extractEntityIds(noneResult.entities);
resultIds = this.differenceIdSets(resultIds, noneIds);
}
return resultIds ? this.idSetToEntityArray(resultIds, querySystem.getAllEntities()) : [];
}
/**
* ID集合
*/
private extractEntityIds(entities: Entity[]): Set<number> {
const idSet = new Set<number>();
for (let i = 0; i < entities.length; i++) {
idSet.add(entities[i].id);
}
return idSet;
}
/**
* ID集合交集运算
*
* 使
*/
private intersectIdSets(setA: Set<number>, setB: Set<number>): Set<number> {
const [smaller, larger] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
const result = new Set<number>();
for (const id of smaller) {
if (larger.has(id)) {
result.add(id);
}
}
return result;
}
/**
* ID集合差集运算
*
* 使setA - setB
*/
private differenceIdSets(setA: Set<number>, setB: Set<number>): Set<number> {
const result = new Set<number>();
for (const id of setA) {
if (!setB.has(id)) {
result.add(id);
}
}
return result;
}
/**
* ID集合构建Entity数组
*
* ID到Entity的映射ID集合构建结果数组
*/
private idSetToEntityArray(idSet: Set<number>, allEntities: Entity[]): Entity[] {
const entityMap = new Map<number, Entity>();
for (const entity of allEntities) {
entityMap.set(entity.id, entity);
}
const result: Entity[] = [];
for (const id of idSet) {
const entity = entityMap.get(id);
if (entity) {
result.push(entity);
}
}
return result;
}
/**
*
*
* 使ID集合的单次扫描算法进行复杂查询
*/
private executeComplexQuery(condition: any, querySystem: QuerySystem): Entity[] {
return this.executeComplexQueryWithIdSets(condition, querySystem);
}
/**
*
*/
public update(): void {
if (!this._enabled || !this.onCheckProcessing()) {
return;
}
const startTime = this._performanceMonitor.startMonitoring(this._systemName);
let entityCount = 0;
try {
this.onBegin();
// 查询实体并存储到帧缓存中
this._frameEntities = this.queryEntities();
entityCount = this._frameEntities.length;
this.process(this._frameEntities);
} finally {
this._performanceMonitor.endMonitoring(this._systemName, startTime, entityCount);
}
}
/**
*
*/
public lateUpdate(): void {
if (!this._enabled || !this.onCheckProcessing()) {
return;
}
const startTime = this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);
let entityCount = 0;
try {
// 使用缓存的实体列表,避免重复查询
const entities = this._frameEntities || [];
entityCount = entities.length;
this.lateProcess(entities);
this.onEnd();
} finally {
this._performanceMonitor.endMonitoring(`${this._systemName}_Late`, startTime, entityCount);
// 清理帧缓存
this._frameEntities = null;
}
}
/**
*
*
*
*/
protected onBegin(): void {
// 子类可以重写此方法
}
/**
*
*
*
*
* @param entities
*/
2025-09-24 10:45:33 +08:00
protected process(entities: Entity[]): void {
// 子类必须实现此方法
}
/**
*
*
*
*
* @param entities
*/
protected lateProcess(_entities: Entity[]): void {
// 子类可以重写此方法
}
/**
*
*
*
*/
protected onEnd(): void {
// 子类可以重写此方法
}
/**
*
*
*
*
*
* @returns truefalse
*/
protected onCheckProcessing(): boolean {
return true;
}
/**
*
*
* @returns undefined
*/
public getPerformanceData() {
return this._performanceMonitor.getSystemData(this._systemName);
}
/**
*
*
* @returns undefined
*/
public getPerformanceStats() {
return this._performanceMonitor.getSystemStats(this._systemName);
}
/**
*
*/
public resetPerformanceData(): void {
this._performanceMonitor.resetSystem(this._systemName);
}
/**
*
*
* @returns
*/
public toString(): string {
const entityCount = this.entities.length;
const perfData = this.getPerformanceData();
const perfInfo = perfData ? ` (${perfData.executionTime.toFixed(2)}ms)` : '';
return `${this._systemName}[${entityCount} entities]${perfInfo}`;
}
/**
*
*/
private updateEntityTracking(currentEntities: Entity[]): void {
const currentSet = new Set(currentEntities);
let hasChanged = false;
// 检查新增的实体
for (const entity of currentEntities) {
if (!this._trackedEntities.has(entity)) {
this._trackedEntities.add(entity);
this.onAdded(entity);
hasChanged = true;
}
}
// 检查移除的实体
for (const entity of this._trackedEntities) {
if (!currentSet.has(entity)) {
this._trackedEntities.delete(entity);
this.onRemoved(entity);
hasChanged = true;
}
}
// 如果实体发生了变化,使缓存失效
if (hasChanged) {
this._cachedEntities = null;
}
}
/**
*
*
*
*
* @param entity
*/
2025-09-24 10:45:33 +08:00
protected onAdded(entity: Entity): void {
// 子类可以重写此方法
}
/**
*
*
*
*
* @param entity
*/
2025-09-24 10:45:33 +08:00
protected onRemoved(entity: Entity): void {
// 子类可以重写此方法
}
/**
*
*
* 使eventSystem.on()
*
*
* @param eventType
* @param handler
* @param config
*/
protected addEventListener<T = any>(
eventType: string,
handler: EventHandler<T>,
config?: EventListenerConfig
): void {
if (!this.scene?.eventSystem) {
console.warn(`[${this.systemName}] Cannot add event listener: scene.eventSystem not available`);
return;
}
const listenerRef = this.scene.eventSystem.on(eventType, handler, config);
// 跟踪监听器以便后续清理
if (listenerRef) {
this._eventListeners.push({
eventSystem: this.scene.eventSystem,
eventType,
handler,
listenerRef
});
}
}
/**
*
*
* @param eventType
* @param handler
*/
protected removeEventListener<T = any>(
eventType: string,
handler: EventHandler<T>
): void {
const listenerIndex = this._eventListeners.findIndex(
listener => listener.eventType === eventType && listener.handler === handler
);
if (listenerIndex >= 0) {
const listener = this._eventListeners[listenerIndex];
// 从事件系统中移除
listener.eventSystem.off(eventType, listener.listenerRef);
// 从跟踪列表中移除
this._eventListeners.splice(listenerIndex, 1);
}
}
/**
*
*
* addEventListener添加的监听器
*/
private cleanupEventListeners(): void {
for (const listener of this._eventListeners) {
try {
listener.eventSystem.off(listener.eventType, listener.listenerRef);
} catch (error) {
console.warn(`[${this.systemName}] Failed to remove event listener for "${listener.eventType}":`, error);
}
}
// 清空跟踪列表
this._eventListeners.length = 0;
}
/**
*
*
*
*
*/
protected onDestroy(): void {
// 子类可以重写此方法进行清理操作
}
}