@esengine/ecs-framework
Version:
用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架
2,390 lines (2,371 loc) • 176 kB
TypeScript
/**
* @esengine/ecs-framework v2.1.41
* TypeScript definitions
*/
/**
* 全局管理器的基类。所有全局管理器都应该从此类继承。
*/
declare class GlobalManager {
/**
* 表示管理器是否启用
*/
_enabled: boolean;
/**
* 获取或设置管理器是否启用
*/
get enabled(): boolean;
set enabled(value: boolean);
/**
* 设置管理器是否启用
* @param isEnabled 如果为true,则启用管理器;否则禁用管理器
*/
setEnabled(isEnabled: boolean): void;
/**
* 在启用管理器时调用的回调方法
*/
protected onEnabled(): void;
/**
* 在禁用管理器时调用的回调方法
*/
protected onDisabled(): void;
/**
* 更新管理器状态的方法
*/
update(): void;
}
interface ITimer<TContext = unknown> {
context: TContext;
/**
* 调用stop以停止此计时器再次运行。这对非重复计时器没有影响。
*/
stop(): void;
/**
* 将计时器的运行时间重置为0
*/
reset(): void;
/**
* 返回投向T的上下文,作为方便
*/
getContext<T>(): T;
}
/**
* 私有类隐藏ITimer的实现
*/
declare class Timer<TContext = unknown> implements ITimer<TContext> {
context: TContext;
_timeInSeconds: number;
_repeats: boolean;
_onTime: (timer: ITimer<TContext>) => void;
_isDone: boolean;
_elapsedTime: number;
getContext<T>(): T;
/**
* 定时器是否已完成
*/
get isDone(): boolean;
/**
* 定时器已运行的时间
*/
get elapsedTime(): number;
reset(): void;
stop(): void;
tick(): boolean;
initialize(timeInsSeconds: number, repeats: boolean, context: TContext, onTime: (timer: ITimer<TContext>) => void): void;
/**
* 空出对象引用,以便在js需要时GC可以清理它们的引用
*/
unload(): void;
}
/**
* 允许动作的延迟和重复执行
*/
declare class TimerManager extends GlobalManager {
_timers: Array<Timer<unknown>>;
update(): void;
/**
* 调度一个一次性或重复的计时器,该计时器将调用已传递的动作
* @param timeInSeconds
* @param repeats
* @param context
* @param onTime
*/
schedule<TContext = unknown>(timeInSeconds: number, repeats: boolean, context: TContext, onTime: (timer: ITimer<TContext>) => void): Timer<TContext>;
}
/**
* 性能监控数据
*/
interface PerformanceData {
/** 系统名称 */
name: string;
/** 执行时间(毫秒) */
executionTime: number;
/** 处理的实体数量 */
entityCount: number;
/** 平均每个实体的处理时间 */
averageTimePerEntity: number;
/** 最后更新时间戳 */
lastUpdateTime: number;
/** 内存使用量(字节) */
memoryUsage?: number;
/** CPU使用率(百分比) */
cpuUsage?: number;
}
/**
* 性能统计信息
*/
interface PerformanceStats {
/** 总执行时间 */
totalTime: number;
/** 平均执行时间 */
averageTime: number;
/** 最小执行时间 */
minTime: number;
/** 最大执行时间 */
maxTime: number;
/** 执行次数 */
executionCount: number;
/** 最近的执行时间列表 */
recentTimes: number[];
/** 标准差 */
standardDeviation: number;
/** 95百分位数 */
percentile95: number;
/** 99百分位数 */
percentile99: number;
}
/**
* 性能警告类型
*/
declare enum PerformanceWarningType {
HIGH_EXECUTION_TIME = "high_execution_time",
HIGH_MEMORY_USAGE = "high_memory_usage",
HIGH_CPU_USAGE = "high_cpu_usage",
FREQUENT_GC = "frequent_gc",
LOW_FPS = "low_fps",
HIGH_ENTITY_COUNT = "high_entity_count"
}
/**
* 性能警告
*/
interface PerformanceWarning {
type: PerformanceWarningType;
systemName: string;
message: string;
severity: 'low' | 'medium' | 'high' | 'critical';
timestamp: number;
value: number;
threshold: number;
suggestion?: string;
}
/**
* 性能阈值配置
*/
interface PerformanceThresholds {
/** 执行时间阈值(毫秒) */
executionTime: {
warning: number;
critical: number;
};
/** 内存使用阈值(MB) */
memoryUsage: {
warning: number;
critical: number;
};
/** CPU使用率阈值(百分比) */
cpuUsage: {
warning: number;
critical: number;
};
/** FPS阈值 */
fps: {
warning: number;
critical: number;
};
/** 实体数量阈值 */
entityCount: {
warning: number;
critical: number;
};
}
/**
* 高性能监控器
* 用于监控ECS系统的性能表现,提供详细的分析和优化建议
*/
declare class PerformanceMonitor {
private static _instance;
private _systemData;
private _systemStats;
private _warnings;
private _isEnabled;
private _maxRecentSamples;
private _maxWarnings;
private _thresholds;
private _fpsHistory;
private _lastFrameTime;
private _frameCount;
private _fpsUpdateInterval;
private _lastFpsUpdate;
private _currentFps;
private _memoryCheckInterval;
private _lastMemoryCheck;
private _memoryHistory;
private _gcCount;
private _lastGcCheck;
private _gcCheckInterval;
/**
* 获取单例实例
*/
static get instance(): PerformanceMonitor;
private constructor();
/**
* 启用性能监控
*/
enable(): void;
/**
* 禁用性能监控
*/
disable(): void;
/**
* 检查是否启用了性能监控
*/
get isEnabled(): boolean;
/**
* 开始监控系统性能
* @param systemName 系统名称
* @returns 开始时间戳
*/
startMonitoring(systemName: string): number;
/**
* 结束监控并记录性能数据
* @param systemName 系统名称
* @param startTime 开始时间戳
* @param entityCount 处理的实体数量
*/
endMonitoring(systemName: string, startTime: number, entityCount?: number): void;
/**
* 更新系统统计信息
* @param systemName 系统名称
* @param executionTime 执行时间
*/
private updateStats;
/**
* 计算高级统计信息
* @param stats 统计信息对象
*/
private calculateAdvancedStats;
/**
* 获取系统的当前性能数据
* @param systemName 系统名称
* @returns 性能数据或undefined
*/
getSystemData(systemName: string): PerformanceData | undefined;
/**
* 获取系统的统计信息
* @param systemName 系统名称
* @returns 统计信息或undefined
*/
getSystemStats(systemName: string): PerformanceStats | undefined;
/**
* 获取所有系统的性能数据
* @returns 所有系统的性能数据
*/
getAllSystemData(): Map<string, PerformanceData>;
/**
* 获取所有系统的统计信息
* @returns 所有系统的统计信息
*/
getAllSystemStats(): Map<string, PerformanceStats>;
/**
* 获取性能报告
* @returns 格式化的性能报告字符串
*/
getPerformanceReport(): string;
/**
* 重置所有性能数据
*/
reset(): void;
/**
* 重置指定系统的性能数据
* @param systemName 系统名称
*/
resetSystem(systemName: string): void;
/**
* 获取性能警告
* @param thresholdMs 警告阈值(毫秒)
* @returns 超过阈值的系统列表
*/
getPerformanceWarnings(thresholdMs?: number): string[];
/**
* 设置最大保留样本数
* @param maxSamples 最大样本数
*/
setMaxRecentSamples(maxSamples: number): void;
}
/**
* 可池化对象接口
*/
interface IPoolable {
/**
* 重置对象状态,准备重用
*/
reset(): void;
}
/**
* 对象池统计信息
*/
interface PoolStats {
/** 池中对象数量 */
size: number;
/** 池的最大大小 */
maxSize: number;
/** 总共创建的对象数量 */
totalCreated: number;
/** 总共获取的次数 */
totalObtained: number;
/** 总共释放的次数 */
totalReleased: number;
/** 命中率(从池中获取的比例) */
hitRate: number;
/** 内存使用估算(字节) */
estimatedMemoryUsage: number;
}
/**
* 高性能通用对象池
* 支持任意类型的对象池化,包含详细的统计信息
*/
declare class Pool<T extends IPoolable> {
private static _pools;
private _objects;
private _createFn;
private _maxSize;
private _stats;
private _objectSize;
/**
* 构造函数
* @param createFn 创建对象的函数
* @param maxSize 池的最大大小,默认100
* @param estimatedObjectSize 估算的单个对象大小(字节),默认1024
*/
constructor(createFn: () => T, maxSize?: number, estimatedObjectSize?: number);
/**
* 获取指定类型的对象池
* @param type 对象类型
* @param maxSize 池的最大大小
* @param estimatedObjectSize 估算的单个对象大小
* @returns 对象池实例
*/
static getPool<T extends IPoolable>(type: new (...args: unknown[]) => T, maxSize?: number, estimatedObjectSize?: number): Pool<T>;
/**
* 从池中获取对象
* @returns 对象实例
*/
obtain(): T;
/**
* 释放对象回池中
* @param obj 要释放的对象
*/
release(obj: T): void;
/**
* 获取池统计信息
* @returns 统计信息对象
*/
getStats(): Readonly<PoolStats>;
/**
* 清空池
*/
clear(): void;
/**
* 压缩池(移除多余的对象)
* @param targetSize 目标大小,默认为当前大小的一半
*/
compact(targetSize?: number): void;
/**
* 预填充池
* @param count 预填充的对象数量
*/
prewarm(count: number): void;
/**
* 设置最大池大小
* @param maxSize 新的最大大小
*/
setMaxSize(maxSize: number): void;
/**
* 获取池中可用对象数量
* @returns 可用对象数量
*/
getAvailableCount(): number;
/**
* 检查池是否为空
* @returns 如果池为空返回true
*/
isEmpty(): boolean;
/**
* 检查池是否已满
* @returns 如果池已满返回true
*/
isFull(): boolean;
/**
* 获取所有已注册的池类型
* @returns 所有池类型的数组
*/
static getAllPoolTypes(): Function[];
/**
* 获取所有池的统计信息
* @returns 包含所有池统计信息的对象
*/
static getAllPoolStats(): Record<string, PoolStats>;
/**
* 压缩所有池
*/
static compactAllPools(): void;
/**
* 清空所有池
*/
static clearAllPools(): void;
/**
* 获取全局池统计信息的格式化字符串
* @returns 格式化的统计信息字符串
*/
static getGlobalStatsString(): string;
/**
* 更新命中率
*/
private _updateHitRate;
/**
* 更新内存使用估算
*/
private _updateMemoryUsage;
}
/**
* 池管理器
* 统一管理所有对象池
*/
declare class PoolManager {
private static instance;
private pools;
private autoCompactInterval;
private lastCompactTime;
static getInstance(): PoolManager;
/**
* 注册池
* @param name 池名称
* @param pool 池实例
*/
registerPool<T extends IPoolable>(name: string, pool: Pool<T>): void;
/**
* 获取池
* @param name 池名称
* @returns 池实例
*/
getPool<T extends IPoolable>(name: string): Pool<T> | null;
/**
* 更新池管理器(应在游戏循环中调用)
*/
update(): void;
/**
* 创建或获取标准池
* @param name 池名称
* @param createFn 创建函数
* @param maxSize 最大大小
* @param estimatedObjectSize 估算对象大小
* @returns 池实例
*/
createPool<T extends IPoolable>(name: string, createFn: () => T, maxSize?: number, estimatedObjectSize?: number): Pool<T>;
/**
* 移除池
* @param name 池名称
* @returns 是否成功移除
*/
removePool(name: string): boolean;
/**
* 获取所有池名称
* @returns 池名称数组
*/
getPoolNames(): string[];
/**
* 获取池数量
* @returns 池数量
*/
getPoolCount(): number;
/**
* 压缩所有池
*/
compactAllPools(): void;
/**
* 清空所有池
*/
clearAllPools(): void;
/**
* 获取所有池的统计信息
* @returns 统计信息映射
*/
getAllStats(): Map<string, PoolStats>;
/**
* 获取总体统计信息
* @returns 总体统计信息
*/
getGlobalStats(): PoolStats;
/**
* 获取格式化的统计信息字符串
* @returns 格式化字符串
*/
getStatsString(): string;
/**
* 设置自动压缩间隔
* @param intervalMs 间隔毫秒数
*/
setAutoCompactInterval(intervalMs: number): void;
/**
* 预填充所有池
*/
prewarmAllPools(): void;
/**
* 重置池管理器
*/
reset(): void;
}
/**
* 框架核心类型定义
*/
/**
* 组件接口
*
* 定义组件的基本契约,所有组件都应该实现此接口
*/
interface IComponent {
/** 组件唯一标识符 */
readonly id: number;
/** 组件所属的实体ID */
entityId?: string | number;
/** 组件启用状态 */
enabled: boolean;
/** 更新顺序 */
updateOrder: number;
/** 组件添加到实体时的回调 */
onAddedToEntity(): void;
/** 组件从实体移除时的回调 */
onRemovedFromEntity(): void;
/** 组件启用时的回调 */
onEnabled(): void;
/** 组件禁用时的回调 */
onDisabled(): void;
/** 更新组件 */
update(): void;
}
/**
* 系统基础接口
*
* 为现有的EntitySystem类提供类型定义
*/
interface ISystemBase {
/** 系统名称 */
readonly systemName: string;
/** 更新顺序/优先级 */
updateOrder: number;
/** 系统启用状态 */
enabled: boolean;
/** 系统初始化 */
initialize(): void;
/** 更新系统(主要处理阶段) */
update(): void;
/** 延迟更新系统 */
lateUpdate?(): void;
}
/**
* 组件类型定义
*
* 用于类型安全的组件操作
* 支持任意构造函数签名,提供更好的类型安全性
*/
type ComponentType$1<T extends IComponent = IComponent> = new (...args: any[]) => T;
/**
* 事件总线接口
* 提供类型安全的事件发布订阅机制
*/
interface IEventBus {
/**
* 发射事件
* @param eventType 事件类型
* @param data 事件数据
*/
emit<T>(eventType: string, data: T): void;
/**
* 异步发射事件
* @param eventType 事件类型
* @param data 事件数据
*/
emitAsync<T>(eventType: string, data: T): Promise<void>;
/**
* 监听事件
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
on<T>(eventType: string, handler: (data: T) => void, config?: IEventListenerConfig): string;
/**
* 监听事件(一次性)
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
once<T>(eventType: string, handler: (data: T) => void, config?: IEventListenerConfig): string;
/**
* 异步监听事件
* @param eventType 事件类型
* @param handler 异步事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
onAsync<T>(eventType: string, handler: (data: T) => Promise<void>, config?: IEventListenerConfig): string;
/**
* 移除事件监听器
* @param eventType 事件类型
* @param listenerId 监听器ID
*/
off(eventType: string, listenerId: string): boolean;
/**
* 移除指定事件类型的所有监听器
* @param eventType 事件类型
*/
offAll(eventType: string): void;
/**
* 检查是否有指定事件的监听器
* @param eventType 事件类型
*/
hasListeners(eventType: string): boolean;
/**
* 获取事件统计信息
* @param eventType 事件类型(可选)
*/
getStats(eventType?: string): IEventStats | Map<string, IEventStats>;
/**
* 清空所有监听器
*/
clear(): void;
}
/**
* 事件监听器配置接口
*/
interface IEventListenerConfig {
/** 是否只执行一次 */
once?: boolean;
/** 优先级(数字越大优先级越高) */
priority?: number;
/** 是否异步执行 */
async?: boolean;
/** 执行上下文 */
context?: unknown;
}
/**
* 事件统计信息接口
*/
interface IEventStats {
/** 事件类型 */
eventType: string;
/** 监听器数量 */
listenerCount: number;
/** 触发次数 */
triggerCount: number;
/** 总执行时间(毫秒) */
totalExecutionTime: number;
/** 平均执行时间(毫秒) */
averageExecutionTime: number;
/** 最后触发时间 */
lastTriggerTime: number;
}
/**
* 事件数据基类接口
*/
interface IEventData {
/** 事件时间戳 */
timestamp: number;
/** 事件来源 */
source?: string;
/** 事件ID */
eventId?: string;
}
/**
* 实体事件数据接口
*/
interface IEntityEventData extends IEventData {
/** 实体ID */
entityId: number;
/** 实体名称 */
entityName?: string;
/** 实体标签 */
entityTag?: string;
}
/**
* 组件事件数据接口
*/
interface IComponentEventData extends IEntityEventData {
/** 组件类型名称 */
componentType: string;
/** 组件实例 */
component?: IComponent;
}
/**
* 系统事件数据接口
*/
interface ISystemEventData extends IEventData {
/** 系统名称 */
systemName: string;
/** 系统类型 */
systemType: string;
}
/**
* 场景事件数据接口
*/
interface ISceneEventData extends IEventData {
/** 场景名称 */
sceneName: string;
/** 前一个场景名称 */
previousSceneName?: string;
}
/**
* 性能事件数据接口
*/
interface IPerformanceEventData extends IEventData {
/** 操作类型 */
operation: string;
/** 执行时间(毫秒) */
executionTime: number;
/** 内存使用量 */
memoryUsage?: number;
/** 额外数据 */
metadata?: Record<string, unknown>;
}
/**
* ECS调试配置接口
*/
interface IECSDebugConfig {
/** 是否启用调试 */
enabled: boolean;
/** WebSocket服务器URL */
websocketUrl: string;
/** 是否自动重连 */
autoReconnect?: boolean;
/** 数据更新间隔(毫秒)- 已弃用,使用debugFrameRate替代 */
updateInterval?: number;
/** 调试数据发送帧率 (60fps, 30fps, 15fps) */
debugFrameRate?: 60 | 30 | 15;
/** 数据通道配置 */
channels: {
entities: boolean;
systems: boolean;
performance: boolean;
components: boolean;
scenes: boolean;
};
}
/**
* Core配置接口
*/
interface ICoreConfig {
/** 是否启用调试模式 */
debug?: boolean;
/** 是否启用实体系统 */
enableEntitySystems?: boolean;
/** 调试配置 */
debugConfig?: IECSDebugConfig;
}
/**
* ECS调试数据接口
*/
interface IECSDebugData {
/** 时间戳 */
timestamp: number;
/** 框架版本 */
frameworkVersion?: string;
/** 是否正在运行 */
isRunning: boolean;
/** 框架是否已加载 */
frameworkLoaded: boolean;
/** 当前场景名称 */
currentScene: string;
/** 实体数据 */
entities?: IEntityDebugData;
/** 系统数据 */
systems?: ISystemDebugData;
/** 性能数据 */
performance?: IPerformanceDebugData;
/** 组件数据 */
components?: IComponentDebugData;
/** 场景数据 */
scenes?: ISceneDebugData;
}
/**
* 实体层次结构节点接口
*/
interface IEntityHierarchyNode {
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
componentCount: number;
componentTypes: string[];
parentId: number | null;
children: IEntityHierarchyNode[];
depth: number;
tag: number;
updateOrder: number;
}
/**
* 实体调试数据接口
*/
interface IEntityDebugData {
/** 总实体数 */
totalEntities: number;
/** 激活实体数 */
activeEntities: number;
/** 待添加实体数 */
pendingAdd: number;
/** 待移除实体数 */
pendingRemove: number;
/** 按Archetype分组的实体分布 */
entitiesPerArchetype: Array<{
signature: string;
count: number;
memory: number;
}>;
/** 组件数量最多的前几个实体 */
topEntitiesByComponents: Array<{
id: string;
name: string;
componentCount: number;
memory: number;
}>;
/** 实体详情列表 */
entityDetails?: Array<{
id: string | number;
name?: string;
tag?: string;
enabled: boolean;
componentCount: number;
components: string[];
}>;
/** 实体层次结构(根实体) */
entityHierarchy?: Array<{
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
componentCount: number;
componentTypes: string[];
parentId: number | null;
children: IEntityHierarchyNode[];
depth: number;
tag: number;
updateOrder: number;
}>;
/** 实体详细信息映射 */
entityDetailsMap?: Record<number, {
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
destroyed: boolean;
tag: number;
updateOrder: number;
componentMask: string;
parentId: number | null;
parentName: string | null;
childCount: number;
childIds: number[];
depth: number;
components: Array<{
typeName: string;
properties: Record<string, unknown>;
}>;
componentCount: number;
componentTypes: string[];
}>;
}
/**
* 系统调试数据接口
*/
interface ISystemDebugData {
/** 总系统数 */
totalSystems: number;
/** 系统信息列表 */
systemsInfo: Array<{
name: string;
type: string;
entityCount: number;
executionTime?: number;
averageExecutionTime?: number;
minExecutionTime?: number;
maxExecutionTime?: number;
executionTimeHistory?: number[];
memoryUsage?: number;
updateOrder: number;
enabled: boolean;
lastUpdateTime?: number;
}>;
}
/**
* 性能调试数据接口
*/
interface IPerformanceDebugData {
/** ECS框架执行时间(毫秒) */
frameTime: number;
/** 引擎总帧时间(毫秒) */
engineFrameTime?: number;
/** ECS占总帧时间百分比 */
ecsPercentage?: number;
/** 内存使用量(MB) */
memoryUsage: number;
/** FPS */
fps: number;
/** 平均ECS执行时间(毫秒) */
averageFrameTime: number;
/** 最小ECS执行时间(毫秒) */
minFrameTime: number;
/** 最大ECS执行时间(毫秒) */
maxFrameTime: number;
/** ECS执行时间历史记录 */
frameTimeHistory: number[];
/** 系统性能详情 */
systemPerformance: Array<{
systemName: string;
averageTime: number;
maxTime: number;
minTime: number;
samples: number;
percentage?: number;
}>;
/** 系统占比分析数据 */
systemBreakdown?: Array<{
systemName: string;
executionTime: number;
percentage: number;
}>;
/** 内存分配详情 */
memoryDetails?: {
entities: number;
components: number;
systems: number;
pooled: number;
totalMemory: number;
usedMemory: number;
freeMemory: number;
gcCollections: number;
};
}
/**
* 组件调试数据接口
*/
interface IComponentDebugData {
/** 组件类型数 */
componentTypes: number;
/** 组件实例总数 */
componentInstances: number;
/** 组件分布统计 */
componentStats: Array<{
typeName: string;
instanceCount: number;
memoryPerInstance: number;
totalMemory: number;
poolSize: number;
poolUtilization: number;
averagePerEntity?: number;
}>;
}
/**
* 场景调试数据接口
*/
interface ISceneDebugData {
/** 当前场景名称 */
currentSceneName: string;
/** 场景是否已初始化 */
isInitialized: boolean;
/** 场景运行时间(秒) */
sceneRunTime: number;
/** 场景实体数 */
sceneEntityCount: number;
/** 场景系统数 */
sceneSystemCount: number;
/** 场景内存使用量 */
sceneMemory: number;
/** 场景启动时间 */
sceneUptime: number;
}
/**
* 游戏组件基类
*
* ECS架构中的组件(Component),用于实现具体的游戏功能。
* 组件包含数据和行为,可以被添加到实体上以扩展实体的功能。
*
* @example
* ```typescript
* class HealthComponent extends Component {
* public health: number = 100;
*
* public takeDamage(damage: number): void {
* this.health -= damage;
* if (this.health <= 0) {
* this.entity.destroy();
* }
* }
* }
* ```
*/
declare abstract class Component implements IComponent {
/**
* 组件ID生成器
*
* 用于为每个组件分配唯一的ID。
*/
static _idGenerator: number;
/**
* 组件唯一标识符
*
* 在整个游戏生命周期中唯一的数字ID。
*/
readonly id: number;
/**
* 组件所属的实体
*
* 指向拥有此组件的实体实例。
*/
entity: Entity;
/**
* 组件启用状态
*
* 控制组件是否参与更新循环。
*/
private _enabled;
/**
* 更新顺序
*
* 决定组件在更新循环中的执行顺序。
*/
private _updateOrder;
/**
* 创建组件实例
*
* 自动分配唯一ID给组件。
*/
constructor();
/**
* 获取组件启用状态
*
* 组件的实际启用状态取决于自身状态和所属实体的状态。
*
* @returns 如果组件和所属实体都启用则返回true
*/
get enabled(): boolean;
/**
* 设置组件启用状态
*
* 当状态改变时会触发相应的生命周期回调。
*
* @param value - 新的启用状态
*/
set enabled(value: boolean);
/**
* 获取更新顺序
*
* @returns 组件的更新顺序值
*/
get updateOrder(): number;
/**
* 设置更新顺序
*
* @param value - 新的更新顺序值
*/
set updateOrder(value: number);
/**
* 组件添加到实体时的回调
*
* 当组件被添加到实体时调用,可以在此方法中进行初始化操作。
*/
onAddedToEntity(): void;
/**
* 组件从实体移除时的回调
*
* 当组件从实体中移除时调用,可以在此方法中进行清理操作。
*/
onRemovedFromEntity(): void;
/**
* 组件启用时的回调
*
* 当组件被启用时调用。
*/
onEnabled(): void;
/**
* 组件禁用时的回调
*
* 当组件被禁用时调用。
*/
onDisabled(): void;
/**
* 更新组件
*
* 每帧调用,用于更新组件的逻辑。
* 子类应该重写此方法来实现具体的更新逻辑。
*/
update(): void;
}
/**
* 高性能实体列表管理器
* 管理场景中的所有实体,支持快速查找和批量操作
*/
declare class EntityList {
buffer: Entity[];
private _scene;
private _idToEntity;
private _nameToEntities;
private _entitiesToAdd;
private _entitiesToRemove;
private _isUpdating;
get count(): number;
constructor(scene: any);
/**
* 添加实体(立即添加或延迟添加)
* @param entity 要添加的实体
*/
add(entity: Entity): void;
/**
* 立即添加实体
* @param entity 要添加的实体
*/
private addImmediate;
/**
* 移除实体(立即移除或延迟移除)
* @param entity 要移除的实体
*/
remove(entity: Entity): void;
/**
* 立即移除实体
* @param entity 要移除的实体
*/
private removeImmediate;
/**
* 移除所有实体
*/
removeAllEntities(): void;
/**
* 更新实体列表,处理延迟操作
*/
updateLists(): void;
/**
* 更新所有实体
*/
update(): void;
/**
* 根据名称查找实体(使用索引,O(1)复杂度)
* @param name 实体名称
* @returns 找到的第一个实体或null
*/
findEntity(name: string): Entity | null;
/**
* 根据名称查找所有实体
* @param name 实体名称
* @returns 找到的所有实体数组
*/
findEntitiesByName(name: string): Entity[];
/**
* 根据ID查找实体(使用索引,O(1)复杂度)
* @param id 实体ID
* @returns 找到的实体或null
*/
findEntityById(id: number): Entity | null;
/**
* 根据标签查找实体
* @param tag 标签
* @returns 找到的所有实体数组
*/
findEntitiesByTag(tag: number): Entity[];
/**
* 根据组件类型查找实体
* @param componentType 组件类型
* @returns 找到的所有实体数组
*/
findEntitiesWithComponent<T extends Component>(componentType: new (...args: unknown[]) => T): Entity[];
/**
* 批量操作:对所有实体执行指定操作
* @param action 要执行的操作
*/
forEach(action: (entity: Entity) => void): void;
/**
* 批量操作:对符合条件的实体执行指定操作
* @param predicate 筛选条件
* @param action 要执行的操作
*/
forEachWhere(predicate: (entity: Entity) => boolean, action: (entity: Entity) => void): void;
/**
* 更新名称索引
* @param entity 实体
* @param isAdd 是否为添加操作
*/
private updateNameIndex;
/**
* 获取实体列表的统计信息
* @returns 统计信息
*/
getStats(): {
totalEntities: number;
activeEntities: number;
pendingAdd: number;
pendingRemove: number;
nameIndexSize: number;
};
}
/**
* 事件处理器函数类型
*/
type EventHandler$1<T = any> = (event: T) => void;
/**
* 异步事件处理器函数类型
*/
type AsyncEventHandler$1<T = any> = (event: T) => Promise<void>;
/**
* 事件监听器配置
*/
interface EventListenerConfig {
/** 是否只执行一次 */
once?: boolean;
/** 优先级(数字越大优先级越高) */
priority?: number;
/** 是否异步执行 */
async?: boolean;
/** 执行上下文 */
context?: any;
}
/**
* 事件统计信息
*/
interface EventStats {
/** 事件类型 */
eventType: string;
/** 监听器数量 */
listenerCount: number;
/** 触发次数 */
triggerCount: number;
/** 总执行时间(毫秒) */
totalExecutionTime: number;
/** 平均执行时间(毫秒) */
averageExecutionTime: number;
/** 最后触发时间 */
lastTriggerTime: number;
}
/**
* 事件批处理配置
*/
interface EventBatchConfig {
/** 批处理大小 */
batchSize: number;
/** 批处理延迟(毫秒) */
delay: number;
/** 是否启用批处理 */
enabled: boolean;
}
/**
* 类型安全的高性能事件系统
* 支持同步/异步事件、优先级、批处理等功能
*/
declare class TypeSafeEventSystem {
private static readonly _logger;
private listeners;
private stats;
private batchQueue;
private batchTimers;
private batchConfigs;
private nextListenerId;
private isEnabled;
private maxListeners;
/**
* 添加事件监听器
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID(用于移除)
*/
on<T>(eventType: string, handler: EventHandler$1<T>, config?: EventListenerConfig): string;
/**
* 添加一次性事件监听器
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
once<T>(eventType: string, handler: EventHandler$1<T>, config?: EventListenerConfig): string;
/**
* 添加异步事件监听器
* @param eventType 事件类型
* @param handler 异步事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
onAsync<T>(eventType: string, handler: AsyncEventHandler$1<T>, config?: EventListenerConfig): string;
/**
* 移除事件监听器
* @param eventType 事件类型
* @param listenerId 监听器ID
* @returns 是否成功移除
*/
off(eventType: string, listenerId: string): boolean;
/**
* 移除指定事件类型的所有监听器
* @param eventType 事件类型
*/
offAll(eventType: string): void;
/**
* 触发事件
* @param eventType 事件类型
* @param event 事件数据
* @returns Promise(如果有异步监听器)
*/
emit<T>(eventType: string, event: T): Promise<void>;
/**
* 同步触发事件(忽略异步监听器)
* @param eventType 事件类型
* @param event 事件数据
*/
emitSync<T>(eventType: string, event: T): void;
/**
* 设置事件批处理配置
* @param eventType 事件类型
* @param config 批处理配置
*/
setBatchConfig(eventType: string, config: EventBatchConfig): void;
/**
* 立即处理指定事件类型的批处理队列
* @param eventType 事件类型
*/
flushBatch(eventType: string): void;
/**
* 获取事件统计信息
* @param eventType 事件类型(可选)
* @returns 统计信息
*/
getStats(eventType?: string): EventStats | Map<string, EventStats>;
/**
* 重置统计信息
* @param eventType 事件类型(可选,不指定则重置所有)
*/
resetStats(eventType?: string): void;
/**
* 启用/禁用事件系统
* @param enabled 是否启用
*/
setEnabled(enabled: boolean): void;
/**
* 检查是否有指定事件类型的监听器
* @param eventType 事件类型
* @returns 是否有监听器
*/
hasListeners(eventType: string): boolean;
/**
* 获取指定事件类型的监听器数量
* @param eventType 事件类型
* @returns 监听器数量
*/
getListenerCount(eventType: string): number;
/**
* 清空所有事件监听器和数据
*/
clear(): void;
/**
* 设置每个事件类型的最大监听器数量
* @param max 最大数量
*/
setMaxListeners(max: number): void;
/**
* 添加监听器的内部实现
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 配置
* @returns 监听器ID
*/
private addListener;
/**
* 执行事件的内部实现
* @param eventType 事件类型
* @param event 事件数据
*/
private executeEvent;
/**
* 按优先级排序监听器
* @param listeners 监听器数组
* @returns 排序后的监听器数组
*/
private sortListenersByPriority;
/**
* 移除指定的监听器
* @param eventType 事件类型
* @param listenerIds 要移除的监听器ID数组
*/
private removeListeners;
/**
* 添加事件到批处理队列
* @param eventType 事件类型
* @param event 事件数据
*/
private addToBatch;
/**
* 处理批处理事件
* @param eventType 事件类型
* @param batch 批处理事件数组
*/
private processBatch;
/**
* 清除指定事件类型的批处理
* @param eventType 事件类型
*/
private clearBatch;
/**
* 清除所有批处理
*/
private clearAllBatches;
/**
* 更新事件统计信息
* @param eventType 事件类型
* @param executionTime 执行时间
*/
private updateStats;
/**
* 创建空的统计信息
* @param eventType 事件类型
* @returns 空的统计信息
*/
private createEmptyStats;
}
/**
* 日志级别
*/
declare enum LogLevel {
Debug = 0,
Info = 1,
Warn = 2,
Error = 3,
Fatal = 4,
None = 5
}
/**
* 日志接口
*/
interface ILogger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
fatal(message: string, ...args: unknown[]): void;
}
/**
* 日志配置
*/
interface LoggerConfig {
/** 日志级别 */
level: LogLevel;
/** 是否启用时间戳 */
enableTimestamp: boolean;
/** 是否启用颜色 */
enableColors: boolean;
/** 日志前缀 */
prefix?: string;
/** 自定义输出函数 */
output?: (level: LogLevel, message: string) => void;
}
/**
* 默认控制台日志实现
*/
declare class ConsoleLogger implements ILogger {
private _config;
constructor(config?: Partial<LoggerConfig>);
/**
* 输出调试级别日志
* @param message 日志消息
* @param args 附加参数
*/
debug(message: string, ...args: unknown[]): void;
/**
* 输出信息级别日志
* @param message 日志消息
* @param args 附加参数
*/
info(message: string, ...args: unknown[]): void;
/**
* 输出警告级别日志
* @param message 日志消息
* @param args 附加参数
*/
warn(message: string, ...args: unknown[]): void;
/**
* 输出错误级别日志
* @param message 日志消息
* @param args 附加参数
*/
error(message: string, ...args: unknown[]): void;
/**
* 输出致命错误级别日志
* @param message 日志消息
* @param args 附加参数
*/
fatal(message: string, ...args: unknown[]): void;
/**
* 设置日志级别
* @param level 日志级别
*/
setLevel(level: LogLevel): void;
/**
* 设置日志前缀
* @param prefix 前缀字符串
*/
setPrefix(prefix: string): void;
/**
* 内部日志输出方法
* @param level 日志级别
* @param message 日志消息
* @param args 附加参数
*/
private log;
/**
* 输出到控制台
* @param level 日志级别
* @param message 格式化后的消息
* @param args 附加参数
*/
private outputToConsole;
/**
* 获取控制台颜色配置
* @returns 颜色配置对象
*/
private getColors;
}
/**
* 日志管理器
*/
declare class LoggerManager {
private static _instance;
private _loggers;
private _defaultLogger;
private constructor();
/**
* 获取日志管理器实例
* @returns 日志管理器实例
*/
static getInstance(): LoggerManager;
/**
* 获取或创建日志器
* @param name 日志器名称
* @returns 日志器实例
*/
getLogger(name?: string): ILogger;
/**
* 设置日志器
* @param name 日志器名称
* @param logger 日志器实例
*/
setLogger(name: string, logger: ILogger): void;
/**
* 设置全局日志级别
* @param level 日志级别
*/
setGlobalLevel(level: LogLevel): void;
/**
* 创建子日志器
* @param parentName 父日志器名称
* @param childName 子日志器名称
* @returns 子日志器实例
*/
createChildLogger(parentName: string, childName: string): ILogger;
}
/**
* 默认日志器实例
*/
declare const Logger: ILogger;
/**
* 创建命名日志器
* @param name 日志器名称
* @returns 日志器实例
*/
declare function createLogger(name: string): ILogger;
/**
* 设置全局日志级别
* @param level 日志级别
*/
declare function setGlobalLogLevel(level: LogLevel): void;
/**
* BigInt兼容性抽象层
*
* 为不支持BigInt的环境提供兼容实现,确保ECS框架在所有平台上都能正常运行。
* 自动检测运行时环境的BigInt支持情况,并提供统一的接口。
*
* @example
* ```typescript
* // 创建兼容的BigInt值
* const value = BigIntFactory.create(123);
*
* // 位运算
* const result = value.or(BigIntFactory.create(456));
*
* // 检查兼容性
* console.log(BigIntFactory.isNativeSupported()); // true/false
* ```
*/
/**
* BigInt兼容接口
*
* 定义了BigInt的基本操作接口,支持原生BigInt和兼容实现的统一调用。
*/
interface IBigIntLike {
/**
* 获取数值表示
* @returns 数值
*/
valueOf(): number;
/**
* 转换为字符串
* @param radix 进制,支持2、10、16
* @returns 字符串表示
*/
toString(radix?: number): string;
/**
* 位运算:与
* @param other 另一个BigInt值
* @returns 运算结果
*/
and(other: IBigIntLike): IBigIntLike;
/**
* 位运算:或
* @param other 另一个BigInt值
* @returns 运算结果
*/
or(other: IBigIntLike): IBigIntLike;
/**
* 位运算:异或
* @param other 另一个BigInt值
* @returns 运算结果
*/
xor(other: IBigIntLike): IBigIntLike;
/**
* 位运算:非
* @param maxBits 最大位数限制
* @returns 运算结果
*/
not(maxBits?: number): IBigIntLike;
/**
* 左移位运算
* @param bits 移位数
* @returns 运算结果
*/
shiftLeft(bits: number): IBigIntLike;
/**
* 右移位运算
* @param bits 移位数
* @returns 运算结果
*/
shiftRight(bits: number): IBigIntLike;
/**
* 相等比较
* @param other 另一个BigInt值
* @returns 是否相等
*/
equals(other: IBigIntLike): boolean;
/**
* 检查是否为零
* @returns 是否为零
*/
isZero(): boolean;
/**
* 创建副本
* @returns 新的实例
*/
clone(): IBigIntLike;
}
/**
* BigInt工厂类
*
* 自动检测运行时环境的BigInt支持情况,并提供统一的创建接口。
* 在支持BigInt的环境中使用原生实现,在不支持的环境中使用兼容实现。
*/
declare class BigIntFactory {
private static _supportsBigInt;
private static _cachedZero;
private static _cachedOne;
/**
* 检查是否支持原生BigInt
* @returns 是否支持原生BigInt
*/
static isNativeSupported(): boolean;
/**
* 检测BigInt支持情况
* @returns 是否支持BigInt
*/
private static detectBigIntSupport;
/**
* 创建BigInt兼容值
* @param value 初始值
* @returns IBigIntLike实例
*/
static create(value?: number | string | bigint): IBigIntLike;
/**
* 创建零值
* @returns 零值的IBigIntLike实例
*/
static zero(): IBigIntLike;
/**
* 创建1值
* @returns 1值的IBigIntLike实例
*/
static one(): IBigIntLike;
/**
* 从二进制字符串创建
* @param binary 二进制字符串
* @returns IBigIntLike实例
*/
static fromBinaryString(binary: string): IBigIntLike;
/**
* 从十六进制字符串创建
* @param hex 十六进制字符串
* @returns IBigIntLike实例
*/
static fromHexString(hex: string): IBigIntLike;
/**
* 获取环境信息
* @returns 环境信息对象
*/
static getEnvironmentInfo(): EnvironmentInfo;
/**
* 检测运行环境
* @returns 环境类型
*/
private static detectEnvironment;
/**
* 检测JavaScript引擎
* @returns JS引擎信息
*/
private static detectJSEngine;
}
/**
* 环境信息接口
*/
interface EnvironmentInfo {
/** 是否支持BigInt */
supportsBigInt: boolean;
/** 运行环境 */
environment: string;
/** JavaScript引擎 */
jsEngine: string;
}
/**
* 启用SoA优化装饰器
* 默认关闭SoA,只有在大规模批量操作场景下才建议开启
*/
declare function EnableSoA<T extends ComponentType>(target: T): T;
/**
* 高精度数值装饰器
* 标记字段需要保持完整精度,存储为复杂对象而非TypedArray
*/
declare function HighPrecision(target: any, propertyKey: string | symbol): void;
/**
* 64位浮点数装饰器
* 标记字段使用Float64Array存储(更高精度但更多内存)
*/
declare function Float64(target: any, propertyKey: string | symbol): void;
/**
* 32位浮点数装饰器
* 标记字段使用Float32Array存储(默认类型,平衡性能和精度)
*/
declare function Float32(target: any, propertyKey: string | symbol): void;
/**
* 32位整数装饰器
* 标记字段使用Int32Array存储(适用于整数值)
*/
declare function Int32(target: any, propertyKey: string | symbol): void;
/**
* 序列化Map装饰器
* 标记Map字段需要序列化/反序列化存储
*/
declare function SerializeMap(target: any, propertyKey: string | symbol): void;
/**
* SoA存储器(需要装饰器启用)
* 使用Structure of Arrays存储模式,在大规模批量操作时提供优异性能
*/
declare class SoAStorage<T extends Component> {
private static readonly _logger;
private fields;
private stringFields;
private serializedFields;
private complexFields;
private entityToIndex;
private indexToEntity;
private freeIndices;
private _size;
private _capacity;
readonly type: ComponentType<T>;
constructor(componentType: ComponentType<T>);
private initializeFields;
addComponent(entityId: number, component: T): void;
private updateComponentAtIndex;
/**
* 序列化值为JSON字符串
*/
private serializeValue;
/**
* 反序列化JSON字符串为值
*/
private deserializeValue;
/**
* 深拷贝对象
*/
private deepClone;
getComponent(entityId: number): T | null;
private getFieldType;
hasComponent(entityId: number): boolean;
removeComponent(entityId: number): T | null;
private resize;
getActiveIndices(): number[];
getFieldArray(fieldName: string): Float32Array | Float64Array | Int32Array | null;
size(): number;
clear(): void;
compact(): void;
getStats(): any;
/**
* 执行向量化批量操作
* @param operation 操作函数,接收字段数组和活跃索引
*/
performVectorizedOperation(operation: (fieldArrays: Map<string, Float32Array | Float64Array | Int32Array>, activeIndices: number[]) => void): void;
}
/**
* 组件类型定义
* 支持任意构造函数签名,提供更好的类型安全性
*/
type ComponentType<T extends Component = Component> = new (...args: any[]) => T;
/**
* 组件注册表
* 管理组件类型的位掩码分配
*/
declare class ComponentRegistry {
protected static readonly _logger: ILogger;
private static componentTypes;
private static componentNameToType;
private static componentNameToId;
private static maskCache;
private static nextBitIndex;
private static maxComponents;
/**
* 注册组件类型并分配位掩码
* @param componentType 组件类型
* @returns 分配的位索引
*/
static register<T extends Component>(componentType: ComponentType<T>): number;
/**
* 获取组件类型的位掩码
* @param componentType 组件类型
* @returns 位掩码
*/
static getBitMask<T extends Component>(componentType: ComponentType<T>): IBigIntLike;
/**
* 获取组件类型的位索引
* @param componentType 组件类型
* @returns 位索引
*/
static getBitIndex<T extends Component>(componentType: ComponentType<T>): number;
/**
* 检查组件类型是否已注册
* @param componentType 组件类型
* @returns 是否已注册
*/
static isRegistered<T extends Component>(componentType: ComponentType<T>): boolean;
/**
* 通过名称获取组件类型
* @param componentName 组件名称
* @returns 组件类型构造函数
*/
static getComponentType(componentName: string): Function | null;
/**
* 获取所有已注册的组件类型
* @returns 组件类型映射
*/
static getAllRegisteredTypes(): Map<Function, number>;
/**
* 获取所有组件名称到类型的映射
* @returns 名称到类型的映射
*/
static getAllComponentNames(): Map<string, Function>;
/**
* 通过名称获取组件类型ID
* @param componentName 组件名称
* @returns 组件类型ID
*/
static getComponentId(componentName: string): number | undefined;
/**
* 注册组件类型(通过名称)
* @param componentName 组件名称
* @returns 分配的组件ID
*/
static registerComponentByName(componentName: string): number;
/**
* 创建单个组件的掩码
* @param componentName 组件名称
* @returns 组件掩码
*/
static createSingleComponentMask(componentName: string): IBigIntLike;
/**
* 创建多个组件的掩码
* @param componentNames 组件名称数组
* @returns 组合掩码
*/
static createComponentMask(componentNames: string[]): IBigIntLike;
/**
* 清除掩码缓存
*/
static clearMaskCache(): void;
/**
* 重置注册表(用于测试)
*/
static reset(): void;
}
/**
* 高性能组件存储器
* 使用SoA(Structure of Arrays)模式存储组件
*/
declare class ComponentStorage<T extends Component> {
private components;
private entityToIndex;
private indexToEntity;
private freeIndices;
private componentType;
private _size;
constructor(componentType: ComponentType<T>);
/**
* 添加组件
* @param entityId 实体ID
* @param component 组件实例
*/
addComponent(entityId: number, component: T): void;
/**
* 获取组件
* @param entityId 实体ID
* @returns 组件实例或null
*/
getComponent(entityId: number): T | null;
/**
* 检查实体是否有此组件
* @param entityId 实体ID
* @returns 是否有组件
*/
hasComponent(entityId: number): boolean;
/**
* 移除组件
* @param entityId 实体ID
* @returns 被移除的组件或null
*/
removeComponent(entityId: number): T | null;
/**
* 高效遍历所有组件
* @param callback 回调函数
*/
forEach(callback: (component: T, entityId: number, index: number) => void): void;
/**
* 获取所有组件(密集数组)
* @returns 组件数组
*/
getDenseArray(): {
components: T[];
entityIds: number[];
};
/**
* 清空所有组件
*/
clear(): void;
/**
* 获取组件数量
*/
get size(): number;
/**
* 获取组件类型
*/
get type(): ComponentType<T>;
/**
* 压缩存储(移除空洞)
*/
compact(): void;
/**
* 获取存储统计信息
*/
getStats(): {
totalSlots: number;
usedSlots: number;
freeSlots: number;
fragmentation: number;
};
}
/**
* 组件存储管理器
* 管理所有组件类型的存储器
*/
declare class ComponentStorageManager {
private static readonly _logger;
private storages;
/**
* 获取或创建组件存储器(默认原始存储)
* @param componentType 组件类型
* @returns 组件存储器
*/
getStorage<T extends Component>(componentType: ComponentType<T>): ComponentStorage<T> | SoAStorage<T>;
/**
* 添加组件
* @param entityId 实体ID
* @param component 组件实例
*/
addComponent<T extends Component>(entityId: number, component: T): void;
/**
* 获取组件
* @param entityId 实体ID
* @param componentType 组件类型
* @returns 组件实例或null
*/
getComponent<T extends Component>(entityId: number, componentType: ComponentType<T>): T | null;
/**
* 检查实体是否有组件
* @param entityId 实体ID
* @param componentType 组件类型
* @returns 是否有组件
*/
hasComponent<T extends Component>(entityId: number, componentType: ComponentType<T>): boolean;
/**
* 移除组件
* @param entityId 实体ID
* @param componentType 组件类型
* @returns 被移除的组件或null
*/
removeComponent<T extends Component>(entityId: number, componentType: ComponentType<T>): T | null;
/**
* 移除实体的所有组件
* @param entityId 实体ID
*/
removeAllComponents(entityId: number): void;
/**
* 获取实体的组件位掩码
* @param entityId 实体ID
* @returns 组件位掩码
*/
getComponentMask(entityId: number): IBigIntLike;
/**
* 压缩所有存储器
*/
compactAll(): void;
/**
* 获取所有存储器的统计信息
*/
getAllStats(): Map<string, any>;
/**
* 清空所有存储器
*/
clear(): void;
}
/**
* 组件索引类型
*/
declare enum IndexType {
/** 哈希索引 - 最快查找 */
HASH = "hash",
/** 位图索引 - 内存高效 */
BITMAP = "bitmap",
/** 排序索引 - 支持范围查询 */
SORTED = "sorted"
}
/**
* 索引统计信息
*/
interface IndexStats {
/** 索引类型 */
type: IndexType;
/** 索引大小 */
size: number;
/** 内存使用量(字节) */
memoryUsage: number;
/** 查询次数 */
queryCount: number;
/** 平均查询时间(毫秒) */
avgQueryTime: number;
/** 最后更新时间 */
lastUpdated: number;
}
/**
* 组件索引接口
*/
interface IComponentIndex {
/** 索引类型 */
readonly type: IndexType;
/** 添加实体到索引 */
addEntity(entity: Entity): void;
/** 从索引中移除实体 */
removeEntity(entity: Entity): void;
/** 查询包含指定组件的实体 */
query(componentType: ComponentType): Set<Entity>;
/** 批量查询多个组件 */
queryMultiple(componentTypes: ComponentType[], operation: 'AND' | 'OR'): Set<Entity>;
/** 清空索引 */
clear(): void;
/** 获取索引统计信息 */
getStats(): IndexStats;
}
/**
* 哈希索引实现
*
* 使用Map数据结构,提供O(1)的查找性能。
* 适合大多数查询场景。
*/
declare class HashComponentIndex implements IComponentIndex {
readonly type = IndexType.HASH;
private _componentToEntities;
private _entityToComponents;
private _queryCount;
private _totalQueryTime;
private _lastUpdated;
private _setPool;
private _componentTypeSetPool;
addEntity(entity: Entity): void;
removeEntity(entity: Entity): void;
query(componentType: ComponentType): Set<Entity>;
queryMultiple(componentTypes: ComponentType[], operation: 'AND' | 'OR'): Set<Entity>;
clear(): void;
getStats(): IndexStats;
}
/**
* 位图索引实现
*
* 使用位操作进行快速集合运算,内存效率高。
* 适合有限组件类型和大量实体的场景。
*/
declare class BitmapComponentIndex implements IComponentIndex {
readonly type = IndexType.BITMAP;
private _componentTypeToBit;
private _entityToBitmap;
private _bitToEntities;
private _nextBit;
private _queryCount;
private _totalQueryTime;
private _lastUpdated;
addEntity(entity: Entity): void;
removeEntity(entity: Entity): void;
query(componentType: ComponentType): Set<Entity>;
queryMultiple(componentTypes: ComponentType[], operation: 'AND' | 'OR'): Set<Entity>;
clear(): void;
getStats(): IndexStats;
}
/**
* 智能组件索引管理器
*
* 根据使用模式自动选择最优的索引策略。
* 支持动态切换索引类型以获得最佳性能。
*/
declare class ComponentIndexManager {
private _activeIndex;
private _indexHistory;
private _autoOptimize;
private _optimizationThreshold;
constructor(initialType?: IndexType);
/**
* 添加实体到索引
*/
addEntity(entity: Entity): void;
/**
* 从索引中移除实体
*/
removeEntity(entity: Entity): void;
/**
* 查询包含指定组件的实体
*/
query(componentType: ComponentType): Set<Entity>;
/**
* 批量查询多个组件
*/
queryMultiple(componentTypes: ComponentType[], operation: 'AND' | 'OR'): Set<Entity>;
/**
* 手动切换索引类型
*/
switchIndexType(type: IndexType): void;
/**
* 启用/禁用自动优化
*/
setAutoOptimize(enabled: boolean): void;
/**
* 获取当前索引统计信息
*/
getStats(): IndexStats;
/**
* 获取所有索引类型的历史统计信息
*/
getAllStats(): Map<IndexType, IndexStats>;
/**
* 清空索引
*/
clear(): void;
/**
* 创建指定类型的索引
*/
private createIndex;
/**
* 检查是否需要优化索引
*/
private checkOptimization;
}
/**
* 原型标识符
*/
type ArchetypeId = string;
/**
* 原型数据结构
*/
interface Archetype {
/** 原型唯一标识符 */
id: ArchetypeId;
/** 包含的组件类型 */
componentTypes: ComponentType[];
/** 属于该原型的实体列表 */
entities: Entity[];
/** 原型创建时间 */
createdAt: number;
/** 最后更新时间 */
updatedAt: number;
}
/**
* 原型查询结果
*/
interface ArchetypeQueryResult {
/** 匹配的原型列表 */
archetypes: Archetype[];
/** 所有匹配实体的总数 */
totalEntities: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否使用了缓存 */
fromCache: boolean;
}
/**
* Archetype系统
*
* 根据实体的组件组合将实体分组到不同的原型中,提供高效的查询性能。
*/
declare class ArchetypeSystem {
/** 所有原型的映射表 */
private _archetypes;
/** 实体到原型的映射 */
private _entityToArchetype;
/** 组件类型到原型的映射 */
private _componentToArchetypes;
/** 查询缓存 */
private _queryCache;
private _cacheTimeout;
private _maxCacheSize;
/**
* 添加实体到原型系统
*/
addEntity(entity: Entity): void;
/**
* 从原型系统中移除实体
*/
removeEntity(entity: Entity): void;
/**
* 查询包含指定组件组合的原型
*/
queryArchetypes(componentTypes: ComponentType[], operation?: 'AND' | 'OR'): ArchetypeQueryResult;
/**
* 获取实体所属的原型
*/
getEntityArchetype(entity: Entity): Archetype | undefined;
/**
* 获取所有原型
*/
getAllArchetypes(): Archetype[];
/**
* 清空所有数据
*/
clear(): void;
/**
* 获取实体的组件类型列表
*/
private getEntityComponentTypes;
/**
* 生成原型ID
*/
private generateArchetypeId;
/**
* 创建新原型
*/
private createArchetype;
/**
* 检查原型是否包含所有指定组件
*/
private archetypeContainsAllComponents;
/**
* 更新组件索引
*/
private updateComponentIndexes;
/**
* 使查询缓存失效
*/
private invalidateQueryCache;
}
/**
* 实体查询结果接口
*/
interface QueryResult {
entities: Entity[];
count: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否来自缓存 */
fromCache: boolean;
}
/**
* 高性能实体查询系统
*
* 提供快速的实体查询功能,支持按组件类型、标签、名称等多种方式查询实体。
* 系统采用多级索引和智能缓存机制,确保在大量实体场景下的查询性能。
*
* 主要特性:
* - 支持单组件和多组件查询
* - 自动索引管理和缓存优化
* - WebAssembly计算加速(如果可用)
* - 详细的性能统计信息
*
* @example
* ```typescript
* // 查询所有包含Position和Velocity组件的实体
* const movingEntities = querySystem.queryAll(PositionComponent, VelocityComponent);
*
* // 查询特定标签的实体
* const playerEntities = querySystem.queryByTag(PLAYER_TAG);
* ```
*/
declare class QuerySystem {
private _logger;
private entities;
private entityIndex;
private indexDirty;
private _version;
private queryCache;
private cacheMaxSize;
private cacheTimeout;
private componentPoolManager;
private componentIndexManager;
private archetypeSystem;
private dirtyTrackingSystem;
private queryStats;
constructor();
/**
* 设置实体列表并重建索引
*
* 当实体集合发生大规模变化时调用此方法。
* 系统将重新构建所有索引以确保查询性能。
*
* @param entities 新的实体列表
*/
setEntities(entities: Entity[]): void;
/**
* 添加单个实体到查询系统
*
* 将新实体添加到查询系统中,并自动更新相关索引。
* 为了提高批量添加性能,可以延迟缓存清理。