@esengine/ecs-framework 2.1.12 → 2.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/COCOS_USAGE.md CHANGED
@@ -8,11 +8,14 @@
8
8
  npm install @esengine/ecs-framework
9
9
  ```
10
10
 
11
- ## 重要说明
11
+ ## WASM 支持(可选)
12
12
 
13
- ⚠️ **Cocos Creator 环境下无法直接使用 WASM 加速**
13
+ 🚀 **WASM 模块已独立发布,需要手动下载和配置**
14
14
 
15
- 由于 Cocos Creator 的特殊 WASM 加载机制,框架会自动检测 Cocos 环境并回退到 JavaScript 实现。这不会影响功能,只是性能稍有差异。
15
+ WASM 模块不再包含在 npm 包中,如需使用请从 [GitHub Release](https://github.com/esengine/ecs-framework/releases) 下载。
16
+
17
+ - 不使用 WASM:框架自动使用 JavaScript 实现,功能完全正常
18
+ - 使用 WASM:提供查询性能优化,需要手动配置
16
19
 
17
20
  ## 基本使用
18
21
 
@@ -26,9 +29,34 @@ export class GameManager extends Component {
26
29
  private core: Core;
27
30
 
28
31
  onLoad() {
29
- // 创建核心实例(Cocos环境会自动禁用WASM)
32
+ // 创建核心实例
30
33
  this.core = Core.create(true);
31
34
  console.log('ECS核心已初始化');
35
+
36
+ // 可选:加载WASM支持(需要先下载WASM包)
37
+ this.loadWasmSupport();
38
+ }
39
+
40
+ private async loadWasmSupport() {
41
+ try {
42
+ // 1. 导入WASM胶水代码(需要将文件放到项目中)
43
+ const { default: wasmFactory } = await import('./ecs_wasm_core.js');
44
+
45
+ // 2. 使用Cocos API加载WASM文件(需要先导入到资源管理器)
46
+ const wasmFile = await this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "your-wasm-uuid");
47
+
48
+ // 3. 初始化WASM支持
49
+ const { ecsCore } = await import('@esengine/ecs-framework');
50
+ const success = await ecsCore.initializeWasm(wasmFactory, wasmFile);
51
+
52
+ if (success) {
53
+ console.log('✅ ECS WASM加速已启用');
54
+ } else {
55
+ console.log('⚠️ WASM初始化失败,使用JavaScript实现');
56
+ }
57
+ } catch (error) {
58
+ console.log('⚠️ WASM不可用,使用JavaScript实现:', error);
59
+ }
32
60
  }
33
61
  }
34
62
  ```
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @esengine/ecs-framework v2.1.12
2
+ * @esengine/ecs-framework v2.1.13
3
3
  * TypeScript definitions
4
4
  */
5
5
  /**
@@ -5466,22 +5466,24 @@ declare class WasmLoader {
5466
5466
  private silent;
5467
5467
  setSilent(silent: boolean): void;
5468
5468
  /**
5469
- * 为Cocos Creator手动初始化WASM模块
5469
+ * 手动初始化WASM模块
5470
5470
  *
5471
5471
  * @param wasmFactory WASM工厂函数(从.js文件导入的default)
5472
- * @param wasmFile WASM文件数据(通过loadWasmOrAsm加载的文件)
5472
+ * @param wasmFile WASM文件数据
5473
5473
  * @returns 是否初始化成功
5474
5474
  *
5475
5475
  * @example
5476
5476
  * ```typescript
5477
5477
  * import { ecsCore } from '@esengine/ecs-framework';
5478
5478
  *
5479
- * // 1. 首先导入WASM的JS文件
5479
+ * // 1. 导入WASM的JS文件
5480
5480
  * import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
5481
- * // 2. 使用Cocos的API加载WASM文件
5482
- * this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "your-wasm-uuid").then((wasmFile) => {
5481
+ * // 2. 加载WASM文件(具体方式根据引擎而定)
5482
+ * // Cocos Creator: this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "uuid")
5483
+ * // 其他环境: fetch('./ecs_wasm_core_bg.wasm')
5484
+ * loadWasmFile().then((wasmFile) => {
5483
5485
  * // 3. 手动初始化ECS的WASM支持
5484
- * ecsCore.initializeForCocos(wasmFactory, wasmFile).then((success) => {
5486
+ * ecsCore.initializeWasm(wasmFactory, wasmFile).then((success) => {
5485
5487
  * if (success) {
5486
5488
  * console.log("ECS WASM初始化成功");
5487
5489
  * } else {
@@ -5492,16 +5494,12 @@ declare class WasmLoader {
5492
5494
  * });
5493
5495
  * ```
5494
5496
  */
5495
- initializeForCocos(wasmFactory: any, wasmFile: any): Promise<boolean>;
5497
+ initializeWasm(wasmFactory: any, wasmFile: any): Promise<boolean>;
5496
5498
  /**
5497
- * 按照Cocos Creator的方式初始化WASM
5499
+ * 通用WASM初始化方法
5498
5500
  */
5499
- private initWasmForCocos;
5501
+ private initWasmInstance;
5500
5502
  loadWasmModule(): Promise<boolean>;
5501
- /**
5502
- * 检测是否在Cocos Creator环境中
5503
- */
5504
- private detectCocosEnvironment;
5505
5503
  private initializeWasmModule;
5506
5504
  getWasmCore(): WasmEcsCoreInstance | null;
5507
5505
  getWasmModule(): WasmModule | null;
@@ -5546,13 +5544,13 @@ declare class WasmEcsCore {
5546
5544
  constructor();
5547
5545
  setSilent(silent: boolean): void;
5548
5546
  /**
5549
- * 为Cocos Creator手动初始化WASM模块
5547
+ * 手动初始化WASM模块
5550
5548
  *
5551
5549
  * @param wasmFactory WASM工厂函数(从.js文件导入的default)
5552
- * @param wasmFile WASM文件数据(通过loadWasmOrAsm加载的文件)
5550
+ * @param wasmFile WASM文件数据
5553
5551
  * @returns 是否初始化成功
5554
5552
  */
5555
- initializeForCocos(wasmFactory: any, wasmFile: any): Promise<boolean>;
5553
+ initializeWasm(wasmFactory: any, wasmFile: any): Promise<boolean>;
5556
5554
  initialize(): Promise<boolean>;
5557
5555
  createEntity(): EntityId;
5558
5556
  destroyEntity(entityId: EntityId): boolean;
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- class t{constructor(t,e){this.func=t,this.context=e}}class e{constructor(){this._messageTable=new Map}addObserver(e,s,n){let i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,s)||i.push(new t(s,n))}removeObserver(t,e){let s=this._messageTable.get(t);if(s){let t=s.findIndex((t=>t.func==e));-1!=t&&s.splice(t,1)}}emit(t,...e){let s=this._messageTable.get(t);if(s)for(let t of s)t.func.call(t.context,...e)}hasObserver(t,e){let s=this._messageTable.get(t);return!!s&&s.some((t=>t.func===e))}}var s,n,i;!function(t){t[t.sceneChanged=0]="sceneChanged",t[t.frameUpdated=1]="frameUpdated",t[t.renderChanged=2]="renderChanged"}(s||(s={})),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(n||(n={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(i||(i={}));const o={CORE:{SCENE_CHANGED:"core:scene:changed",FRAME_UPDATED:"core:frame:updated",RENDER_CHANGED:"core:render:changed"},ENTITY:{CREATED:n.ENTITY_CREATED,DESTROYED:n.ENTITY_DESTROYED,ENABLED:n.ENTITY_ENABLED,DISABLED:n.ENTITY_DISABLED,TAG_ADDED:n.ENTITY_TAG_ADDED,TAG_REMOVED:n.ENTITY_TAG_REMOVED,NAME_CHANGED:n.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:n.COMPONENT_ADDED,REMOVED:n.COMPONENT_REMOVED,MODIFIED:n.COMPONENT_MODIFIED,ENABLED:n.COMPONENT_ENABLED,DISABLED:n.COMPONENT_DISABLED},SYSTEM:{ADDED:n.SYSTEM_ADDED,REMOVED:n.SYSTEM_REMOVED,ENABLED:n.SYSTEM_ENABLED,DISABLED:n.SYSTEM_DISABLED,PROCESSING_START:n.SYSTEM_PROCESSING_START,PROCESSING_END:n.SYSTEM_PROCESSING_END,ERROR:n.SYSTEM_ERROR},PERFORMANCE:{WARNING:n.PERFORMANCE_WARNING,CRITICAL:n.PERFORMANCE_CRITICAL,MEMORY_HIGH:n.MEMORY_USAGE_HIGH,FRAME_DROP:n.FRAME_RATE_DROP}};class r{static isValid(t){return this.validTypes.has(t)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(t){this.validTypes.add(t)}static removeCustomType(t){this.validTypes.delete(t)}}r.validTypes=new Set([...Object.values(s).map((t=>t.toString())),...Object.values(n),...Object.values(o.CORE),...Object.values(o.ENTITY),...Object.values(o.COMPONENT),...Object.values(o.SYSTEM),...Object.values(o.PERFORMANCE)]);class a{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(t){this.setEnabled(t)}setEnabled(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}}class h{static update(t=-1){if(-1===t&&(t=Date.now()),this._isFirstUpdate)return this._lastTime=t,void(this._isFirstUpdate=!1);this.unscaledDeltaTime=(t-this._lastTime)/1e3,this.deltaTime=this.unscaledDeltaTime*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++,this._lastTime=t}static sceneChanged(){this._isFirstUpdate=!0}static checkEvery(t,e){return this.totalTime-e>=t}}h.deltaTime=0,h.unscaledDeltaTime=0,h.totalTime=0,h.unscaledTotalTime=0,h.timeScale=1,h.frameCount=0,h._lastTime=0,h._isFirstUpdate=!0;class c{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}reset(){this._elapsedTime=0}stop(){this._isDone=!0}tick(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=h.deltaTime,this._isDone}initialize(t,e,s,n){this._timeInSeconds=t,this._repeats=e,this.context=s,this._onTime=n.bind(s)}unload(){this.context=null,this._onTime=null}}class l extends a{constructor(){super(...arguments),this._timers=[]}update(){for(let t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))}schedule(t,e,s,n){let i=new c;return i.initialize(t,e,s,n),this._timers.push(i),i}}var u;!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(u||(u={}));class m{static get instance(){return m._instance||(m._instance=new m),m._instance}constructor(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(t){return this._isEnabled?performance.now():0}endMonitoring(t,e,s=0){if(!this._isEnabled||0===e)return;const n=performance.now(),i=n-e,o={name:t,executionTime:i,entityCount:s,averageTimePerEntity:s>0?i/s:0,lastUpdateTime:n};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let s=this._systemStats.get(t);s||(s={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,s)),s.totalTime+=e,s.executionCount++,s.averageTime=s.totalTime/s.executionCount,s.minTime=Math.min(s.minTime,e),s.maxTime=Math.max(s.maxTime,e),s.recentTimes.push(e),s.recentTimes.length>this._maxRecentSamples&&s.recentTimes.shift(),this.calculateAdvancedStats(s)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,s=t.recentTimes.reduce(((t,s)=>t+Math.pow(s-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(s);const n=[...t.recentTimes].sort(((t,e)=>t-e)),i=n.length;t.percentile95=n[Math.floor(.95*i)]||0,t.percentile99=n[Math.floor(.99*i)]||0}getSystemData(t){return this._systemData.get(t)}getSystemStats(t){return this._systemStats.get(t)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const t=[];t.push("=== ECS Performance Report ==="),t.push("");const e=Array.from(this._systemStats.entries()).sort(((t,e)=>e[1].averageTime-t[1].averageTime));for(const[s,n]of e){const e=this._systemData.get(s);t.push(`System: ${s}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${n.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${n.minTime.toFixed(2)}ms / ${n.maxTime.toFixed(2)}ms`),t.push(` Total: ${n.totalTime.toFixed(2)}ms (${n.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const s=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${s.toFixed(2)}ms`),t.push(`Systems Count: ${this._systemData.size}`),t.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(t){this._systemData.delete(t),this._systemStats.delete(t)}getPerformanceWarnings(t=16.67){const e=[];for(const[s,n]of this._systemData.entries())n.executionTime>t&&e.push(`${s}: ${n.executionTime.toFixed(2)}ms (>${t}ms)`);return e}setMaxRecentSamples(t){this._maxRecentSamples=t;for(const e of this._systemStats.values())for(;e.recentTimes.length>t;)e.recentTimes.shift()}}class d{constructor(t,e=100,s=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=s,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,s=1024){let n=this._pools.get(t);return n||(n=new d((()=>new t),e,s),this._pools.set(t,n)),n}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}const t=this._createFn();return this._stats.totalCreated++,this._updateHitRate(),t}free(t){this._objects.length<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._stats.totalReleased++,this._updateMemoryUsage())}warmUp(t){const e=Math.min(t,this._maxSize);for(;this._objects.length<e;){const t=this._createFn();this._stats.totalCreated++,this._objects.push(t),this._stats.size++}this._updateMemoryUsage()}clear(){this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}get size(){return this._objects.length}get maxSize(){return this._maxSize}set maxSize(t){for(this._maxSize=t,this._stats.maxSize=t;this._objects.length>this._maxSize;)this._objects.pop(),this._stats.size--;this._updateMemoryUsage()}getStats(){return{...this._stats}}resetStats(){this._stats.totalCreated=0,this._stats.totalObtained=0,this._stats.totalReleased=0,this._stats.hitRate=0}_updateHitRate(){if(this._stats.totalObtained>0){const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}static obtain(t){return this.getPool(t).obtain()}static free(t,e){this.getPool(t).free(e)}static warmUp(t,e){this.getPool(t).warmUp(e)}static clearPool(t){const e=this._pools.get(t);e&&e.clear()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getStats(){const t={};for(const[e,s]of this._pools.entries()){t[e.name||"Unknown"]=s.getStats()}return t}static getTotalMemoryUsage(){let t=0;for(const e of this._pools.values())t+=e.getStats().estimatedMemoryUsage;return t}static getPerformanceReport(){const t=this.getStats(),e=[];e.push("=== Object Pool Performance Report ==="),e.push(`Total Memory Usage: ${(this.getTotalMemoryUsage()/1024/1024).toFixed(2)} MB`),e.push("");for(const[s,n]of Object.entries(t))e.push(`${s}:`),e.push(` Size: ${n.size}/${n.maxSize}`),e.push(` Hit Rate: ${(100*n.hitRate).toFixed(1)}%`),e.push(` Total Created: ${n.totalCreated}`),e.push(` Total Obtained: ${n.totalObtained}`),e.push(` Memory: ${(n.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}}d._pools=new Map;class p{constructor(t,e,s=[10,50,200],n=1024){this.pools=[],this.totalObtained=0,this.totalReleased=0,this.createFn=t,this.resetFn=e,this.tierSizes=s;for(const e of s)this.pools.push(new d(t,e,n))}obtain(){this.totalObtained++;for(const t of this.pools)if(t.size>0)return t.obtain();return this.createFn()}release(t){this.totalReleased++,this.resetFn(t);for(const e of this.pools)if(e.size<e.maxSize)return void e.free(t)}warmUp(t){let e=t;for(const t of this.pools){const s=Math.min(e,t.maxSize);if(t.warmUp(s),e-=s,e<=0)break}}clear(){for(const t of this.pools)t.clear()}getStats(){let t=0,e=0,s=0;const n=[];for(const i of this.pools){const o=i.getStats();n.push(o),t+=o.size,e+=o.maxSize,s+=o.estimatedMemoryUsage}return{totalSize:t,totalMaxSize:e,totalMemoryUsage:s,tierStats:n,hitRate:this.totalObtained>0?(this.totalObtained-this.getTotalCreated())/this.totalObtained:0}}getTotalCreated(){return this.pools.reduce(((t,e)=>t+e.getStats().totalCreated),0)}}class y{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return y.instance||(y.instance=new y),y.instance}registerPool(t,e){this.pools.set(t,e)}getPool(t){return this.pools.get(t)||null}update(){const t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)}compactAllPools(){for(const t of this.pools.values())t instanceof d&&t.resetStats()}getAllStats(){const t=new Map;for(const[e,s]of this.pools.entries())(s instanceof d||s instanceof p)&&t.set(e,s.getStats());return t}generateReport(){const t=[];t.push("=== Pool Manager Report ===");let e=0;for(const[s,n]of this.pools.entries())if(t.push(`\n${s}:`),n instanceof d){const s=n.getStats();t.push(" Type: Standard Pool"),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e+=s.estimatedMemoryUsage}else if(n instanceof p){const s=n.getStats();t.push(" Type: Tiered Pool"),t.push(` Total Size: ${s.totalSize}/${s.totalMaxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.totalMemoryUsage/1024).toFixed(1)} KB`),e+=s.totalMemoryUsage}return t.push(`\nTotal Memory Usage: ${(e/1024/1024).toFixed(2)} MB`),t.join("\n")}}class g{static register(t){if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentTypes.set(t,e),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return BigInt(1)<<BigInt(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getAllRegisteredTypes(){return new Map(this.componentTypes)}}g.componentTypes=new Map,g.nextBitIndex=0,g.maxComponents=64;class _{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,g.isRegistered(t)||g.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${this.componentType.name}`);let s;this.freeIndices.length>0?(s=this.freeIndices.pop(),this.components[s]=e,this.indexToEntity[s]=t):(s=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,s),this._size++}getComponent(t){const e=this.entityToIndex.get(t);return void 0!==e?this.components[e]:null}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const s=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,s}forEach(t){for(let e=0;e<this.components.length;e++){const s=this.components[e];s&&t(s,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let s=0;s<this.components.length;s++){const n=this.components[s];n&&(t.push(n),e.push(this.indexToEntity[s]))}return{components:t,entityIds:e}}clear(){this.components.length=0,this.entityToIndex.clear(),this.indexToEntity.length=0,this.freeIndices.length=0,this._size=0}get size(){return this._size}get type(){return this.componentType}compact(){if(0===this.freeIndices.length)return;const t=[],e=[],s=new Map;let n=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[n]=o,e[n]=this.indexToEntity[i],s.set(this.indexToEntity[i],n),n++)}this.components=t,this.indexToEntity=e,this.entityToIndex=s,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,s=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:s,fragmentation:t>0?s/t:0}}}class f{constructor(){this.storages=new Map}getStorage(t){let e=this.storages.get(t);return e||(e=new _(t),this.storages.set(t,e)),e}addComponent(t,e){const s=e.constructor;this.getStorage(s).addComponent(t,e)}getComponent(t,e){const s=this.storages.get(e);return s?s.getComponent(t):null}hasComponent(t,e){const s=this.storages.get(e);return!!s&&s.hasComponent(t)}removeComponent(t,e){const s=this.storages.get(e);return s?s.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigInt(0);for(const[s,n]of this.storages.entries())n.hasComponent(t)&&(e|=g.getBitMask(s));return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,s]of this.storages.entries()){const n=e.name||"Unknown";t.set(n,s.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}class E{compare(t,e){let s=t.updateOrder-e.updateOrder;return 0==s&&(s=t.id-e.id),s}}class T{constructor(t={maxSize:16,ttl:5e3,enableLRU:!0}){this.cache=new Map,this.accessOrder=[],this.config=t}get(t){const e=this.cache.get(t);return e?Date.now()-e.lastAccessed>this.config.ttl?(this.cache.delete(t),this.removeFromAccessOrder(t),null):(e.lastAccessed=Date.now(),e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.component):null}set(t,e){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLeastRecentlyUsed();const s={component:e,lastAccessed:Date.now(),accessCount:1};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}delete(t){const e=this.cache.delete(t);return e&&this.removeFromAccessOrder(t),e}clear(){this.cache.clear(),this.accessOrder.length=0}has(t){return this.cache.has(t)}evictLeastRecentlyUsed(){if(this.accessOrder.length>0){const t=this.accessOrder[0];this.cache.delete(t),this.accessOrder.shift()}}updateAccessOrder(t){this.removeFromAccessOrder(t),this.accessOrder.push(t)}removeFromAccessOrder(t){const e=this.accessOrder.indexOf(t);-1!==e&&this.accessOrder.splice(e,1)}getStats(){let t=0,e=0;for(const s of this.cache.values())t+=s.accessCount,e++;return{size:this.cache.size,maxSize:this.config.maxSize,hitRate:t>0?e/t:0,averageAccessCount:this.cache.size>0?t/this.cache.size:0}}}class C{constructor(t,e){this.components=[],this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=BigInt(0),this._componentTypeToIndex=new Map,this._componentAccessStats=new Map,this.name=t,this.id=e,this._componentCache=new T}get isDestroyed(){return this._isDestroyed}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(t){this._active!==t&&(this._active=t,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(t){this._tag=t}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}get componentMask(){return this._componentMask}createComponent(t,...e){const s=new t(...e);return this.addComponent(s)}addComponentInternal(t){const e=t.constructor;g.isRegistered(e)||g.register(e),t.entity=this;const s=this.components.length;return this.components.push(t),this._componentTypeToIndex.set(e,s),this._componentMask|=g.getBitMask(e),this._componentCache.set(e,t),this._componentAccessStats.set(e,{accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0}),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${e.name}`);if(this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),C.eventBus&&C.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this);return t}getComponent(t){if(this.updateComponentAccessStats(t),!g.isRegistered(t))return this.recordCacheMiss(t),null;const e=g.getBitMask(t);if((this._componentMask&e)===BigInt(0))return this.recordCacheMiss(t),null;const s=this._componentCache.get(t);if(s)return this.recordCacheHit(t),s;const n=this._componentTypeToIndex.get(t);if(void 0!==n&&n<this.components.length){const e=this.components[n];if(e&&e.constructor===t)return this._componentCache.set(t,e),this.recordCacheHit(t),e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this._componentCache.set(t,e),this.rebuildComponentIndex(),this.recordCacheHit(t),e}for(let e=0;e<this.components.length;e++){const s=this.components[e];if(s instanceof t)return this._componentTypeToIndex.set(t,e),this._componentCache.set(t,s),this.recordCacheHit(t),s}return this.recordCacheMiss(t),null}updateComponentAccessStats(t){let e=this._componentAccessStats.get(t);e||(e={accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0},this._componentAccessStats.set(t,e)),e.accessCount++,e.lastAccessed=Date.now()}recordCacheHit(t){const e=this._componentAccessStats.get(t);e&&e.cacheHits++}recordCacheMiss(t){const e=this._componentAccessStats.get(t);e&&e.cacheMisses++}rebuildComponentIndex(){this._componentTypeToIndex.clear();for(let t=0;t<this.components.length;t++){const e=this.components[t].constructor;this._componentTypeToIndex.set(e,t)}}hasComponent(t){if(!g.isRegistered(t))return!1;const e=g.getBitMask(t);return(this._componentMask&e)!==BigInt(0)}getOrCreateComponent(t,...e){let s=this.getComponent(t);return s||(s=this.createComponent(t,...e)),s}removeComponent(t){const e=t.constructor,s=this.components.indexOf(t);if(-1!==s&&(this.components.splice(s,1),this.rebuildComponentIndex()),this._componentCache.delete(e),this._componentAccessStats.delete(e),g.isRegistered(e)&&(this._componentMask&=~g.getBitMask(e)),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity(),C.eventBus&&C.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),t.entity=null,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentCache.clear(),this._componentTypeToIndex.clear(),this._componentAccessStats.clear(),this._componentMask=BigInt(0);for(const e of t){const t=e.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),e.onRemovedFromEntity(),e.entity=null}if(this.components.length=0,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}addComponents(t){const e=[];for(const s of t)try{e.push(this.addComponent(s))}catch(t){console.warn(`Failed to add component ${s.constructor.name}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const s of t)e.push(this.removeComponentByType(s));return e}getComponentCacheStats(){const t=new Map;for(const[e,s]of this._componentAccessStats){const n=s.cacheHits+s.cacheMisses;t.set(e.name,{...s,hitRate:n>0?s.cacheHits/n:0})}return{cacheStats:this._componentCache.getStats(),accessStats:t,indexMappingSize:this._componentTypeToIndex.size,totalComponents:this.components.length}}warmUpComponentCache(){for(let t=0;t<this.components.length;t++){const e=this.components[t],s=e.constructor;this._componentTypeToIndex.set(s,t),this._componentCache.set(s,e)}}cleanupComponentCache(){const t=Date.now();for(const[e,s]of this._componentAccessStats)t-s.lastAccessed>3e4&&s.accessCount<5&&this._componentCache.delete(e)}getComponents(t){const e=[];for(const s of this.components)s instanceof t&&e.push(s);return e}addChild(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)}removeAllChildren(){const t=[...this._children];for(const e of t)this.removeChild(e)}findChild(t,e=!1){for(const e of this._children)if(e.name===t)return e;if(e)for(const e of this._children){const s=e.findChild(t,!0);if(s)return s}return null}findChildrenByTag(t,e=!1){const s=[];for(const e of this._children)e.tag===t&&s.push(e);if(e)for(const e of this._children)s.push(...e.findChildrenByTag(t,!0));return s}getRoot(){let t=this;for(;t._parent;)t=t._parent;return t}isAncestorOf(t){let e=t._parent;for(;e;){if(e===this)return!0;e=e._parent}return!1}isDescendantOf(t){return t.isAncestorOf(this)}getDepth(){let t=0,e=this._parent;for(;e;)t++,e=e._parent;return t}forEachChild(t,e=!1){this._children.forEach(((s,n)=>{t(s,n),e&&s.forEachChild(t,!0)}))}onActiveChanged(){for(const t of this.components)"onActiveChanged"in t&&"function"==typeof t.onActiveChanged&&t.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}update(){if(this.activeInHierarchy&&!this._isDestroyed){for(const t of this.components)t.enabled&&t.update();for(const t of this._children)t.update()}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const t=[...this._children];for(const e of t)e.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&this.scene.entities&&this.scene.entities.remove(this)}compareTo(t){return E.prototype.compare(this,t)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){const t=this.getComponentCacheStats(),e=Array.from(t.accessStats.entries()).map((([t,e])=>({componentType:t,accessCount:e.accessCount,cacheHits:e.cacheHits,cacheMisses:e.cacheMisses,hitRate:e.hitRate,lastAccessed:new Date(e.lastAccessed).toISOString()})));return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((t=>t.constructor.name)),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),componentCache:t.cacheStats,componentAccessStats:e,indexMappingSize:t.indexMappingSize}}}C.entityComparer=new E,C.eventBus=null;class S{get count(){return this.buffer.length}constructor(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}add(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)}addImmediate(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))}remove(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)}removeImmediate(t){const e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1))}removeAllEntities(){for(let t=this.buffer.length-1;t>=0;t--)this.buffer[t].destroy();this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0}updateLists(){if(this._entitiesToAdd.length>0){for(const t of this._entitiesToAdd)this.addImmediate(t);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const t of this._entitiesToRemove)this.removeImmediate(t);this._entitiesToRemove.length=0}}update(){this._isUpdating=!0;try{for(let t=0;t<this.buffer.length;t++){const e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()}findEntity(t){const e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null}findEntitiesByName(t){return this._nameToEntities.get(t)||[]}findEntityById(t){return this._idToEntity.get(t)||null}findEntitiesByTag(t){const e=[];for(const s of this.buffer)s.tag===t&&e.push(s);return e}findEntitiesWithComponent(t){const e=[];for(const s of this.buffer)s.hasComponent(t)&&e.push(s);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const s of this.buffer)t(s)&&e(s)}updateNameIndex(t,e){if(t.name)if(e){let e=this._nameToEntities.get(t.name);e||(e=[],this._nameToEntities.set(t.name,e)),e.push(t)}else{const e=this._nameToEntities.get(t.name);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._nameToEntities.delete(t.name))}}}getStats(){let t=0;for(const e of this.buffer)e.enabled&&!e.isDestroyed&&t++;return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class M{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(t){this._processors.push(t),this.setDirty()}remove(t){const e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)}getProcessor(t){for(const e of this._processors)if(e instanceof t)return e;return null}begin(){this.sortProcessors();for(const t of this._processors)t.initialize()}end(){}update(){this.sortProcessors();for(const t of this._processors)t.update()}lateUpdate(){for(const t of this._processors)t.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((t,e)=>t.updateOrder-e.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}class w{constructor(){this._nextAvailableId=0,this._ids=[]}checkOut(){return this._ids.length>0?this._ids.pop():this._nextAvailableId++}checkIn(t){this._ids.push(t)}}class b{constructor(){this.wasmModule=null,this.wasmCore=null,this.silent=!1}setSilent(t){this.silent=t}async initializeForCocos(t,e){try{this.silent||console.log("开始为Cocos Creator初始化WASM模块...");const s=await this.initWasmForCocos(t,e);if(s&&s.EcsCore)return this.wasmModule=s,this.wasmCore=new s.EcsCore,this.silent||console.log("✅ Cocos Creator WASM模块初始化成功"),!0;throw new Error("WASM模块缺少EcsCore构造函数")}catch(t){if(!this.silent){const e=t instanceof Error?t.message:String(t);console.warn("❌ Cocos Creator WASM初始化失败:",e)}return!1}}async initWasmForCocos(t,e){const s={wasmBinary:e._file||e,onRuntimeInitialized:()=>{this.silent||console.log("WASM运行时初始化完成")}};return await t(s)}async loadWasmModule(){try{if(this.detectCocosEnvironment())return this.silent||(console.warn("检测到Cocos Creator环境,WASM需要手动配置"),console.warn("请按照文档说明将WASM文件导入为项目资源并手动初始化"),console.warn("参考: https://docs.cocos.com/creator/3.8/manual/zh/advanced-topics/wasm-asm-load.html")),!1;const t=["./wasm/ecs_wasm_core","../wasm/ecs_wasm_core","./node_modules/@esengine/ecs-framework/wasm/ecs_wasm_core","../node_modules/@esengine/ecs-framework/wasm/ecs_wasm_core","../../node_modules/@esengine/ecs-framework/wasm/ecs_wasm_core","../../bin/wasm/ecs_wasm_core"];let e=null;for(const s of t)try{this.silent||console.log(`尝试加载WASM: ${s}`),this.wasmModule=await import(s),this.silent||console.log(`✅ WASM加载成功: ${s}`);break}catch(t){e=t instanceof Error?t:new Error(String(t));continue}if(!this.wasmModule)throw e||new Error("所有WASM路径都加载失败");return await this.initializeWasmModule(),this.wasmCore=new this.wasmModule.EcsCore,!0}catch(t){if(!this.silent){const e=t instanceof Error?t.message:String(t);console.warn("WASM加载失败,使用JavaScript实现:",e)}return!1}}detectCocosEnvironment(){if("undefined"!=typeof window)return!!(window.cc||window.jsb||window.Editor);try{if("undefined"!=typeof cc||"undefined"!=typeof jsb)return!0}catch(t){}return!1}async initializeWasmModule(){if(this.wasmModule)try{await this.wasmModule.default()}catch(t){if(!this.wasmModule.initSync)throw t;try{this.wasmModule.initSync(void 0)}catch(e){throw t}}}getWasmCore(){return this.wasmCore}getWasmModule(){return this.wasmModule}cleanup(){this.wasmCore&&this.wasmCore.free&&this.wasmCore.free(),this.wasmCore=null,this.wasmModule=null}}class A{constructor(){this.jsEntityMasks=new Map,this.jsNextEntityId=1,this.jsQueryCount=0,this.jsUpdateCount=0}createEntity(){const t=this.jsNextEntityId++;return this.jsEntityMasks.set(t,0n),t}destroyEntity(t){return this.jsEntityMasks.delete(t)}updateEntityMask(t,e){this.jsEntityMasks.set(t,e),this.jsUpdateCount++}batchUpdateMasks(t,e){for(let s=0;s<t.length&&s<e.length;s++)this.jsEntityMasks.set(t[s],e[s]);this.jsUpdateCount+=Math.min(t.length,e.length)}queryEntities(t,e=1e4){const s=[];for(const[n,i]of this.jsEntityMasks)if((i&t)===t&&(s.push(n),s.length>=e))break;return this.jsQueryCount++,{entities:new Uint32Array(s),count:s.length}}queryCached(t){return this.queryEntities(t)}queryMultipleComponents(t,e=1e4){const s=[];for(const[n,i]of this.jsEntityMasks){let o=!1;for(const e of t)if((i&e)===e){o=!0;break}if(o&&(s.push(n),s.length>=e))break}return this.jsQueryCount++,{entities:new Uint32Array(s),count:s.length}}queryWithExclusion(t,e,s=1e4){const n=[];for(const[i,o]of this.jsEntityMasks)if((o&t)===t&&0n===(o&e)&&(n.push(i),n.length>=s))break;return this.jsQueryCount++,{entities:new Uint32Array(n),count:n.length}}getEntityMask(t){return this.jsEntityMasks.get(t)||null}entityExists(t){return this.jsEntityMasks.has(t)}createComponentMask(t){let e=0n;for(const s of t)e|=1n<<BigInt(s);return e}maskContainsComponent(t,e){return 0n!=(t&1n<<BigInt(e))}getPerformanceStats(){return{entityCount:this.jsEntityMasks.size,indexCount:0,queryCount:this.jsQueryCount,updateCount:this.jsUpdateCount,wasmEnabled:!1}}clear(){this.jsEntityMasks.clear(),this.jsNextEntityId=1,this.jsQueryCount=0,this.jsUpdateCount=0}getEntityCount(){return this.jsEntityMasks.size}}class I{constructor(){this.initialized=!1,this.usingWasm=!1,this.wasmLoader=new b,this.jsFallback=new A}setSilent(t){this.wasmLoader.setSilent(t)}async initializeForCocos(t,e){const s=await this.wasmLoader.initializeForCocos(t,e);return s&&(this.usingWasm=!0,this.initialized=!0),s}async initialize(){return this.initialized||(console.log("🔄 初始化ECS核心..."),this.usingWasm=await this.wasmLoader.loadWasmModule(),this.initialized=!0),!0}createEntity(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();return t?t.create_entity():this.jsFallback.createEntity()}return this.jsFallback.createEntity()}destroyEntity(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();return e?e.destroy_entity(t):this.jsFallback.destroyEntity(t)}return this.jsFallback.destroyEntity(t)}updateEntityMask(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();s?s.update_entity_mask(t,e):this.jsFallback.updateEntityMask(t,e)}else this.jsFallback.updateEntityMask(t,e)}batchUpdateMasks(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=new Uint32Array(t),i=new BigUint64Array(e);s.batch_update_masks(n,i)}else this.jsFallback.batchUpdateMasks(t,e)}else this.jsFallback.batchUpdateMasks(t,e)}queryEntities(t,e=1e4){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=s.query_entities(t,e),i=s.get_query_result_count(),o=this.wasmLoader.getWasmModule();if(o&&o.memory){const t=new Uint32Array(o.memory.buffer),e=new Uint32Array(i);for(let s=0;s<i;s++)e[s]=t[n/4+s];return{entities:e,count:i}}}}return this.jsFallback.queryEntities(t,e)}queryCached(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e){const s=e.query_cached(t),n=e.get_cached_query_count(t),i=this.wasmLoader.getWasmModule();if(i&&i.memory){const t=new Uint32Array(i.memory.buffer),e=new Uint32Array(n);for(let i=0;i<n;i++)e[i]=t[s/4+i];return{entities:e,count:n}}}}return this.jsFallback.queryCached(t)}queryMultipleComponents(t,e=1e4){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=new BigUint64Array(t),i=s.query_multiple_components(n,e),o=s.get_query_result_count(),r=this.wasmLoader.getWasmModule();if(r&&r.memory){const t=new Uint32Array(r.memory.buffer),e=new Uint32Array(o);for(let s=0;s<o;s++)e[s]=t[i/4+s];return{entities:e,count:o}}}}return this.jsFallback.queryMultipleComponents(t,e)}queryWithExclusion(t,e,s=1e4){if(this.ensureInitialized(),this.usingWasm){const n=this.wasmLoader.getWasmCore();if(n){const i=n.query_with_exclusion(t,e,s),o=n.get_query_result_count(),r=this.wasmLoader.getWasmModule();if(r&&r.memory){const t=new Uint32Array(r.memory.buffer),e=new Uint32Array(o);for(let s=0;s<o;s++)e[s]=t[i/4+s];return{entities:e,count:o}}}}return this.jsFallback.queryWithExclusion(t,e,s)}getEntityMask(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e)return e.get_entity_mask(t)}return this.jsFallback.getEntityMask(t)}entityExists(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e)return e.entity_exists(t)}return this.jsFallback.entityExists(t)}createComponentMask(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmModule();if(e){const s=new Uint32Array(t);return e.create_component_mask(s)}}return this.jsFallback.createComponentMask(t)}maskContainsComponent(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmModule();if(s)return s.mask_contains_component(t,e)}return this.jsFallback.maskContainsComponent(t,e)}getPerformanceStats(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();if(t){const e=t.get_performance_stats();return{entityCount:e[0]||0,indexCount:e[1]||0,queryCount:e[2]||0,updateCount:e[3]||0,wasmEnabled:!0}}}return this.jsFallback.getPerformanceStats()}clear(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();t&&t.clear()}this.jsFallback.clear()}isUsingWasm(){return this.usingWasm}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new Error("ECS核心未初始化,请先调用 initialize() 方法")}cleanup(){this.wasmLoader.cleanup(),this.jsFallback.clear(),this.initialized=!1,this.usingWasm=!1}}const x=new I;async function v(t=!1){return x.setSilent(t),await x.initialize()}var D,O,N,k,R,B,z=Object.freeze({__proto__:null,ecsCore:x,initializeEcs:v});class P{constructor(t,e,s=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=s}acquire(){return this.pool.length>0?this.pool.pop():this.createFn()}release(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))}prewarm(t){for(let e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}}class U{constructor(){this.pools=new Map}static getInstance(){return U.instance||(U.instance=new U),U.instance}registerPool(t,e,s,n){this.pools.set(t,new P(e,s,n))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const s=this.pools.get(t);s&&s.release(e)}prewarmAll(t=100){for(const e of this.pools.values())e.prewarm(t)}clearAll(){for(const t of this.pools.values())t.clear()}getPoolStats(){const t=new Map;for(const[e,s]of this.pools)t.set(e,{available:s.getAvailableCount(),maxSize:s.getMaxSize()});return t}}class q{constructor(){this.maskCache=new Map,this.componentTypeMap=new Map,this.nextComponentId=0}static getInstance(){return q.instance||(q.instance=new q),q.instance}registerComponentType(t){return this.componentTypeMap.has(t)||this.componentTypeMap.set(t,this.nextComponentId++),this.componentTypeMap.get(t)}getComponentTypeId(t){return this.componentTypeMap.get(t)}createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const s=this.getComponentTypeId(t);if(void 0===s)throw new Error(`Component type not registered: ${t}`);const n=1n<<BigInt(s);return this.maskCache.set(e,n),n}createCombinedMask(t){const e=`combined:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let s=0n;for(const e of t){const t=this.getComponentTypeId(e);if(void 0===t)throw new Error(`Component type not registered: ${e}`);s|=1n<<BigInt(t)}return this.maskCache.set(e,s),s}maskContainsComponent(t,e){return 0n!==(t&this.createSingleComponentMask(e))}maskContainsAllComponents(t,e){const s=this.createCombinedMask(e);return(t&s)===s}maskContainsAnyComponent(t,e){return 0n!==(t&this.createCombinedMask(e))}addComponentToMask(t,e){return t|this.createSingleComponentMask(e)}removeComponentFromMask(t,e){return t&~this.createSingleComponentMask(e)}precomputeCommonMasks(t){for(const e of t)this.createCombinedMask(e)}getCacheStats(){return{size:this.maskCache.size,componentTypes:this.componentTypeMap.size}}clearCache(){this.maskCache.clear()}reset(){this.maskCache.clear(),this.componentTypeMap.clear(),this.nextComponentId=0}maskToComponentNames(t){const e=[];for(const[s,n]of this.componentTypeMap){0n!==(t&1n<<BigInt(n))&&e.push(s)}return e}getComponentCount(t){let e=0,s=t;for(;0n!==s;)0n!=(1n&s)&&e++,s>>=1n;return e}}!function(t){t.ADD_ENTITY="add_entity",t.REMOVE_ENTITY="remove_entity",t.UPDATE_ENTITY="update_entity"}(D||(D={}));class F{constructor(){this.pendingOperations=[],this.isProcessing=!1,this.batchSize=1e3,this.flushTimeout=null,this.flushDelay=16}addOperation(t){this.pendingOperations.push(t),this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}addEntities(t){for(const e of t)this.pendingOperations.push({type:D.ADD_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}removeEntities(t){for(const e of t)this.pendingOperations.push({type:D.REMOVE_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}updateEntities(t){for(const e of t)this.pendingOperations.push({type:D.UPDATE_ENTITY,entity:e.entity,oldMask:e.oldMask,newMask:e.newMask});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}scheduleFlush(){this.flushTimeout||(this.flushTimeout=setTimeout((()=>{this.flush()}),this.flushDelay))}flush(){if(!this.isProcessing&&0!==this.pendingOperations.length){this.isProcessing=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null);try{this.processBatch()}finally{this.isProcessing=!1}}}processBatch(){const t=this.pendingOperations;this.pendingOperations=[];const e=[],s=[],n=[];for(const i of t)switch(i.type){case D.ADD_ENTITY:e.push(i.entity);break;case D.REMOVE_ENTITY:s.push(i.entity);break;case D.UPDATE_ENTITY:void 0!==i.oldMask&&void 0!==i.newMask&&n.push({entity:i.entity,oldMask:i.oldMask,newMask:i.newMask})}e.length>0&&this.processBatchAdd(e),s.length>0&&this.processBatchRemove(s),n.length>0&&this.processBatchUpdate(n)}processBatchAdd(t){this.onBatchAdd&&this.onBatchAdd(t)}processBatchRemove(t){this.onBatchRemove&&this.onBatchRemove(t)}processBatchUpdate(t){this.onBatchUpdate&&this.onBatchUpdate(t)}setBatchSize(t){this.batchSize=Math.max(1,t)}setFlushDelay(t){this.flushDelay=Math.max(0,t)}getPendingCount(){return this.pendingOperations.length}clear(){this.pendingOperations.length=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null)}hasPendingOperations(){return this.pendingOperations.length>0}}!function(t){t.HASH="hash",t.BITMAP="bitmap",t.SORTED="sorted"}(O||(O={}));class L{constructor(){this.type=O.HASH,this._componentToEntities=new Map,this._entityToComponents=new Map,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){const e=t.components,s=new Set;for(const n of e){const e=n.constructor;s.add(e);let i=this._componentToEntities.get(e);i||(i=new Set,this._componentToEntities.set(e,i)),i.add(t)}this._entityToComponents.set(t,s),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToComponents.get(t);if(e){for(const s of e){const e=this._componentToEntities.get(s);e&&(e.delete(t),0===e.size&&this._componentToEntities.delete(s))}this._entityToComponents.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=new Set(this._componentToEntities.get(t)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;if(1===t.length)return this.query(t[0]);let n;if("AND"===e){let e,i=1/0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||0===t.size)return this._queryCount++,this._totalQueryTime+=performance.now()-s,new Set;t.size<i&&(i=t.size,e=t)}if(n=new Set,e)for(const s of e){let e=!0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||!t.has(s)){e=!1;break}}e&&n.add(s)}}else{n=new Set;for(const e of t){const t=this._componentToEntities.get(e);if(t)for(const e of t)n.add(e)}}return this._queryCount++,this._totalQueryTime+=performance.now()-s,n}clear(){this._componentToEntities.clear(),this._entityToComponents.clear(),this._lastUpdated=Date.now()}getStats(){let t=0;t+=64*this._componentToEntities.size,t+=64*this._entityToComponents.size;for(const e of this._componentToEntities.values())t+=8*e.size;for(const e of this._entityToComponents.values())t+=8*e.size;return{type:this.type,size:this._componentToEntities.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class H{constructor(){this.type=O.BITMAP,this._componentTypeToBit=new Map,this._entityToBitmap=new Map,this._bitToEntities=new Map,this._nextBit=0,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){let e=0;for(const s of t.components){const n=s.constructor;let i=this._componentTypeToBit.get(n);void 0===i&&(i=this._nextBit++,this._componentTypeToBit.set(n,i)),e|=1<<i;let o=this._bitToEntities.get(1<<i);o||(o=new Set,this._bitToEntities.set(1<<i,o)),o.add(t)}this._entityToBitmap.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToBitmap.get(t);if(void 0!==e){for(const[s,n]of this._bitToEntities)0!==(e&s)&&(n.delete(t),0===n.size&&this._bitToEntities.delete(s));this._entityToBitmap.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=this._componentTypeToBit.get(t);if(void 0===s)return this._queryCount++,this._totalQueryTime+=performance.now()-e,new Set;const n=new Set(this._bitToEntities.get(1<<s)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;let n=0;const i=[];for(const e of t){const t=this._componentTypeToBit.get(e);void 0!==t&&(n|=1<<t,i.push(1<<t))}const o=new Set;if("AND"===e)for(const[t,e]of this._entityToBitmap)(e&n)===n&&o.add(t);else for(const t of i){const e=this._bitToEntities.get(t);if(e)for(const t of e)o.add(t)}return this._queryCount++,this._totalQueryTime+=performance.now()-s,o}clear(){this._componentTypeToBit.clear(),this._entityToBitmap.clear(),this._bitToEntities.clear(),this._nextBit=0,this._lastUpdated=Date.now()}getStats(){let t=0;t+=12*this._componentTypeToBit.size,t+=12*this._entityToBitmap.size,t+=64*this._bitToEntities.size;for(const e of this._bitToEntities.values())t+=8*e.size;return{type:this.type,size:this._componentTypeToBit.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class W{constructor(t=O.HASH){this._indexHistory=new Map,this._autoOptimize=!0,this._optimizationThreshold=1e3,this._activeIndex=this.createIndex(t)}addEntity(t){this._activeIndex.addEntity(t),this.checkOptimization()}removeEntity(t){this._activeIndex.removeEntity(t)}query(t){return this._activeIndex.query(t)}queryMultiple(t,e){return this._activeIndex.queryMultiple(t,e)}switchIndexType(t){if(t===this._activeIndex.type)return;this._indexHistory.set(this._activeIndex.type,this._activeIndex.getStats());const e=this._activeIndex;this._activeIndex=this.createIndex(t),e.clear()}setAutoOptimize(t){this._autoOptimize=t}getStats(){return this._activeIndex.getStats()}getAllStats(){const t=this._activeIndex.getStats();return new Map([...this._indexHistory,[t.type,t]])}clear(){this._activeIndex.clear()}createIndex(t){switch(t){case O.HASH:return new L;case O.BITMAP:return new H;case O.SORTED:default:return new L}}checkOptimization(){if(!this._autoOptimize)return;const t=this._activeIndex.getStats();t.queryCount<this._optimizationThreshold||(t.avgQueryTime>1&&t.type!==O.HASH?this.switchIndexType(O.HASH):t.memoryUsage>10485760&&t.type!==O.BITMAP&&this.switchIndexType(O.BITMAP))}}class ${constructor(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}addEntity(t){const e=this.getEntityComponentTypes(t),s=this.generateArchetypeId(e);let n=this._archetypes.get(s);n||(n=this.createArchetype(e)),n.entities.push(t),n.updatedAt=Date.now(),this._entityToArchetype.set(t,n),this.updateComponentIndexes(n,e,!0),this.invalidateQueryCache()}removeEntity(t){const e=this._entityToArchetype.get(t);if(!e)return;const s=e.entities.indexOf(t);-1!==s&&(e.entities.splice(s,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}queryArchetypes(t,e="AND"){const s=performance.now(),n=`${e}:${t.map((t=>t.name)).sort().join(",")}`,i=this._queryCache.get(n);if(i&&Date.now()-i.timestamp<this._cacheTimeout)return{...i.result,executionTime:performance.now()-s,fromCache:!0};const o=[];let r=0;if("AND"===e)for(const e of this._archetypes.values())this.archetypeContainsAllComponents(e,t)&&(o.push(e),r+=e.entities.length);else{const e=new Set;for(const s of t){const t=this._componentToArchetypes.get(s);if(t)for(const s of t)e.add(s)}for(const t of e)o.push(t),r+=t.entities.length}const a={archetypes:o,totalEntities:r,executionTime:performance.now()-s,fromCache:!1};return this._queryCache.set(n,{result:a,timestamp:Date.now()}),a}getEntityArchetype(t){return this._entityToArchetype.get(t)}getAllArchetypes(){return Array.from(this._archetypes.values())}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()}getEntityComponentTypes(t){return t.components.map((t=>t.constructor))}generateArchetypeId(t){return t.map((t=>t.name)).sort().join("|")}createArchetype(t){const e=this.generateArchetypeId(t),s={id:e,componentTypes:[...t],entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,s),s}archetypeContainsAllComponents(t,e){for(const s of e)if(!t.componentTypes.includes(s))return!1;return!0}updateComponentIndexes(t,e,s){for(const n of e){let e=this._componentToArchetypes.get(n);e||(e=new Set,this._componentToArchetypes.set(n,e)),s?e.add(t):(e.delete(t),0===e.size&&this._componentToArchetypes.delete(n))}}invalidateQueryCache(){this._queryCache.clear()}}!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(N||(N={}));class j{constructor(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}markDirty(t,e,s=[]){this._stats.totalMarkings++;let n=this._dirtyEntities.get(t);n||(n={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,n)),n.flags|=e,n.timestamp=performance.now(),n.frameNumber=this._currentFrame;for(const t of s)n.modifiedComponents.add(t);this.notifyListeners(n,e)}isDirty(t,e=N.ALL){const s=this._dirtyEntities.get(t);return!!s&&0!==(s.flags&e)}clearDirty(t,e=N.ALL){const s=this._dirtyEntities.get(t);s&&(e===N.ALL?this._dirtyEntities.delete(t):(s.flags&=~e,0===s.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)}getDirtyEntities(t=N.ALL){const e=[];for(const s of this._dirtyEntities.values())0!==(s.flags&t)&&e.push(s);return e}processDirtyEntities(){if(this._isProcessing)return;this._isProcessing=!0;const t=performance.now();0===this._processingQueue.length&&this._processingQueue.push(...this._dirtyEntities.values());let e=0;for(;this._processingQueue.length>0&&e<this._batchSize;){if(performance.now()-t>this._maxProcessingTime)break;const s=this._processingQueue.shift();this.processEntity(s),e++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}addListener(t){this._listeners.push(t),this._listeners.sort(((t,e)=>(t.priority||100)-(e.priority||100)))}removeListener(t){const e=this._listeners.findIndex((e=>e.callback===t));-1!==e&&this._listeners.splice(e,1)}beginFrame(){this._currentFrame++}endFrame(){this._isProcessing||this.processDirtyEntities()}getStats(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}}clear(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}}configureBatchProcessing(t,e){this._batchSize=t,this._maxProcessingTime=e}processEntity(t){for(const e of this._listeners)if(0!==(t.flags&e.flags))try{e.callback(t)}catch(t){console.error("Dirty listener error:",t)}this.clearDirty(t.entity)}notifyListeners(t,e){for(const s of this._listeners)if(0!==(e&s.flags))try{s.callback(t)}catch(t){console.error("Dirty listener notification error:",t)}}onFrameEnd(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size}estimateMemoryUsage(){let t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length,t}}!function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(k||(k={}));class Y{constructor(){this.entities=[],this.wasmAvailable=!1,this.indexDirty=!0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=U.getInstance(),this.bitMaskOptimizer=q.getInstance(),this.indexUpdateBatcher=new F,this.componentIndexManager=new W(O.HASH),this.archetypeSystem=new $,this.dirtyTrackingSystem=new j,this.indexUpdateBatcher.onBatchAdd=t=>{for(const e of t)this.addEntityToIndexes(e)},this.indexUpdateBatcher.onBatchRemove=t=>{for(const e of t)this.removeEntityFromIndexes(e)},this.indexUpdateBatcher.onBatchUpdate=t=>{for(const e of t)this.removeEntityFromIndexes(e.entity),this.addEntityToIndexes(e.entity)},this.initializeWasm()}async initializeWasm(){try{const t=await x.initialize();this.wasmAvailable=t&&x.isUsingWasm(),this.wasmAvailable?console.log("QuerySystem: WebAssembly计算加速已启用"):console.log("QuerySystem: 使用JavaScript实现")}catch(t){console.warn("QuerySystem: WebAssembly初始化失败,使用JavaScript实现:",t),this.wasmAvailable=!1}}setEntities(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()}addEntity(t,e=!1){this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_ADDED),e||this.clearQueryCache())}addEntities(t){if(0===t.length)return;const e=new Set(this.entities.map((t=>t.id)));let s=0;for(const n of t)e.has(n.id)||(this.entities.push(n),this.addEntityToIndexes(n),e.add(n.id),s++);s>0&&this.clearQueryCache()}addEntitiesUnchecked(t){if(0!==t.length){for(const e of t)this.entities.push(e);for(const e of t)this.addEntityToIndexes(e);this.clearQueryCache()}}removeEntity(t){const e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_REMOVED),this.clearQueryCache())}addEntityToIndexes(t){const e=t.componentMask;let s=this.entityIndex.byMask.get(e);s||(s=new Set,this.entityIndex.byMask.set(e,s)),s.add(t);const n=t.components;for(let e=0;e<n.length;e++){const s=n[e].constructor;let i=this.entityIndex.byComponentType.get(s);i||(i=new Set,this.entityIndex.byComponentType.set(s,i)),i.add(t)}const i=t.tag;if(void 0!==i){let e=this.entityIndex.byTag.get(i);e||(e=new Set,this.entityIndex.byTag.set(i,e)),e.add(t)}const o=t.name;if(o){let e=this.entityIndex.byName.get(o);e||(e=new Set,this.entityIndex.byName.set(o,e)),e.add(t)}}removeEntityFromIndexes(t){const e=t.componentMask,s=this.entityIndex.byMask.get(e);s&&(s.delete(t),0===s.size&&this.entityIndex.byMask.delete(e));for(const e of t.components){const s=e.constructor,n=this.entityIndex.byComponentType.get(s);n&&(n.delete(t),0===n.size&&this.entityIndex.byComponentType.delete(s))}if(void 0!==t.tag){const e=this.entityIndex.byTag.get(t.tag);e&&(e.delete(t),0===e.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){const e=this.entityIndex.byName.get(t.name);e&&(e.delete(t),0===e.size&&this.entityIndex.byName.delete(t.name))}}rebuildIndexes(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear();for(const t of this.entities)this.addEntityToIndexes(t);this.indexDirty=!1}queryAll(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`all:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};let i;const o=this.archetypeSystem.queryArchetypes(t,"AND");if(o.archetypes.length>0){this.queryStats.archetypeHits++,i=[];for(const t of o.archetypes)i.push(...t.entities)}else if(1===t.length){this.queryStats.indexHits++;const e=this.componentIndexManager.query(t[0]);i=Array.from(e)}else{const e=this.componentIndexManager.queryMultiple(t,"AND");i=Array.from(e)}return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryMultipleComponents(t){let e=null,s=1/0;for(const n of t){const t=this.entityIndex.byComponentType.get(n);if(!t||0===t.size)return[];t.size<s&&(s=t.size,e=t)}if(!e)return this.queryStats.linearScans++,this.queryByLinearScan(t);const n=this.createComponentMask(t),i=[];for(const t of e)(t.componentMask&n)===n&&i.push(t);return i}queryByLinearScan(t){const e=this.createComponentMask(t);return this.entities.filter((t=>(t.componentMask&e)===e))}queryAny(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`any:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};const i=this.archetypeSystem.queryArchetypes(t,"OR");let o;if(i.archetypes.length>0){this.queryStats.archetypeHits++,o=[];for(const t of i.archetypes)o.push(...t.entities)}else{const e=this.componentIndexManager.queryMultiple(t,"OR");o=Array.from(e)}return this.addToCache(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryNone(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`none:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};const i=this.createComponentMask(t),o=this.entities.filter((t=>(t.componentMask&i)===BigInt(0)));return this.addToCache(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryByTag(t){const e=performance.now();this.queryStats.totalQueries++;const s=`tag:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByName(t){const e=performance.now();this.queryStats.totalQueries++;const s=`name:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByComponent(t){const e=performance.now();this.queryStats.totalQueries++;const s=`component:${t.name}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}getFromCache(t){const e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null}addToCache(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[...e],timestamp:Date.now(),hitCount:0})}cleanupCache(){const t=Date.now();for(const[e,s]of this.queryCache.entries())t-s.timestamp>this.cacheTimeout&&this.queryCache.delete(e);if(this.queryCache.size>=this.cacheMaxSize){const t=Array.from(this.queryCache.entries());t.sort(((t,e)=>t[1].hitCount-e[1].hitCount));const e=Math.floor(.2*this.cacheMaxSize);for(let s=0;s<e&&s<t.length;s++)this.queryCache.delete(t[s][0])}}clearQueryCache(){this.queryCache.clear()}clearCache(){this.clearQueryCache()}batchUpdateComponents(t){if(this.wasmAvailable&&t.length>100)try{const e=t.map((t=>t.entityId)),s=t.map((t=>t.componentMask));x.batchUpdateMasks(e,s),console.log(`WebAssembly加速批量更新 ${t.length} 个实体`)}catch(e){console.warn("WebAssembly批量更新失败,回退到JavaScript实现:",e),this.batchUpdateComponentsJS(t)}else this.batchUpdateComponentsJS(t);this.clearQueryCache()}batchUpdateComponentsJS(t){for(const e of t){this.entities.find((t=>t.id===e.entityId))&&console.log(`更新实体 ${e.entityId} 的组件掩码: ${e.componentMask}`)}this.rebuildIndexes()}getAccelerationStatus(){return{wasmEnabled:this.wasmAvailable,currentProvider:this.wasmAvailable?"hybrid":"javascript",availableProviders:["javascript","hybrid"],performanceInfo:{entityCount:this.entities.length,wasmEnabled:this.wasmAvailable,cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}}async switchAccelerationProvider(t){return!0}createComponentMask(t){const e=t.map((t=>t.name));for(const t of e)this.bitMaskOptimizer.registerComponentType(t);return this.bitMaskOptimizer.createCombinedMask(e)}getStats(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},accelerationStatus:this.getAccelerationStatus(),queryStats:{...this.queryStats,cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this.dirtyTrackingSystem.getStats()}}}switchComponentIndexType(t){this.componentIndexManager.switchIndexType(t)}configureDirtyTracking(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)}optimizePerformance(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache();const t=this.componentIndexManager.getStats();t.avgQueryTime>2&&t.type!==O.HASH?this.switchComponentIndexType(O.HASH):t.memoryUsage>52428800&&t.type!==O.BITMAP&&this.switchComponentIndexType(O.BITMAP)}beginFrame(){this.dirtyTrackingSystem.beginFrame()}endFrame(){this.dirtyTrackingSystem.endFrame()}markEntityDirty(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_MODIFIED,e),this.clearQueryCache()}getEntityArchetype(t){return this.archetypeSystem.getEntityArchetype(t)}}class Q{constructor(t){this.conditions=[],this.querySystem=t}withAll(...t){return this.conditions.push({type:k.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this}withAny(...t){return this.conditions.push({type:k.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this}without(...t){return this.conditions.push({type:k.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this}execute(){const t=performance.now();if(1===this.conditions.length){const t=this.conditions[0];switch(t.type){case k.ALL:return this.querySystem.queryAll(...t.componentTypes);case k.ANY:return this.querySystem.queryAny(...t.componentTypes);case k.NONE:return this.querySystem.queryNone(...t.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-t,fromCache:!1}}createComponentMask(t){let e=BigInt(0);for(const s of t)try{e|=g.getBitMask(s)}catch(t){console.warn(`组件类型 ${s.name} 未注册,跳过`)}return e}reset(){return this.conditions=[],this}}class G{constructor(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}on(t,e,s={}){return this.addListener(t,e,s)}once(t,e,s={}){return this.addListener(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.addListener(t,e,{...s,async:!0})}off(t,e){const s=this.listeners.get(t);if(!s)return!1;const n=s.findIndex((t=>t.id===e));return-1!==n&&(s.splice(n,1),0===s.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)}offAll(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)}async emit(t,e){if(!this.isEnabled)return;const s=this.batchConfigs.get(t);s?.enabled?this.addToBatch(t,e):await this.executeEvent(t,e)}emitSync(t,e){if(!this.isEnabled)return;const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s);for(const s of o)if(!s.config.async)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in event handler for ${t}:`,e)}this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}setBatchConfig(t,e){this.batchConfigs.set(t,e)}flushBatch(t){const e=this.batchQueue.get(t);if(!e||0===e.length)return;const s=this.batchTimers.get(t);s&&(clearTimeout(s),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}getStats(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)}resetStats(t){t?this.stats.delete(t):this.stats.clear()}setEnabled(t){this.isEnabled=t}hasListeners(t){const e=this.listeners.get(t);return!!e&&e.length>0}getListenerCount(t){const e=this.listeners.get(t);return e?e.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(t){this.maxListeners=t}addListener(t,e,s){let n=this.listeners.get(t);if(n||(n=[],this.listeners.set(t,n)),n.length>=this.maxListeners)return console.warn(`Maximum listeners (${this.maxListeners}) exceeded for event type: ${t}`),"";const i="listener_"+this.nextListenerId++,o={handler:e,config:{priority:0,...s},id:i};return n.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),i}async executeEvent(t,e){const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s),r=o.filter((t=>!t.config.async)),a=o.filter((t=>t.config.async));for(const s of r)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in sync event handler for ${t}:`,e)}const h=a.map((async s=>{try{s.config.context?await s.handler.call(s.config.context,e):await s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in async event handler for ${t}:`,e)}}));await Promise.all(h),this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}sortListenersByPriority(t){return t.slice().sort(((t,e)=>(e.config.priority||0)-(t.config.priority||0)))}removeListeners(t,e){if(0===e.length)return;const s=this.listeners.get(t);if(s){for(const t of e){const e=s.findIndex((e=>e.id===t));-1!==e&&s.splice(e,1)}0===s.length&&(this.listeners.delete(t),this.stats.delete(t))}}addToBatch(t,e){let s=this.batchQueue.get(t);s||(s=[],this.batchQueue.set(t,s)),s.push(e);const n=this.batchConfigs.get(t);if(s.length>=n.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){const e=setTimeout((()=>{this.flushBatch(t)}),n.delay);this.batchTimers.set(t,e)}}async processBatch(t,e){const s={type:t,events:e,count:e.length,timestamp:Date.now()};await this.executeEvent(`${t}:batch`,s)}clearBatch(t){this.batchQueue.delete(t);const e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))}clearAllBatches(){this.batchQueue.clear();for(const t of this.batchTimers.values())clearTimeout(t);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(t,e){let s=this.stats.get(t);s||(s=this.createEmptyStats(t),this.stats.set(t,s)),s.triggerCount++,s.totalExecutionTime+=e,s.averageExecutionTime=s.totalExecutionTime/s.triggerCount,s.lastTriggerTime=Date.now(),s.listenerCount=this.getListenerCount(t)}createEmptyStats(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}class V{get systems(){return this.entityProcessors.processors}constructor(t=!0){this.name="",this._didSceneBegin=!1,this.entities=new S(this),this.entityProcessors=new M,this.identifierPool=new w,this.componentStorageManager=new f,this.querySystem=new Y,this.eventSystem=new G,this.initialize()}initialize(){}onStart(){}unload(){}begin(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()}update(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()}createEntity(t){let e=new C(t,this.identifierPool.checkOut());return this.addEntity(e)}addEntity(t,e=!1){return this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t}createEntities(t,e="Entity"){const s=[];for(let n=0;n<t;n++){const t=new C(`${e}_${n}`,this.identifierPool.checkOut());t.scene=this,s.push(t)}for(const t of s)this.entities.add(t);return this.querySystem.addEntitiesUnchecked(s),this.eventSystem.emitSync("entities:batch_added",{entities:s,scene:this,count:t}),s}createEntitiesOld(t,e="Entity"){const s=[];for(let n=0;n<t;n++){const t=new C(`${e}_${n}`,this.identifierPool.checkOut());s.push(t),this.addEntity(t,!0)}return this.querySystem.clearCache(),s}destroyAllEntities(){for(let t=0;t<this.entities.count;t++)this.entities.buffer[t].destroy()}findEntity(t){return this.entities.findEntity(t)}findEntityById(t){return this.entities.findEntityById(t)}findEntitiesByTag(t){const e=[];for(const s of this.entities.buffer)s.tag===t&&e.push(s);return e}getEntityByName(t){return this.findEntity(t)}getEntitiesByTag(t){return this.findEntitiesByTag(t)}addEntityProcessor(t){return t.scene=this,this.entityProcessors.add(t),t.setUpdateOrder(this.entityProcessors.count-1),t}addSystem(t){return this.addEntityProcessor(t)}removeEntityProcessor(t){this.entityProcessors.remove(t)}getEntityProcessor(t){return this.entityProcessors.getProcessor(t)}getStats(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}}compactComponentStorage(){this.componentStorageManager.compactAll()}getDebugInfo(){return{name:this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((t=>({name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name))}))),processors:this.entityProcessors.processors.map((t=>({name:t.constructor.name,updateOrder:t.updateOrder,entityCount:t._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}}class Z{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new C("",t.identifierPool.checkOut())}named(t){return this.entity.name=t,this}tagged(t){return this.entity.tag=t,this}with(t){return this.entity.addComponent(t),this}withComponents(...t){for(const e of t)this.entity.addComponent(e);return this}withIf(t,e){return t&&this.entity.addComponent(e),this}withFactory(t){const e=t();return this.entity.addComponent(e),this}configure(t,e){const s=this.entity.getComponent(t);return s&&e(s),this}enabled(t=!0){return this.entity.enabled=t,this}active(t=!0){return this.entity.active=t,this}withChild(t){const e=t.build();return this.entity.addChild(e),this}withChildren(...t){for(const e of t){const t=e.build();this.entity.addChild(t)}return this}withChildFactory(t){const e=t(this.entity).build();return this.entity.addChild(e),this}withChildIf(t,e){if(t){const t=e.build();this.entity.addChild(t)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const t=new Z(this.scene,this.storageManager);return t.entity=this.entity,t}}class J{constructor(){this.scene=new V}named(t){return this.scene.name=t,this}withEntity(t){return this.scene.addEntity(t),this}withEntityBuilder(t){const e=t(new Z(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this}withEntities(...t){for(const e of t)this.scene.addEntity(e);return this}withSystem(t){return this.scene.addSystem(t),this}withSystems(...t){for(const e of t)this.scene.addSystem(e);return this}build(){return this.scene}}class K{constructor(t,...e){this.component=new t(...e)}set(t,e){return this.component[t]=e,this}configure(t){return t(this.component),this}setIf(t,e,s){return t&&(this.component[e]=s),this}build(){return this.component}}class X{constructor(t,e,s){this.scene=t,this.querySystem=e,this.eventSystem=s}createEntity(){return new Z(this.scene,this.scene.componentStorageManager)}createScene(){return new J}createComponent(t,...e){return new K(t,...e)}query(){return new Q(this.querySystem)}find(...t){return this.querySystem.queryAll(...t).entities}findFirst(...t){const e=this.querySystem.queryAll(...t);return e.entities.length>0?e.entities[0]:null}findByName(t){return this.scene.getEntityByName(t)}findByTag(t){return this.scene.getEntitiesByTag(t)}emit(t,e){this.eventSystem.emitSync(t,e)}async emitAsync(t,e){await this.eventSystem.emit(t,e)}on(t,e){return this.eventSystem.on(t,e)}once(t,e){return this.eventSystem.once(t,e)}off(t,e){this.eventSystem.off(t,e)}batch(t){return new tt(t)}getStats(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}}}class tt{constructor(t){this.entities=t}addComponent(t){for(const e of this.entities)e.addComponent(t);return this}removeComponent(t){for(const e of this.entities)e.removeComponentByType(t);return this}setActive(t){for(const e of this.entities)e.active=t;return this}setTag(t){for(const e of this.entities)e.tag=t;return this}forEach(t){return this.entities.forEach(t),this}filter(t){return new tt(this.entities.filter(t))}toArray(){return this.entities.slice()}count(){return this.entities.length}}function et(t,e,s){return new X(t,e,s)}class st{constructor(t=!0,n=!0){this._nextScene=null,this._globalManagers=[],st._instance=this,st.emitter=new e,st.emitter.addObserver(s.frameUpdated,this.update,this),this._timerManager=new l,st.registerGlobalManager(this._timerManager),this._performanceMonitor=m.instance,this._poolManager=y.getInstance(),st.entitySystemsEnabled=n,this.debug=t,this.initialize()}static get Instance(){return this._instance}static get scene(){return this._instance&&this._instance._scene||null}static set scene(t){if(t){if(!t)throw new Error("场景不能为空");null==this._instance._scene?(this._instance._scene=t,this._instance.onSceneChanged(),this._instance._scene.begin()):this._instance._nextScene=t}}static create(t=!0,e){return null==this._instance&&(this._instance=new st(t),e?.disableWasm&&this.disableWasm()),this._instance}static disableWasm(){Promise.resolve().then((function(){return z})).then((({ecsCore:t})=>{t.setSilent(!0)})).catch((()=>{}))}static registerGlobalManager(t){this._instance._globalManagers.push(t),t.enabled=!0}static unregisterGlobalManager(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1}static getGlobalManager(t){for(const e of this._instance._globalManagers)if(e instanceof t)return e;return null}static schedule(t,e=!1,s=null,n){return this._instance._timerManager.schedule(t,e,s,n)}static get ecsAPI(){return this._instance?._ecsAPI||null}onSceneChanged(){if(h.sceneChanged(),this._scene&&void 0!==this._scene.querySystem){const t=this._scene;this._ecsAPI=et(t,t.querySystem,t.eventSystem)}}initialize(){}update(t=-1){if(st.paused)return;const e=this._performanceMonitor.startMonitoring("Core.update");h.update(t),"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(h.deltaTime);const s=this._performanceMonitor.startMonitoring("GlobalManagers.update");for(const t of this._globalManagers)t.enabled&&t.update();if(this._performanceMonitor.endMonitoring("GlobalManagers.update",s,this._globalManagers.length),this._poolManager.update(),null!=this._nextScene&&(null!=this._scene&&this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this._scene.begin()),null!=this._scene&&this._scene.update){const t=this._performanceMonitor.startMonitoring("Scene.update");this._scene.update();const e=this._scene.entities?.count||0;this._performanceMonitor.endMonitoring("Scene.update",t,e)}this._performanceMonitor.endMonitoring("Core.update",e)}}st.paused=!1;class nt{constructor(){this._enabled=!0,this._updateOrder=0,this.id=nt._idGenerator++}get enabled(){return this.entity?this.entity.enabled&&this._enabled:this._enabled}set enabled(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}onAddedToEntity(){}onRemovedFromEntity(){}onEnabled(){}onDisabled(){}update(){}}nt._idGenerator=0;class it{constructor(){this._words=[],this._words=[]}set(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;for(;this._words.length<=e;)this._words.push(0);this._words[e]|=1<<s}clear(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;e<this._words.length&&(this._words[e]&=~(1<<s))}get(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;return!(e>=this._words.length)&&!!(this._words[e]&1<<s)}containsAll(t){const e=Math.max(this._words.length,t._words.length);for(let s=0;s<e;s++){const e=s<this._words.length?this._words[s]:0,n=s<t._words.length?t._words[s]:0;if((e&n)!==n)return!1}return!0}intersects(t){const e=Math.min(this._words.length,t._words.length);for(let s=0;s<e;s++)if(0!==(this._words[s]&t._words[s]))return!0;return!1}excludes(t){return!this.intersects(t)}clearAll(){this._words.length=0}isEmpty(){for(const t of this._words)if(0!==t)return!1;return!0}cardinality(){let t=0;for(const e of this._words)t+=this.popCount(e);return t}popCount(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24}copyFrom(t){this._words=[...t._words]}clone(){const t=new it;return t.copyFrom(this),t}}it.WORD_SIZE=32;class ot{static get instance(){return ot._instance||(ot._instance=new ot),ot._instance}constructor(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}getTypeId(t){let e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,t.name)),e}getTypeName(t){return this._typeNames.get(t)||"Unknown"}createBits(...t){const e=new it;for(const s of t){const t=this.getTypeId(s);e.set(t)}return e}getEntityBits(t){const e=new it;for(const s of t){const t=this.getTypeId(s.constructor);e.set(t)}return e}reset(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0}get registeredTypeCount(){return this._componentTypes.size}}class rt{constructor(){this.allSet=[],this.exclusionSet=[],this.oneSet=[],this._isDirty=!0}static empty(){return new rt}getAllSet(){return this.allSet}getExclusionSet(){return this.exclusionSet}getOneSet(){return this.oneSet}isInterestedEntity(t){const e=this.getEntityBits(t);return this.isInterested(e)}isInterested(t){return this.updateBitsIfDirty(),!(this._allBits&&!t.containsAll(this._allBits))&&((!this._exclusionBits||!t.intersects(this._exclusionBits))&&!(this._oneBits&&!t.intersects(this._oneBits)))}all(...t){return this.allSet.push(...t),this._isDirty=!0,this}exclude(...t){return this.exclusionSet.push(...t),this._isDirty=!0,this}one(...t){return this.oneSet.push(...t),this._isDirty=!0,this}getEntityBits(t){const e=t.components;return ot.instance.getEntityBits(e)}updateBitsIfDirty(){if(!this._isDirty)return;const t=ot.instance;this.allSet.length>0?this._allBits=t.createBits(...this.allSet):this._allBits=void 0,this.exclusionSet.length>0?this._exclusionBits=t.createBits(...this.exclusionSet):this._exclusionBits=void 0,this.oneSet.length>0?this._oneBits=t.createBits(...this.oneSet):this._oneBits=void 0,this._isDirty=!1}toString(){const t=[];return this.allSet.length>0&&t.push(`all: [${this.allSet.map((t=>t.name)).join(", ")}]`),this.exclusionSet.length>0&&t.push(`exclude: [${this.exclusionSet.map((t=>t.name)).join(", ")}]`),this.oneSet.length>0&&t.push(`one: [${this.oneSet.map((t=>t.name)).join(", ")}]`),`Matcher(${t.join(", ")})`}}class at{get entities(){return this._entities}get updateOrder(){return this._updateOrder}set updateOrder(t){this.setUpdateOrder(t)}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get systemName(){return this._systemName}constructor(t){this._entities=[],this._updateOrder=0,this._enabled=!0,this._performanceMonitor=m.instance,this._matcher=t||rt.empty(),this._systemName=this.constructor.name,this.initialize()}get scene(){return this._scene}set scene(t){this._scene=t,this._entities=[]}get matcher(){return this._matcher}setUpdateOrder(t){this._updateOrder=t,this.scene.entityProcessors.setDirty()}initialize(){}onChanged(t){const e=this._entities.includes(t),s=this._matcher.isInterestedEntity(t);s&&!e?this.add(t):!s&&e&&this.remove(t)}add(t){this._entities.includes(t)||(this._entities.push(t),this.onAdded(t))}onAdded(t){}remove(t){const e=this._entities.indexOf(t);-1!==e&&(this._entities.splice(e,1),this.onRemoved(t))}onRemoved(t){}update(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(this._systemName);try{this.begin(),this.process(this._entities)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,this._entities.length)}}lateUpdate(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);try{this.lateProcess(this._entities),this.end()}finally{this._performanceMonitor.endMonitoring(`${this._systemName}_Late`,t,this._entities.length)}}begin(){}process(t){}lateProcess(t){}end(){}checkProcessing(){return!0}getPerformanceData(){return this._performanceMonitor.getSystemData(this._systemName)}getPerformanceStats(){return this._performanceMonitor.getSystemStats(this._systemName)}resetPerformanceData(){this._performanceMonitor.resetSystem(this._systemName)}toString(){const t=this._entities.length,e=this.getPerformanceData(),s=e?` (${e.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${t} entities]${s}`}}class ht extends at{onChanged(t){}process(t){this.processSystem()}}class ct extends at{onChanged(t){}process(t){}}class lt extends at{constructor(t,e){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}checkProcessing(){return this.acc+=h.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class ut{constructor(t=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new G,this.isDebugMode=t}emit(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] Emitting event: ${t}`,s),this.eventSystem.emitSync(t,s)}async emitAsync(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] Emitting async event: ${t}`,s),await this.eventSystem.emit(t,s)}on(t,e,s={}){this.validateEventType(t);const n={once:s.once||!1,priority:s.priority||i.NORMAL,async:s.async||!1,context:s.context};return this.isDebugMode&&console.log(`[EventBus] Adding listener for: ${t}`,n),this.eventSystem.on(t,e,n)}once(t,e,s={}){return this.on(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.on(t,e,{...s,async:!0})}off(t,e){return this.isDebugMode&&console.log(`[EventBus] Removing listener: ${e} for event: ${t}`),this.eventSystem.off(t,e)}offAll(t){this.isDebugMode&&console.log(`[EventBus] Removing all listeners for event: ${t}`),this.eventSystem.offAll(t)}hasListeners(t){return this.eventSystem.hasListeners(t)}getStats(t){const e=this.eventSystem.getStats(t);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(s,this.convertEventStats(e))})),t}return this.convertEventStats(e)}clear(){this.isDebugMode&&console.log("[EventBus] Clearing all listeners"),this.eventSystem.clear()}setEnabled(t){this.eventSystem.setEnabled(t)}setDebugMode(t){this.isDebugMode=t}setMaxListeners(t){this.eventSystem.setMaxListeners(t)}getListenerCount(t){return this.eventSystem.getListenerCount(t)}setBatchConfig(t,e,s){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:s,enabled:!0})}flushBatch(t){this.eventSystem.flushBatch(t)}resetStats(t){this.eventSystem.resetStats(t)}emitEntityCreated(t){this.emit(n.ENTITY_CREATED,t)}emitEntityDestroyed(t){this.emit(n.ENTITY_DESTROYED,t)}emitComponentAdded(t){this.emit(n.COMPONENT_ADDED,t)}emitComponentRemoved(t){this.emit(n.COMPONENT_REMOVED,t)}emitSystemAdded(t){this.emit(n.SYSTEM_ADDED,t)}emitSystemRemoved(t){this.emit(n.SYSTEM_REMOVED,t)}emitSceneChanged(t){this.emit(o.CORE.SCENE_CHANGED,t)}emitPerformanceWarning(t){this.emit(n.PERFORMANCE_WARNING,t)}onEntityCreated(t,e){return this.on(n.ENTITY_CREATED,t,e)}onComponentAdded(t,e){return this.on(n.COMPONENT_ADDED,t,e)}onSystemError(t,e){return this.on(n.SYSTEM_ERROR,t,e)}onPerformanceWarning(t,e){return this.on(n.PERFORMANCE_WARNING,t,e)}validateEventType(t){r.isValid(t)||(this.isDebugMode&&console.warn(`[EventBus] Unknown event type: ${t}`),this.isDebugMode&&r.addCustomType(t))}enhanceEventData(t,e){const s=e;return s.timestamp||(s.timestamp=Date.now()),s.eventId||(s.eventId=`${t}_${++this.eventIdCounter}`),s.source||(s.source="EventBus"),s}convertEventStats(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}}}class mt{static getInstance(t=!1){return this.instance||(this.instance=new ut(t)),this.instance}static reset(t=!1){return this.instance&&this.instance.clear(),this.instance=new ut(t),this.instance}}function dt(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().on(t,o.bind(this),e)},i}}function pt(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().onAsync(t,o.bind(this),e)},i}}class yt{constructor(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}withAll(...t){return this._allComponents.push(...t),this}withAny(...t){return this._anyComponents.push(...t),this}without(...t){return this._withoutComponents.push(...t),this}withTag(t){return this._withTags.push(t),this}withoutTag(t){return this._withoutTags.push(t),this}active(){return this._activeOnly=!0,this}enabled(){return this._enabledOnly=!0,this}where(t){return this._customPredicates.push(t),this}execute(){let t=[];if(this._allComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");t=Array.from(e)}else if(this._anyComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");t=Array.from(e)}else t=this.entityManager.getAllEntities();return t.filter((t=>this.matchesEntity(t)))}first(){return this.entityManager.getAllEntities().find((t=>this.matchesEntity(t)))||null}count(){return this.entityManager.getAllEntities().filter((t=>this.matchesEntity(t))).length}forEach(t){this.entityManager.getAllEntities().forEach((e=>{this.matchesEntity(e)&&t(e)}))}matchesEntity(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(const e of this._allComponents)if(!t.hasComponent(e))return!1;if(this._anyComponents.length>0){let e=!1;for(const s of this._anyComponents)if(t.hasComponent(s)){e=!0;break}if(!e)return!1}if(this._withoutComponents.length>0)for(const e of this._withoutComponents)if(t.hasComponent(e))return!1;if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(const e of this._customPredicates)if(!e(t))return!1;return!0}}class gt{constructor(){this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new w,this._componentIndexManager=new W(O.HASH),this._archetypeSystem=new $,this._dirtyTrackingSystem=new j,this._eventBus=new ut(!1),C.eventBus=this._eventBus}get entityCount(){return this._entities.size}get activeEntityCount(){let t=0;for(const e of this._entities.values())e.active&&!e.isDestroyed&&t++;return t}createEntity(t=`Entity_${Date.now()}`){const e=this._identifierPool.checkOut(),s=new C(t,e);return this._entities.set(e,s),this.updateNameIndex(s,!0),this.updateTagIndex(s,!0),this._componentIndexManager.addEntity(s),this._archetypeSystem.addEntity(s),this._dirtyTrackingSystem.markDirty(s,N.COMPONENT_ADDED),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:s.id,entityName:s.name,entityTag:s.tag?.toString()}),s}destroyEntity(t){let e=null;return e="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null,!!e&&(this._destroyedEntities.add(e.id),this.updateNameIndex(e,!1),this.updateTagIndex(e,!1),this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e),this._dirtyTrackingSystem.markDirty(e,N.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()}),e.destroy(),this._entities.delete(e.id),this._identifierPool.checkIn(e.id),!0)}getAllEntities(){return Array.from(this._entities.values())}getEntity(t){const e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null}getEntityByName(t){const e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null}getEntitiesByTag(t){return[...this._entitiesByTag.get(t)||[]]}getEntitiesWithComponent(t){const e=this._componentIndexManager.query(t);return Array.from(e)}query(){return new yt(this)}queryWithComponentIndex(t,e){return this._componentIndexManager.queryMultiple(t,e)}markEntityDirty(t,e){this._dirtyTrackingSystem.markDirty(t,N.COMPONENT_MODIFIED,e)}getOptimizationStats(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this._dirtyTrackingSystem.getStats()}}get eventBus(){return this._eventBus}updateNameIndex(t,e){if(t.name)if(e){let e=this._entitiesByName.get(t.name);e||(e=[],this._entitiesByName.set(t.name,e)),e.push(t)}else{const e=this._entitiesByName.get(t.name);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._entitiesByName.delete(t.name))}}}updateTagIndex(t,e){if(e){let e=this._entitiesByTag.get(t.tag);e||(e=[],this._entitiesByTag.set(t.tag,e)),e.push(t)}else{const e=this._entitiesByTag.get(t.tag);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._entitiesByTag.delete(t.tag))}}}}class _t{static getType(t){return t.constructor}}class ft{static toNumber(t){return null==t?0:Number(t)}}!function(t){t[t.Error=0]="Error",t[t.Assert=1]="Assert",t[t.Warning=2]="Warning",t[t.Log=3]="Log",t[t.Exception=4]="Exception"}(R||(R={})),function(t){t[t.Position=1]="Position",t[t.Scale=2]="Scale",t[t.Rotation=4]="Rotation"}(B||(B={}));export{$ as ArchetypeSystem,pt as AsyncEventHandler,q as BitMaskOptimizer,H as BitmapComponentIndex,it as Bits,nt as Component,W as ComponentIndexManager,P as ComponentPool,_ as ComponentStorage,B as ComponentTransform,ot as ComponentTypeManager,st as Core,s as CoreEvents,N as DirtyFlag,j as DirtyTrackingSystem,n as ECSEventType,X as ECSFluentAPI,o as EVENT_TYPES,e as Emitter,C as Entity,S as EntityList,gt as EntityManager,M as EntityProcessorList,yt as EntityQueryBuilder,at as EntitySystem,ut as EventBus,dt as EventHandler,i as EventPriority,r as EventTypeValidator,t as FuncPack,mt as GlobalEventBus,a as GlobalManager,L as HashComponentIndex,w as IdentifierPool,O as IndexType,F as IndexUpdateBatcher,lt as IntervalSystem,A as JavaScriptFallback,R as LogType,rt as Matcher,ft as NumberExtension,ct as PassiveSystem,m as PerformanceMonitor,u as PerformanceWarningType,d as Pool,y as PoolManager,ht as ProcessingSystem,Y as QuerySystem,V as Scene,p as TieredObjectPool,h as Time,c as Timer,l as TimerManager,G as TypeSafeEventSystem,_t as TypeUtils,I as WasmEcsCore,b as WasmLoader,et as createECSAPI,x as ecsCore,v as initializeEcs};
1
+ class t{constructor(t,e){this.func=t,this.context=e}}class e{constructor(){this._messageTable=new Map}addObserver(e,s,n){let i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,s)||i.push(new t(s,n))}removeObserver(t,e){let s=this._messageTable.get(t);if(s){let t=s.findIndex((t=>t.func==e));-1!=t&&s.splice(t,1)}}emit(t,...e){let s=this._messageTable.get(t);if(s)for(let t of s)t.func.call(t.context,...e)}hasObserver(t,e){let s=this._messageTable.get(t);return!!s&&s.some((t=>t.func===e))}}var s,n,i;!function(t){t[t.sceneChanged=0]="sceneChanged",t[t.frameUpdated=1]="frameUpdated",t[t.renderChanged=2]="renderChanged"}(s||(s={})),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(n||(n={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(i||(i={}));const o={CORE:{SCENE_CHANGED:"core:scene:changed",FRAME_UPDATED:"core:frame:updated",RENDER_CHANGED:"core:render:changed"},ENTITY:{CREATED:n.ENTITY_CREATED,DESTROYED:n.ENTITY_DESTROYED,ENABLED:n.ENTITY_ENABLED,DISABLED:n.ENTITY_DISABLED,TAG_ADDED:n.ENTITY_TAG_ADDED,TAG_REMOVED:n.ENTITY_TAG_REMOVED,NAME_CHANGED:n.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:n.COMPONENT_ADDED,REMOVED:n.COMPONENT_REMOVED,MODIFIED:n.COMPONENT_MODIFIED,ENABLED:n.COMPONENT_ENABLED,DISABLED:n.COMPONENT_DISABLED},SYSTEM:{ADDED:n.SYSTEM_ADDED,REMOVED:n.SYSTEM_REMOVED,ENABLED:n.SYSTEM_ENABLED,DISABLED:n.SYSTEM_DISABLED,PROCESSING_START:n.SYSTEM_PROCESSING_START,PROCESSING_END:n.SYSTEM_PROCESSING_END,ERROR:n.SYSTEM_ERROR},PERFORMANCE:{WARNING:n.PERFORMANCE_WARNING,CRITICAL:n.PERFORMANCE_CRITICAL,MEMORY_HIGH:n.MEMORY_USAGE_HIGH,FRAME_DROP:n.FRAME_RATE_DROP}};class r{static isValid(t){return this.validTypes.has(t)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(t){this.validTypes.add(t)}static removeCustomType(t){this.validTypes.delete(t)}}r.validTypes=new Set([...Object.values(s).map((t=>t.toString())),...Object.values(n),...Object.values(o.CORE),...Object.values(o.ENTITY),...Object.values(o.COMPONENT),...Object.values(o.SYSTEM),...Object.values(o.PERFORMANCE)]);class a{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(t){this.setEnabled(t)}setEnabled(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}}class h{static update(t=-1){if(-1===t&&(t=Date.now()),this._isFirstUpdate)return this._lastTime=t,void(this._isFirstUpdate=!1);this.unscaledDeltaTime=(t-this._lastTime)/1e3,this.deltaTime=this.unscaledDeltaTime*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++,this._lastTime=t}static sceneChanged(){this._isFirstUpdate=!0}static checkEvery(t,e){return this.totalTime-e>=t}}h.deltaTime=0,h.unscaledDeltaTime=0,h.totalTime=0,h.unscaledTotalTime=0,h.timeScale=1,h.frameCount=0,h._lastTime=0,h._isFirstUpdate=!0;class c{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}reset(){this._elapsedTime=0}stop(){this._isDone=!0}tick(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=h.deltaTime,this._isDone}initialize(t,e,s,n){this._timeInSeconds=t,this._repeats=e,this.context=s,this._onTime=n.bind(s)}unload(){this.context=null,this._onTime=null}}class l extends a{constructor(){super(...arguments),this._timers=[]}update(){for(let t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))}schedule(t,e,s,n){let i=new c;return i.initialize(t,e,s,n),this._timers.push(i),i}}var u;!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(u||(u={}));class m{static get instance(){return m._instance||(m._instance=new m),m._instance}constructor(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(t){return this._isEnabled?performance.now():0}endMonitoring(t,e,s=0){if(!this._isEnabled||0===e)return;const n=performance.now(),i=n-e,o={name:t,executionTime:i,entityCount:s,averageTimePerEntity:s>0?i/s:0,lastUpdateTime:n};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let s=this._systemStats.get(t);s||(s={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,s)),s.totalTime+=e,s.executionCount++,s.averageTime=s.totalTime/s.executionCount,s.minTime=Math.min(s.minTime,e),s.maxTime=Math.max(s.maxTime,e),s.recentTimes.push(e),s.recentTimes.length>this._maxRecentSamples&&s.recentTimes.shift(),this.calculateAdvancedStats(s)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,s=t.recentTimes.reduce(((t,s)=>t+Math.pow(s-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(s);const n=[...t.recentTimes].sort(((t,e)=>t-e)),i=n.length;t.percentile95=n[Math.floor(.95*i)]||0,t.percentile99=n[Math.floor(.99*i)]||0}getSystemData(t){return this._systemData.get(t)}getSystemStats(t){return this._systemStats.get(t)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const t=[];t.push("=== ECS Performance Report ==="),t.push("");const e=Array.from(this._systemStats.entries()).sort(((t,e)=>e[1].averageTime-t[1].averageTime));for(const[s,n]of e){const e=this._systemData.get(s);t.push(`System: ${s}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${n.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${n.minTime.toFixed(2)}ms / ${n.maxTime.toFixed(2)}ms`),t.push(` Total: ${n.totalTime.toFixed(2)}ms (${n.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const s=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${s.toFixed(2)}ms`),t.push(`Systems Count: ${this._systemData.size}`),t.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(t){this._systemData.delete(t),this._systemStats.delete(t)}getPerformanceWarnings(t=16.67){const e=[];for(const[s,n]of this._systemData.entries())n.executionTime>t&&e.push(`${s}: ${n.executionTime.toFixed(2)}ms (>${t}ms)`);return e}setMaxRecentSamples(t){this._maxRecentSamples=t;for(const e of this._systemStats.values())for(;e.recentTimes.length>t;)e.recentTimes.shift()}}class d{constructor(t,e=100,s=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=s,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,s=1024){let n=this._pools.get(t);return n||(n=new d((()=>new t),e,s),this._pools.set(t,n)),n}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}const t=this._createFn();return this._stats.totalCreated++,this._updateHitRate(),t}free(t){this._objects.length<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._stats.totalReleased++,this._updateMemoryUsage())}warmUp(t){const e=Math.min(t,this._maxSize);for(;this._objects.length<e;){const t=this._createFn();this._stats.totalCreated++,this._objects.push(t),this._stats.size++}this._updateMemoryUsage()}clear(){this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}get size(){return this._objects.length}get maxSize(){return this._maxSize}set maxSize(t){for(this._maxSize=t,this._stats.maxSize=t;this._objects.length>this._maxSize;)this._objects.pop(),this._stats.size--;this._updateMemoryUsage()}getStats(){return{...this._stats}}resetStats(){this._stats.totalCreated=0,this._stats.totalObtained=0,this._stats.totalReleased=0,this._stats.hitRate=0}_updateHitRate(){if(this._stats.totalObtained>0){const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}static obtain(t){return this.getPool(t).obtain()}static free(t,e){this.getPool(t).free(e)}static warmUp(t,e){this.getPool(t).warmUp(e)}static clearPool(t){const e=this._pools.get(t);e&&e.clear()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getStats(){const t={};for(const[e,s]of this._pools.entries()){t[e.name||"Unknown"]=s.getStats()}return t}static getTotalMemoryUsage(){let t=0;for(const e of this._pools.values())t+=e.getStats().estimatedMemoryUsage;return t}static getPerformanceReport(){const t=this.getStats(),e=[];e.push("=== Object Pool Performance Report ==="),e.push(`Total Memory Usage: ${(this.getTotalMemoryUsage()/1024/1024).toFixed(2)} MB`),e.push("");for(const[s,n]of Object.entries(t))e.push(`${s}:`),e.push(` Size: ${n.size}/${n.maxSize}`),e.push(` Hit Rate: ${(100*n.hitRate).toFixed(1)}%`),e.push(` Total Created: ${n.totalCreated}`),e.push(` Total Obtained: ${n.totalObtained}`),e.push(` Memory: ${(n.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}}d._pools=new Map;class p{constructor(t,e,s=[10,50,200],n=1024){this.pools=[],this.totalObtained=0,this.totalReleased=0,this.createFn=t,this.resetFn=e,this.tierSizes=s;for(const e of s)this.pools.push(new d(t,e,n))}obtain(){this.totalObtained++;for(const t of this.pools)if(t.size>0)return t.obtain();return this.createFn()}release(t){this.totalReleased++,this.resetFn(t);for(const e of this.pools)if(e.size<e.maxSize)return void e.free(t)}warmUp(t){let e=t;for(const t of this.pools){const s=Math.min(e,t.maxSize);if(t.warmUp(s),e-=s,e<=0)break}}clear(){for(const t of this.pools)t.clear()}getStats(){let t=0,e=0,s=0;const n=[];for(const i of this.pools){const o=i.getStats();n.push(o),t+=o.size,e+=o.maxSize,s+=o.estimatedMemoryUsage}return{totalSize:t,totalMaxSize:e,totalMemoryUsage:s,tierStats:n,hitRate:this.totalObtained>0?(this.totalObtained-this.getTotalCreated())/this.totalObtained:0}}getTotalCreated(){return this.pools.reduce(((t,e)=>t+e.getStats().totalCreated),0)}}class y{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return y.instance||(y.instance=new y),y.instance}registerPool(t,e){this.pools.set(t,e)}getPool(t){return this.pools.get(t)||null}update(){const t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)}compactAllPools(){for(const t of this.pools.values())t instanceof d&&t.resetStats()}getAllStats(){const t=new Map;for(const[e,s]of this.pools.entries())(s instanceof d||s instanceof p)&&t.set(e,s.getStats());return t}generateReport(){const t=[];t.push("=== Pool Manager Report ===");let e=0;for(const[s,n]of this.pools.entries())if(t.push(`\n${s}:`),n instanceof d){const s=n.getStats();t.push(" Type: Standard Pool"),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e+=s.estimatedMemoryUsage}else if(n instanceof p){const s=n.getStats();t.push(" Type: Tiered Pool"),t.push(` Total Size: ${s.totalSize}/${s.totalMaxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.totalMemoryUsage/1024).toFixed(1)} KB`),e+=s.totalMemoryUsage}return t.push(`\nTotal Memory Usage: ${(e/1024/1024).toFixed(2)} MB`),t.join("\n")}}class g{static register(t){if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentTypes.set(t,e),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return BigInt(1)<<BigInt(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getAllRegisteredTypes(){return new Map(this.componentTypes)}}g.componentTypes=new Map,g.nextBitIndex=0,g.maxComponents=64;class _{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,g.isRegistered(t)||g.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${this.componentType.name}`);let s;this.freeIndices.length>0?(s=this.freeIndices.pop(),this.components[s]=e,this.indexToEntity[s]=t):(s=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,s),this._size++}getComponent(t){const e=this.entityToIndex.get(t);return void 0!==e?this.components[e]:null}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const s=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,s}forEach(t){for(let e=0;e<this.components.length;e++){const s=this.components[e];s&&t(s,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let s=0;s<this.components.length;s++){const n=this.components[s];n&&(t.push(n),e.push(this.indexToEntity[s]))}return{components:t,entityIds:e}}clear(){this.components.length=0,this.entityToIndex.clear(),this.indexToEntity.length=0,this.freeIndices.length=0,this._size=0}get size(){return this._size}get type(){return this.componentType}compact(){if(0===this.freeIndices.length)return;const t=[],e=[],s=new Map;let n=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[n]=o,e[n]=this.indexToEntity[i],s.set(this.indexToEntity[i],n),n++)}this.components=t,this.indexToEntity=e,this.entityToIndex=s,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,s=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:s,fragmentation:t>0?s/t:0}}}class f{constructor(){this.storages=new Map}getStorage(t){let e=this.storages.get(t);return e||(e=new _(t),this.storages.set(t,e)),e}addComponent(t,e){const s=e.constructor;this.getStorage(s).addComponent(t,e)}getComponent(t,e){const s=this.storages.get(e);return s?s.getComponent(t):null}hasComponent(t,e){const s=this.storages.get(e);return!!s&&s.hasComponent(t)}removeComponent(t,e){const s=this.storages.get(e);return s?s.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigInt(0);for(const[s,n]of this.storages.entries())n.hasComponent(t)&&(e|=g.getBitMask(s));return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,s]of this.storages.entries()){const n=e.name||"Unknown";t.set(n,s.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}class E{compare(t,e){let s=t.updateOrder-e.updateOrder;return 0==s&&(s=t.id-e.id),s}}class T{constructor(t={maxSize:16,ttl:5e3,enableLRU:!0}){this.cache=new Map,this.accessOrder=[],this.config=t}get(t){const e=this.cache.get(t);return e?Date.now()-e.lastAccessed>this.config.ttl?(this.cache.delete(t),this.removeFromAccessOrder(t),null):(e.lastAccessed=Date.now(),e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.component):null}set(t,e){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLeastRecentlyUsed();const s={component:e,lastAccessed:Date.now(),accessCount:1};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}delete(t){const e=this.cache.delete(t);return e&&this.removeFromAccessOrder(t),e}clear(){this.cache.clear(),this.accessOrder.length=0}has(t){return this.cache.has(t)}evictLeastRecentlyUsed(){if(this.accessOrder.length>0){const t=this.accessOrder[0];this.cache.delete(t),this.accessOrder.shift()}}updateAccessOrder(t){this.removeFromAccessOrder(t),this.accessOrder.push(t)}removeFromAccessOrder(t){const e=this.accessOrder.indexOf(t);-1!==e&&this.accessOrder.splice(e,1)}getStats(){let t=0,e=0;for(const s of this.cache.values())t+=s.accessCount,e++;return{size:this.cache.size,maxSize:this.config.maxSize,hitRate:t>0?e/t:0,averageAccessCount:this.cache.size>0?t/this.cache.size:0}}}class C{constructor(t,e){this.components=[],this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=BigInt(0),this._componentTypeToIndex=new Map,this._componentAccessStats=new Map,this.name=t,this.id=e,this._componentCache=new T}get isDestroyed(){return this._isDestroyed}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(t){this._active!==t&&(this._active=t,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(t){this._tag=t}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}get componentMask(){return this._componentMask}createComponent(t,...e){const s=new t(...e);return this.addComponent(s)}addComponentInternal(t){const e=t.constructor;g.isRegistered(e)||g.register(e),t.entity=this;const s=this.components.length;return this.components.push(t),this._componentTypeToIndex.set(e,s),this._componentMask|=g.getBitMask(e),this._componentCache.set(e,t),this._componentAccessStats.set(e,{accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0}),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${e.name}`);if(this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),C.eventBus&&C.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this);return t}getComponent(t){if(this.updateComponentAccessStats(t),!g.isRegistered(t))return this.recordCacheMiss(t),null;const e=g.getBitMask(t);if((this._componentMask&e)===BigInt(0))return this.recordCacheMiss(t),null;const s=this._componentCache.get(t);if(s)return this.recordCacheHit(t),s;const n=this._componentTypeToIndex.get(t);if(void 0!==n&&n<this.components.length){const e=this.components[n];if(e&&e.constructor===t)return this._componentCache.set(t,e),this.recordCacheHit(t),e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this._componentCache.set(t,e),this.rebuildComponentIndex(),this.recordCacheHit(t),e}for(let e=0;e<this.components.length;e++){const s=this.components[e];if(s instanceof t)return this._componentTypeToIndex.set(t,e),this._componentCache.set(t,s),this.recordCacheHit(t),s}return this.recordCacheMiss(t),null}updateComponentAccessStats(t){let e=this._componentAccessStats.get(t);e||(e={accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0},this._componentAccessStats.set(t,e)),e.accessCount++,e.lastAccessed=Date.now()}recordCacheHit(t){const e=this._componentAccessStats.get(t);e&&e.cacheHits++}recordCacheMiss(t){const e=this._componentAccessStats.get(t);e&&e.cacheMisses++}rebuildComponentIndex(){this._componentTypeToIndex.clear();for(let t=0;t<this.components.length;t++){const e=this.components[t].constructor;this._componentTypeToIndex.set(e,t)}}hasComponent(t){if(!g.isRegistered(t))return!1;const e=g.getBitMask(t);return(this._componentMask&e)!==BigInt(0)}getOrCreateComponent(t,...e){let s=this.getComponent(t);return s||(s=this.createComponent(t,...e)),s}removeComponent(t){const e=t.constructor,s=this.components.indexOf(t);if(-1!==s&&(this.components.splice(s,1),this.rebuildComponentIndex()),this._componentCache.delete(e),this._componentAccessStats.delete(e),g.isRegistered(e)&&(this._componentMask&=~g.getBitMask(e)),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity(),C.eventBus&&C.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),t.entity=null,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentCache.clear(),this._componentTypeToIndex.clear(),this._componentAccessStats.clear(),this._componentMask=BigInt(0);for(const e of t){const t=e.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),e.onRemovedFromEntity(),e.entity=null}if(this.components.length=0,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}addComponents(t){const e=[];for(const s of t)try{e.push(this.addComponent(s))}catch(t){console.warn(`Failed to add component ${s.constructor.name}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const s of t)e.push(this.removeComponentByType(s));return e}getComponentCacheStats(){const t=new Map;for(const[e,s]of this._componentAccessStats){const n=s.cacheHits+s.cacheMisses;t.set(e.name,{...s,hitRate:n>0?s.cacheHits/n:0})}return{cacheStats:this._componentCache.getStats(),accessStats:t,indexMappingSize:this._componentTypeToIndex.size,totalComponents:this.components.length}}warmUpComponentCache(){for(let t=0;t<this.components.length;t++){const e=this.components[t],s=e.constructor;this._componentTypeToIndex.set(s,t),this._componentCache.set(s,e)}}cleanupComponentCache(){const t=Date.now();for(const[e,s]of this._componentAccessStats)t-s.lastAccessed>3e4&&s.accessCount<5&&this._componentCache.delete(e)}getComponents(t){const e=[];for(const s of this.components)s instanceof t&&e.push(s);return e}addChild(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)}removeAllChildren(){const t=[...this._children];for(const e of t)this.removeChild(e)}findChild(t,e=!1){for(const e of this._children)if(e.name===t)return e;if(e)for(const e of this._children){const s=e.findChild(t,!0);if(s)return s}return null}findChildrenByTag(t,e=!1){const s=[];for(const e of this._children)e.tag===t&&s.push(e);if(e)for(const e of this._children)s.push(...e.findChildrenByTag(t,!0));return s}getRoot(){let t=this;for(;t._parent;)t=t._parent;return t}isAncestorOf(t){let e=t._parent;for(;e;){if(e===this)return!0;e=e._parent}return!1}isDescendantOf(t){return t.isAncestorOf(this)}getDepth(){let t=0,e=this._parent;for(;e;)t++,e=e._parent;return t}forEachChild(t,e=!1){this._children.forEach(((s,n)=>{t(s,n),e&&s.forEachChild(t,!0)}))}onActiveChanged(){for(const t of this.components)"onActiveChanged"in t&&"function"==typeof t.onActiveChanged&&t.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}update(){if(this.activeInHierarchy&&!this._isDestroyed){for(const t of this.components)t.enabled&&t.update();for(const t of this._children)t.update()}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const t=[...this._children];for(const e of t)e.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&this.scene.entities&&this.scene.entities.remove(this)}compareTo(t){return E.prototype.compare(this,t)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){const t=this.getComponentCacheStats(),e=Array.from(t.accessStats.entries()).map((([t,e])=>({componentType:t,accessCount:e.accessCount,cacheHits:e.cacheHits,cacheMisses:e.cacheMisses,hitRate:e.hitRate,lastAccessed:new Date(e.lastAccessed).toISOString()})));return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((t=>t.constructor.name)),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),componentCache:t.cacheStats,componentAccessStats:e,indexMappingSize:t.indexMappingSize}}}C.entityComparer=new E,C.eventBus=null;class S{get count(){return this.buffer.length}constructor(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}add(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)}addImmediate(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))}remove(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)}removeImmediate(t){const e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1))}removeAllEntities(){for(let t=this.buffer.length-1;t>=0;t--)this.buffer[t].destroy();this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0}updateLists(){if(this._entitiesToAdd.length>0){for(const t of this._entitiesToAdd)this.addImmediate(t);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const t of this._entitiesToRemove)this.removeImmediate(t);this._entitiesToRemove.length=0}}update(){this._isUpdating=!0;try{for(let t=0;t<this.buffer.length;t++){const e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()}findEntity(t){const e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null}findEntitiesByName(t){return this._nameToEntities.get(t)||[]}findEntityById(t){return this._idToEntity.get(t)||null}findEntitiesByTag(t){const e=[];for(const s of this.buffer)s.tag===t&&e.push(s);return e}findEntitiesWithComponent(t){const e=[];for(const s of this.buffer)s.hasComponent(t)&&e.push(s);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const s of this.buffer)t(s)&&e(s)}updateNameIndex(t,e){if(t.name)if(e){let e=this._nameToEntities.get(t.name);e||(e=[],this._nameToEntities.set(t.name,e)),e.push(t)}else{const e=this._nameToEntities.get(t.name);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._nameToEntities.delete(t.name))}}}getStats(){let t=0;for(const e of this.buffer)e.enabled&&!e.isDestroyed&&t++;return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class M{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(t){this._processors.push(t),this.setDirty()}remove(t){const e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)}getProcessor(t){for(const e of this._processors)if(e instanceof t)return e;return null}begin(){this.sortProcessors();for(const t of this._processors)t.initialize()}end(){}update(){this.sortProcessors();for(const t of this._processors)t.update()}lateUpdate(){for(const t of this._processors)t.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((t,e)=>t.updateOrder-e.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}class w{constructor(){this._nextAvailableId=0,this._ids=[]}checkOut(){return this._ids.length>0?this._ids.pop():this._nextAvailableId++}checkIn(t){this._ids.push(t)}}class I{constructor(){this.wasmModule=null,this.wasmCore=null,this.silent=!1}setSilent(t){this.silent=t}async initializeWasm(t,e){try{this.silent||console.log("开始手动初始化WASM模块...");const s=await this.initWasmInstance(t,e);if(s&&s.EcsCore)return this.wasmModule=s,this.wasmCore=new s.EcsCore,this.silent||console.log("✅ WASM模块初始化成功"),!0;throw new Error("WASM模块缺少EcsCore构造函数")}catch(t){if(!this.silent){const e=t instanceof Error?t.message:String(t);console.warn("❌ WASM初始化失败:",e)}return!1}}async initWasmInstance(t,e){const s={wasmBinary:e._file||e,onRuntimeInitialized:()=>{this.silent||console.log("WASM运行时初始化完成")}};return await t(s)}async loadWasmModule(){return this.silent||(console.log("📦 WASM模块需要手动初始化"),console.log("请从GitHub Release下载WASM包并调用相应的初始化方法"),console.log("参考文档: COCOS_USAGE.md 或 README.md")),!1}async initializeWasmModule(){if(this.wasmModule)try{await this.wasmModule.default()}catch(t){if(!this.wasmModule.initSync)throw t;try{this.wasmModule.initSync(void 0)}catch(e){throw t}}}getWasmCore(){return this.wasmCore}getWasmModule(){return this.wasmModule}cleanup(){this.wasmCore&&this.wasmCore.free&&this.wasmCore.free(),this.wasmCore=null,this.wasmModule=null}}class b{constructor(){this.jsEntityMasks=new Map,this.jsNextEntityId=1,this.jsQueryCount=0,this.jsUpdateCount=0}createEntity(){const t=this.jsNextEntityId++;return this.jsEntityMasks.set(t,0n),t}destroyEntity(t){return this.jsEntityMasks.delete(t)}updateEntityMask(t,e){this.jsEntityMasks.set(t,e),this.jsUpdateCount++}batchUpdateMasks(t,e){for(let s=0;s<t.length&&s<e.length;s++)this.jsEntityMasks.set(t[s],e[s]);this.jsUpdateCount+=Math.min(t.length,e.length)}queryEntities(t,e=1e4){const s=[];for(const[n,i]of this.jsEntityMasks)if((i&t)===t&&(s.push(n),s.length>=e))break;return this.jsQueryCount++,{entities:new Uint32Array(s),count:s.length}}queryCached(t){return this.queryEntities(t)}queryMultipleComponents(t,e=1e4){const s=[];for(const[n,i]of this.jsEntityMasks){let o=!1;for(const e of t)if((i&e)===e){o=!0;break}if(o&&(s.push(n),s.length>=e))break}return this.jsQueryCount++,{entities:new Uint32Array(s),count:s.length}}queryWithExclusion(t,e,s=1e4){const n=[];for(const[i,o]of this.jsEntityMasks)if((o&t)===t&&0n===(o&e)&&(n.push(i),n.length>=s))break;return this.jsQueryCount++,{entities:new Uint32Array(n),count:n.length}}getEntityMask(t){return this.jsEntityMasks.get(t)||null}entityExists(t){return this.jsEntityMasks.has(t)}createComponentMask(t){let e=0n;for(const s of t)e|=1n<<BigInt(s);return e}maskContainsComponent(t,e){return 0n!=(t&1n<<BigInt(e))}getPerformanceStats(){return{entityCount:this.jsEntityMasks.size,indexCount:0,queryCount:this.jsQueryCount,updateCount:this.jsUpdateCount,wasmEnabled:!1}}clear(){this.jsEntityMasks.clear(),this.jsNextEntityId=1,this.jsQueryCount=0,this.jsUpdateCount=0}getEntityCount(){return this.jsEntityMasks.size}}class A{constructor(){this.initialized=!1,this.usingWasm=!1,this.wasmLoader=new I,this.jsFallback=new b}setSilent(t){this.wasmLoader.setSilent(t)}async initializeWasm(t,e){const s=await this.wasmLoader.initializeWasm(t,e);return s&&(this.usingWasm=!0,this.initialized=!0),s}async initialize(){return this.initialized||(console.log("🔄 初始化ECS核心..."),this.usingWasm=await this.wasmLoader.loadWasmModule(),this.initialized=!0),!0}createEntity(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();return t?t.create_entity():this.jsFallback.createEntity()}return this.jsFallback.createEntity()}destroyEntity(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();return e?e.destroy_entity(t):this.jsFallback.destroyEntity(t)}return this.jsFallback.destroyEntity(t)}updateEntityMask(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();s?s.update_entity_mask(t,e):this.jsFallback.updateEntityMask(t,e)}else this.jsFallback.updateEntityMask(t,e)}batchUpdateMasks(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=new Uint32Array(t),i=new BigUint64Array(e);s.batch_update_masks(n,i)}else this.jsFallback.batchUpdateMasks(t,e)}else this.jsFallback.batchUpdateMasks(t,e)}queryEntities(t,e=1e4){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=s.query_entities(t,e),i=s.get_query_result_count(),o=this.wasmLoader.getWasmModule();if(o&&o.memory){const t=new Uint32Array(o.memory.buffer),e=new Uint32Array(i);for(let s=0;s<i;s++)e[s]=t[n/4+s];return{entities:e,count:i}}}}return this.jsFallback.queryEntities(t,e)}queryCached(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e){const s=e.query_cached(t),n=e.get_cached_query_count(t),i=this.wasmLoader.getWasmModule();if(i&&i.memory){const t=new Uint32Array(i.memory.buffer),e=new Uint32Array(n);for(let i=0;i<n;i++)e[i]=t[s/4+i];return{entities:e,count:n}}}}return this.jsFallback.queryCached(t)}queryMultipleComponents(t,e=1e4){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmCore();if(s){const n=new BigUint64Array(t),i=s.query_multiple_components(n,e),o=s.get_query_result_count(),r=this.wasmLoader.getWasmModule();if(r&&r.memory){const t=new Uint32Array(r.memory.buffer),e=new Uint32Array(o);for(let s=0;s<o;s++)e[s]=t[i/4+s];return{entities:e,count:o}}}}return this.jsFallback.queryMultipleComponents(t,e)}queryWithExclusion(t,e,s=1e4){if(this.ensureInitialized(),this.usingWasm){const n=this.wasmLoader.getWasmCore();if(n){const i=n.query_with_exclusion(t,e,s),o=n.get_query_result_count(),r=this.wasmLoader.getWasmModule();if(r&&r.memory){const t=new Uint32Array(r.memory.buffer),e=new Uint32Array(o);for(let s=0;s<o;s++)e[s]=t[i/4+s];return{entities:e,count:o}}}}return this.jsFallback.queryWithExclusion(t,e,s)}getEntityMask(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e)return e.get_entity_mask(t)}return this.jsFallback.getEntityMask(t)}entityExists(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmCore();if(e)return e.entity_exists(t)}return this.jsFallback.entityExists(t)}createComponentMask(t){if(this.ensureInitialized(),this.usingWasm){const e=this.wasmLoader.getWasmModule();if(e){const s=new Uint32Array(t);return e.create_component_mask(s)}}return this.jsFallback.createComponentMask(t)}maskContainsComponent(t,e){if(this.ensureInitialized(),this.usingWasm){const s=this.wasmLoader.getWasmModule();if(s)return s.mask_contains_component(t,e)}return this.jsFallback.maskContainsComponent(t,e)}getPerformanceStats(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();if(t){const e=t.get_performance_stats();return{entityCount:e[0]||0,indexCount:e[1]||0,queryCount:e[2]||0,updateCount:e[3]||0,wasmEnabled:!0}}}return this.jsFallback.getPerformanceStats()}clear(){if(this.ensureInitialized(),this.usingWasm){const t=this.wasmLoader.getWasmCore();t&&t.clear()}this.jsFallback.clear()}isUsingWasm(){return this.usingWasm}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new Error("ECS核心未初始化,请先调用 initialize() 方法")}cleanup(){this.wasmLoader.cleanup(),this.jsFallback.clear(),this.initialized=!1,this.usingWasm=!1}}const x=new A;async function v(t=!1){return x.setSilent(t),await x.initialize()}var D,O,N,R,k,B,z=Object.freeze({__proto__:null,ecsCore:x,initializeEcs:v});class P{constructor(t,e,s=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=s}acquire(){return this.pool.length>0?this.pool.pop():this.createFn()}release(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))}prewarm(t){for(let e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}}class U{constructor(){this.pools=new Map}static getInstance(){return U.instance||(U.instance=new U),U.instance}registerPool(t,e,s,n){this.pools.set(t,new P(e,s,n))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const s=this.pools.get(t);s&&s.release(e)}prewarmAll(t=100){for(const e of this.pools.values())e.prewarm(t)}clearAll(){for(const t of this.pools.values())t.clear()}getPoolStats(){const t=new Map;for(const[e,s]of this.pools)t.set(e,{available:s.getAvailableCount(),maxSize:s.getMaxSize()});return t}}class q{constructor(){this.maskCache=new Map,this.componentTypeMap=new Map,this.nextComponentId=0}static getInstance(){return q.instance||(q.instance=new q),q.instance}registerComponentType(t){return this.componentTypeMap.has(t)||this.componentTypeMap.set(t,this.nextComponentId++),this.componentTypeMap.get(t)}getComponentTypeId(t){return this.componentTypeMap.get(t)}createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const s=this.getComponentTypeId(t);if(void 0===s)throw new Error(`Component type not registered: ${t}`);const n=1n<<BigInt(s);return this.maskCache.set(e,n),n}createCombinedMask(t){const e=`combined:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let s=0n;for(const e of t){const t=this.getComponentTypeId(e);if(void 0===t)throw new Error(`Component type not registered: ${e}`);s|=1n<<BigInt(t)}return this.maskCache.set(e,s),s}maskContainsComponent(t,e){return 0n!==(t&this.createSingleComponentMask(e))}maskContainsAllComponents(t,e){const s=this.createCombinedMask(e);return(t&s)===s}maskContainsAnyComponent(t,e){return 0n!==(t&this.createCombinedMask(e))}addComponentToMask(t,e){return t|this.createSingleComponentMask(e)}removeComponentFromMask(t,e){return t&~this.createSingleComponentMask(e)}precomputeCommonMasks(t){for(const e of t)this.createCombinedMask(e)}getCacheStats(){return{size:this.maskCache.size,componentTypes:this.componentTypeMap.size}}clearCache(){this.maskCache.clear()}reset(){this.maskCache.clear(),this.componentTypeMap.clear(),this.nextComponentId=0}maskToComponentNames(t){const e=[];for(const[s,n]of this.componentTypeMap){0n!==(t&1n<<BigInt(n))&&e.push(s)}return e}getComponentCount(t){let e=0,s=t;for(;0n!==s;)0n!=(1n&s)&&e++,s>>=1n;return e}}!function(t){t.ADD_ENTITY="add_entity",t.REMOVE_ENTITY="remove_entity",t.UPDATE_ENTITY="update_entity"}(D||(D={}));class F{constructor(){this.pendingOperations=[],this.isProcessing=!1,this.batchSize=1e3,this.flushTimeout=null,this.flushDelay=16}addOperation(t){this.pendingOperations.push(t),this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}addEntities(t){for(const e of t)this.pendingOperations.push({type:D.ADD_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}removeEntities(t){for(const e of t)this.pendingOperations.push({type:D.REMOVE_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}updateEntities(t){for(const e of t)this.pendingOperations.push({type:D.UPDATE_ENTITY,entity:e.entity,oldMask:e.oldMask,newMask:e.newMask});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}scheduleFlush(){this.flushTimeout||(this.flushTimeout=setTimeout((()=>{this.flush()}),this.flushDelay))}flush(){if(!this.isProcessing&&0!==this.pendingOperations.length){this.isProcessing=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null);try{this.processBatch()}finally{this.isProcessing=!1}}}processBatch(){const t=this.pendingOperations;this.pendingOperations=[];const e=[],s=[],n=[];for(const i of t)switch(i.type){case D.ADD_ENTITY:e.push(i.entity);break;case D.REMOVE_ENTITY:s.push(i.entity);break;case D.UPDATE_ENTITY:void 0!==i.oldMask&&void 0!==i.newMask&&n.push({entity:i.entity,oldMask:i.oldMask,newMask:i.newMask})}e.length>0&&this.processBatchAdd(e),s.length>0&&this.processBatchRemove(s),n.length>0&&this.processBatchUpdate(n)}processBatchAdd(t){this.onBatchAdd&&this.onBatchAdd(t)}processBatchRemove(t){this.onBatchRemove&&this.onBatchRemove(t)}processBatchUpdate(t){this.onBatchUpdate&&this.onBatchUpdate(t)}setBatchSize(t){this.batchSize=Math.max(1,t)}setFlushDelay(t){this.flushDelay=Math.max(0,t)}getPendingCount(){return this.pendingOperations.length}clear(){this.pendingOperations.length=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null)}hasPendingOperations(){return this.pendingOperations.length>0}}!function(t){t.HASH="hash",t.BITMAP="bitmap",t.SORTED="sorted"}(O||(O={}));class L{constructor(){this.type=O.HASH,this._componentToEntities=new Map,this._entityToComponents=new Map,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){const e=t.components,s=new Set;for(const n of e){const e=n.constructor;s.add(e);let i=this._componentToEntities.get(e);i||(i=new Set,this._componentToEntities.set(e,i)),i.add(t)}this._entityToComponents.set(t,s),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToComponents.get(t);if(e){for(const s of e){const e=this._componentToEntities.get(s);e&&(e.delete(t),0===e.size&&this._componentToEntities.delete(s))}this._entityToComponents.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=new Set(this._componentToEntities.get(t)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;if(1===t.length)return this.query(t[0]);let n;if("AND"===e){let e,i=1/0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||0===t.size)return this._queryCount++,this._totalQueryTime+=performance.now()-s,new Set;t.size<i&&(i=t.size,e=t)}if(n=new Set,e)for(const s of e){let e=!0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||!t.has(s)){e=!1;break}}e&&n.add(s)}}else{n=new Set;for(const e of t){const t=this._componentToEntities.get(e);if(t)for(const e of t)n.add(e)}}return this._queryCount++,this._totalQueryTime+=performance.now()-s,n}clear(){this._componentToEntities.clear(),this._entityToComponents.clear(),this._lastUpdated=Date.now()}getStats(){let t=0;t+=64*this._componentToEntities.size,t+=64*this._entityToComponents.size;for(const e of this._componentToEntities.values())t+=8*e.size;for(const e of this._entityToComponents.values())t+=8*e.size;return{type:this.type,size:this._componentToEntities.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class H{constructor(){this.type=O.BITMAP,this._componentTypeToBit=new Map,this._entityToBitmap=new Map,this._bitToEntities=new Map,this._nextBit=0,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){let e=0;for(const s of t.components){const n=s.constructor;let i=this._componentTypeToBit.get(n);void 0===i&&(i=this._nextBit++,this._componentTypeToBit.set(n,i)),e|=1<<i;let o=this._bitToEntities.get(1<<i);o||(o=new Set,this._bitToEntities.set(1<<i,o)),o.add(t)}this._entityToBitmap.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToBitmap.get(t);if(void 0!==e){for(const[s,n]of this._bitToEntities)0!==(e&s)&&(n.delete(t),0===n.size&&this._bitToEntities.delete(s));this._entityToBitmap.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=this._componentTypeToBit.get(t);if(void 0===s)return this._queryCount++,this._totalQueryTime+=performance.now()-e,new Set;const n=new Set(this._bitToEntities.get(1<<s)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;let n=0;const i=[];for(const e of t){const t=this._componentTypeToBit.get(e);void 0!==t&&(n|=1<<t,i.push(1<<t))}const o=new Set;if("AND"===e)for(const[t,e]of this._entityToBitmap)(e&n)===n&&o.add(t);else for(const t of i){const e=this._bitToEntities.get(t);if(e)for(const t of e)o.add(t)}return this._queryCount++,this._totalQueryTime+=performance.now()-s,o}clear(){this._componentTypeToBit.clear(),this._entityToBitmap.clear(),this._bitToEntities.clear(),this._nextBit=0,this._lastUpdated=Date.now()}getStats(){let t=0;t+=12*this._componentTypeToBit.size,t+=12*this._entityToBitmap.size,t+=64*this._bitToEntities.size;for(const e of this._bitToEntities.values())t+=8*e.size;return{type:this.type,size:this._componentTypeToBit.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class W{constructor(t=O.HASH){this._indexHistory=new Map,this._autoOptimize=!0,this._optimizationThreshold=1e3,this._activeIndex=this.createIndex(t)}addEntity(t){this._activeIndex.addEntity(t),this.checkOptimization()}removeEntity(t){this._activeIndex.removeEntity(t)}query(t){return this._activeIndex.query(t)}queryMultiple(t,e){return this._activeIndex.queryMultiple(t,e)}switchIndexType(t){if(t===this._activeIndex.type)return;this._indexHistory.set(this._activeIndex.type,this._activeIndex.getStats());const e=this._activeIndex;this._activeIndex=this.createIndex(t),e.clear()}setAutoOptimize(t){this._autoOptimize=t}getStats(){return this._activeIndex.getStats()}getAllStats(){const t=this._activeIndex.getStats();return new Map([...this._indexHistory,[t.type,t]])}clear(){this._activeIndex.clear()}createIndex(t){switch(t){case O.HASH:return new L;case O.BITMAP:return new H;case O.SORTED:default:return new L}}checkOptimization(){if(!this._autoOptimize)return;const t=this._activeIndex.getStats();t.queryCount<this._optimizationThreshold||(t.avgQueryTime>1&&t.type!==O.HASH?this.switchIndexType(O.HASH):t.memoryUsage>10485760&&t.type!==O.BITMAP&&this.switchIndexType(O.BITMAP))}}class ${constructor(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}addEntity(t){const e=this.getEntityComponentTypes(t),s=this.generateArchetypeId(e);let n=this._archetypes.get(s);n||(n=this.createArchetype(e)),n.entities.push(t),n.updatedAt=Date.now(),this._entityToArchetype.set(t,n),this.updateComponentIndexes(n,e,!0),this.invalidateQueryCache()}removeEntity(t){const e=this._entityToArchetype.get(t);if(!e)return;const s=e.entities.indexOf(t);-1!==s&&(e.entities.splice(s,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}queryArchetypes(t,e="AND"){const s=performance.now(),n=`${e}:${t.map((t=>t.name)).sort().join(",")}`,i=this._queryCache.get(n);if(i&&Date.now()-i.timestamp<this._cacheTimeout)return{...i.result,executionTime:performance.now()-s,fromCache:!0};const o=[];let r=0;if("AND"===e)for(const e of this._archetypes.values())this.archetypeContainsAllComponents(e,t)&&(o.push(e),r+=e.entities.length);else{const e=new Set;for(const s of t){const t=this._componentToArchetypes.get(s);if(t)for(const s of t)e.add(s)}for(const t of e)o.push(t),r+=t.entities.length}const a={archetypes:o,totalEntities:r,executionTime:performance.now()-s,fromCache:!1};return this._queryCache.set(n,{result:a,timestamp:Date.now()}),a}getEntityArchetype(t){return this._entityToArchetype.get(t)}getAllArchetypes(){return Array.from(this._archetypes.values())}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()}getEntityComponentTypes(t){return t.components.map((t=>t.constructor))}generateArchetypeId(t){return t.map((t=>t.name)).sort().join("|")}createArchetype(t){const e=this.generateArchetypeId(t),s={id:e,componentTypes:[...t],entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,s),s}archetypeContainsAllComponents(t,e){for(const s of e)if(!t.componentTypes.includes(s))return!1;return!0}updateComponentIndexes(t,e,s){for(const n of e){let e=this._componentToArchetypes.get(n);e||(e=new Set,this._componentToArchetypes.set(n,e)),s?e.add(t):(e.delete(t),0===e.size&&this._componentToArchetypes.delete(n))}}invalidateQueryCache(){this._queryCache.clear()}}!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(N||(N={}));class j{constructor(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}markDirty(t,e,s=[]){this._stats.totalMarkings++;let n=this._dirtyEntities.get(t);n||(n={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,n)),n.flags|=e,n.timestamp=performance.now(),n.frameNumber=this._currentFrame;for(const t of s)n.modifiedComponents.add(t);this.notifyListeners(n,e)}isDirty(t,e=N.ALL){const s=this._dirtyEntities.get(t);return!!s&&0!==(s.flags&e)}clearDirty(t,e=N.ALL){const s=this._dirtyEntities.get(t);s&&(e===N.ALL?this._dirtyEntities.delete(t):(s.flags&=~e,0===s.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)}getDirtyEntities(t=N.ALL){const e=[];for(const s of this._dirtyEntities.values())0!==(s.flags&t)&&e.push(s);return e}processDirtyEntities(){if(this._isProcessing)return;this._isProcessing=!0;const t=performance.now();0===this._processingQueue.length&&this._processingQueue.push(...this._dirtyEntities.values());let e=0;for(;this._processingQueue.length>0&&e<this._batchSize;){if(performance.now()-t>this._maxProcessingTime)break;const s=this._processingQueue.shift();this.processEntity(s),e++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}addListener(t){this._listeners.push(t),this._listeners.sort(((t,e)=>(t.priority||100)-(e.priority||100)))}removeListener(t){const e=this._listeners.findIndex((e=>e.callback===t));-1!==e&&this._listeners.splice(e,1)}beginFrame(){this._currentFrame++}endFrame(){this._isProcessing||this.processDirtyEntities()}getStats(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}}clear(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}}configureBatchProcessing(t,e){this._batchSize=t,this._maxProcessingTime=e}processEntity(t){for(const e of this._listeners)if(0!==(t.flags&e.flags))try{e.callback(t)}catch(t){console.error("Dirty listener error:",t)}this.clearDirty(t.entity)}notifyListeners(t,e){for(const s of this._listeners)if(0!==(e&s.flags))try{s.callback(t)}catch(t){console.error("Dirty listener notification error:",t)}}onFrameEnd(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size}estimateMemoryUsage(){let t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length,t}}!function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(R||(R={}));class Y{constructor(){this.entities=[],this.wasmAvailable=!1,this.indexDirty=!0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=U.getInstance(),this.bitMaskOptimizer=q.getInstance(),this.indexUpdateBatcher=new F,this.componentIndexManager=new W(O.HASH),this.archetypeSystem=new $,this.dirtyTrackingSystem=new j,this.indexUpdateBatcher.onBatchAdd=t=>{for(const e of t)this.addEntityToIndexes(e)},this.indexUpdateBatcher.onBatchRemove=t=>{for(const e of t)this.removeEntityFromIndexes(e)},this.indexUpdateBatcher.onBatchUpdate=t=>{for(const e of t)this.removeEntityFromIndexes(e.entity),this.addEntityToIndexes(e.entity)},this.initializeWasm()}async initializeWasm(){try{const t=await x.initialize();this.wasmAvailable=t&&x.isUsingWasm(),this.wasmAvailable?console.log("QuerySystem: WebAssembly计算加速已启用"):console.log("QuerySystem: 使用JavaScript实现")}catch(t){console.warn("QuerySystem: WebAssembly初始化失败,使用JavaScript实现:",t),this.wasmAvailable=!1}}setEntities(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()}addEntity(t,e=!1){this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_ADDED),e||this.clearQueryCache())}addEntities(t){if(0===t.length)return;const e=new Set(this.entities.map((t=>t.id)));let s=0;for(const n of t)e.has(n.id)||(this.entities.push(n),this.addEntityToIndexes(n),e.add(n.id),s++);s>0&&this.clearQueryCache()}addEntitiesUnchecked(t){if(0!==t.length){for(const e of t)this.entities.push(e);for(const e of t)this.addEntityToIndexes(e);this.clearQueryCache()}}removeEntity(t){const e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_REMOVED),this.clearQueryCache())}addEntityToIndexes(t){const e=t.componentMask;let s=this.entityIndex.byMask.get(e);s||(s=new Set,this.entityIndex.byMask.set(e,s)),s.add(t);const n=t.components;for(let e=0;e<n.length;e++){const s=n[e].constructor;let i=this.entityIndex.byComponentType.get(s);i||(i=new Set,this.entityIndex.byComponentType.set(s,i)),i.add(t)}const i=t.tag;if(void 0!==i){let e=this.entityIndex.byTag.get(i);e||(e=new Set,this.entityIndex.byTag.set(i,e)),e.add(t)}const o=t.name;if(o){let e=this.entityIndex.byName.get(o);e||(e=new Set,this.entityIndex.byName.set(o,e)),e.add(t)}}removeEntityFromIndexes(t){const e=t.componentMask,s=this.entityIndex.byMask.get(e);s&&(s.delete(t),0===s.size&&this.entityIndex.byMask.delete(e));for(const e of t.components){const s=e.constructor,n=this.entityIndex.byComponentType.get(s);n&&(n.delete(t),0===n.size&&this.entityIndex.byComponentType.delete(s))}if(void 0!==t.tag){const e=this.entityIndex.byTag.get(t.tag);e&&(e.delete(t),0===e.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){const e=this.entityIndex.byName.get(t.name);e&&(e.delete(t),0===e.size&&this.entityIndex.byName.delete(t.name))}}rebuildIndexes(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear();for(const t of this.entities)this.addEntityToIndexes(t);this.indexDirty=!1}queryAll(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`all:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};let i;const o=this.archetypeSystem.queryArchetypes(t,"AND");if(o.archetypes.length>0){this.queryStats.archetypeHits++,i=[];for(const t of o.archetypes)i.push(...t.entities)}else if(1===t.length){this.queryStats.indexHits++;const e=this.componentIndexManager.query(t[0]);i=Array.from(e)}else{const e=this.componentIndexManager.queryMultiple(t,"AND");i=Array.from(e)}return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryMultipleComponents(t){let e=null,s=1/0;for(const n of t){const t=this.entityIndex.byComponentType.get(n);if(!t||0===t.size)return[];t.size<s&&(s=t.size,e=t)}if(!e)return this.queryStats.linearScans++,this.queryByLinearScan(t);const n=this.createComponentMask(t),i=[];for(const t of e)(t.componentMask&n)===n&&i.push(t);return i}queryByLinearScan(t){const e=this.createComponentMask(t);return this.entities.filter((t=>(t.componentMask&e)===e))}queryAny(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`any:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};const i=this.archetypeSystem.queryArchetypes(t,"OR");let o;if(i.archetypes.length>0){this.queryStats.archetypeHits++,o=[];for(const t of i.archetypes)o.push(...t.entities)}else{const e=this.componentIndexManager.queryMultiple(t,"OR");o=Array.from(e)}return this.addToCache(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryNone(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`none:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};const i=this.createComponentMask(t),o=this.entities.filter((t=>(t.componentMask&i)===BigInt(0)));return this.addToCache(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryByTag(t){const e=performance.now();this.queryStats.totalQueries++;const s=`tag:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByName(t){const e=performance.now();this.queryStats.totalQueries++;const s=`name:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByComponent(t){const e=performance.now();this.queryStats.totalQueries++;const s=`component:${t.name}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}getFromCache(t){const e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null}addToCache(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[...e],timestamp:Date.now(),hitCount:0})}cleanupCache(){const t=Date.now();for(const[e,s]of this.queryCache.entries())t-s.timestamp>this.cacheTimeout&&this.queryCache.delete(e);if(this.queryCache.size>=this.cacheMaxSize){const t=Array.from(this.queryCache.entries());t.sort(((t,e)=>t[1].hitCount-e[1].hitCount));const e=Math.floor(.2*this.cacheMaxSize);for(let s=0;s<e&&s<t.length;s++)this.queryCache.delete(t[s][0])}}clearQueryCache(){this.queryCache.clear()}clearCache(){this.clearQueryCache()}batchUpdateComponents(t){if(this.wasmAvailable&&t.length>100)try{const e=t.map((t=>t.entityId)),s=t.map((t=>t.componentMask));x.batchUpdateMasks(e,s),console.log(`WebAssembly加速批量更新 ${t.length} 个实体`)}catch(e){console.warn("WebAssembly批量更新失败,回退到JavaScript实现:",e),this.batchUpdateComponentsJS(t)}else this.batchUpdateComponentsJS(t);this.clearQueryCache()}batchUpdateComponentsJS(t){for(const e of t){this.entities.find((t=>t.id===e.entityId))&&console.log(`更新实体 ${e.entityId} 的组件掩码: ${e.componentMask}`)}this.rebuildIndexes()}getAccelerationStatus(){return{wasmEnabled:this.wasmAvailable,currentProvider:this.wasmAvailable?"hybrid":"javascript",availableProviders:["javascript","hybrid"],performanceInfo:{entityCount:this.entities.length,wasmEnabled:this.wasmAvailable,cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}}async switchAccelerationProvider(t){return!0}createComponentMask(t){const e=t.map((t=>t.name));for(const t of e)this.bitMaskOptimizer.registerComponentType(t);return this.bitMaskOptimizer.createCombinedMask(e)}getStats(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},accelerationStatus:this.getAccelerationStatus(),queryStats:{...this.queryStats,cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this.dirtyTrackingSystem.getStats()}}}switchComponentIndexType(t){this.componentIndexManager.switchIndexType(t)}configureDirtyTracking(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)}optimizePerformance(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache();const t=this.componentIndexManager.getStats();t.avgQueryTime>2&&t.type!==O.HASH?this.switchComponentIndexType(O.HASH):t.memoryUsage>52428800&&t.type!==O.BITMAP&&this.switchComponentIndexType(O.BITMAP)}beginFrame(){this.dirtyTrackingSystem.beginFrame()}endFrame(){this.dirtyTrackingSystem.endFrame()}markEntityDirty(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,N.COMPONENT_MODIFIED,e),this.clearQueryCache()}getEntityArchetype(t){return this.archetypeSystem.getEntityArchetype(t)}}class Q{constructor(t){this.conditions=[],this.querySystem=t}withAll(...t){return this.conditions.push({type:R.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this}withAny(...t){return this.conditions.push({type:R.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this}without(...t){return this.conditions.push({type:R.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this}execute(){const t=performance.now();if(1===this.conditions.length){const t=this.conditions[0];switch(t.type){case R.ALL:return this.querySystem.queryAll(...t.componentTypes);case R.ANY:return this.querySystem.queryAny(...t.componentTypes);case R.NONE:return this.querySystem.queryNone(...t.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-t,fromCache:!1}}createComponentMask(t){let e=BigInt(0);for(const s of t)try{e|=g.getBitMask(s)}catch(t){console.warn(`组件类型 ${s.name} 未注册,跳过`)}return e}reset(){return this.conditions=[],this}}class G{constructor(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}on(t,e,s={}){return this.addListener(t,e,s)}once(t,e,s={}){return this.addListener(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.addListener(t,e,{...s,async:!0})}off(t,e){const s=this.listeners.get(t);if(!s)return!1;const n=s.findIndex((t=>t.id===e));return-1!==n&&(s.splice(n,1),0===s.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)}offAll(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)}async emit(t,e){if(!this.isEnabled)return;const s=this.batchConfigs.get(t);s?.enabled?this.addToBatch(t,e):await this.executeEvent(t,e)}emitSync(t,e){if(!this.isEnabled)return;const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s);for(const s of o)if(!s.config.async)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in event handler for ${t}:`,e)}this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}setBatchConfig(t,e){this.batchConfigs.set(t,e)}flushBatch(t){const e=this.batchQueue.get(t);if(!e||0===e.length)return;const s=this.batchTimers.get(t);s&&(clearTimeout(s),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}getStats(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)}resetStats(t){t?this.stats.delete(t):this.stats.clear()}setEnabled(t){this.isEnabled=t}hasListeners(t){const e=this.listeners.get(t);return!!e&&e.length>0}getListenerCount(t){const e=this.listeners.get(t);return e?e.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(t){this.maxListeners=t}addListener(t,e,s){let n=this.listeners.get(t);if(n||(n=[],this.listeners.set(t,n)),n.length>=this.maxListeners)return console.warn(`Maximum listeners (${this.maxListeners}) exceeded for event type: ${t}`),"";const i="listener_"+this.nextListenerId++,o={handler:e,config:{priority:0,...s},id:i};return n.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),i}async executeEvent(t,e){const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s),r=o.filter((t=>!t.config.async)),a=o.filter((t=>t.config.async));for(const s of r)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in sync event handler for ${t}:`,e)}const h=a.map((async s=>{try{s.config.context?await s.handler.call(s.config.context,e):await s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`Error in async event handler for ${t}:`,e)}}));await Promise.all(h),this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}sortListenersByPriority(t){return t.slice().sort(((t,e)=>(e.config.priority||0)-(t.config.priority||0)))}removeListeners(t,e){if(0===e.length)return;const s=this.listeners.get(t);if(s){for(const t of e){const e=s.findIndex((e=>e.id===t));-1!==e&&s.splice(e,1)}0===s.length&&(this.listeners.delete(t),this.stats.delete(t))}}addToBatch(t,e){let s=this.batchQueue.get(t);s||(s=[],this.batchQueue.set(t,s)),s.push(e);const n=this.batchConfigs.get(t);if(s.length>=n.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){const e=setTimeout((()=>{this.flushBatch(t)}),n.delay);this.batchTimers.set(t,e)}}async processBatch(t,e){const s={type:t,events:e,count:e.length,timestamp:Date.now()};await this.executeEvent(`${t}:batch`,s)}clearBatch(t){this.batchQueue.delete(t);const e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))}clearAllBatches(){this.batchQueue.clear();for(const t of this.batchTimers.values())clearTimeout(t);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(t,e){let s=this.stats.get(t);s||(s=this.createEmptyStats(t),this.stats.set(t,s)),s.triggerCount++,s.totalExecutionTime+=e,s.averageExecutionTime=s.totalExecutionTime/s.triggerCount,s.lastTriggerTime=Date.now(),s.listenerCount=this.getListenerCount(t)}createEmptyStats(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}class V{get systems(){return this.entityProcessors.processors}constructor(t=!0){this.name="",this._didSceneBegin=!1,this.entities=new S(this),this.entityProcessors=new M,this.identifierPool=new w,this.componentStorageManager=new f,this.querySystem=new Y,this.eventSystem=new G,this.initialize()}initialize(){}onStart(){}unload(){}begin(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()}update(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()}createEntity(t){let e=new C(t,this.identifierPool.checkOut());return this.addEntity(e)}addEntity(t,e=!1){return this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t}createEntities(t,e="Entity"){const s=[];for(let n=0;n<t;n++){const t=new C(`${e}_${n}`,this.identifierPool.checkOut());t.scene=this,s.push(t)}for(const t of s)this.entities.add(t);return this.querySystem.addEntitiesUnchecked(s),this.eventSystem.emitSync("entities:batch_added",{entities:s,scene:this,count:t}),s}createEntitiesOld(t,e="Entity"){const s=[];for(let n=0;n<t;n++){const t=new C(`${e}_${n}`,this.identifierPool.checkOut());s.push(t),this.addEntity(t,!0)}return this.querySystem.clearCache(),s}destroyAllEntities(){for(let t=0;t<this.entities.count;t++)this.entities.buffer[t].destroy()}findEntity(t){return this.entities.findEntity(t)}findEntityById(t){return this.entities.findEntityById(t)}findEntitiesByTag(t){const e=[];for(const s of this.entities.buffer)s.tag===t&&e.push(s);return e}getEntityByName(t){return this.findEntity(t)}getEntitiesByTag(t){return this.findEntitiesByTag(t)}addEntityProcessor(t){return t.scene=this,this.entityProcessors.add(t),t.setUpdateOrder(this.entityProcessors.count-1),t}addSystem(t){return this.addEntityProcessor(t)}removeEntityProcessor(t){this.entityProcessors.remove(t)}getEntityProcessor(t){return this.entityProcessors.getProcessor(t)}getStats(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}}compactComponentStorage(){this.componentStorageManager.compactAll()}getDebugInfo(){return{name:this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((t=>({name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name))}))),processors:this.entityProcessors.processors.map((t=>({name:t.constructor.name,updateOrder:t.updateOrder,entityCount:t._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}}class Z{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new C("",t.identifierPool.checkOut())}named(t){return this.entity.name=t,this}tagged(t){return this.entity.tag=t,this}with(t){return this.entity.addComponent(t),this}withComponents(...t){for(const e of t)this.entity.addComponent(e);return this}withIf(t,e){return t&&this.entity.addComponent(e),this}withFactory(t){const e=t();return this.entity.addComponent(e),this}configure(t,e){const s=this.entity.getComponent(t);return s&&e(s),this}enabled(t=!0){return this.entity.enabled=t,this}active(t=!0){return this.entity.active=t,this}withChild(t){const e=t.build();return this.entity.addChild(e),this}withChildren(...t){for(const e of t){const t=e.build();this.entity.addChild(t)}return this}withChildFactory(t){const e=t(this.entity).build();return this.entity.addChild(e),this}withChildIf(t,e){if(t){const t=e.build();this.entity.addChild(t)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const t=new Z(this.scene,this.storageManager);return t.entity=this.entity,t}}class J{constructor(){this.scene=new V}named(t){return this.scene.name=t,this}withEntity(t){return this.scene.addEntity(t),this}withEntityBuilder(t){const e=t(new Z(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this}withEntities(...t){for(const e of t)this.scene.addEntity(e);return this}withSystem(t){return this.scene.addSystem(t),this}withSystems(...t){for(const e of t)this.scene.addSystem(e);return this}build(){return this.scene}}class K{constructor(t,...e){this.component=new t(...e)}set(t,e){return this.component[t]=e,this}configure(t){return t(this.component),this}setIf(t,e,s){return t&&(this.component[e]=s),this}build(){return this.component}}class X{constructor(t,e,s){this.scene=t,this.querySystem=e,this.eventSystem=s}createEntity(){return new Z(this.scene,this.scene.componentStorageManager)}createScene(){return new J}createComponent(t,...e){return new K(t,...e)}query(){return new Q(this.querySystem)}find(...t){return this.querySystem.queryAll(...t).entities}findFirst(...t){const e=this.querySystem.queryAll(...t);return e.entities.length>0?e.entities[0]:null}findByName(t){return this.scene.getEntityByName(t)}findByTag(t){return this.scene.getEntitiesByTag(t)}emit(t,e){this.eventSystem.emitSync(t,e)}async emitAsync(t,e){await this.eventSystem.emit(t,e)}on(t,e){return this.eventSystem.on(t,e)}once(t,e){return this.eventSystem.once(t,e)}off(t,e){this.eventSystem.off(t,e)}batch(t){return new tt(t)}getStats(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}}}class tt{constructor(t){this.entities=t}addComponent(t){for(const e of this.entities)e.addComponent(t);return this}removeComponent(t){for(const e of this.entities)e.removeComponentByType(t);return this}setActive(t){for(const e of this.entities)e.active=t;return this}setTag(t){for(const e of this.entities)e.tag=t;return this}forEach(t){return this.entities.forEach(t),this}filter(t){return new tt(this.entities.filter(t))}toArray(){return this.entities.slice()}count(){return this.entities.length}}function et(t,e,s){return new X(t,e,s)}class st{constructor(t=!0,n=!0){this._nextScene=null,this._globalManagers=[],st._instance=this,st.emitter=new e,st.emitter.addObserver(s.frameUpdated,this.update,this),this._timerManager=new l,st.registerGlobalManager(this._timerManager),this._performanceMonitor=m.instance,this._poolManager=y.getInstance(),st.entitySystemsEnabled=n,this.debug=t,this.initialize()}static get Instance(){return this._instance}static get scene(){return this._instance&&this._instance._scene||null}static set scene(t){if(t){if(!t)throw new Error("场景不能为空");null==this._instance._scene?(this._instance._scene=t,this._instance.onSceneChanged(),this._instance._scene.begin()):this._instance._nextScene=t}}static create(t=!0,e){return null==this._instance&&(this._instance=new st(t),e?.disableWasm&&this.disableWasm()),this._instance}static disableWasm(){Promise.resolve().then((function(){return z})).then((({ecsCore:t})=>{t.setSilent(!0)})).catch((()=>{}))}static registerGlobalManager(t){this._instance._globalManagers.push(t),t.enabled=!0}static unregisterGlobalManager(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1}static getGlobalManager(t){for(const e of this._instance._globalManagers)if(e instanceof t)return e;return null}static schedule(t,e=!1,s=null,n){return this._instance._timerManager.schedule(t,e,s,n)}static get ecsAPI(){return this._instance?._ecsAPI||null}onSceneChanged(){if(h.sceneChanged(),this._scene&&void 0!==this._scene.querySystem){const t=this._scene;this._ecsAPI=et(t,t.querySystem,t.eventSystem)}}initialize(){}update(t=-1){if(st.paused)return;const e=this._performanceMonitor.startMonitoring("Core.update");h.update(t),"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(h.deltaTime);const s=this._performanceMonitor.startMonitoring("GlobalManagers.update");for(const t of this._globalManagers)t.enabled&&t.update();if(this._performanceMonitor.endMonitoring("GlobalManagers.update",s,this._globalManagers.length),this._poolManager.update(),null!=this._nextScene&&(null!=this._scene&&this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this._scene.begin()),null!=this._scene&&this._scene.update){const t=this._performanceMonitor.startMonitoring("Scene.update");this._scene.update();const e=this._scene.entities?.count||0;this._performanceMonitor.endMonitoring("Scene.update",t,e)}this._performanceMonitor.endMonitoring("Core.update",e)}}st.paused=!1;class nt{constructor(){this._enabled=!0,this._updateOrder=0,this.id=nt._idGenerator++}get enabled(){return this.entity?this.entity.enabled&&this._enabled:this._enabled}set enabled(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}onAddedToEntity(){}onRemovedFromEntity(){}onEnabled(){}onDisabled(){}update(){}}nt._idGenerator=0;class it{constructor(){this._words=[],this._words=[]}set(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;for(;this._words.length<=e;)this._words.push(0);this._words[e]|=1<<s}clear(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;e<this._words.length&&(this._words[e]&=~(1<<s))}get(t){const e=Math.floor(t/it.WORD_SIZE),s=t%it.WORD_SIZE;return!(e>=this._words.length)&&!!(this._words[e]&1<<s)}containsAll(t){const e=Math.max(this._words.length,t._words.length);for(let s=0;s<e;s++){const e=s<this._words.length?this._words[s]:0,n=s<t._words.length?t._words[s]:0;if((e&n)!==n)return!1}return!0}intersects(t){const e=Math.min(this._words.length,t._words.length);for(let s=0;s<e;s++)if(0!==(this._words[s]&t._words[s]))return!0;return!1}excludes(t){return!this.intersects(t)}clearAll(){this._words.length=0}isEmpty(){for(const t of this._words)if(0!==t)return!1;return!0}cardinality(){let t=0;for(const e of this._words)t+=this.popCount(e);return t}popCount(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24}copyFrom(t){this._words=[...t._words]}clone(){const t=new it;return t.copyFrom(this),t}}it.WORD_SIZE=32;class ot{static get instance(){return ot._instance||(ot._instance=new ot),ot._instance}constructor(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}getTypeId(t){let e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,t.name)),e}getTypeName(t){return this._typeNames.get(t)||"Unknown"}createBits(...t){const e=new it;for(const s of t){const t=this.getTypeId(s);e.set(t)}return e}getEntityBits(t){const e=new it;for(const s of t){const t=this.getTypeId(s.constructor);e.set(t)}return e}reset(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0}get registeredTypeCount(){return this._componentTypes.size}}class rt{constructor(){this.allSet=[],this.exclusionSet=[],this.oneSet=[],this._isDirty=!0}static empty(){return new rt}getAllSet(){return this.allSet}getExclusionSet(){return this.exclusionSet}getOneSet(){return this.oneSet}isInterestedEntity(t){const e=this.getEntityBits(t);return this.isInterested(e)}isInterested(t){return this.updateBitsIfDirty(),!(this._allBits&&!t.containsAll(this._allBits))&&((!this._exclusionBits||!t.intersects(this._exclusionBits))&&!(this._oneBits&&!t.intersects(this._oneBits)))}all(...t){return this.allSet.push(...t),this._isDirty=!0,this}exclude(...t){return this.exclusionSet.push(...t),this._isDirty=!0,this}one(...t){return this.oneSet.push(...t),this._isDirty=!0,this}getEntityBits(t){const e=t.components;return ot.instance.getEntityBits(e)}updateBitsIfDirty(){if(!this._isDirty)return;const t=ot.instance;this.allSet.length>0?this._allBits=t.createBits(...this.allSet):this._allBits=void 0,this.exclusionSet.length>0?this._exclusionBits=t.createBits(...this.exclusionSet):this._exclusionBits=void 0,this.oneSet.length>0?this._oneBits=t.createBits(...this.oneSet):this._oneBits=void 0,this._isDirty=!1}toString(){const t=[];return this.allSet.length>0&&t.push(`all: [${this.allSet.map((t=>t.name)).join(", ")}]`),this.exclusionSet.length>0&&t.push(`exclude: [${this.exclusionSet.map((t=>t.name)).join(", ")}]`),this.oneSet.length>0&&t.push(`one: [${this.oneSet.map((t=>t.name)).join(", ")}]`),`Matcher(${t.join(", ")})`}}class at{get entities(){return this._entities}get updateOrder(){return this._updateOrder}set updateOrder(t){this.setUpdateOrder(t)}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get systemName(){return this._systemName}constructor(t){this._entities=[],this._updateOrder=0,this._enabled=!0,this._performanceMonitor=m.instance,this._matcher=t||rt.empty(),this._systemName=this.constructor.name,this.initialize()}get scene(){return this._scene}set scene(t){this._scene=t,this._entities=[]}get matcher(){return this._matcher}setUpdateOrder(t){this._updateOrder=t,this.scene.entityProcessors.setDirty()}initialize(){}onChanged(t){const e=this._entities.includes(t),s=this._matcher.isInterestedEntity(t);s&&!e?this.add(t):!s&&e&&this.remove(t)}add(t){this._entities.includes(t)||(this._entities.push(t),this.onAdded(t))}onAdded(t){}remove(t){const e=this._entities.indexOf(t);-1!==e&&(this._entities.splice(e,1),this.onRemoved(t))}onRemoved(t){}update(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(this._systemName);try{this.begin(),this.process(this._entities)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,this._entities.length)}}lateUpdate(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);try{this.lateProcess(this._entities),this.end()}finally{this._performanceMonitor.endMonitoring(`${this._systemName}_Late`,t,this._entities.length)}}begin(){}process(t){}lateProcess(t){}end(){}checkProcessing(){return!0}getPerformanceData(){return this._performanceMonitor.getSystemData(this._systemName)}getPerformanceStats(){return this._performanceMonitor.getSystemStats(this._systemName)}resetPerformanceData(){this._performanceMonitor.resetSystem(this._systemName)}toString(){const t=this._entities.length,e=this.getPerformanceData(),s=e?` (${e.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${t} entities]${s}`}}class ht extends at{onChanged(t){}process(t){this.processSystem()}}class ct extends at{onChanged(t){}process(t){}}class lt extends at{constructor(t,e){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}checkProcessing(){return this.acc+=h.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class ut{constructor(t=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new G,this.isDebugMode=t}emit(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] Emitting event: ${t}`,s),this.eventSystem.emitSync(t,s)}async emitAsync(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] Emitting async event: ${t}`,s),await this.eventSystem.emit(t,s)}on(t,e,s={}){this.validateEventType(t);const n={once:s.once||!1,priority:s.priority||i.NORMAL,async:s.async||!1,context:s.context};return this.isDebugMode&&console.log(`[EventBus] Adding listener for: ${t}`,n),this.eventSystem.on(t,e,n)}once(t,e,s={}){return this.on(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.on(t,e,{...s,async:!0})}off(t,e){return this.isDebugMode&&console.log(`[EventBus] Removing listener: ${e} for event: ${t}`),this.eventSystem.off(t,e)}offAll(t){this.isDebugMode&&console.log(`[EventBus] Removing all listeners for event: ${t}`),this.eventSystem.offAll(t)}hasListeners(t){return this.eventSystem.hasListeners(t)}getStats(t){const e=this.eventSystem.getStats(t);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(s,this.convertEventStats(e))})),t}return this.convertEventStats(e)}clear(){this.isDebugMode&&console.log("[EventBus] Clearing all listeners"),this.eventSystem.clear()}setEnabled(t){this.eventSystem.setEnabled(t)}setDebugMode(t){this.isDebugMode=t}setMaxListeners(t){this.eventSystem.setMaxListeners(t)}getListenerCount(t){return this.eventSystem.getListenerCount(t)}setBatchConfig(t,e,s){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:s,enabled:!0})}flushBatch(t){this.eventSystem.flushBatch(t)}resetStats(t){this.eventSystem.resetStats(t)}emitEntityCreated(t){this.emit(n.ENTITY_CREATED,t)}emitEntityDestroyed(t){this.emit(n.ENTITY_DESTROYED,t)}emitComponentAdded(t){this.emit(n.COMPONENT_ADDED,t)}emitComponentRemoved(t){this.emit(n.COMPONENT_REMOVED,t)}emitSystemAdded(t){this.emit(n.SYSTEM_ADDED,t)}emitSystemRemoved(t){this.emit(n.SYSTEM_REMOVED,t)}emitSceneChanged(t){this.emit(o.CORE.SCENE_CHANGED,t)}emitPerformanceWarning(t){this.emit(n.PERFORMANCE_WARNING,t)}onEntityCreated(t,e){return this.on(n.ENTITY_CREATED,t,e)}onComponentAdded(t,e){return this.on(n.COMPONENT_ADDED,t,e)}onSystemError(t,e){return this.on(n.SYSTEM_ERROR,t,e)}onPerformanceWarning(t,e){return this.on(n.PERFORMANCE_WARNING,t,e)}validateEventType(t){r.isValid(t)||(this.isDebugMode&&console.warn(`[EventBus] Unknown event type: ${t}`),this.isDebugMode&&r.addCustomType(t))}enhanceEventData(t,e){const s=e;return s.timestamp||(s.timestamp=Date.now()),s.eventId||(s.eventId=`${t}_${++this.eventIdCounter}`),s.source||(s.source="EventBus"),s}convertEventStats(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}}}class mt{static getInstance(t=!1){return this.instance||(this.instance=new ut(t)),this.instance}static reset(t=!1){return this.instance&&this.instance.clear(),this.instance=new ut(t),this.instance}}function dt(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().on(t,o.bind(this),e)},i}}function pt(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().onAsync(t,o.bind(this),e)},i}}class yt{constructor(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}withAll(...t){return this._allComponents.push(...t),this}withAny(...t){return this._anyComponents.push(...t),this}without(...t){return this._withoutComponents.push(...t),this}withTag(t){return this._withTags.push(t),this}withoutTag(t){return this._withoutTags.push(t),this}active(){return this._activeOnly=!0,this}enabled(){return this._enabledOnly=!0,this}where(t){return this._customPredicates.push(t),this}execute(){let t=[];if(this._allComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");t=Array.from(e)}else if(this._anyComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");t=Array.from(e)}else t=this.entityManager.getAllEntities();return t.filter((t=>this.matchesEntity(t)))}first(){return this.entityManager.getAllEntities().find((t=>this.matchesEntity(t)))||null}count(){return this.entityManager.getAllEntities().filter((t=>this.matchesEntity(t))).length}forEach(t){this.entityManager.getAllEntities().forEach((e=>{this.matchesEntity(e)&&t(e)}))}matchesEntity(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(const e of this._allComponents)if(!t.hasComponent(e))return!1;if(this._anyComponents.length>0){let e=!1;for(const s of this._anyComponents)if(t.hasComponent(s)){e=!0;break}if(!e)return!1}if(this._withoutComponents.length>0)for(const e of this._withoutComponents)if(t.hasComponent(e))return!1;if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(const e of this._customPredicates)if(!e(t))return!1;return!0}}class gt{constructor(){this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new w,this._componentIndexManager=new W(O.HASH),this._archetypeSystem=new $,this._dirtyTrackingSystem=new j,this._eventBus=new ut(!1),C.eventBus=this._eventBus}get entityCount(){return this._entities.size}get activeEntityCount(){let t=0;for(const e of this._entities.values())e.active&&!e.isDestroyed&&t++;return t}createEntity(t=`Entity_${Date.now()}`){const e=this._identifierPool.checkOut(),s=new C(t,e);return this._entities.set(e,s),this.updateNameIndex(s,!0),this.updateTagIndex(s,!0),this._componentIndexManager.addEntity(s),this._archetypeSystem.addEntity(s),this._dirtyTrackingSystem.markDirty(s,N.COMPONENT_ADDED),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:s.id,entityName:s.name,entityTag:s.tag?.toString()}),s}destroyEntity(t){let e=null;return e="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null,!!e&&(this._destroyedEntities.add(e.id),this.updateNameIndex(e,!1),this.updateTagIndex(e,!1),this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e),this._dirtyTrackingSystem.markDirty(e,N.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()}),e.destroy(),this._entities.delete(e.id),this._identifierPool.checkIn(e.id),!0)}getAllEntities(){return Array.from(this._entities.values())}getEntity(t){const e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null}getEntityByName(t){const e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null}getEntitiesByTag(t){return[...this._entitiesByTag.get(t)||[]]}getEntitiesWithComponent(t){const e=this._componentIndexManager.query(t);return Array.from(e)}query(){return new yt(this)}queryWithComponentIndex(t,e){return this._componentIndexManager.queryMultiple(t,e)}markEntityDirty(t,e){this._dirtyTrackingSystem.markDirty(t,N.COMPONENT_MODIFIED,e)}getOptimizationStats(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this._dirtyTrackingSystem.getStats()}}get eventBus(){return this._eventBus}updateNameIndex(t,e){if(t.name)if(e){let e=this._entitiesByName.get(t.name);e||(e=[],this._entitiesByName.set(t.name,e)),e.push(t)}else{const e=this._entitiesByName.get(t.name);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._entitiesByName.delete(t.name))}}}updateTagIndex(t,e){if(e){let e=this._entitiesByTag.get(t.tag);e||(e=[],this._entitiesByTag.set(t.tag,e)),e.push(t)}else{const e=this._entitiesByTag.get(t.tag);if(e){const s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._entitiesByTag.delete(t.tag))}}}}class _t{static getType(t){return t.constructor}}class ft{static toNumber(t){return null==t?0:Number(t)}}!function(t){t[t.Error=0]="Error",t[t.Assert=1]="Assert",t[t.Warning=2]="Warning",t[t.Log=3]="Log",t[t.Exception=4]="Exception"}(k||(k={})),function(t){t[t.Position=1]="Position",t[t.Scale=2]="Scale",t[t.Rotation=4]="Rotation"}(B||(B={}));export{$ as ArchetypeSystem,pt as AsyncEventHandler,q as BitMaskOptimizer,H as BitmapComponentIndex,it as Bits,nt as Component,W as ComponentIndexManager,P as ComponentPool,_ as ComponentStorage,B as ComponentTransform,ot as ComponentTypeManager,st as Core,s as CoreEvents,N as DirtyFlag,j as DirtyTrackingSystem,n as ECSEventType,X as ECSFluentAPI,o as EVENT_TYPES,e as Emitter,C as Entity,S as EntityList,gt as EntityManager,M as EntityProcessorList,yt as EntityQueryBuilder,at as EntitySystem,ut as EventBus,dt as EventHandler,i as EventPriority,r as EventTypeValidator,t as FuncPack,mt as GlobalEventBus,a as GlobalManager,L as HashComponentIndex,w as IdentifierPool,O as IndexType,F as IndexUpdateBatcher,lt as IntervalSystem,b as JavaScriptFallback,k as LogType,rt as Matcher,ft as NumberExtension,ct as PassiveSystem,m as PerformanceMonitor,u as PerformanceWarningType,d as Pool,y as PoolManager,ht as ProcessingSystem,Y as QuerySystem,V as Scene,p as TieredObjectPool,h as Time,c as Timer,l as TimerManager,G as TypeSafeEventSystem,_t as TypeUtils,A as WasmEcsCore,I as WasmLoader,et as createECSAPI,x as ecsCore,v as initializeEcs};
2
2
  //# sourceMappingURL=index.js.map