@esengine/ecs-framework 2.2.11 → 2.2.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/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.d.ts +454 -372
- package/index.es5.js +2 -2
- package/index.es5.js.map +1 -1
- package/index.mjs +1 -1
- package/index.mjs.map +1 -1
- package/index.umd.js +2 -2
- package/index.umd.js.map +1 -1
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e,t,n,s){var i,r=arguments.length,o=r<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(r<3?i(o):r>3?i(t,n,o):i(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}function t(e,t){return function(n,s){t(n,s,e)}}function n(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;class s{static update(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++}static sceneChanged(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0}static checkEvery(e,t){return this.totalTime-t>=e}}s.deltaTime=0,s.unscaledDeltaTime=0,s.totalTime=0,s.unscaledTotalTime=0,s.timeScale=1,s.frameCount=0;class i{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}get isDone(){return this._isDone}get elapsedTime(){return this._elapsedTime}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+=s.deltaTime,this._isDone}initialize(e,t,n,s){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}const r=new WeakMap,o=new WeakMap,a=new WeakMap;function c(){return function(e){const t=r.get(e);return r.set(e,{injectable:!0,dependencies:[],properties:t?.properties}),e}}function h(e=0){return function(t){const n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error(`@Updatable() decorator requires class ${t.name} to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.`);return a.set(t,{updatable:!0,priority:e}),t}}function l(e){return function(t,n,s){let i=o.get(t);i||(i=new Map,o.set(t,i)),i.set(s,e)}}function u(e){const t=r.get(e);return t?.injectable??!1}function d(e,t){const n=(s=e,o.get(s)||new Map);var s;const i=[],r=e.length;for(let s=0;s<r;s++){const r=n.get(s);if(r){if("string"==typeof r||"symbol"==typeof r)throw new Error(`String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for ${e.name} parameter ${s}`);i.push(t.resolve(r))}else i.push(void 0)}return new e(...i)}function p(e,t){const n=e.constructor,s=(i=n,r.get(i));var i;if(s?.properties&&0!==s.properties.size)for(const[n,i]of s.properties){const s=t.resolve(i);null!==s&&(e[n]=s)}}function m(e){const t=a.get(e);return t?.updatable??!1}function g(e){return a.get(e)}var f;exports.TimerManager=class{constructor(){this._timers=[]}update(){for(let e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))}schedule(e,t,n,s){let r=new i;return r.initialize(e,t,n,s),this._timers.push(r),r}dispose(){for(const e of this._timers)e.unload();this._timers=[]}},exports.TimerManager=e([h()],exports.TimerManager),exports.PerformanceWarningType=void 0,(f=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",f.HIGH_MEMORY_USAGE="high_memory_usage",f.HIGH_CPU_USAGE="high_cpu_usage",f.FREQUENT_GC="frequent_gc",f.LOW_FPS="low_fps",f.HIGH_ENTITY_COUNT="high_entity_count";class y{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(e){return this._isEnabled?performance.now():0}endMonitoring(e,t,n=0){if(!this._isEnabled||0===t)return;const s=performance.now(),i=s-t,r={name:e,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(e,r),this.updateStats(e,i)}updateStats(e,t){let n=this._systemStats.get(e);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(e,n)),n.totalTime+=t,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,t),n.maxTime=Math.max(n.maxTime,t),n.recentTimes.push(t),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(e){if(0===e.recentTimes.length)return;const t=e.recentTimes.reduce(((e,t)=>e+t),0)/e.recentTimes.length,n=e.recentTimes.reduce(((e,n)=>e+Math.pow(n-t,2)),0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);const s=[...e.recentTimes].sort(((e,t)=>e-t)),i=s.length;e.percentile95=s[Math.floor(.95*i)]||0,e.percentile99=s[Math.floor(.99*i)]||0}getSystemData(e){return this._systemData.get(e)}getSystemStats(e){return this._systemStats.get(e)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const e=[];e.push("=== ECS Performance Report ==="),e.push("");const t=Array.from(this._systemStats.entries()).sort(((e,t)=>t[1].averageTime-e[1].averageTime));for(const[n,s]of t){const t=this._systemData.get(n);e.push(`System: ${n}`),e.push(` Current: ${t?.executionTime.toFixed(2)}ms (${t?.entityCount} entities)`),e.push(` Average: ${s.averageTime.toFixed(2)}ms`),e.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),e.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),t?.averageTimePerEntity&&t.averageTimePerEntity>0&&e.push(` Per Entity: ${t.averageTimePerEntity.toFixed(4)}ms`),e.push("")}const n=Array.from(this._systemData.values()).reduce(((e,t)=>e+t.executionTime),0);return e.push(`Total Frame Time: ${n.toFixed(2)}ms`),e.push(`Systems Count: ${this._systemData.size}`),e.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(e){this._systemData.delete(e),this._systemStats.delete(e)}getPerformanceWarnings(e=16.67){const t=[];for(const[n,s]of this._systemData.entries())s.executionTime>e&&t.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${e}ms)`);return t}setMaxRecentSamples(e){this._maxRecentSamples=e;for(const t of this._systemStats.values())for(;t.recentTimes.length>e;)t.recentTimes.shift()}dispose(){this._systemData.clear(),this._systemStats.clear(),this._warnings=[],this._fpsHistory=[],this._memoryHistory=[],this._isEnabled=!1}}class _{constructor(e,t=100,n=1024){this._objects=[],this._createFn=e,this._maxSize=t,this._objectSize=n,this._stats={size:0,maxSize:t,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(e,t=100,n=1024){let s=this._pools.get(e);return s||(s=new _((()=>new e),t,n),this._pools.set(e,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const e of this._objects)e.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(e){const t=e??Math.floor(this._objects.length/2);for(;this._objects.length>t;){const e=this._objects.pop();e&&(e.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(e){const t=Math.min(e,this._maxSize-this._objects.length);for(let e=0;e<t;e++){const e=this._createFn();e.reset(),this._objects.push(e),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)}getAvailableCount(){return this._objects.length}isEmpty(){return 0===this._objects.length}isFull(){return this._objects.length>=this._maxSize}static getAllPoolTypes(){return Array.from(this._pools.keys())}static getAllPoolStats(){const e={};for(const[t,n]of this._pools){e[t.name||t.toString()]=n.getStats()}return e}static compactAllPools(){for(const e of this._pools.values())e.compact()}static clearAllPools(){for(const e of this._pools.values())e.clear();this._pools.clear()}static getGlobalStatsString(){const e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(const[n,s]of Object.entries(e))t.push(`${n}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Total Created: ${s.totalCreated}`),t.push(` Total Obtained: ${s.totalObtained}`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");return t.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}_._pools=new Map;class S{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}registerPool(e,t){this.pools.set(e,t)}getPool(e){return this.pools.get(e)||null}update(){const e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)}createPool(e,t,n=100,s=1024){let i=this.pools.get(e);return i||(i=new _(t,n,s),this.pools.set(e,i)),i}removePool(e){const t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const e of this.pools.values())e.compact()}clearAllPools(){for(const e of this.pools.values())e.clear()}getAllStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,n.getStats());return e}getGlobalStats(){let e=0,t=0,n=0,s=0,i=0,r=0;for(const o of this.pools.values()){const a=o.getStats();e+=a.size,t+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,r+=a.estimatedMemoryUsage}return{size:e,maxSize:t,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:r}}getStatsString(){const e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");const t=this.getGlobalStats();e.push(`Total Pools: ${this.pools.size}`),e.push(`Global Hit Rate: ${(100*t.hitRate).toFixed(1)}%`),e.push(`Global Memory Usage: ${(t.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");for(const[t,n]of this.pools){const s=n.getStats();e.push(`${t}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("")}return e.join("\n")}setAutoCompactInterval(e){this.autoCompactInterval=e}prewarmAllPools(){for(const e of this.pools.values()){const t=e.getStats(),n=Math.floor(.2*t.maxSize);e.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}dispose(){this.reset()}}const v=Symbol("ComponentTypeName"),C=Symbol("SystemTypeName");function E(e){return e.__systemMetadata__}function b(e){const t=e[v];return t||(e.name||"UnknownComponent")}function w(e){const t=e[C];return t||(e.name||"UnknownSystem")}function T(e){return b(e.constructor)}function A(e){return w(e.constructor)}var M;exports.LogLevel=void 0,(M=exports.LogLevel||(exports.LogLevel={}))[M.Debug=0]="Debug",M[M.Info=1]="Info",M[M.Warn=2]="Warn",M[M.Error=3]="Error",M[M.Fatal=4]="Fatal",M[M.None=5]="None";const I={BLACK:"[30m",RED:"[31m",GREEN:"[32m",YELLOW:"[33m",BLUE:"[34m",MAGENTA:"[35m",CYAN:"[36m",WHITE:"[37m",BRIGHT_BLACK:"[90m",BRIGHT_RED:"[91m",BRIGHT_GREEN:"[92m",BRIGHT_YELLOW:"[93m",BRIGHT_BLUE:"[94m",BRIGHT_MAGENTA:"[95m",BRIGHT_CYAN:"[96m",BRIGHT_WHITE:"[97m",RESET:"[0m",BOLD:"[1m",UNDERLINE:"[4m"};class x{constructor(e={}){this._config={level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...e}}debug(e,...t){this.log(exports.LogLevel.Debug,e,...t)}info(e,...t){this.log(exports.LogLevel.Info,e,...t)}warn(e,...t){this.log(exports.LogLevel.Warn,e,...t)}error(e,...t){this.log(exports.LogLevel.Error,e,...t)}fatal(e,...t){this.log(exports.LogLevel.Fatal,e,...t)}setLevel(e){this._config.level=e}setColors(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors={...this._config.colors,...e}}setPrefix(e){this._config.prefix=e}log(e,t,...n){if(e<this._config.level)return;let s=t;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${exports.LogLevel[e].toUpperCase()}] ${s}`,this._config.output?this._config.output(e,s):this.outputToConsole(e,s,...n)}outputToConsole(e,t,...n){const s=this._config.enableColors?this.getColors():null;switch(e){case exports.LogLevel.Debug:s?console.debug(`${s.debug}${t}${s.reset}`,...n):console.debug(t,...n);break;case exports.LogLevel.Info:s?console.info(`${s.info}${t}${s.reset}`,...n):console.info(t,...n);break;case exports.LogLevel.Warn:s?console.warn(`${s.warn}${t}${s.reset}`,...n):console.warn(t,...n);break;case exports.LogLevel.Error:s?console.error(`${s.error}${t}${s.reset}`,...n):console.error(t,...n);break;case exports.LogLevel.Fatal:s?console.error(`${s.fatal}${t}${s.reset}`,...n):console.error(t,...n)}}getColors(){return{...{debug:I.BRIGHT_BLACK,info:I.GREEN,warn:I.YELLOW,error:I.RED,fatal:I.BRIGHT_RED,reset:I.RESET},...this._config.colors}}}class D{constructor(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info}get defaultLogger(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}createDefaultLogger(){return this._loggerFactory?this._loggerFactory():new x({level:this._defaultLevel})}static getInstance(){return D._instance||(D._instance=new D),D._instance}getLogger(e){if(!e)return this.defaultLogger;if(!this._loggers.has(e)){const t=this._loggerFactory?this._loggerFactory(e):new x({prefix:e,level:this._defaultLevel});this._loggers.set(e,t)}return this._loggers.get(e)}setLogger(e,t){this._loggers.set(e,t)}setGlobalLevel(e){this._defaultLevel=e,this._defaultLogger instanceof x&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof x&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof x&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof x&&t.setColors(e)}resetColors(){this._defaultLogger instanceof x&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof x&&e.setColors({})}setLoggerFactory(e){(this._defaultLogger||this._loggers.size>0)&&console.warn("[LoggerManager] setLoggerFactory 应该在导入 ECS 模块之前调用。已创建的 logger 引用不会被更新。"),this._loggerFactory=e,this._defaultLogger=void 0,this._loggers.clear()}}const k=D.getInstance().getLogger();function R(e){return D.getInstance().getLogger(e)}R("ReferenceTracker");const O="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||class{constructor(e){this._target=e}deref(){return this._target}},z=new Map;function P(e){const t=z.get(e);return t?.deref()||null}class N{constructor(){this._references=new Map,this._scene=null}registerReference(e,t,n){const s=e.id;let i=this._references.get(s);i||(i=new Set,this._references.set(s,i));this._findRecord(i,t,n)||i.add({component:new O(t),propertyKey:n})}unregisterReference(e,t,n){const s=e.id,i=this._references.get(s);if(!i)return;const r=this._findRecord(i,t,n);r&&(i.delete(r),0===i.size&&this._references.delete(s))}clearReferencesTo(e){const t=this._references.get(e);if(!t)return;const n=[];for(const e of t){e.component.deref()&&n.push(e)}for(const e of n){const t=e.component.deref();t&&(t[e.propertyKey]=null)}this._references.delete(e)}clearComponentReferences(e){for(const[t,n]of this._references.entries()){const s=[];for(const t of n){const n=t.component.deref();n&&n!==e||s.push(t)}for(const e of s)n.delete(e);0===n.size&&this._references.delete(t)}}getReferencesTo(e){const t=this._references.get(e);if(!t)return[];const n=[];for(const e of t){e.component.deref()&&n.push(e)}return n}cleanup(){const e=[];for(const[t,n]of this._references.entries()){const s=[];for(const e of n)e.component.deref()||s.push(e);for(const e of s)n.delete(e);0===n.size&&e.push(t)}for(const t of e)this._references.delete(t)}setScene(e){this._scene=new O(e)}registerEntityScene(e,t){z.set(e,new O(t))}unregisterEntityScene(e){z.delete(e)}getDebugInfo(){const e={};for(const[t,n]of this._references.entries()){const s=[];for(const e of n){const t=e.component.deref();t&&s.push({componentId:t.id,propertyKey:e.propertyKey})}s.length>0&&(e[`entity_${t}`]=s)}return e}_findRecord(e,t,n){for(const s of e){if(s.component.deref()===t&&s.propertyKey===n)return s}}}const B=R("EntityRefDecorator"),L=Symbol("EntityRefMetadata"),$=Symbol("EntityRefValues");function W(e){let t=e[$];return t||(t=new Map,e[$]=t),t}function F(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[L]||null}class H{collectEntityData(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeData(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(e){if(!e)return[];const t=e.entities;return t?.buffer?t.buffer.map((e=>({id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>T(e))),parentId:e.parent?.id||null,childIds:e.children?.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}))):[]}getEntityDetails(e,t){try{if(!t)return null;const n=t.entities;if(!n?.buffer)return null;const s=n.buffer.find((t=>t.id===e));if(!s)return null;const i=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t),r=this.extractComponentDetails(s.components),o=this.getSceneInfo(t);return{...i,scene:o.name,sceneName:o.name,sceneType:o.type,parentName:s.parent?.name||null,components:r||[],componentCount:s.components?.length||0,componentTypes:s.components?.map((e=>T(e)))||[]}}catch(e){return{error:`获取实体详情失败: ${e instanceof Error?e.message:String(e)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(e){let t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{const s=Object.getPrototypeOf(e)?.constructor?.name;s&&"Object"!==s&&(t=s,n=s)}}catch(e){t="场景名获取失败"}return{name:t,type:n}}collectEntityDataWithMemory(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeDataWithMemory(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:this.buildEntityHierarchyTree(t),entityDetailsMap:this.buildEntityDetailsMap(t,e)}}collectArchetypeData(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionFast(t),topEntities:this.getTopEntitiesByComponentsFast(t)}}getArchetypeDistributionFast(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>T(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);i?i.count++:t.set(s,{count:1,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:0}))).sort(((e,t)=>t.count-e.count)).slice(0,20)}getTopEntitiesByComponentsFast(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}collectArchetypeDataWithMemory(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionWithMemory(t),topEntities:this.getTopEntitiesByComponentsWithMemory(t)}}extractArchetypeStatistics(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;n.push({signature:t,count:i,memory:0}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}extractArchetypeStatisticsWithMemory(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;let r=0;if(e.entities&&e.entities.length>0){const t=Math.min(5,e.entities.length);let n=0;for(let s=0;s<t;s++)n+=this.estimateEntityMemoryUsage(e.entities[s]);r=n/t*i}n.push({signature:t,count:i,memory:r}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}getArchetypeDistribution(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.componentMask?.toString()||"0",s=t.get(n);t.set(n,(s||0)+1)})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t,memory:0}))).sort(((e,t)=>t.count-e.count))}getArchetypeDistributionWithMemory(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>T(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);let r=this.estimateEntityMemoryUsage(e);(isNaN(r)||r<0)&&(r=0),i?(i.count++,i.memory+=r):t.set(s,{count:1,memory:r,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:isNaN(t.memory)?0:t.memory}))).sort(((e,t)=>t.count-e.count))}getTopEntitiesByComponents(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}getTopEntitiesByComponentsWithMemory(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}getEmptyEntityDebugData(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}calculateFallbackEntityStats(e){const t=e.buffer||[],n=t.filter((e=>e.enabled&&!e._isDestroyed));return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce(((e,t)=>e+(t.components?.length||0)),0)/n.length:0}}estimateEntityMemoryUsage(e){try{let t=0;const n=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(n)&&n>0&&(t+=n),e.components&&Array.isArray(e.components)&&e.components.forEach((e=>{const n=this.calculateObjectSize(e,["entity"]);!isNaN(n)&&n>0&&(t+=n)})),isNaN(t)||t<0?0:t}catch(e){return 0}}calculateObjectSize(e,t=[]){if(!e||"object"!=typeof e)return 0;const n=new WeakSet,s=(e,i=0)=>{if(!e||"object"!=typeof e||i>=2)return 0;if(n.has(e))return 0;n.add(e);let r=32;try{const n=Object.keys(e),o=Math.min(n.length,20);for(let a=0;a<o;a++){const o=n[a];if(t.includes(o)||"constructor"===o||"__proto__"===o||o.startsWith("_cc_")||o.startsWith("__"))continue;const c=e[o];r+=2*o.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:Array.isArray(c)?r+=40+Math.min(8*c.length,160):"object"==typeof c&&null!==c&&(r+=s(c,i+1))}}catch(e){return 64}return r};try{const t=s(e);return Math.max(t,32)}catch(e){return 64}}buildEntityHierarchyTree(e){if(!e?.buffer)return[];const t=[];return e.buffer.forEach((e=>{if(!e.parent){const n=this.buildEntityHierarchyNode(e);t.push(n)}})),t.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:e.id-t.id)),t}buildEntityHierarchyNode(e){let t={id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>T(e))),parentId:e.parent?.id||null,children:[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0};if(e.children&&e.children.length>0&&(t.children=e.children.map((e=>this.buildEntityHierarchyNode(e)))),"function"==typeof e.getDebugInfo){const n=e.getDebugInfo();t={...t,...n}}return e.components&&e.components.length>0&&(t.componentDetails=this.extractComponentDetails(e.components)),t}buildEntityDetailsMap(e,t){if(!e?.buffer)return{};const n={},s=e.buffer;for(let e=0;e<s.length;e+=100){s.slice(e,e+100).forEach((e=>{const s=e.getDebugInfo?e.getDebugInfo():this.buildFallbackEntityInfo(e,t),i=e.getComponentCacheStats?e.getComponentCacheStats():null,r=this.extractComponentDetails(e.components);n[e.id]={...s,parentName:e.parent?.name||null,components:r,componentTypes:s.componentTypes||r.map((e=>e.typeName)),cachePerformance:i?{hitRate:i.cacheStats.hitRate,size:i.cacheStats.size,maxSize:i.cacheStats.maxSize}:null}}))}return n}buildFallbackEntityInfo(e,t){const n=this.getSceneInfo(t);return{name:e.name||`Entity_${e.id}`,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:!1!==e.activeInHierarchy,destroyed:e.isDestroyed||!1,scene:n.name,sceneName:n.name,sceneType:n.type,componentCount:e.components.length,componentTypes:e.components.map((e=>T(e))),componentMask:e.componentMask?.toString()||"0",parentId:e.parent?.id||null,childCount:e.children?.length||0,childIds:e.children.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}}extractComponentDetails(e){return e.map((e=>{const t=T(e),n={};try{Object.keys(e).forEach((t=>{if(!t.startsWith("_")&&"entity"!==t&&"constructor"!==t){const s=e[t];null!=s&&(n[t]=this.formatPropertyValue(s))}})),0===Object.keys(n).length&&(n._info="该组件没有公开属性",n._componentId=T(e))}catch(t){n._error="属性提取失败",n._componentId=T(e)}return{typeName:t,properties:n}}))}getComponentProperties(e,t,n){try{if(!n)return{};const s=n.entities;if(!s?.buffer)return{};const i=s.buffer.find((t=>t.id===e));if(!i||t>=i.components.length)return{};const r=i.components[t],o={};return Object.keys(r).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e){const t=r[e];null!=t&&(o[e]=this.formatPropertyValue(t))}})),o}catch(e){return{_error:"属性提取失败"}}}formatPropertyValue(e,t=0){return null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?`[长字符串: ${e.length}字符] ${e.substring(0,100)}...`:e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)}formatObjectFirstLevel(e){try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){const t=e.slice(0,3).map((e=>this.formatPropertyValue(e,1)));return{_isLazyArray:!0,_arrayLength:e.length,_sample:t,_summary:`数组[${e.length}个元素]`}}return e.map((e=>this.formatPropertyValue(e,1)))}const t=Object.keys(e);if(0===t.length)return{};const n={};let s=0;const i=15;for(const r of t){if(s>=i){n._hasMoreProperties=!0,n._totalProperties=t.length,n._hiddenCount=t.length-s;break}if(!r.startsWith("_")&&!r.startsWith("$")&&"function"!=typeof e[r])try{const t=e[r];null!=t&&(n[r]=this.formatPropertyValue(t,1),s++)}catch(e){n[r]=`[访问失败: ${e instanceof Error?e.message:String(e)}]`,s++}}return n}catch(e){return`[对象解析失败: ${e instanceof Error?e.message:String(e)}]`}}createLazyLoadPlaceholder(e){try{const t=e.constructor?.name||"Object";return{_isLazyObject:!0,_typeName:t,_summary:this.getObjectSummary(e,t),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:`无法分析的对象: ${e instanceof Error?e.message:String(e)}`,_objectId:Math.random().toString(36).substr(2,9)}}}getObjectSummary(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){const n=void 0!==e.z?e.z:"";return`${t}(${e.x}, ${e.y}${n?", "+n:""})`}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){const n=void 0!==e.a?e.a:1;return`${t}(${e.r}, ${e.g}, ${e.b}, ${n})`}if(t.toLowerCase().includes("node")){return`${t}: ${e.name||e._name||"未命名"}`}if(t.toLowerCase().includes("component")){const n=e.node?.name||e.node?._name||"";return`${t}${n?` on ${n}`:""}`}const n=Object.keys(e);return 0===n.length?`${t} (空对象)`:`${t} (${n.length}个属性)`}catch(e){return`${t} (无法分析)`}}generateObjectId(e){try{return void 0!==e.id?`obj_${e.id}`:void 0!==e._id?`obj_${e._id}`:void 0!==e.uuid?`obj_${e.uuid}`:void 0!==e._uuid?`obj_${e._uuid}`:`obj_${Math.random().toString(36).substr(2,9)}`}catch{return`obj_${Math.random().toString(36).substr(2,9)}`}}expandLazyObject(e,t,n,s){try{if(!s)return null;const i=s.entities;if(!i?.buffer)return null;const r=i.buffer.find((t=>t.id===e));if(!r)return null;if(t>=r.components.length)return null;const o=r.components[t],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:`展开失败: ${e instanceof Error?e.message:String(e)}`}}}getObjectByPath(e,t){if(!t)return e;const n=t.split(".");let s=e;for(const e of n){if(null==s)return null;if(e.includes("[")&&e.includes("]")){const t=e.substring(0,e.indexOf("[")),n=parseInt(e.substring(e.indexOf("[")+1,e.indexOf("]")));if(t&&(s=s[t]),!(Array.isArray(s)&&n>=0&&n<s.length))return null;s=s[n]}else s=s[e]}return s}}class U{collectSystemData(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};const n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};const s=n.processors||[];let i=new Map,r=new Map;if(e)try{i=e.getAllSystemStats(),r=e.getAllSystemData()}catch(e){}return{totalSystems:s.length,systemsInfo:s.map((e=>{const t=e.systemName||A(e),n=i.get(t),s=r.get(t);return{name:t,type:A(e),entityCount:e.entities?.length||0,executionTime:n?.averageTime||s?.executionTime||0,minExecutionTime:n?.minTime===Number.MAX_VALUE?0:n?.minTime||0,maxExecutionTime:n?.maxTime||0,executionTimeHistory:n?.recentTimes||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:s?.lastUpdateTime||0}}))}}}class q{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(e){const t=s.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,a=n>0?o/n*100:0;let c=0;performance.memory&&(c=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const h=this.frameTimeHistory.filter((e=>e>=0));return{frameTime:o,engineFrameTime:n,ecsPercentage:a,memoryUsage:c,fps:i,averageFrameTime:h.length>0?h.reduce(((e,t)=>e+t),0)/h.length:o,minFrameTime:h.length>0?Math.min(...h):o,maxFrameTime:h.length>0?Math.max(...h):o,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{let t=0;const n=[],s=e.getAllSystemStats();if(0===s.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[e,i]of s.entries()){const s=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;t+=s,n.push({systemName:e,executionTime:s,percentage:0})}return n.forEach((e=>{e.percentage=t>0?e.executionTime/t*100:0})),n.sort(((e,t)=>t.executionTime-e.executionTime)),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(e){if(!e)return[];try{const t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map((([e,t])=>{const s=n.get(e);return{systemName:e,averageTime:t.averageTime||0,maxTime:t.maxTime||0,minTime:t.minTime===Number.MAX_VALUE?0:t.minTime||0,samples:t.executionCount||0,percentage:0,entityCount:s?.entityCount||0,lastExecutionTime:s?.executionTime||0}}))}catch(e){return[]}}getMemoryDetails(){const e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){const t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0){this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++}this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e}updateGCCount(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}}}class G{constructor(e,t,n=1e3,s=10,i=1.5){this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,this.resetFn=t,this.maxSize=n,this.minSize=Math.max(1,s),this.growthFactor=Math.max(1.1,i)}acquire(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())}release(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))}prewarm(e){const t=Math.min(e,this.maxSize);for(let e=this.pool.length;e<t;e++){const e=this.createFn();this.resetFn&&this.resetFn(e),this.pool.push(e),this.stats.totalCreated++}}shrink(){for(;this.pool.length>this.minSize;)this.pool.pop()}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}getStats(){const e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}}}class j{constructor(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}static getInstance(){return j.instance||(j.instance=new j),j.instance}registerPool(e,t,n,s,i){this.pools.set(e,new G(t,n,s,i)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})}acquireComponent(e){const t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null}releaseComponent(e,t){const n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)}trackUsage(e,t){let n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()}update(){const e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(const[t,n]of this.usageTracker.entries()){if(e-n.lastAccessTime>12e4){const e=this.pools.get(t);e&&e.shrink()}}this.lastCleanupTime=e}}getHotComponents(e=100){return Array.from(this.usageTracker.entries()).filter((([t,n])=>n.createCount>e)).map((([e])=>e))}prewarmAll(e=100){for(const t of this.pools.values())t.prewarm(e)}clearAll(){for(const e of this.pools.values())e.clear()}reset(){this.pools.clear(),this.usageTracker.clear()}getGlobalStats(){const e=[];for(const[t,n]of this.pools.entries())e.push({componentName:t,poolStats:n.getStats(),usage:this.usageTracker.get(t)});return e}getPoolStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return e}getPoolUtilization(){const e=new Map;for(const[t,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),r=i-s,o=i>0?r/i*100:0;e.set(t,{used:r,total:i,utilization:o})}return e}getComponentUtilization(e){const t=this.pools.get(e);if(!t)return 0;const n=t.getAvailableCount(),s=t.getMaxSize();return s>0?(s-n)/s*100:0}}class Q{collectComponentData(e){if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};const t=e.entities;if(!t?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const n=new Map;let s=0;t.buffer.forEach((e=>{e.components&&e.components.forEach((e=>{const t=T(e),i=n.get(t)||{count:0,entities:0};i.count++,s++,n.set(t,i)}))}));let i=new Map,r=new Map;try{const e=j.getInstance(),t=e.getPoolStats(),n=e.getPoolUtilization();for(const[e,n]of t.entries())r.set(e,n.maxSize);for(const[e,t]of n.entries())i.set(e,t.utilization)}catch(e){}return{componentTypes:n.size,componentInstances:s,componentStats:Array.from(n.entries()).map((([n,s])=>{const o=r.get(n)||0,a=i.get(n)||0,c=this.getEstimatedComponentSize(n,e);return{typeName:n,instanceCount:s.count,memoryPerInstance:c,totalMemory:s.count*c,poolSize:o,poolUtilization:a,averagePerEntity:s.count/t.buffer.length}}))}}getEstimatedComponentSize(e,t){if(Q.componentSizeCache.has(e))return Q.componentSizeCache.get(e);if(!t)return 64;const n=t.entities;if(!n?.buffer)return 64;let s=64;try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>T(t)===e));if(n){s=this.calculateQuickObjectSize(n);break}}}catch(e){s=64}return Q.componentSizeCache.set(e,s),s}calculateQuickObjectSize(e){if(!e||"object"!=typeof e)return 8;let t=32;const n=new WeakSet,s=(e,t=0)=>{if(!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);let i=0;try{const n=Object.keys(e);for(let r=0;r<Math.min(n.length,20);r++){const o=n[r];if("entity"===o||"_entity"===o||"constructor"===o)continue;const a=e[o];i+=2*o.length,"string"==typeof a?i+=Math.min(2*a.length,200):"number"==typeof a?i+=8:"boolean"==typeof a?i+=4:"object"==typeof a&&null!==a&&(i+=s(a,t+1))}}catch(e){return 32}return i};return t+=s(e),Math.max(t,32)}calculateDetailedComponentMemory(e,t){if(!t)return this.getEstimatedComponentSize(e,t);const n=t.entities;if(!n?.buffer)return this.getEstimatedComponentSize(e,t);try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>T(t)===e));if(n)return this.estimateObjectSize(n)}}catch(e){}return this.getEstimatedComponentSize(e,t)}estimateObjectSize(e,t=new WeakSet,n=0){if(null==e||n>10)return 0;if(t.has(e))return 0;let s=0;switch(typeof e){case"boolean":s=4;break;case"number":default:s=8;break;case"string":s=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){s=40+8*e.length;const i=Math.min(e.length,50);for(let r=0;r<i;r++)s+=this.estimateObjectSize(e[r],t,n+1)}else{s=32;try{const i=Object.getOwnPropertyNames(e),r=Math.min(i.length,30);for(let o=0;o<r;o++){const r=i[o];if("constructor"!==r&&"__proto__"!==r&&"entity"!==r&&"_entity"!==r&&!r.startsWith("_cc_")&&!r.startsWith("__"))try{s+=16+2*r.length;const i=e[r];null!=i&&(s+=this.estimateObjectSize(i,t,n+1))}catch(e){continue}}}catch(e){s=128}}}return 8*Math.ceil(s/8)}static clearCache(){Q.componentSizeCache.clear()}}Q.componentSizeCache=new Map;class V{constructor(){this.sceneStartTime=Date.now()}collectSceneData(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};const t=(Date.now()-this.sceneStartTime)/1e3,n=e.entities,s=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:t,sceneEntityCount:n?.buffer?.length||0,sceneSystemCount:s?.processors?.length||0,sceneMemory:0,sceneUptime:t}}setSceneStartTime(e){this.sceneStartTime=e}}class Y{constructor(e,t=!0){this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=e,this.autoReconnect=t}setMessageHandler(e){this.messageHandler=e}connect(){return new Promise(((e,t)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=t=>{this.handleOpen(t),e()},this.ws.onclose=e=>{this.handleClose(e)},this.ws.onerror=e=>{this.handleError(e),t(e)},this.ws.onmessage=e=>{this.handleMessage(e)}}catch(e){this.handleConnectionFailure(e),t(e)}}))}disconnect(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1}send(e){if(this.isConnected&&this.ws)try{const t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}}getConnectionStatus(){return this.isConnected}setMaxReconnectAttempts(e){this.maxReconnectAttempts=e}setReconnectInterval(e){this.reconnectInterval=e}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((()=>{this.connect().catch((e=>{this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}))}),e)}handleMessage(e){try{const t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}}handleOpen(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)}handleClose(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}handleError(e){this.onError&&this.onError(e)}handleConnectionFailure(e){this.onError&&this.onError(e)}}var J,Z;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(J||(J={}));class X{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0],segments:void 0};return X.setBit(t,e),t}static fromNumber(e){return{base:[e>>>0,0],segments:void 0}}static hasAny(e,t){const n=t.base,s=e.base,i=t.segments,r=e.segments,o=0!==(s[J.LOW]&n[J.LOW])||0!==(s[J.HIGH]&n[J.HIGH]);return!o&&i&&r?r.some(((e,t)=>0!==(e[J.LOW]&i[t][J.LOW])||0!==(e[J.HIGH]&i[t][J.HIGH]))):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[J.LOW]&s[J.LOW])===s[J.LOW]&&(n[J.HIGH]&s[J.HIGH])===s[J.HIGH];if(!o||!r)return o;const a=i?.length??0;if(i)for(let e=0;e<Math.min(a,r.length);e++)if((i[e][J.LOW]&r[e][J.LOW])!==r[e][J.LOW]||(i[e][J.HIGH]&r[e][J.HIGH])!==r[e][J.HIGH])return!1;for(let e=a;e<r.length;e++)if(0!==r[e][J.LOW]||0!==r[e][J.HIGH])return!1;return!0}static hasNone(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=0===(n[J.LOW]&s[J.LOW])&&0===(n[J.HIGH]&s[J.HIGH]);return i&&o&&r?i.every(((e,t)=>0===(e[J.LOW]&r[t][J.LOW])&&0===(e[J.HIGH]&r[t][J.HIGH]))):o}static isZero(e){const t=0===e.base[J.LOW]&&0===e.base[J.HIGH];return e.segments&&t?e.segments.every((e=>0===e[J.LOW]&&0===e[J.HIGH])):t}static equals(e,t){let n=e.base[J.LOW]===t.base[J.LOW]&&e.base[J.HIGH]===t.base[J.HIGH];if(!n||!e.segments&&!t.segments)return n;const s=e.segments??[],i=t.segments??[];for(let e=0;e<Math.max(s.length,i.length);e++){const t=s[e],n=i[e];if(t&&!n){if(0!==t[J.LOW]||0!==t[J.HIGH])return!1}else if(!t&&n){if(0!==n[J.LOW]||0!==n[J.HIGH])return!1}else if(t[J.LOW]!==n[J.LOW]||t[J.HIGH]!==n[J.HIGH])return!1}return!0}static setBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t),s=63&t;s<32?n[J.LOW]|=1<<s:n[J.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[J.LOW]&1<<s):!!(n[J.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[J.LOW]&=~(1<<s):n[J.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[J.LOW]|=t.base[J.LOW],e.base[J.HIGH]|=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++)t[e][J.LOW]|=n[e][J.LOW],t[e][J.HIGH]|=n[e][J.HIGH]}}static andInPlace(e,t){e.base[J.LOW]&=t.base[J.LOW],e.base[J.HIGH]&=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++)t[e][J.LOW]&=n[e][J.LOW],t[e][J.HIGH]&=n[e][J.HIGH]}}static xorInPlace(e,t){e.base[J.LOW]^=t.base[J.LOW],e.base[J.HIGH]^=t.base[J.HIGH];const n=t.segments;if(!n||0==n.length)return;e.segments||(e.segments=[]);const s=e.segments;for(;s.length<n.length;)s.push([0,0]);for(let e=0;e<n.length;e++)s[e][J.LOW]^=n[e][J.LOW],s[e][J.HIGH]^=n[e][J.HIGH]}static clear(e){e.base[J.LOW]=0,e.base[J.HIGH]=0;for(let t=0;t<(e.segments?.length??0);t++){const n=e.segments[t];n[J.LOW]=0,n[J.HIGH]=0}}static copy(e,t){if(X.clear(t),t.base[J.LOW]=e.base[J.LOW],t.base[J.HIGH]=e.base[J.HIGH],!e.segments||0==e.segments.length)return;if(!t.segments)return void(t.segments=e.segments.map((e=>[...e])));const n=e.segments.length-t.segments.length;for(let e=0;e<n;e++)t.segments.push([0,0]);for(let n=0;n<length;n++){const s=t.segments[n],i=e.segments[n];s[J.LOW]=i[J.LOW],s[J.HIGH]=i[J.HIGH]}}static clone(e){return{base:e.base.slice(),segments:e.segments?e.segments.map((e=>[...e])):void 0}}static toString(e,t=2,n=!1){2!=t&&16!=t&&(t=2);const s=e.segments?.length??0;let i="";if(n){let e=0;e=2===t?66:19;for(let t=0;t<=s;t++){i+=(0===t?"0 (Base):":`${t} (${64*t}):`).toString().padEnd(e)}i+="\n"}for(let r=-1;r<s;r++){let s="";const o=-1==r?e.base:e.segments[r];let a=o[J.HIGH],c=o[J.LOW];if(2==t){s=a.toString(2).padStart(32,"0")+"_"+c.toString(2).padStart(32,"0")}else{let e=a?a.toString(16).toUpperCase():"";n&&(e=e.padStart(8,"0"));let t=c.toString(16).toUpperCase();e&&(t=t.padStart(8,"0")),s="0x"+e+t}i+=-1===r?s:" "+s}return i}static popCount(e){let t=0;for(let n=-1;n<(e.segments?.length??0);n++){const s=-1==n?e.base:e.segments[n];let i=s[J.LOW],r=s[J.HIGH];for(;i;)i&=i-1,t++;for(;r;)r&=r-1,t++}return t}static getSegmentByBitIndex(e,t,n=!0){if(t<=63)return e.base;{let s=e.segments;if(!s){if(!n)return null;s=e.segments=[]}const i=(t>>6)-1;if(s.length<=i){if(!n)return null;const e=i-s.length+1;for(let t=0;t<e;t++)s.push([0,0])}return s[i]}}}X.ZERO={base:[0,0],segments:void 0};class K{static inferOptimalType(e,t={}){const n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";const{minValue:s,maxValue:i,precision:r,signed:o}=t;if(!0===r)return Math.abs(e)>34028235e31||void 0!==s&&Math.abs(s)>34028235e31||void 0!==i&&Math.abs(i)>34028235e31?"float64":"float32";if(!1===r||Number.isInteger(e)){const t=void 0!==s?s:e,n=void 0!==i?i:e;return!1!==o&&(t<0||e<0)?t>=-128&&n<=127?"int8":t>=-32768&&n<=32767?"int16":t>=-2147483648&&n<=2147483647?"int32":"float64":n<=255?"uint8":n<=65535?"uint16":n<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"}static getTypedArrayConstructor(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}}}class ee{constructor(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}initializeFields(e){const t=new e,n=e.__highPrecisionFields||new Set,s=e.__float64Fields||new Set,i=e.__float32Fields||new Set,r=e.__int32Fields||new Set,o=e.__uint32Fields||new Set,a=e.__int16Fields||new Set,c=e.__uint16Fields||new Set,h=e.__int8Fields||new Set,l=e.__uint8Fields||new Set,u=e.__uint8ClampedFields||new Set,d=e.__autoTypedFields||new Map,p=e.__serializeMapFields||new Set,m=e.__serializeSetFields||new Set,g=e.__serializeArrayFields||new Set;for(const e in t)if(t.hasOwnProperty(e)&&"id"!==e){const f=t[e],y=typeof f;if("number"===y)if(n.has(e));else if(d.has(e)){const t=d.get(e),n=K.inferOptimalType(f,t),s=K.getTypedArrayConstructor(n);this.fields.set(e,new s(this._capacity)),ee._logger.info(`字段 ${e} 自动推断为 ${n} 类型,值: ${f}, 选项:`,t)}else s.has(e)?this.fields.set(e,new Float64Array(this._capacity)):r.has(e)?this.fields.set(e,new Int32Array(this._capacity)):o.has(e)?this.fields.set(e,new Uint32Array(this._capacity)):a.has(e)?this.fields.set(e,new Int16Array(this._capacity)):c.has(e)?this.fields.set(e,new Uint16Array(this._capacity)):h.has(e)?this.fields.set(e,new Int8Array(this._capacity)):l.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):u.has(e)?this.fields.set(e,new Uint8ClampedArray(this._capacity)):(i.has(e),this.fields.set(e,new Float32Array(this._capacity)));else"boolean"===y?l.has(e)||!i.has(e)&&!s.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):this.fields.set(e,new Float32Array(this._capacity)):"string"===y?this.stringFields.set(e,new Array(this._capacity)):"object"===y&&null!==f&&(p.has(e)||m.has(e)||g.has(e))&&this.serializedFields.set(e,new Array(this._capacity))}}addComponent(e,t){if(this.entityToIndex.has(e)){const n=this.entityToIndex.get(e);return void this.updateComponentAtIndex(n,t)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(e,n),this.indexToEntity[n]=e,this.updateComponentAtIndex(n,t),this._size++}updateComponentAtIndex(e,t){const n=this.indexToEntity[e],s=new Map,i=this.type.__highPrecisionFields||new Set,r=this.type.__serializeMapFields||new Set,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(const n in t)if(t.hasOwnProperty(n)&&"id"!==n){const h=t[n],l=typeof h;if("number"===l)if(i.has(n)||!this.fields.has(n))s.set(n,h);else{this.fields.get(n)[e]=h}else if("boolean"===l&&this.fields.has(n)){this.fields.get(n)[e]=h?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[e]=String(h)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[e]=this.serializeValue(h,n,r,o,a)}else c.has(n)?s.set(n,this.deepClone(h)):s.set(n,h)}s.size>0&&this.complexFields.set(n,s)}serializeValue(e,t,n,s,i){try{return n.has(t)&&e instanceof Map?JSON.stringify(Array.from(e.entries())):s.has(t)&&e instanceof Set?JSON.stringify(Array.from(e)):(i.has(t)&&Array.isArray(e),JSON.stringify(e))}catch(e){return ee._logger.warn(`SoA序列化字段 ${t} 失败:`,e),"{}"}}deserializeValue(e,t,n,s,i){try{const r=JSON.parse(e);return n.has(t)?new Map(r):s.has(t)?new Set(r):(i.has(t),r)}catch(e){return ee._logger.warn(`SoA反序列化字段 ${t} 失败:`,e),null}}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map((e=>this.deepClone(e)));if(e instanceof Map){const t=new Map;for(const[n,s]of e.entries())t.set(n,this.deepClone(s));return t}if(e instanceof Set){const t=new Set;for(const n of e.values())t.add(this.deepClone(n));return t}const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}getComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=new this.type,s=this.type.__serializeMapFields||new Set,i=this.type.__serializeSetFields||new Set,r=this.type.__serializeArrayFields||new Set;for(const[e,s]of this.fields.entries()){const i=s[t],r=this.getFieldType(e);n[e]="boolean"===r?1===i:i}for(const[e,s]of this.stringFields.entries())n[e]=s[t];for(const[e,o]of this.serializedFields.entries()){const a=o[t];a&&(n[e]=this.deserializeValue(a,e,s,i,r))}const o=this.complexFields.get(e);if(o)for(const[e,t]of o.entries())n[e]=t;return n}getFieldType(e){return typeof(new this.type)[e]}hasComponent(e){return this.entityToIndex.has(e)}removeComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n}resize(e){for(const[t,n]of this.fields.entries()){let s;n instanceof Float32Array?s=new Float32Array(e):n instanceof Float64Array?s=new Float64Array(e):n instanceof Int32Array?s=new Int32Array(e):n instanceof Uint32Array?s=new Uint32Array(e):n instanceof Int16Array?s=new Int16Array(e):n instanceof Uint16Array?s=new Uint16Array(e):n instanceof Int8Array?s=new Int8Array(e):n instanceof Uint8Array?s=new Uint8Array(e):n instanceof Uint8ClampedArray?s=new Uint8ClampedArray(e):(s=new Float32Array(e),ee._logger.warn(`未知的TypedArray类型用于字段 ${t},回退到Float32Array`)),s.set(n),this.fields.set(t,s)}for(const[t,n]of this.stringFields.entries()){const s=new Array(e);for(let e=0;e<n.length;e++)s[e]=n[e];this.stringFields.set(t,s)}for(const[t,n]of this.serializedFields.entries()){const s=new Array(e);for(let e=0;e<n.length;e++)s[e]=n[e];this.serializedFields.set(t,s)}this._capacity=e}getActiveIndices(){return Array.from(this.entityToIndex.values())}getFieldArray(e){return this.fields.get(e)||null}getTypedFieldArray(e){return this.fields.get(String(e))||null}getEntityIndex(e){return this.entityToIndex.get(e)}getEntityIdByIndex(e){return this.indexToEntity[e]}size(){return this._size}clear(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(const e of this.fields.values())e.fill(0);for(const e of this.stringFields.values())for(let t=0;t<e.length;t++)e[t]=void 0;for(const e of this.serializedFields.values())for(let t=0;t<e.length;t++)e[t]=void 0}compact(){if(0===this.freeIndices.length)return;const e=Array.from(this.entityToIndex.entries()).sort(((e,t)=>e[1]-t[1])),t=new Map,n=[];for(let s=0;s<e.length;s++){const[i,r]=e[s];if(t.set(i,s),n[s]=i,s!==r){for(const[,e]of this.fields.entries())e[s]=e[r];for(const[,e]of this.stringFields.entries())e[s]=e[r];for(const[,e]of this.serializedFields.entries())e[s]=e[r]}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}getStats(){let e=0;const t=new Map;for(const[n,s]of this.fields.entries()){let i,r;s instanceof Float32Array?(i=4,r="float32"):s instanceof Float64Array?(i=8,r="float64"):s instanceof Int32Array?(i=4,r="int32"):s instanceof Uint32Array?(i=4,r="uint32"):s instanceof Int16Array?(i=2,r="int16"):s instanceof Uint16Array?(i=2,r="uint16"):s instanceof Int8Array?(i=1,r="int8"):s instanceof Uint8Array?(i=1,r="uint8"):s instanceof Uint8ClampedArray?(i=1,r="uint8clamped"):(i=4,r="unknown");const o=s.length*i;e+=o,t.set(n,{size:this._size,capacity:s.length,type:r,memory:o})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:e,fieldStats:t}}performVectorizedOperation(e){const t=this.getActiveIndices();e(this.fields,t)}}ee._logger=R("SoAStorage");class te{static register(e){const t=b(e);if(this.componentTypes.has(e)){return this.componentTypes.get(e)}const n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n}static getBitMask(e){const t=this.componentTypes.get(e);if(void 0===t){const t=b(e);throw new Error(`Component type ${t} is not registered`)}return X.create(t)}static getBitIndex(e){const t=this.componentTypes.get(e);if(void 0===t){const t=b(e);throw new Error(`Component type ${t} is not registered`)}return t}static isRegistered(e){return this.componentTypes.has(e)}static getTypeByBitIndex(e){return this.bitIndexToType.get(e)||null}static getRegisteredCount(){return this.nextBitIndex}static getComponentType(e){return this.componentNameToType.get(e)||null}static getAllRegisteredTypes(){return new Map(this.componentTypes)}static getAllComponentNames(){return new Map(this.componentNameToType)}static getComponentId(e){return this.componentNameToId.get(e)}static registerComponentByName(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);const t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t}static createSingleComponentMask(e){const t=`single:${e}`;if(this.maskCache.has(t))return this.maskCache.get(t);const n=this.getComponentId(e);if(void 0===n)throw new Error(`Component type ${e} is not registered`);const s=X.create(n);return this.maskCache.set(t,s),s}static createComponentMask(e){const t=`multi:${[...e].sort().join(",")}`;if(this.maskCache.has(t))return this.maskCache.get(t);let n=X.clone(X.ZERO);for(const t of e){const e=this.getComponentId(t);if(void 0!==e){const t=X.create(e);X.orInPlace(n,t)}}return this.maskCache.set(t,n),n}static clearMaskCache(){this.maskCache.clear()}static reset(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0}}te._logger=R("ComponentStorage"),te.componentTypes=new Map,te.bitIndexToType=new Map,te.componentNameToType=new Map,te.componentNameToId=new Map,te.maskCache=new Map,te.nextBitIndex=0;class ne{constructor(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,te.isRegistered(e)||te.register(e)}addComponent(e,t){if(this.entityToIndex.has(e))throw new Error(`Entity ${e} already has component ${b(this.componentType)}`);const n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)}getComponent(e){const t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null}hasComponent(e){return this.entityToIndex.has(e)}removeComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=this.dense[t],s=this.dense.length-1;if(t!==s){const e=this.dense[s],n=this.entityIds[s];this.dense[t]=e,this.entityIds[t]=n,this.entityToIndex.set(n,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n}forEach(e){for(let t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)}getDenseArray(){return{components:[...this.dense],entityIds:[...this.entityIds]}}clear(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()}get size(){return this.dense.length}get type(){return this.componentType}getStats(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}}}class se{constructor(){this.storages=new Map}isSoAStorage(e){return this.storages.get(e)instanceof ee}getSoAStorage(e){const t=this.getStorage(e);return t instanceof ee?t:null}getFieldArray(e,t){const n=this.getSoAStorage(e);return n?n.getFieldArray(t):null}getTypedFieldArray(e,t){const n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null}getActiveIndices(e){const t=this.getSoAStorage(e);return t?t.getActiveIndices():[]}getEntityIndex(e,t){const n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0}getEntityIdByIndex(e,t){const n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0}getStorage(e){let t=this.storages.get(e);if(!t){e.__enableSoA?(t=new ee(e),se._logger.info(`为 ${b(e)} 启用SoA优化(适用于大规模批量操作)`)):t=new ne(e),this.storages.set(e,t)}return t}addComponent(e,t){const n=t.constructor;this.getStorage(n).addComponent(e,t)}getComponent(e,t){const n=this.storages.get(t);return n?n.getComponent(e):null}hasComponent(e,t){const n=this.storages.get(t);return!!n&&n.hasComponent(e)}removeComponent(e,t){const n=this.storages.get(t);return n?n.removeComponent(e):null}removeAllComponents(e){for(const t of this.storages.values())t.removeComponent(e)}getComponentMask(e){let t=X.clone(X.ZERO);for(const[n,s]of this.storages.entries())if(s.hasComponent(e)){const e=te.getBitMask(n);X.orInPlace(t,e)}return t}getAllStats(){const e=new Map;for(const[t,n]of this.storages.entries()){const s=b(t);e.set(s,n.getStats())}return e}clear(){for(const e of this.storages.values())e.clear();this.storages.clear()}}se._logger=R("ComponentStorage");class ie{compare(e,t){let n=e.updateOrder-t.updateOrder;return 0==n&&(n=e.id-t.id),n}}class re{static notifyQuerySystems(e){e.scene&&e.scene.querySystem&&(e.scene.querySystem.updateEntity(e),e.scene.clearSystemEntityCaches())}constructor(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=X.clone(X.ZERO),this._componentCache=null,this.name=e,this.id=t}get isDestroyed(){return this._isDestroyed}get components(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}_rebuildComponentCache(){const e=[];if(!this.scene?.componentStorageManager)return void(this._componentCache=e);const t=this._componentMask,n=te.getRegisteredCount();for(let s=0;s<n;s++)if(X.getBit(t,s)){const t=te.getTypeByBitIndex(s);if(t){const n=this.scene.componentStorageManager.getComponent(this.id,t);n&&e.push(n)}}this._componentCache=e}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(e){this._active!==e&&(this._active=e,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(e){this._tag=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get updateOrder(){return this._updateOrder}set updateOrder(e){this._updateOrder=e}get componentMask(){return this._componentMask}createComponent(e,...t){const n=new e(...t);return this.addComponent(n)}addComponentInternal(e){const t=e.constructor;te.isRegistered(t)||te.register(t);const n=te.getBitMask(t);return X.orInPlace(this._componentMask,n),this._componentCache=null,e}addComponent(e){const t=e.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(t))throw new Error(`Entity ${this.name} already has component ${b(t)}`);return this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),e.onAddedToEntity(),re.eventBus&&re.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:b(t),component:e}),re.notifyQuerySystems(this),e}getComponent(e){if(!this.hasComponent(e))return null;if(!this.scene?.componentStorageManager)return null;return this.scene.componentStorageManager.getComponent(this.id,e)}hasComponent(e){if(!te.isRegistered(e))return!1;const t=te.getBitMask(e);return X.hasAny(this._componentMask,t)}getOrCreateComponent(e,...t){let n=this.getComponent(e);return n||(n=this.createComponent(e,...t)),n}removeComponent(e){const t=e.constructor;if(!te.isRegistered(t))return;const n=te.getBitIndex(t);X.clearBit(this._componentMask,n),this._componentCache=null,this.scene?.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),this.scene?.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(e),e.onRemovedFromEntity&&e.onRemovedFromEntity(),e.entityId=null,re.eventBus&&re.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:b(t),component:e}),re.notifyQuerySystems(this)}removeComponentByType(e){const t=this.getComponent(e);return t?(this.removeComponent(t),t):null}removeAllComponents(){const e=[...this.components];X.clear(this._componentMask),this._componentCache=null;for(const t of e){const e=t.constructor;this.scene?.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity()}re.notifyQuerySystems(this)}addComponents(e){const t=[];for(const n of e)try{t.push(this.addComponent(n))}catch(e){re._logger.warn(`添加组件失败 ${T(n)}:`,e)}return t}removeComponentsByTypes(e){const t=[];for(const n of e)t.push(this.removeComponentByType(n));return t}getComponents(e){const t=[];for(const n of this.components)n instanceof e&&t.push(n);return t}getComponentByType(e){for(const t of this.components)if(t instanceof e)return t;return null}addChild(e){if(e===this)throw new Error("Entity cannot be its own child");return e._parent===this||(e._parent&&e._parent.removeChild(e),e._parent=this,this._children.push(e),!e.scene&&this.scene&&(e.scene=this.scene,this.scene.addEntity(e))),e}removeChild(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e._parent=null,!0)}removeAllChildren(){const e=[...this._children];for(const t of e)this.removeChild(t)}findChild(e,t=!1){for(const t of this._children)if(t.name===e)return t;if(t)for(const t of this._children){const n=t.findChild(e,!0);if(n)return n}return null}findChildrenByTag(e,t=!1){const n=[];for(const t of this._children)t.tag===e&&n.push(t);if(t)for(const t of this._children)n.push(...t.findChildrenByTag(e,!0));return n}getRoot(){let e=this;for(;e._parent;)e=e._parent;return e}isAncestorOf(e){let t=e._parent;for(;t;){if(t===this)return!0;t=t._parent}return!1}isDescendantOf(e){return e.isAncestorOf(this)}getDepth(){let e=0,t=this._parent;for(;t;)e++,t=t._parent;return e}forEachChild(e,t=!1){this._children.forEach(((n,s)=>{e(n,s),t&&n.forEachChild(e,!0)}))}onActiveChanged(){for(const e of this.components)"onActiveChanged"in e&&"function"==typeof e.onActiveChanged&&e.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));const e=[...this._children];for(const t of e)t.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}destroyAllChildren(){if(0===this._children.length)return;const e=this.scene,t=[],n=e=>{for(const s of e._children)t.push(s),n(s)};n(this);for(const e of t)e._isDestroyed=!0;for(const e of t)e.removeAllComponents();if(e){for(const n of t)e.entities.remove(n),e.querySystem.removeEntity(n);e.clearSystemEntityCaches()}this._children.length=0}compareTo(e){return ie.prototype.compare(this,e)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){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((e=>T(e))),componentMask:X.toString(this._componentMask,2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((e=>e.id)),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}}}re._logger=R("Entity"),re.entityComparer=new ie,re.eventBus=null;class oe{constructor(e,t){this.scene=e,this.storageManager=t;const n=e.identifierPool.checkOut();this.entity=new re("",n),this.entity.scene=this.scene}named(e){return this.entity.name=e,this}tagged(e){return this.entity.tag=e,this}with(e){return this.entity.addComponent(e),this}withComponents(...e){for(const t of e)this.entity.addComponent(t);return this}withIf(e,t){return e&&this.entity.addComponent(t),this}withFactory(e){const t=e();return this.entity.addComponent(t),this}configure(e,t){const n=this.entity.getComponent(e);return n&&t(n),this}enabled(e=!0){return this.entity.enabled=e,this}active(e=!0){return this.entity.active=e,this}withChild(e){const t=e.build();return this.entity.addChild(t),this}withChildren(...e){for(const t of e){const e=t.build();this.entity.addChild(e)}return this}withChildFactory(e){const t=e(this.entity).build();return this.entity.addChild(t),this}withChildIf(e,t){if(e){const e=t.build();this.entity.addChild(e)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const e=new oe(this.scene,this.storageManager);return e.entity=this.entity,e}}class ae{get count(){return this.buffer.length}constructor(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}add(e){this.addImmediate(e)}addImmediate(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))}remove(e){this.removeImmediate(e)}removeImmediate(e){const t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))}removeAllEntities(){const e=[];for(let t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(const t of e)this._scene.identifierPool.checkIn(t);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 e of this._entitiesToAdd)this.addImmediate(e);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const e of this._entitiesToRemove)this.removeImmediate(e);this._entitiesToRemove.length=0}}update(){this.updateLists()}findEntity(e){const t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null}findEntitiesByName(e){return this._nameToEntities.get(e)||[]}findEntityById(e){return this._idToEntity.get(e)||null}findEntitiesByTag(e){const t=[];for(const n of this.buffer)n.tag===e&&t.push(n);return t}findEntitiesWithComponent(e){const t=[];for(const n of this.buffer)n.hasComponent(e)&&t.push(n);return t}forEach(e){for(const t of this.buffer)e(t)}forEachWhere(e,t){for(const n of this.buffer)e(n)&&t(n)}updateNameIndex(e,t){if(e.name)if(t){let t=this._nameToEntities.get(e.name);t||(t=[],this._nameToEntities.set(e.name,t)),t.push(e)}else{const t=this._nameToEntities.get(e.name);if(t){const n=t.indexOf(e);-1!==n&&(t.splice(n,1),0===t.length&&this._nameToEntities.delete(e.name))}}}getStats(){let e=0;for(const t of this.buffer)t.enabled&&!t.isDestroyed&&e++;return{totalEntities:this.buffer.length,activeEntities:e,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class ce{constructor(e=100,t=1024){this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}checkOut(){let e;if(this._processDelayedRecycle(),this._freeIndices.length>0)e=this._freeIndices.pop();else{if(this._nextAvailableIndex>ce.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${ce.MAX_INDEX})。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。`);e=this._nextAvailableIndex++,this._ensureGenerationCapacity(e)}const t=this._generations.get(e)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(e,t)}checkIn(e){const t=this._unpackIndex(e),n=this._unpackGeneration(e);if(!this._isValidId(t,n))return!1;return!this._pendingRecycle.some((e=>e.index===t&&e.generation===n))&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0)}isValid(e){const t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)}getStats(){let e=0,t=0;for(const[n,s]of this._generations)n<this._nextAvailableIndex&&(e+=s,t++);const n=t>0?e/t:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:ce.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*n)/100,generationStorageSize:this._generations.size}}forceProcessDelayedRecycle(){this._processDelayedRecycle(!0)}_processDelayedRecycle(e=!1){if(0===this._pendingRecycle.length)return;const t=Date.now(),n=[],s=[];for(const i of this._pendingRecycle)e||t-i.timestamp>=this._recycleDelay?n.push(i):s.push(i);for(const e of n)if(this._isValidId(e.index,e.generation)){let t=e.generation+1;t>ce.MAX_GENERATION&&(t=1),this._generations.set(e.index,t),this._freeIndices.push(e.index)}this._pendingRecycle=s}_preAllocateGenerations(e,t){for(let n=0;n<t;n++){const t=e+n;t<=ce.MAX_INDEX&&this._generations.set(t,1)}this._stats.memoryExpansions++}_ensureGenerationCapacity(e){if(!this._generations.has(e)){const t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}}_calculateMemoryUsage(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length}_packId(e,t){return t<<16|e}_unpackIndex(e){return 65535&e}_unpackGeneration(e){return e>>>16&65535}_isValidId(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;const n=this._generations.get(e);return void 0!==n&&n===t}}ce.MAX_INDEX=65535,ce.MAX_GENERATION=65535;class he{constructor(){this.condition={all:[],any:[],none:[]}}static all(...e){return(new he).all(...e)}static any(...e){return(new he).any(...e)}static none(...e){return(new he).none(...e)}static byTag(e){return(new he).withTag(e)}static byName(e){return(new he).withName(e)}static byComponent(e){return(new he).withComponent(e)}static complex(){return new he}static empty(){return new he}all(...e){return this.condition.all.push(...e),this}any(...e){return this.condition.any.push(...e),this}none(...e){return this.condition.none.push(...e),this}exclude(...e){return this.none(...e)}one(...e){return this.any(...e)}withTag(e){return this.condition.tag=e,this}withName(e){return this.condition.name=e,this}withComponent(e){return this.condition.component=e,this}withoutTag(){return delete this.condition.tag,this}withoutName(){return delete this.condition.name,this}withoutComponent(){return delete this.condition.component,this}getCondition(){return{all:[...this.condition.all],any:[...this.condition.any],none:[...this.condition.none],tag:this.condition.tag,name:this.condition.name,component:this.condition.component}}isEmpty(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component}reset(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this}clone(){const e=new he;return e.condition.all.push(...this.condition.all),e.condition.any.push(...this.condition.any),e.condition.none.push(...this.condition.none),void 0!==this.condition.tag&&(e.condition.tag=this.condition.tag),void 0!==this.condition.name&&(e.condition.name=this.condition.name),void 0!==this.condition.component&&(e.condition.component=this.condition.component),e}toString(){const e=[];return this.condition.all.length>0&&e.push(`all(${this.condition.all.map((e=>b(e))).join(", ")})`),this.condition.any.length>0&&e.push(`any(${this.condition.any.map((e=>b(e))).join(", ")})`),this.condition.none.length>0&&e.push(`none(${this.condition.none.map((e=>b(e))).join(", ")})`),void 0!==this.condition.tag&&e.push(`tag(${this.condition.tag})`),void 0!==this.condition.name&&e.push(`name(${this.condition.name})`),void 0!==this.condition.component&&e.push(`component(${b(this.condition.component)})`),`Matcher[${e.join(" & ")}]`}}class le{get entities(){return null!==this._entityCache.frame?this._entityCache.frame:(null===this._entityCache.persistent&&(this._entityCache.persistent=this.queryEntities()),this._entityCache.persistent)}get updateOrder(){return this._updateOrder}set updateOrder(e){this.setUpdateOrder(e)}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get systemName(){return this._systemName}constructor(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=A(this),this._initialized=!1,this._matcher=e||he.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=R(this.getLoggerName()),this._entityCache={frame:null,persistent:null,tracked:new Set,invalidate(){this.persistent=null},clearFrame(){this.frame=null},clearAll(){this.frame=null,this.persistent=null,this.tracked.clear()}}}get scene(){return this._scene}set scene(e){this._scene=e}setPerformanceMonitor(e){this._performanceMonitor=e}getPerformanceMonitor(){if(!this._performanceMonitor)throw new Error(`${this._systemName}: PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene`);return this._performanceMonitor}get matcher(){return this._matcher}setUpdateOrder(e){this._updateOrder=e}initialize(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())}onInitialize(){}clearEntityCache(){this._entityCache.invalidate()}reset(){this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.destroy()}queryEntities(){if(!this.scene?.querySystem||!this._matcher)return[];const e=this._matcher.getCondition(),t=this.scene.querySystem;let n=[];return n=this._matcher.isEmpty()?t.getAllEntities():this.isSingleCondition(e)?this.executeSingleConditionQuery(e,t):this.executeComplexQuery(e,t),this.updateEntityTracking(n),n}isSingleCondition(e){const t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)}executeSingleConditionQuery(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll(...e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny(...e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone(...e.none).entities:[]}executeComplexQueryWithIdSets(e,t){let n=null;if(void 0!==e.tag){const s=t.queryByTag(e.tag);n=this.extractEntityIds(s.entities)}if(void 0!==e.name){const s=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,s):s}if(void 0!==e.component){const s=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,s):s}if(e.all.length>0){const s=this.extractEntityIds(t.queryAll(...e.all).entities);n=n?this.intersectIdSets(n,s):s}if(e.any.length>0){const s=this.extractEntityIds(t.queryAny(...e.any).entities);n=n?this.intersectIdSets(n,s):s}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));const s=t.queryAny(...e.none),i=this.extractEntityIds(s.entities);n=this.differenceIdSets(n,i)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]}extractEntityIds(e){const t=e.length,n=new Set;for(let s=0;s<t;s=s+1|0)n.add(0|e[s].id);return n}intersectIdSets(e,t){let n,s;e.size<=t.size?(n=e,s=t):(n=t,s=e);const i=new Set;for(const e of n)s.has(e)&&i.add(e);return i}differenceIdSets(e,t){const n=new Set;for(const s of e)t.has(s)||n.add(s);return n}getEntityIdMap(e){const t=this.scene?.querySystem?.version??0;return null!==this._entityIdMap&&this._entityIdMapVersion===t?this._entityIdMap:this.rebuildEntityIdMap(e,t)}rebuildEntityIdMap(e,t){let n=this._entityIdMap;n?n.clear():n=new Map;const s=e.length;for(let t=0;t<s;t=t+1|0){const s=e[t];n.set(0|s.id,s)}return this._entityIdMap=n,this._entityIdMapVersion=t,this._entityIdMapSize=s,n}idSetToEntityArray(e,t){const n=this.getEntityIdMap(t),s=e.size,i=new Array(s);let r=0;for(const t of e){const e=n.get(t);void 0!==e&&(i[r]=e,r=r+1|0)}return r<s&&(i.length=r),i}executeComplexQuery(e,t){return this.executeComplexQueryWithIdSets(e,t)}update(){if(!this._enabled||!this.onCheckProcessing())return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName);let n=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),n=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{e.endMonitoring(this._systemName,t,n)}}lateUpdate(){if(!this._enabled||!this.onCheckProcessing())return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(`${this._systemName}_Late`);let n=0;try{const e=this._entityCache.frame||[];n=e.length,this.lateProcess(e),this.onEnd()}finally{e.endMonitoring(`${this._systemName}_Late`,t,n),this._entityCache.clearFrame()}}onBegin(){}process(e){}lateProcess(e){}onEnd(){}onCheckProcessing(){return!0}getPerformanceData(){return this.getPerformanceMonitor().getSystemData(this._systemName)}getPerformanceStats(){return this.getPerformanceMonitor().getSystemStats(this._systemName)}resetPerformanceData(){this.getPerformanceMonitor().resetSystem(this._systemName)}toString(){const e=this.entities.length,t=this.getPerformanceData(),n=t?` (${t.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${e} entities]${n}`}updateEntityTracking(e){const t=new Set(e);let n=!1;for(const t of e)this._entityCache.tracked.has(t)||(this._entityCache.tracked.add(t),this.onAdded(t),n=!0);for(const e of this._entityCache.tracked)t.has(e)||(this._entityCache.tracked.delete(e),this.onRemoved(e),n=!0);n&&this._entityCache.invalidate()}onAdded(e){}onRemoved(e){}dispose(){this.cleanupManualEventListeners(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this.logger.debug(`System ${this._systemName} disposed`)}addEventListener(e,t,n){if(!this.scene?.eventSystem)return void this.logger.warn(`${this.systemName}: 无法添加事件监听器,scene.eventSystem 不可用`);const s=this.scene.eventSystem.on(e,t,n);s&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,handler:t,listenerRef:s})}removeEventListener(e,t){const n=this._eventListeners.findIndex((n=>n.eventType===e&&n.handler===t));if(n>=0){const t=this._eventListeners[n];t.eventSystem.off(e,t.listenerRef),this._eventListeners.splice(n,1)}}cleanupManualEventListeners(){for(const e of this._eventListeners)try{e.eventSystem.off(e.eventType,e.listenerRef)}catch(t){this.logger.warn(`${this.systemName}: 移除事件监听器失败 "${e.eventType}"`,t)}this._eventListeners.length=0}destroy(){this.cleanupManualEventListeners(),this.onDestroy()}getLoggerName(){return A(this)}onDestroy(){}requireComponent(e,t){const n=e.getComponent(t);if(!n)throw new Error(`Component ${t.name} not found on entity ${e.name} in ${this.systemName}`);return n}getComponents(e,...t){return t.map((t=>this.requireComponent(e,t)))}forEach(e,t){for(let n=0;n<e.length;n++)t(e[n],n)}filterEntities(e,t){return Array.from(e).filter(t)}mapEntities(e,t){return Array.from(e).map(t)}findEntity(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return e[n]}someEntity(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1}everyEntity(e,t){for(let n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0}}class ue{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(e){this._processors.push(e),this.setDirty()}remove(e){const t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)}getProcessor(e){for(const t of this._processors)if(t instanceof e)return t;return null}begin(){this.sortProcessors()}end(){for(const e of this._processors)try{e.reset()}catch(t){ue._logger.error(`Error in processor ${A(e)}:`,t)}this._isDirty=!1,this._processors.length=0}update(){this.sortProcessors();for(const e of this._processors)try{e.update()}catch(t){ue._logger.error(`Error in processor ${A(e)}:`,t)}}lateUpdate(){for(const e of this._processors)e.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((e,t)=>e.updateOrder-t.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}ue._logger=R("EntityProcessorList");class de{constructor(e){if(e&&"object"==typeof e)this._value=X.clone(e);else if("number"==typeof e)this._value=X.fromNumber(e);else if("string"==typeof e){const t=parseInt(e,10);this._value=X.fromNumber(t)}else this._value=X.clone(X.ZERO)}set(e){if(e<0)throw new Error("Bit index cannot be negative");X.setBit(this._value,e)}clear(e){if(e<0)throw new Error("Bit index cannot be negative");X.clearBit(this._value,e)}get(e){return X.getBit(this._value,e)}containsAll(e){return X.hasAll(this._value,e._value)}intersects(e){return X.hasAny(this._value,e._value)}excludes(e){return X.hasNone(this._value,e._value)}clearAll(){X.clear(this._value)}isEmpty(){return X.isZero(this._value)}cardinality(){return X.popCount(this._value)}and(e){const t=new de;return X.copy(this._value,t._value),X.andInPlace(t._value,e._value),t}or(e){const t=new de;return X.copy(this._value,t._value),X.orInPlace(t._value,e._value),t}xor(e){const t=new de;return X.copy(this._value,t._value),X.xorInPlace(t._value,e._value),t}not(e=64){e>64&&(e=64);const t=new de;if(X.copy(this._value,t._value),e<=32){const n=(1<<e)-1;t._value.base[J.LOW]=~t._value.base[J.LOW]&n,t._value.base[J.HIGH]=0}else if(t._value.base[J.LOW]=~t._value.base[J.LOW],e<64){const n=(1<<e-32)-1;t._value.base[J.HIGH]=~t._value.base[J.HIGH]&n}else t._value.base[J.HIGH]=~t._value.base[J.HIGH];return t}copyFrom(e){X.copy(e._value,this._value)}clone(){return new de(this._value)}getValue(){return this._value}setValue(e){if("object"==typeof e)X.copy(e,this._value);else if("number"==typeof e)this._value=X.fromNumber(e);else{const t=parseInt(e,10);this._value=X.fromNumber(t)}}toString(){const e=[];for(let t=0;t<64;t++)this.get(t)&&e.push(t.toString());return`Bits[${e.join(", ")}]`}toBinaryString(e=0){0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));let t="";for(let n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t}toHexString(){return X.toString(this._value,16)}static fromBinaryString(e){const t=e.replace(/\s/g,"");let n={base:void 0,segments:void 0};if(t.length<=32){const e=parseInt(t,2);n.base=[e>>>0,0]}else{const e=t.substring(t.length-32),s=t.substring(0,t.length-32),i=parseInt(e,2),r=parseInt(s,2);n.base=[i>>>0,r>>>0]}return new de(n)}static fromHexString(e){const t=e.replace(/^0x/i,"");let n={base:void 0,segments:void 0};if(t.length<=8){const e=parseInt(t,16);n.base=[e>>>0,0]}else{const e=t.substring(t.length-8),s=t.substring(0,t.length-8),i=parseInt(e,16),r=parseInt(s,16);n.base=[i>>>0,r>>>0]}return new de(n)}equals(e){return X.equals(this._value,e._value)}getHighestBitIndex(){if(X.isZero(this._value))return-1;if(0!==this._value.base[J.HIGH])for(let e=31;e>=0;e--)if(this._value.base[J.HIGH]&1<<e)return e+32;for(let e=31;e>=0;e--)if(this._value.base[J.LOW]&1<<e)return e;return-1}getLowestBitIndex(){if(X.isZero(this._value))return-1;for(let e=0;e<32;e++)if(this._value.base[J.LOW]&1<<e)return e;for(let e=0;e<32;e++)if(this._value.base[J.HIGH]&1<<e)return e+32;return-1}}class pe{constructor(){this._dense=[],this._sparse=new Map}add(e){if(this._sparse.has(e))return!1;const t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0}remove(e){const t=this._sparse.get(e);if(void 0===t)return!1;const n=this._dense.length-1;if(t!==n){const e=this._dense[n];this._dense[t]=e,this._sparse.set(e,t)}return this._dense.pop(),this._sparse.delete(e),!0}has(e){return this._sparse.has(e)}getIndex(e){return this._sparse.get(e)}getByIndex(e){return this._dense[e]}get size(){return this._dense.length}get isEmpty(){return 0===this._dense.length}forEach(e){for(let t=0;t<this._dense.length;t++)e(this._dense[t],t)}map(e){const t=[];for(let n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t}filter(e){const t=[];for(let n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t}find(e){for(let t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]}some(e){for(let t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1}every(e){for(let t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0}getDenseArray(){return[...this._dense]}getDenseArrayUnsafe(){return this._dense}clear(){this._dense.length=0,this._sparse.clear()}toArray(){return[...this._dense]}toSet(){return new Set(this._dense)}getMemoryStats(){const e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}}validate(){if(this._dense.length!==this._sparse.size)return!1;for(let e=0;e<this._dense.length;e++){const t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(const[e,t]of this._sparse)if(t>=this._dense.length||this._dense[t]!==e)return!1;return!0}}class me extends Set{constructor(...e){super()}reset(){this.clear()}}class ge{constructor(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new pe}addEntity(e){this._entities.has(e)&&this.removeEntity(e);let t=X.clone(X.ZERO);const n=new Set;for(const s of e.components){const e=s.constructor;n.add(e),te.isRegistered(e)||te.register(e);const i=te.getBitMask(e);X.orInPlace(t,i)}this._entities.add(e);const s=this._entities.getIndex(e);for(;this._componentMasks.length<=s;)this._componentMasks.push(X.clone(X.ZERO));this._componentMasks[s]=t,this.updateComponentMappings(e,n,!0)}removeEntity(e){const t=this._entities.getIndex(e);if(void 0===t)return;const n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);const s=this._componentMasks.length-1;t!==s&&(this._componentMasks[t]=this._componentMasks[s]),this._componentMasks.pop()}queryByComponent(e){const t=this._componentToEntities.get(e);return t?new Set(t):new Set}queryMultipleAnd(e){if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);let t=X.clone(X.ZERO);for(const n of e){if(!te.isRegistered(n))return new Set;const e=te.getBitMask(n);X.orInPlace(t,e)}const n=ge._entitySetPool.obtain();return this._entities.forEach(((e,s)=>{const i=this._componentMasks[s];X.hasAll(i,t)&&n.add(e)})),n}queryMultipleOr(e){if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);let t=X.clone(X.ZERO);for(const n of e)if(te.isRegistered(n)){const e=te.getBitMask(n);X.orInPlace(t,e)}if(X.equals(t,X.ZERO))return new Set;const n=ge._entitySetPool.obtain();return this._entities.forEach(((e,s)=>{const i=this._componentMasks[s];X.hasAny(i,t)&&n.add(e)})),n}hasComponent(e,t){const n=this._entities.getIndex(e);if(void 0===n)return!1;if(!te.isRegistered(t))return!1;const s=this._componentMasks[n],i=te.getBitMask(t);return X.hasAny(s,i)}getEntityMask(e){const t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]}getAllEntities(){return this._entities.toArray()}get size(){return this._entities.size}get isEmpty(){return this._entities.isEmpty}forEach(e){this._entities.forEach(((t,n)=>{e(t,this._componentMasks[n],n)}))}clear(){this._entities.clear(),this._componentMasks.length=0;for(const e of this._componentToEntities.values())ge._entitySetPool.release(e);this._componentToEntities.clear()}getMemoryStats(){const e=this._entities.getMemoryStats(),t=16*this._componentMasks.length;let n=16*this._componentToEntities.size;for(const e of this._componentToEntities.values())n+=8*e.size;return{entitiesMemory:e.totalMemory,masksMemory:t,mappingsMemory:n,totalMemory:e.totalMemory+t+n}}validate(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;const e=new Set;for(const t of this._componentToEntities.values())for(const n of t)e.add(n);for(const t of e)if(!this._entities.has(t))return!1;return!0}getEntityComponentTypes(e){const t=new Set;for(const n of e.components)t.add(n.constructor);return t}updateComponentMappings(e,t,n){for(const s of t){let t=this._componentToEntities.get(s);n?(t||(t=ge._entitySetPool.obtain(),this._componentToEntities.set(s,t)),t.add(e)):t&&(t.delete(e),0===t.size&&(this._componentToEntities.delete(s),ge._entitySetPool.release(t)))}}}ge._entitySetPool=_.getPool(me,50,512);class fe{constructor(){this.buckets=new Map,this._size=0}get size(){return this._size}get innerBuckets(){return this.buckets}murmur32(e,t){let n=t>>>0;const s=e=>{e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n^=e,n=n<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(s(e.base[0]>>>0),s(e.base[1]>>>0),e.segments)for(const t of e.segments)s(t[0]>>>0),s(t[1]>>>0);return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,n^=n>>>16,n>>>0}getHashes(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]}set(e,t){const[n,s]=this.getHashes(e);let i=this.buckets.get(n);i||(i=[],this.buckets.set(n,i));for(let e=0;e<i.length;e++)if(i[e][0]===s)return i[e][1]=t,this;return i.push([s,t]),this._size++,this}get(e){const[t,n]=this.getHashes(e),s=this.buckets.get(t);if(s)for(let e=0;e<s.length;e++)if(s[e][0]===n)return s[e][1]}has(e){return void 0!==this.get(e)}delete(e){const[t,n]=this.getHashes(e),s=this.buckets.get(t);if(!s)return!1;for(let e=0;e<s.length;e++)if(s[e][0]===n)return s.splice(e,1),this._size--,0===s.length&&this.buckets.delete(t),!0;return!1}clear(){this.buckets.clear(),this._size=0}*entries(){for(const[e,t]of this.buckets)for(const[e,n]of t)yield[void 0,n]}*values(){for(const e of this.buckets.values())for(const[t,n]of e)yield n}}class ye{constructor(){this._archetypes=new fe,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}addEntity(e){const t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t);let s=this._archetypes.get(n);s||(s=this.createArchetype(t)),s.entities.add(e),this._entityToArchetype.set(e,s)}removeEntity(e){const t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))}updateEntity(e){const t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);const n=this.getEntityComponentTypes(e),s=this.generateArchetypeId(n);if(t&&t.id===s)return;t&&t.entities.delete(e);let i=this._archetypes.get(s);i||(i=this.createArchetype(n)),i.entities.add(e),this._entityToArchetype.set(e,i)}queryArchetypes(e,t="AND"){const n=[];let s=0;if("AND"===t){if(0===e.length){for(const e of this._allArchetypes)n.push(e),s+=e.entities.size;return{archetypes:n,totalEntities:s}}if(1===e.length){const t=this._componentToArchetypes.get(e[0]);if(t)for(const e of t)n.push(e),s+=e.entities.size;return{archetypes:n,totalEntities:s}}let t,i=1/0;for(const n of e){const e=this._componentToArchetypes.get(n);if(!e||0===e.size)return{archetypes:[],totalEntities:0};e.size<i&&(i=e.size,t=e)}const r=this.generateArchetypeId(e);if(t)for(const e of t)X.hasAll(e.id,r)&&(n.push(e),s+=e.entities.size)}else{const t=new Set;for(const n of e){const e=this._componentToArchetypes.get(n);if(e)for(const n of e)t.add(n)}for(const e of t)n.push(e),s+=e.entities.size}return{archetypes:n,totalEntities:s}}getEntityArchetype(e){return this._entityToArchetype.get(e)}getAllArchetypes(){return this._allArchetypes.slice()}getEntitiesByComponent(e){const t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];const n=[];for(const e of t)for(const t of e.entities)n.push(t);return n}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]}updateAllArchetypeArrays(){this._allArchetypes=[];for(let e of this._archetypes.values())this._allArchetypes.push(e)}getEntityComponentTypes(e){let t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((e=>e.constructor)),this._entityComponentTypesCache.set(e,t)),t}generateArchetypeId(e){let t=X.clone(X.ZERO);for(const n of e){te.isRegistered(n)||te.register(n);const e=te.getBitMask(n);X.orInPlace(t,e)}return t}createArchetype(e){const t=this.generateArchetypeId(e),n={id:t,componentTypes:[...e],entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(const t of e){let e=this._componentToArchetypes.get(t);e||(e=new Set,this._componentToArchetypes.set(t,e)),e.add(n)}return n}}!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Z||(Z={}));const _e=R("ReactiveQuery");var Se,ve,Ce;exports.ReactiveQueryChangeType=void 0,(Se=exports.ReactiveQueryChangeType||(exports.ReactiveQueryChangeType={})).ADDED="added",Se.REMOVED="removed",Se.BATCH_UPDATE="batch_update";class Ee{constructor(e,t={}){this._entities=[],this._entityIdSet=new Set,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:t.enableBatchMode??!0,batchDelay:t.batchDelay??16,debug:t.debug??!1},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&_e.debug(`创建ReactiveQuery: ${this._id}`)}generateQueryId(){return`${this._condition.type}:${this._condition.componentTypes.map((e=>e.name)).sort().join(",")}`}subscribe(e){if(!this._active)throw new Error(`Cannot subscribe to disposed ReactiveQuery ${this._id}`);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&_e.debug(`订阅ReactiveQuery: ${this._id}, 监听器数量: ${this._listeners.length}`),()=>{const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}unsubscribeAll(){this._listeners.length=0}getEntities(){return this._entities}get count(){return this._entities.length}matches(e){const t=e.componentMask;switch(this._condition.type){case Z.ALL:return X.hasAll(t,this._condition.mask);case Z.ANY:return X.hasAny(t,this._condition.mask);case Z.NONE:return X.hasNone(t,this._condition.mask);default:return!1}}notifyEntityAdded(e){this._active&&this.matches(e)&&(this._entityIdSet.has(e.id)||(this._entities.push(e),this._entityIdSet.add(e.id),this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.ADDED,entity:e}),this._config.debug&&_e.debug(`ReactiveQuery ${this._id}: 实体添加 ${e.name}(${e.id})`)))}notifyEntityRemoved(e){if(!this._active)return;if(!this._entityIdSet.has(e.id))return;const t=this._entities.indexOf(e);-1!==t&&this._entities.splice(t,1),this._entityIdSet.delete(e.id),this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.REMOVED,entity:e}),this._config.debug&&_e.debug(`ReactiveQuery ${this._id}: 实体移除 ${e.name}(${e.id})`)}notifyEntityChanged(e){if(!this._active)return;const t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}initializeWith(e){this._entities.length=0,this._entityIdSet.clear();for(const t of e)this.matches(t)&&(this._entities.push(t),this._entityIdSet.add(t.id));this._config.debug&&_e.debug(`ReactiveQuery ${this._id}: 初始化 ${this._entities.length} 个实体`)}addToBatch(e,t){"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout((()=>{this.flushBatchChanges()}),this._config.batchDelay))}flushBatchChanges(){if(0===this._batchChanges.added.length&&0===this._batchChanges.removed.length)return void(this._batchChanges.timer=null);const e=[...this._batchChanges.added],t=[...this._batchChanges.removed];this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:exports.ReactiveQueryChangeType.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&_e.debug(`ReactiveQuery ${this._id}: 批量更新 +${e.length} -${t.length}`)}notifyListeners(e){const t=[...this._listeners];for(const n of t)try{n(e)}catch(e){_e.error(`ReactiveQuery ${this._id}: 监听器执行出错`,e)}}pause(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0}resume(){this._active=!0}dispose(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._config.debug&&_e.debug(`ReactiveQuery ${this._id}: 已销毁`)}get condition(){return this._condition}get id(){return this._id}get active(){return this._active}get listenerCount(){return this._listeners.length}}class be{constructor(){this._logger=R("QuerySystem"),this.entities=[],this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.componentMaskCache=new Map,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.resultArrayPool=[],this.poolMaxSize=50,this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this.entityIndex={byTag:new Map,byName:new Map},this.archetypeSystem=new ye}acquireResultArray(){return this.resultArrayPool.length>0?this.resultArrayPool.pop():[]}releaseResultArray(e){this.resultArrayPool.length<this.poolMaxSize&&(e.length=0,this.resultArrayPool.push(e))}setEntities(e){this.entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()}addEntity(e,t=!1){this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)}addEntities(e){if(0===e.length)return;const t=new Set(this.entities.map((e=>e.id)));let n=0;for(const s of e)t.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),this.archetypeSystem.addEntity(s),t.add(s.id),n++);n>0&&this.clearQueryCache()}addEntitiesUnchecked(e){if(0!==e.length){for(const t of e)this.entities.push(t);for(const t of e)this.addEntityToIndexes(t),this.archetypeSystem.addEntity(t);this.clearQueryCache()}}removeEntity(e){const t=this.entities.indexOf(e);if(-1!==t){const n=[];for(const t of e.components)n.push(t.constructor);this.entities.splice(t,1),this.removeEntityFromIndexes(e),this.archetypeSystem.removeEntity(e),n.length>0?this.notifyReactiveQueriesEntityRemoved(e,n):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}}updateEntity(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)}addEntityToIndexes(e){const t=e.tag;if(void 0!==t){(this.entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e)}const n=e.name;if(n){(this.entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)}}createAndSetTagIndex(e){const t=new Set;return this.entityIndex.byTag.set(e,t),t}createAndSetNameIndex(e){const t=new Set;return this.entityIndex.byName.set(e,t),t}removeEntityFromIndexes(e){if(void 0!==e.tag){const t=this.entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){const t=this.entityIndex.byName.get(e.name);t&&(t.delete(e),0===t.size&&this.entityIndex.byName.delete(e.name))}}rebuildIndexes(){this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear();for(const e of this.entities)this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e)}queryAll(...e){const t=performance.now();this.queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.ALL,e).getEntities();return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryMultipleComponents(e){const t=this.archetypeSystem.queryArchetypes(e,"AND"),n=[];for(const e of t.archetypes)for(const t of e.entities)n.push(t);return n}queryAny(...e){const t=performance.now();this.queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.ANY,e).getEntities();return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryNone(...e){const t=performance.now();this.queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.NONE,e).getEntities();return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryByTag(e){const t=performance.now();this.queryStats.totalQueries++;const n=`tag:${e}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}queryByName(e){const t=performance.now();this.queryStats.totalQueries++;const n=`name:${e}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}queryByComponent(e){const t=performance.now();this.queryStats.totalQueries++;const n=this.generateCacheKey("component",[e]),s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;const i=this.archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}getFromCache(e){const t=this.queryCache.get(e);return t?Date.now()-t.timestamp>this.cacheTimeout||t.version!==this._version?(this.queryCache.delete(e),null):(t.hitCount++,t.entities):null}addToCache(e,t){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})}cleanupCache(){const e=Date.now();for(const[t,n]of this.queryCache.entries())e-n.timestamp>this.cacheTimeout&&this.queryCache.delete(t);if(this.queryCache.size>=this.cacheMaxSize){let e=1/0,t="",n=1/0;for(const[s,i]of this.queryCache.entries())(i.hitCount<e||i.hitCount===e&&i.timestamp<n)&&(e=i.hitCount,t=s,n=i.timestamp);t&&this.queryCache.delete(t)}}clearQueryCache(){this.queryCache.clear(),this.componentMaskCache.clear()}clearReactiveQueries(){for(const e of this._reactiveQueries.values())e.dispose();this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()}generateCacheKey(e,t){if(1===t.length){return`${e}:${b(t[0])}`}return`${e}:${t.map((e=>b(e))).sort().join(",")}`}clearCache(){this.clearQueryCache(),this.clearReactiveQueries()}createReactiveQuery(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");const n=this.createComponentMask(e),s={type:Z.ALL,componentTypes:e,mask:n},i=new Ee(s,t),r=this.executeTraditionalQuery(Z.ALL,e);i.initializeWith(r);const o=this.generateCacheKey("all",e);this._reactiveQueries.set(o,i);for(const t of e){let e=this._reactiveQueriesByComponent.get(t);e||(e=new Set,this._reactiveQueriesByComponent.set(t,e)),e.add(i)}return i}destroyReactiveQuery(e){if(!e)return;const t=e.id;this._reactiveQueries.delete(t);for(const t of e.condition.componentTypes){const n=this._reactiveQueriesByComponent.get(t);n&&(n.delete(e),0===n.size&&this._reactiveQueriesByComponent.delete(t))}e.dispose()}createComponentMask(e){const t=e.map((e=>b(e))).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;let s=X.clone(X.ZERO);for(const t of e){te.isRegistered(t)||te.register(t);const e=te.getBitMask(t);X.orInPlace(s,e)}return this.componentMaskCache.set(t,s),s}get version(){return this._version}getAllEntities(){return this.entities}getStats(){return{entityCount:this.entities.length,indexStats:{componentIndexSize:this.archetypeSystem.getAllArchetypes().length,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:{...this.queryStats,cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{archetypeSystem:this.archetypeSystem.getAllArchetypes().map((e=>({id:e.id,componentTypes:e.componentTypes.map((e=>b(e))),entityCount:e.entities.size})))},cacheStats:{size:this._reactiveQueries.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}getEntityArchetype(e){return this.archetypeSystem.getEntityArchetype(e)}getOrCreateReactiveQuery(e,t){const n=this.generateCacheKey(e,t);let s=this._reactiveQueries.get(n);if(!s){const i=this.createComponentMask(t);s=new Ee({type:e,componentTypes:t,mask:i},{enableBatchMode:!1,debug:!1});const r=this.executeTraditionalQuery(e,t);s.initializeWith(r),this._reactiveQueries.set(n,s);for(const e of t){let t=this._reactiveQueriesByComponent.get(e);t||(t=new Set,this._reactiveQueriesByComponent.set(e,t)),t.add(s)}this._logger.debug(`创建内部响应式查询缓存: ${n}`)}return s}executeTraditionalQuery(e,t){switch(e){case Z.ALL:{const e=this.archetypeSystem.queryArchetypes(t,"AND"),n=[];for(const t of e.archetypes)for(const e of t.entities)n.push(e);return n}case Z.ANY:{const e=this.archetypeSystem.queryArchetypes(t,"OR"),n=[];for(const t of e.archetypes)for(const e of t.entities)n.push(e);return n}case Z.NONE:{const e=this.createComponentMask(t);return this.entities.filter((t=>X.hasNone(t.componentMask,e)))}default:return[]}}notifyReactiveQueriesEntityAdded(e){if(0===this._reactiveQueries.size)return;const t=new Set;for(const n of e.components){const s=n.constructor,i=this._reactiveQueriesByComponent.get(s);if(i)for(const n of i)t.has(n)||(n.notifyEntityAdded(e),t.add(n))}}notifyReactiveQueriesEntityRemoved(e,t){if(0===this._reactiveQueries.size)return;const n=new Set;for(const s of t){const t=this._reactiveQueriesByComponent.get(s);if(t)for(const s of t)n.has(s)||(s.notifyEntityRemoved(e),n.add(s))}}notifyReactiveQueriesEntityRemovedFallback(e){if(0!==this._reactiveQueries.size)for(const t of this._reactiveQueries.values())t.notifyEntityRemoved(e)}notifyReactiveQueriesEntityChanged(e){if(0===this._reactiveQueries.size)return;const t=new Set;for(const n of e.components){const s=n.constructor,i=this._reactiveQueriesByComponent.get(s);if(i)for(const n of i)t.has(n)||(n.notifyEntityChanged(e),t.add(n))}for(const n of this._reactiveQueries.values())t.has(n)||n.notifyEntityChanged(e)}}class we{constructor(e){this._logger=R("QueryBuilder"),this.conditions=[],this.querySystem=e}withAll(...e){return this.conditions.push({type:Z.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this}withAny(...e){return this.conditions.push({type:Z.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this}without(...e){return this.conditions.push({type:Z.NONE,componentTypes:e,mask:this.createComponentMask(e)}),this}execute(){const e=performance.now();if(1===this.conditions.length){const e=this.conditions[0];switch(e.type){case Z.ALL:return this.querySystem.queryAll(...e.componentTypes);case Z.ANY:return this.querySystem.queryAny(...e.componentTypes);case Z.NONE:return this.querySystem.queryNone(...e.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-e,fromCache:!1}}createComponentMask(e){let t=X.clone(X.ZERO);for(const n of e)try{const e=te.getBitMask(n);X.orInPlace(t,e)}catch(e){this._logger.warn(`组件类型 ${b(n)} 未注册,跳过`)}return t}reset(){return this.conditions=[],this}}class Te{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(e,t,n={}){return this.addListener(e,t,n)}once(e,t,n={}){return this.addListener(e,t,{...n,once:!0})}onAsync(e,t,n={}){return this.addListener(e,t,{...n,async:!0})}off(e,t){const n=this.listeners.get(e);if(!n)return!1;const s=n.findIndex((e=>e.id===t));return-1!==s&&(n.splice(s,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)}offAll(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)}async emit(e,t){if(!this.isEnabled)return;const n=this.batchConfigs.get(e);n?.enabled?this.addToBatch(e,t):await this.executeEvent(e,t)}emitSync(e,t){if(!this.isEnabled)return;const n=this.listeners.get(e);if(!n||0===n.length)return;const s=performance.now(),i=[],r=this.sortListenersByPriority(n);for(const n of r)if(!n.config.async)try{n.config.context?n.handler.call(n.config.context,t):n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`事件处理器执行错误 ${e}:`,t)}this.removeListeners(e,i),this.updateStats(e,performance.now()-s)}setBatchConfig(e,t){this.batchConfigs.set(e,t)}flushBatch(e){const t=this.batchQueue.get(e);if(!t||0===t.length)return;const n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}getStats(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)}resetStats(e){e?this.stats.delete(e):this.stats.clear()}setEnabled(e){this.isEnabled=e}hasListeners(e){const t=this.listeners.get(e);return!!t&&t.length>0}getListenerCount(e){const t=this.listeners.get(e);return t?t.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(e){this.maxListeners=e}addListener(e,t,n){let s=this.listeners.get(e);if(s||(s=[],this.listeners.set(e,s)),s.length>=this.maxListeners)return Te._logger.warn(`事件类型 ${e} 的监听器数量超过最大限制 (${this.maxListeners})`),"";const i="listener_"+this.nextListenerId++,r={handler:t,config:{priority:0,...n},id:i};return s.push(r),this.stats.has(e)||this.stats.set(e,this.createEmptyStats(e)),i}async executeEvent(e,t){const n=this.listeners.get(e);if(!n||0===n.length)return;const s=performance.now(),i=[],r=this.sortListenersByPriority(n),o=r.filter((e=>!e.config.async)),a=r.filter((e=>e.config.async));for(const n of o)try{n.config.context?n.handler.call(n.config.context,t):n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`同步事件处理器执行错误 ${e}:`,t)}const c=a.map((async n=>{try{n.config.context?await n.handler.call(n.config.context,t):await n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`异步事件处理器执行错误 ${e}:`,t)}}));await Promise.all(c),this.removeListeners(e,i),this.updateStats(e,performance.now()-s)}sortListenersByPriority(e){return e.slice().sort(((e,t)=>(t.config.priority||0)-(e.config.priority||0)))}removeListeners(e,t){if(0===t.length)return;const n=this.listeners.get(e);if(n){for(const e of t){const t=n.findIndex((t=>t.id===e));-1!==t&&n.splice(t,1)}0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}addToBatch(e,t){let n=this.batchQueue.get(e);n||(n=[],this.batchQueue.set(e,n)),n.push(t);const s=this.batchConfigs.get(e);if(n.length>=s.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){const t=setTimeout((()=>{this.flushBatch(e)}),s.delay);this.batchTimers.set(e,t)}}async processBatch(e,t){const n={type:e,events:t,count:t.length,timestamp:Date.now()};await this.executeEvent(`${e}:batch`,n)}clearBatch(e){this.batchQueue.delete(e);const t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))}clearAllBatches(){this.batchQueue.clear();for(const e of this.batchTimers.values())clearTimeout(e);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(e,t){let n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)}createEmptyStats(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}Te._logger=R("EventSystem"),exports.ECSEventType=void 0,(ve=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",ve.ENTITY_DESTROYED="entity:destroyed",ve.ENTITY_ENABLED="entity:enabled",ve.ENTITY_DISABLED="entity:disabled",ve.ENTITY_TAG_ADDED="entity:tag:added",ve.ENTITY_TAG_REMOVED="entity:tag:removed",ve.ENTITY_NAME_CHANGED="entity:name:changed",ve.COMPONENT_ADDED="component:added",ve.COMPONENT_REMOVED="component:removed",ve.COMPONENT_MODIFIED="component:modified",ve.COMPONENT_ENABLED="component:enabled",ve.COMPONENT_DISABLED="component:disabled",ve.SYSTEM_ADDED="system:added",ve.SYSTEM_REMOVED="system:removed",ve.SYSTEM_ENABLED="system:enabled",ve.SYSTEM_DISABLED="system:disabled",ve.SYSTEM_PROCESSING_START="system:processing:start",ve.SYSTEM_PROCESSING_END="system:processing:end",ve.SYSTEM_ERROR="system:error",ve.SCENE_CREATED="scene:created",ve.SCENE_DESTROYED="scene:destroyed",ve.SCENE_ACTIVATED="scene:activated",ve.SCENE_DEACTIVATED="scene:deactivated",ve.SCENE_PAUSED="scene:paused",ve.SCENE_RESUMED="scene:resumed",ve.QUERY_EXECUTED="query:executed",ve.QUERY_CACHE_HIT="query:cache:hit",ve.QUERY_CACHE_MISS="query:cache:miss",ve.QUERY_OPTIMIZED="query:optimized",ve.PERFORMANCE_WARNING="performance:warning",ve.PERFORMANCE_CRITICAL="performance:critical",ve.MEMORY_USAGE_HIGH="memory:usage:high",ve.FRAME_RATE_DROP="frame:rate:drop",ve.INDEX_CREATED="index:created",ve.INDEX_UPDATED="index:updated",ve.INDEX_OPTIMIZED="index:optimized",ve.ARCHETYPE_CREATED="archetype:created",ve.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",ve.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",ve.DIRTY_MARK_ADDED="dirty:mark:added",ve.DIRTY_BATCH_PROCESSED="dirty:batch:processed",ve.ERROR_OCCURRED="error:occurred",ve.WARNING_ISSUED="warning:issued",ve.FRAMEWORK_INITIALIZED="framework:initialized",ve.FRAMEWORK_SHUTDOWN="framework:shutdown",ve.DEBUG_INFO="debug:info",ve.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(Ce=exports.EventPriority||(exports.EventPriority={}))[Ce.LOWEST=0]="LOWEST",Ce[Ce.LOW=25]="LOW",Ce[Ce.NORMAL=50]="NORMAL",Ce[Ce.HIGH=75]="HIGH",Ce[Ce.HIGHEST=100]="HIGHEST",Ce[Ce.CRITICAL=200]="CRITICAL";const Ae={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}};class Me{static isValid(e){return this.validTypes.has(e)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(e){this.validTypes.add(e)}static removeCustomType(e){this.validTypes.delete(e)}}Me.validTypes=new Set([...Object.values(exports.ECSEventType),...Object.values(Ae.ENTITY),...Object.values(Ae.COMPONENT),...Object.values(Ae.SYSTEM),...Object.values(Ae.PERFORMANCE)]);class Ie{constructor(e=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new Te,this.isDebugMode=e}emit(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&Ie._logger.info(`发射事件: ${e}`,s),this.eventSystem.emitSync(e,s)}async emitAsync(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&Ie._logger.info(`发射异步事件: ${e}`,s),await this.eventSystem.emit(e,s)}on(e,t,n={}){this.validateEventType(e);const s={once:n.once||!1,priority:n.priority||exports.EventPriority.NORMAL,async:n.async||!1,context:n.context};return this.isDebugMode&&Ie._logger.info(`添加监听器: ${e}`,s),this.eventSystem.on(e,t,s)}once(e,t,n={}){return this.on(e,t,{...n,once:!0})}onAsync(e,t,n={}){return this.on(e,t,{...n,async:!0})}off(e,t){return this.isDebugMode&&Ie._logger.info(`移除监听器: ${t} 事件: ${e}`),this.eventSystem.off(e,t)}offAll(e){this.isDebugMode&&Ie._logger.info(`移除所有监听器: ${e}`),this.eventSystem.offAll(e)}hasListeners(e){return this.eventSystem.hasListeners(e)}getStats(e){const t=this.eventSystem.getStats(e);if(t instanceof Map){const e=new Map;return t.forEach(((t,n)=>{e.set(n,this.convertEventStats(t))})),e}return this.convertEventStats(t)}clear(){this.isDebugMode&&Ie._logger.info("清空所有监听器"),this.eventSystem.clear()}setEnabled(e){this.eventSystem.setEnabled(e)}setDebugMode(e){this.isDebugMode=e}setMaxListeners(e){this.eventSystem.setMaxListeners(e)}getListenerCount(e){return this.eventSystem.getListenerCount(e)}setBatchConfig(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})}flushBatch(e){this.eventSystem.flushBatch(e)}resetStats(e){this.eventSystem.resetStats(e)}emitEntityCreated(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)}emitEntityDestroyed(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)}emitComponentAdded(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)}emitComponentRemoved(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)}emitSystemAdded(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)}emitSystemRemoved(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)}emitSceneChanged(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)}emitPerformanceWarning(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)}onEntityCreated(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)}onComponentAdded(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)}onSystemError(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)}onPerformanceWarning(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)}validateEventType(e){this.isDebugMode&&(Me.isValid(e)||(Ie._logger.warn(`未知事件类型: ${e}`),Me.addCustomType(e)))}enhanceEventData(e,t){if(null==t)return{timestamp:Date.now(),eventId:`${e}_${++this.eventIdCounter}`,source:"EventBus"};const n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=`${e}_${++this.eventIdCounter}`),n.source||(n.source="EventBus"),n}convertEventStats(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}}}Ie._logger=R("EventBus");class xe{constructor(e,t){this._entities=e,this._componentTypes=t}get entities(){return this._entities}get length(){return this._entities.length}forEach(e){this._entities.forEach(e)}map(e){return this._entities.map(e)}filter(e){return new xe(this._entities.filter(e),this._componentTypes)}find(e){return this._entities.find(e)}some(e){return this._entities.some(e)}every(e){return this._entities.every(e)}get(e){return this._entities[e]}get first(){return this._entities[0]}get last(){return this._entities[this._entities.length-1]}get isEmpty(){return 0===this._entities.length}toArray(){return[...this._entities]}getComponentTypes(){return this._componentTypes}[Symbol.iterator](){return this._entities[Symbol.iterator]()}}class De{constructor(e,t,n,s,i){this._all=e||[],this._any=t||[],this._none=n||[],this._tag=s,this._name=i}withAll(...e){return new De([...this._all,...e],this._any,this._none,this._tag,this._name)}withAny(...e){return new De(this._all,[...this._any,...e],this._none,this._tag,this._name)}withNone(...e){return new De(this._all,this._any,[...this._none,...e],this._tag,this._name)}withTag(e){return new De(this._all,this._any,this._none,e,this._name)}withName(e){return new De(this._all,this._any,this._none,this._tag,e)}buildMatcher(){let e=he.complex();return this._all.length>0&&(e=e.all(...this._all)),this._any.length>0&&(e=e.any(...this._any)),this._none.length>0&&(e=e.none(...this._none)),void 0!==this._tag&&(e=e.withTag(this._tag)),void 0!==this._name&&(e=e.withName(this._name)),e}getCondition(){return{all:[...this._all],any:[...this._any],none:[...this._none],tag:this._tag,name:this._name}}getRequiredTypes(){return this._all}clone(){return new De([...this._all],[...this._any],[...this._none],this._tag,this._name)}}const ke=Symbol("SerializableMetadata"),Re=Symbol("SerializeField"),Oe=Symbol("SerializeOptions");function ze(e){return function(t,n){const s=t.constructor;let i=s[ke];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},s[ke]=i),i.fields.set(n,e||{})}}function Pe(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[ke]||null}class Ne{static serialize(e){const t=Pe(e);if(!t)return null;const n=e.constructor,s=t.options.typeId||b(n),i={};for(const[n,s]of t.fields){const r="symbol"==typeof n?n.toString():n,o=e[n];if(t.ignoredFields.has(n))continue;const a=s.serializer?s.serializer(o):this.serializeValue(o);i[s.alias||r]=a}return{type:s,version:t.options.version,data:i}}static deserialize(e,t){const n=t.get(e.type);if(!n)return console.warn(`未找到组件类型: ${e.type}`),null;const s=Pe(n);if(!s)return console.warn(`组件 ${e.type} 不可序列化`),null;const i=new n;for(const[t,n]of s.fields){const s="symbol"==typeof t?t.toString():t,r=n.alias||s,o=e.data[r];if(void 0===o)continue;const a=n.deserializer?n.deserializer(o):this.deserializeValue(o);i[t]=a}return i}static serializeComponents(e){const t=[];for(const n of e){const e=this.serialize(n);e&&t.push(e)}return t}static deserializeComponents(e,t){const n=[];for(const s of e){const e=this.deserialize(s,t);e&&n.push(e)}return n}static serializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((e=>this.serializeValue(e)));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.serializeValue(e[n]));return t}}static deserializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if("object"===t&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((e=>this.deserializeValue(e)));if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deserializeValue(e[n]));return t}return e}static validateVersion(e,t){return e.version===t}static getSerializationInfo(e){const t=Pe(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};const n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||b(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((e=>"symbol"==typeof e?e.toString():e)),ignoredFields:Array.from(t.ignoredFields).map((e=>"symbol"==typeof e?e.toString():e)),isSerializable:!0}}}class Be{static serialize(e,t=!0){const n=Ne.serializeComponents(Array.from(e.components)),s={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(s.parentId=e.parent.id),t)for(const t of e.children)s.children.push(this.serialize(t,!0));return s}static deserialize(e,t,n,s=!1,i){const r=s?e.id:n(),o=new re(e.name,r);i&&(o.scene=i),o.tag=e.tag,o.active=e.active,o.enabled=e.enabled,o.updateOrder=e.updateOrder;const a=Ne.deserializeComponents(e.components,t);for(const e of a)o.addComponent(e);for(const r of e.children){const e=this.deserialize(r,t,n,s,i);o.addChild(e)}return o}static serializeEntities(e,t=!0){const n=[];for(const s of e)s.parent&&t||n.push(this.serialize(s,t));return n}static deserializeEntities(e,t,n,s=!1,i){const r=[];for(const o of e){const e=this.deserialize(o,t,n,s,i);r.push(e)}return r}static clone(e,t,n){const s=this.serialize(e,!0);return this.deserialize(s,t,n,!1)}}var Le=Uint8Array,$e=Uint16Array,We=Int32Array,Fe=new Le([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),He=new Le([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ue=new Le([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qe=function(e,t){for(var n=new $e(31),s=0;s<31;++s)n[s]=t+=1<<e[s-1];var i=new We(n[30]);for(s=1;s<30;++s)for(var r=n[s];r<n[s+1];++r)i[r]=r-n[s]<<5|s;return{b:n,r:i}},Ge=qe(Fe,2),je=Ge.b,Qe=Ge.r;je[28]=258,Qe[258]=28;for(var Ve=qe(He,0),Ye=Ve.b,Je=Ve.r,Ze=new $e(32768),Xe=0;Xe<32768;++Xe){var Ke=(43690&Xe)>>1|(21845&Xe)<<1;Ke=(61680&(Ke=(52428&Ke)>>2|(13107&Ke)<<2))>>4|(3855&Ke)<<4,Ze[Xe]=((65280&Ke)>>8|(255&Ke)<<8)>>1}var et=function(e,t,n){for(var s=e.length,i=0,r=new $e(t);i<s;++i)e[i]&&++r[e[i]-1];var o,a=new $e(t);for(i=1;i<t;++i)a[i]=a[i-1]+r[i-1]<<1;if(n){o=new $e(1<<t);var c=15-t;for(i=0;i<s;++i)if(e[i])for(var h=i<<4|e[i],l=t-e[i],u=a[e[i]-1]++<<l,d=u|(1<<l)-1;u<=d;++u)o[Ze[u]>>c]=h}else for(o=new $e(s),i=0;i<s;++i)e[i]&&(o[i]=Ze[a[e[i]-1]++]>>15-e[i]);return o},tt=new Le(288);for(Xe=0;Xe<144;++Xe)tt[Xe]=8;for(Xe=144;Xe<256;++Xe)tt[Xe]=9;for(Xe=256;Xe<280;++Xe)tt[Xe]=7;for(Xe=280;Xe<288;++Xe)tt[Xe]=8;var nt=new Le(32);for(Xe=0;Xe<32;++Xe)nt[Xe]=5;var st=et(tt,9,0),it=et(tt,9,1),rt=et(nt,5,0),ot=et(nt,5,1),at=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ct=function(e,t,n){var s=t/8|0;return(e[s]|e[s+1]<<8)>>(7&t)&n},ht=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},lt=function(e){return(e+7)/8|0},ut=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new Le(e.subarray(t,n))},dt=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],pt=function(e,t,n){var s=new Error(t||dt[e]);if(s.code=e,Error.captureStackTrace&&Error.captureStackTrace(s,pt),!n)throw s;return s},mt=function(e,t,n){n<<=7&t;var s=t/8|0;e[s]|=n,e[s+1]|=n>>8},gt=function(e,t,n){n<<=7&t;var s=t/8|0;e[s]|=n,e[s+1]|=n>>8,e[s+2]|=n>>16},ft=function(e,t){for(var n=[],s=0;s<e.length;++s)e[s]&&n.push({s:s,f:e[s]});var i=n.length,r=n.slice();if(!i)return{t:bt,l:0};if(1==i){var o=new Le(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort((function(e,t){return e.f-t.f})),n.push({s:-1,f:25001});var a=n[0],c=n[1],h=0,l=1,u=2;for(n[0]={s:-1,f:a.f+c.f,l:a,r:c};l!=i-1;)a=n[n[h].f<n[u].f?h++:u++],c=n[h!=l&&n[h].f<n[u].f?h++:u++],n[l++]={s:-1,f:a.f+c.f,l:a,r:c};var d=r[0].s;for(s=1;s<i;++s)r[s].s>d&&(d=r[s].s);var p=new $e(d+1),m=yt(n[l-1],p,0);if(m>t){s=0;var g=0,f=m-t,y=1<<f;for(r.sort((function(e,t){return p[t.s]-p[e.s]||e.f-t.f}));s<i;++s){var _=r[s].s;if(!(p[_]>t))break;g+=y-(1<<m-p[_]),p[_]=t}for(g>>=f;g>0;){var S=r[s].s;p[S]<t?g-=1<<t-p[S]++-1:++s}for(;s>=0&&g;--s){var v=r[s].s;p[v]==t&&(--p[v],++g)}m=t}return{t:new Le(p),l:m}},yt=function(e,t,n){return-1==e.s?Math.max(yt(e.l,t,n+1),yt(e.r,t,n+1)):t[e.s]=n},_t=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new $e(++t),s=0,i=e[0],r=1,o=function(e){n[s++]=e},a=1;a<=t;++a)if(e[a]==i&&a!=t)++r;else{if(!i&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(i),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(i);r=1,i=e[a]}return{c:n.subarray(0,s),n:t}},St=function(e,t){for(var n=0,s=0;s<t.length;++s)n+=e[s]*t[s];return n},vt=function(e,t,n){var s=n.length,i=lt(t+2);e[i]=255&s,e[i+1]=s>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var r=0;r<s;++r)e[i+r+4]=n[r];return 8*(i+4+s)},Ct=function(e,t,n,s,i,r,o,a,c,h,l){mt(t,l++,n),++i[256];for(var u=ft(i,15),d=u.t,p=u.l,m=ft(r,15),g=m.t,f=m.l,y=_t(d),_=y.c,S=y.n,v=_t(g),C=v.c,E=v.n,b=new $e(19),w=0;w<_.length;++w)++b[31&_[w]];for(w=0;w<C.length;++w)++b[31&C[w]];for(var T=ft(b,7),A=T.t,M=T.l,I=19;I>4&&!A[Ue[I-1]];--I);var x,D,k,R,O=h+5<<3,z=St(i,tt)+St(r,nt)+o,P=St(i,d)+St(r,g)+o+14+3*I+St(b,A)+2*b[16]+3*b[17]+7*b[18];if(c>=0&&O<=z&&O<=P)return vt(t,l,e.subarray(c,c+h));if(mt(t,l,1+(P<z)),l+=2,P<z){x=et(d,p,0),D=d,k=et(g,f,0),R=g;var N=et(A,M,0);mt(t,l,S-257),mt(t,l+5,E-1),mt(t,l+10,I-4),l+=14;for(w=0;w<I;++w)mt(t,l+3*w,A[Ue[w]]);l+=3*I;for(var B=[_,C],L=0;L<2;++L){var $=B[L];for(w=0;w<$.length;++w){var W=31&$[w];mt(t,l,N[W]),l+=A[W],W>15&&(mt(t,l,$[w]>>5&127),l+=$[w]>>12)}}}else x=st,D=tt,k=rt,R=nt;for(w=0;w<a;++w){var F=s[w];if(F>255){gt(t,l,x[(W=F>>18&31)+257]),l+=D[W+257],W>7&&(mt(t,l,F>>23&31),l+=Fe[W]);var H=31&F;gt(t,l,k[H]),l+=R[H],H>3&&(gt(t,l,F>>5&8191),l+=He[H])}else gt(t,l,x[F]),l+=D[F]}return gt(t,l,x[256]),l+D[256]},Et=new We([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bt=new Le(0),wt=function(){var e=1,t=0;return{p:function(n){for(var s=e,i=t,r=0|n.length,o=0;o!=r;){for(var a=Math.min(o+2655,r);o<a;++o)i+=s+=n[o];s=(65535&s)+15*(s>>16),i=(65535&i)+15*(i>>16)}e=s,t=i},d:function(){return(255&(e%=65521))<<24|(65280&e)<<8|(255&(t%=65521))<<8|t>>8}}},Tt=function(e,t,n,s,i){if(!i&&(i={l:1},t.dictionary)){var r=t.dictionary.subarray(-32768),o=new Le(r.length+e.length);o.set(r),o.set(e,r.length),e=o,i.w=r.length}return function(e,t,n,s,i,r){var o=r.z||e.length,a=new Le(s+o+5*(1+Math.ceil(o/7e3))+i),c=a.subarray(s,a.length-i),h=r.l,l=7&(r.r||0);if(t){l&&(c[0]=r.r>>3);for(var u=Et[t-1],d=u>>13,p=8191&u,m=(1<<n)-1,g=r.p||new $e(32768),f=r.h||new $e(m+1),y=Math.ceil(n/3),_=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<_)&m},v=new We(25e3),C=new $e(288),E=new $e(32),b=0,w=0,T=r.i||0,A=0,M=r.w||0,I=0;T+2<o;++T){var x=S(T),D=32767&T,k=f[x];if(g[D]=k,f[x]=D,M<=T){var R=o-T;if((b>7e3||A>24576)&&(R>423||!h)){l=Ct(e,c,0,v,C,E,w,A,I,T-I,l),A=b=w=0,I=T;for(var O=0;O<286;++O)C[O]=0;for(O=0;O<30;++O)E[O]=0}var z=2,P=0,N=p,B=D-k&32767;if(R>2&&x==S(T-B))for(var L=Math.min(d,R)-1,$=Math.min(32767,T),W=Math.min(258,R);B<=$&&--N&&D!=k;){if(e[T+z]==e[T+z-B]){for(var F=0;F<W&&e[T+F]==e[T+F-B];++F);if(F>z){if(z=F,P=B,F>L)break;var H=Math.min(B,F-2),U=0;for(O=0;O<H;++O){var q=T-B+O&32767,G=q-g[q]&32767;G>U&&(U=G,k=q)}}}B+=(D=k)-(k=g[D])&32767}if(P){v[A++]=268435456|Qe[z]<<18|Je[P];var j=31&Qe[z],Q=31&Je[P];w+=Fe[j]+He[Q],++C[257+j],++E[Q],M=T+z,++b}else v[A++]=e[T],++C[e[T]]}}for(T=Math.max(T,M);T<o;++T)v[A++]=e[T],++C[e[T]];l=Ct(e,c,h,v,C,E,w,A,I,T-I,l),h||(r.r=7&l|c[l/8|0]<<3,l-=7,r.h=f,r.p=g,r.i=T,r.w=M)}else{for(T=r.w||0;T<o+h;T+=65535){var V=T+65535;V>=o&&(c[l/8|0]=h,V=o),l=vt(c,l+1,e.subarray(T,V))}r.i=o}return ut(a,0,s+lt(l)+i)}(e,null==t.level?6:t.level,null==t.mem?i.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,n,s,i)},At=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Mt(e,t){t||(t={});var n=wt();n.p(e);var s=Tt(e,t,t.dictionary?6:2,4);return function(e,t){var n=t.level,s=0==n?0:n<6?1:9==n?3:2;if(e[0]=120,e[1]=s<<6|(t.dictionary&&32),e[1]|=31-(e[0]<<8|e[1])%31,t.dictionary){var i=wt();i.p(t.dictionary),At(e,2,i.d())}}(s,t),At(s,s.length-4,n.d()),s}function It(e,t){return function(e,t,n,s){var i=e.length;if(!i||t.f&&!t.l)return n||new Le(0);var r=!n,o=r||2!=t.i,a=t.i;r&&(n=new Le(3*i));var c=function(e){var t=n.length;if(e>t){var s=new Le(Math.max(2*t,e));s.set(n),n=s}},h=t.f||0,l=t.p||0,u=t.b||0,d=t.l,p=t.d,m=t.m,g=t.n,f=8*i;do{if(!d){h=ct(e,l,1);var y=ct(e,l+1,3);if(l+=3,!y){var _=e[(x=lt(l)+4)-4]|e[x-3]<<8,S=x+_;if(S>i){a&&pt(0);break}o&&c(u+_),n.set(e.subarray(x,S),u),t.b=u+=_,t.p=l=8*S,t.f=h;continue}if(1==y)d=it,p=ot,m=9,g=5;else if(2==y){var v=ct(e,l,31)+257,C=ct(e,l+10,15)+4,E=v+ct(e,l+5,31)+1;l+=14;for(var b=new Le(E),w=new Le(19),T=0;T<C;++T)w[Ue[T]]=ct(e,l+3*T,7);l+=3*C;var A=at(w),M=(1<<A)-1,I=et(w,A,1);for(T=0;T<E;){var x,D=I[ct(e,l,M)];if(l+=15&D,(x=D>>4)<16)b[T++]=x;else{var k=0,R=0;for(16==x?(R=3+ct(e,l,3),l+=2,k=b[T-1]):17==x?(R=3+ct(e,l,7),l+=3):18==x&&(R=11+ct(e,l,127),l+=7);R--;)b[T++]=k}}var O=b.subarray(0,v),z=b.subarray(v);m=at(O),g=at(z),d=et(O,m,1),p=et(z,g,1)}else pt(1);if(l>f){a&&pt(0);break}}o&&c(u+131072);for(var P=(1<<m)-1,N=(1<<g)-1,B=l;;B=l){var L=(k=d[ht(e,l)&P])>>4;if((l+=15&k)>f){a&&pt(0);break}if(k||pt(2),L<256)n[u++]=L;else{if(256==L){B=l,d=null;break}var $=L-254;if(L>264){var W=Fe[T=L-257];$=ct(e,l,(1<<W)-1)+je[T],l+=W}var F=p[ht(e,l)&N],H=F>>4;if(F||pt(3),l+=15&F,z=Ye[H],H>3&&(W=He[H],z+=ht(e,l)&(1<<W)-1,l+=W),l>f){a&&pt(0);break}o&&c(u+131072);var U=u+$;if(u<z){var q=0-z,G=Math.min(z,U);for(q+u<0&&pt(3);u<G;++u)n[u]=s[q+u]}for(;u<U;++u)n[u]=n[u-z]}}t.l=d,t.p=B,t.b=u,t.f=h,d&&(h=1,t.m=m,t.d=p,t.n=g)}while(!h);return u!=n.length&&r?ut(n,0,u):n.subarray(0,u)}(e.subarray(((8!=(15&(n=e)[0])||n[0]>>4>7||(n[0]<<8|n[1])%31)&&pt(6,"invalid zlib data"),1==(n[1]>>5&1)&&pt(6,"invalid zlib data: "+(32&n[1]?"need":"unexpected")+" dictionary"),2+(n[1]>>3&4)),-4),{i:2},t,t);var n}var xt="undefined"!=typeof TextEncoder&&new TextEncoder,Dt="undefined"!=typeof TextDecoder&&new TextDecoder;try{Dt.decode(bt,{stream:!0})}catch(e){}var kt;function Rt(e,t){if(Dt)return Dt.decode(e);var n=function(e){for(var t="",n=0;;){var s=e[n++],i=(s>127)+(s>223)+(s>239);if(n+i>e.length)return{s:t,r:ut(e,n-1)};i?3==i?(s=((15&s)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|s>>10,56320|1023&s)):t+=1&i?String.fromCharCode((31&s)<<6|63&e[n++]):String.fromCharCode((15&s)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(s)}}(e),s=n.s;return n.r.length&&pt(8),s}class Ot{static encode(e){const t=function(e,t){if(xt)return xt.encode(e);for(var n=e.length,s=new Le(e.length+(e.length>>1)),i=0,r=function(e){s[i++]=e},o=0;o<n;++o){if(i+5>s.length){var a=new Le(i+8+(n-o<<1));a.set(s),s=a}var c=e.charCodeAt(o);c<128||t?r(c):c<2048?(r(192|c>>6),r(128|63&c)):c>55295&&c<57344?(r(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++o))>>18),r(128|c>>12&63),r(128|c>>6&63),r(128|63&c)):(r(224|c>>12),r(128|c>>6&63),r(128|63&c))}return ut(s,0,i)}(JSON.stringify(e));return Mt(t)}static decode(e){const t=Rt(It(e));return JSON.parse(t)}}class zt{static serialize(e,t){const n={systems:!1,format:"json",pretty:!0,includeMetadata:!0,...t},s=this.filterEntities(e,n),i=Be.serializeEntities(s,!0),r=this.buildComponentTypeRegistry(s),o=this.serializeSceneData(e.sceneData),a={name:e.name,version:this.SERIALIZATION_VERSION,entities:i,componentTypeRegistry:r};return o&&Object.keys(o).length>0&&(a.sceneData=o),n.includeMetadata&&(a.timestamp=Date.now(),a.metadata={entityCount:i.length,componentTypeCount:r.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(a,null,2):JSON.stringify(a):Ot.encode(a)}static deserialize(e,t,n){const s={strategy:"replace",preserveIds:!1,...n};let i;try{i="string"==typeof t?JSON.parse(t):Ot.decode(t)}catch(e){throw new Error(`Failed to parse save data: ${e}`)}s.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=s.migration(i.version,this.SERIALIZATION_VERSION,i));const r=s.componentRegistry||this.getGlobalComponentRegistry();"replace"===s.strategy&&e.destroyAllEntities();const o=Be.deserializeEntities(i.entities,r,(()=>e.identifierPool.checkOut()),s.preserveIds||!1,e);for(const t of o)e.addEntity(t,!0),this.addChildrenRecursively(t,e);e.querySystem.clearCache(),e.clearSystemEntityCaches(),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData)}static addChildrenRecursively(e,t){for(const n of e.children)t.addEntity(n,!0),this.addChildrenRecursively(n,t)}static serializeSceneData(e){const t={};for(const[n,s]of e)t[n]=this.serializeValue(s);return t}static deserializeSceneData(e,t){t.clear();for(const[n,s]of Object.entries(e))t.set(n,this.deserializeValue(s))}static serializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((e=>this.serializeValue(e)));if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.serializeValue(e[n]));return t}}static deserializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if("object"===t&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((e=>this.deserializeValue(e)));if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deserializeValue(e[n]));return t}return e}static filterEntities(e,t){const n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){const e=new Set(t.components);return n.filter((t=>Array.from(t.components).some((t=>e.has(t.constructor)))))}return n}static buildComponentTypeRegistry(e){const t=new Map;for(const n of e)for(const e of n.components){const n=b(e.constructor),s=Pe(e);s&&!t.has(n)&&t.set(n,s.options.version)}return Array.from(t.entries()).map((([e,t])=>({typeName:e,version:t})))}static getGlobalComponentRegistry(){return te.getAllComponentNames()}static validate(e){const t=[];try{const n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,errors:t.length>0?t:void 0}}catch(e){return{valid:!1,errors:[`JSON parse error: ${e}`]}}}static getInfo(e){try{const t=JSON.parse(e);return{name:t.name,version:t.version,timestamp:t.timestamp,entityCount:t.metadata?.entityCount||t.entities.length,componentTypeCount:t.componentTypeRegistry.length}}catch(e){return null}}}zt.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(kt=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",kt.EntityRemoved="entity_removed",kt.EntityUpdated="entity_updated",kt.ComponentAdded="component_added",kt.ComponentRemoved="component_removed",kt.ComponentUpdated="component_updated",kt.SceneDataUpdated="scene_data_updated";class Pt{static createSnapshot(e,t){const n={deepComponentComparison:!0,trackSceneData:!0,...t},s={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map};for(const t of e.entities.buffer)if(s.entityIds.add(t.id),s.entities.set(t.id,{name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,parentId:t.parent?.id}),n.deepComponentComparison){const e=new Map;for(const n of t.components){const t=Ne.serialize(n);t&&e.set(t.type,JSON.stringify(t.data))}e.size>0&&s.components.set(t.id,e)}if(n.trackSceneData)for(const[t,n]of e.sceneData)s.sceneData.set(t,JSON.stringify(n));return s}static computeIncremental(e,t,n){const s={deepComponentComparison:!0,trackSceneData:!0,...n},i={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},r=new Set;for(const n of e.entities.buffer)if(r.add(n.id),t.entityIds.has(n.id)){const e=t.entities.get(n.id);(e.name!==n.name||e.tag!==n.tag||e.active!==n.active||e.enabled!==n.enabled||e.updateOrder!==n.updateOrder||e.parentId!==n.parent?.id)&&i.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:n.id,entityData:{name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,parentId:n.parent?.id}}),s.deepComponentComparison&&this.detectComponentChanges(n,t,i.componentChanges)}else{i.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:n.id,entityName:n.name,entityData:{id:n.id,name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,parentId:n.parent?.id,components:[],children:[]}});for(const e of n.components){const t=Ne.serialize(e);t&&i.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:n.id,componentType:t.type,componentData:t})}}for(const e of t.entityIds)r.has(e)||i.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:e});return s.trackSceneData&&this.detectSceneDataChanges(e,t,i.sceneDataChanges),i}static detectComponentChanges(e,t,n){const s=t.components.get(e.id),i=new Map;for(const t of e.components){const e=Ne.serialize(t);e&&i.set(e.type,e)}for(const[t,r]of i){const i=JSON.stringify(r.data);s&&s.has(t)?s.get(t)!==i&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:t,componentData:r}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:t,componentData:r})}if(s)for(const t of s.keys())i.has(t)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:t})}static detectSceneDataChanges(e,t,n){const s=new Set;for(const[i,r]of e.sceneData){s.add(i);const e=JSON.stringify(r),o=t.sceneData.get(i);o&&o===e||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:i,value:r})}for(const e of t.sceneData.keys())s.has(e)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:e,value:void 0,deleted:!0})}static applyIncremental(e,t,n){for(const n of t.entityChanges)switch(n.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,n);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,n);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,n)}for(const s of t.componentChanges)switch(s.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,s,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,s,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,s,n)}for(const n of t.sceneDataChanges)n.deleted?e.sceneData.delete(n.key):e.sceneData.set(n.key,n.value)}static applyEntityAdded(e,t){if(!t.entityData)return;const n=new re(t.entityName||"Entity",t.entityId);n.tag=t.entityData.tag||0,n.active=t.entityData.active??!0,n.enabled=t.entityData.enabled??!0,n.updateOrder=t.entityData.updateOrder||0,e.addEntity(n)}static applyEntityRemoved(e,t){const n=e.entities.findEntityById(t.entityId);n&&n.destroy()}static applyEntityUpdated(e,t){if(!t.entityData)return;const n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){const s=e.entities.findEntityById(t.entityData.parentId);s&&n.parent!==s&&(n.parent&&n.parent.removeChild(n),s.addChild(n))}else n.parent&&n.parent.removeChild(n)}static applyComponentAdded(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=Ne.deserialize(t.componentData,n);i&&s.addComponent(i)}static applyComponentRemoved(e,t,n){const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=n.get(t.componentType);i&&s.removeComponentByType(i)}static applyComponentUpdated(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=n.get(t.componentType);if(!i)return;s.removeComponentByType(i);const r=Ne.deserialize(t.componentData,n);r&&s.addComponent(r)}static serializeIncremental(e,t){const n={format:"json",pretty:!1,...t};return"binary"===n.format?Ot.encode(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}static deserializeIncremental(e){return"string"==typeof e?JSON.parse(e):Ot.decode(e)}static getIncrementalStats(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityAdded)).length,removedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityRemoved)).length,updatedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityUpdated)).length,addedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentAdded)).length,removedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentRemoved)).length,updatedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentUpdated)).length}}static resetVersion(){this.snapshotVersion=0}}Pt.snapshotVersion=0;const Nt=R("ServiceContainer");var Bt;exports.ServiceLifetime=void 0,(Bt=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",Bt.Transient="transient";class Lt{constructor(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}registerSingleton(e,t){this._services.has(e)?Nt.warn(`Service ${e.name} is already registered`):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Singleton}),Nt.debug(`Registered singleton service: ${e.name}`))}registerTransient(e,t){this._services.has(e)?Nt.warn(`Service ${e.name} is already registered`):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Transient}),Nt.debug(`Registered transient service: ${e.name}`))}registerInstance(e,t){if(this._services.has(e))Nt.warn(`Service ${e.name} is already registered`);else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),m(e)){const n=g(e),s=n?.priority??0;this._updatableServices.push({instance:t,priority:s}),this._updatableServices.sort(((e,t)=>e.priority-t.priority)),Nt.debug(`Service ${e.name} is updatable (priority: ${s}), added to update list`)}Nt.debug(`Registered service instance: ${e.name}`)}}resolve(e){const t=this._services.get(e);if(!t)throw new Error(`Service ${e.name} is not registered`);if(this._resolving.has(e)){const t=Array.from(this._resolving).map((e=>e.name)).join(" -> ");throw new Error(`Circular dependency detected: ${t} -> ${e.name}`)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{let n;if(n=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=n,m(t.type))){const s=g(t.type),i=s?.priority??0;this._updatableServices.push({instance:n,priority:i}),this._updatableServices.sort(((e,t)=>e.priority-t.priority)),Nt.debug(`Service ${e.name} is updatable (priority: ${i}), added to update list`)}return n}finally{this._resolving.delete(e)}}tryResolve(e){try{return this.resolve(e)}catch{return null}}isRegistered(e){return this._services.has(e)}unregister(e){const t=this._services.get(e);if(!t)return!1;if(t.instance){const e=this._updatableServices.findIndex((e=>e.instance===t.instance));-1!==e&&this._updatableServices.splice(e,1),t.instance.dispose()}return this._services.delete(e),Nt.debug(`Unregistered service: ${e.name}`),!0}clear(){for(const[,e]of this._services)e.instance&&e.instance.dispose();this._services.clear(),this._updatableServices=[],Nt.debug("Cleared all services")}getRegisteredServices(){return Array.from(this._services.keys())}updateAll(e){for(const{instance:t}of this._updatableServices)t.update(e)}getUpdatableCount(){return this._updatableServices.length}getAll(){const e=[];for(const t of this._services.values())t.instance&&e.push(t.instance);return e}}class $t{get systems(){const e=this._services.getAll(),t=[];for(const n of e)n instanceof le&&t.push(n);return t.sort(((e,t)=>e.updateOrder-t.updateOrder)),t}getSystem(e){return this._services.tryResolve(e)}get services(){return this._services}constructor(e){this.name="",this.sceneData=new Map,this._performanceMonitor=null,this._didSceneBegin=!1,this.entities=new ae(this),this.identifierPool=new ce,this.componentStorageManager=new se,this.querySystem=new be,this.eventSystem=new Te,this.referenceTracker=new N,this._services=new Lt,this.logger=R("Scene"),e?.name&&(this.name=e.name),re.eventBus||(re.eventBus=new Ie(!1)),re.eventBus&&re.eventBus.onComponentAdded((e=>{this.eventSystem.emitSync("component:added",e)}))}get performanceMonitor(){return this._performanceMonitor||(this._performanceMonitor=this._services.tryResolve(y)??new y),this._performanceMonitor}initialize(){}onStart(){}unload(){}begin(){this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this.unload()}update(){j.getInstance().update(),this.entities.updateLists();const e=this.systems;for(const t of e)if(t.enabled)try{t.update()}catch(e){this.logger.error(`Error in system ${t.constructor.name}.update():`,e)}for(const t of e)if(t.enabled)try{t.lateUpdate()}catch(e){this.logger.error(`Error in system ${t.constructor.name}.lateUpdate():`,e)}}createEntity(e){let t=new re(e,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)}clearSystemEntityCaches(){for(const e of this.systems)e.clearEntityCache()}addEntity(e,t=!1){return this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e}createEntities(e,t="Entity"){const n=[];for(let s=0;s<e;s++){const e=new re(`${t}_${s}`,this.identifierPool.checkOut());e.scene=this,n.push(e)}for(const e of n)this.entities.add(e);return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n}destroyEntities(e){if(0!==e.length){for(const t of e)t._isDestroyed=!0;for(const t of e)t.removeAllComponents();for(const t of e)this.entities.remove(t),this.querySystem.removeEntity(t);this.querySystem.clearCache(),this.clearSystemEntityCaches()}}destroyAllEntities(){this.entities.removeAllEntities(),this.querySystem.setEntities([])}findEntity(e){return this.entities.findEntity(e)}findEntityById(e){return this.entities.findEntityById(e)}findEntitiesByTag(e){const t=[];for(const n of this.entities.buffer)n.tag===e&&t.push(n);return t}getEntityByName(e){return this.findEntity(e)}getEntitiesByTag(e){return this.findEntitiesByTag(e)}queryAll(...e){return this.querySystem.queryAll(...e)}queryAny(...e){return this.querySystem.queryAny(...e)}queryNone(...e){return this.querySystem.queryNone(...e)}query(){return new De}addEntityProcessor(e){let t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n)){const e=this._services.resolve(n);return this.logger.debug(`System ${n.name} already registered, returning existing instance`),e}t=u(n)?d(n,this._services):new n}else if(t=e,n=t.constructor,this._services.isRegistered(n)){const e=this._services.resolve(n);return e===t?(this.logger.debug(`System ${n.name} instance already registered, returning it`),t):(this.logger.warn(`Attempting to register a different instance of ${n.name}, but type is already registered. Returning existing instance.`),e)}t.scene=this,t.setPerformanceMonitor(this.performanceMonitor);const s=E(n);return void 0!==s?.updateOrder&&t.setUpdateOrder(s.updateOrder),void 0!==s?.enabled&&(t.enabled=s.enabled),this._services.registerInstance(n,t),p(t,this._services),t.initialize(),this.logger.debug(`System ${n.name} registered and initialized`),t}registerSystems(e){const t=[];for(const n of e){const e=this.addEntityProcessor(n);t.push(e)}return t}addSystem(e){return this.addEntityProcessor(e)}removeEntityProcessor(e){const t=e.constructor;this._services.unregister(t),e.reset()}removeSystem(e){this.removeEntityProcessor(e)}getEntityProcessor(e){return this._services.tryResolve(e)}getStats(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}}getDebugInfo(){const e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((e=>({name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((e=>T(e)))}))),processors:e.map((e=>({name:A(e),updateOrder:e.updateOrder,entityCount:e._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}serialize(e){return zt.serialize(this,e)}deserialize(e,t){zt.deserialize(this,e,t)}createIncrementalSnapshot(e){this._incrementalBaseSnapshot=Pt.createSnapshot(this,e)}serializeIncremental(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Pt.computeIncremental(this,this._incrementalBaseSnapshot,e)}applyIncremental(e,t){const n="string"==typeof e||e instanceof Uint8Array?Pt.deserializeIncremental(e):e,s=t||te.getAllComponentNames();Pt.applyIncremental(this,n,s)}updateIncrementalSnapshot(e){this.createIncrementalSnapshot(e)}clearIncrementalSnapshot(){this._incrementalBaseSnapshot=void 0}hasIncrementalSnapshot(){return void 0!==this._incrementalBaseSnapshot}}class Wt{constructor(){this.scene=new $t}named(e){return this.scene.name=e,this}withEntity(e){return this.scene.addEntity(e),this}withEntityBuilder(e){const t=e(new oe(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this}withEntities(...e){for(const t of e)this.scene.addEntity(t);return this}withSystem(e){return this.scene.addSystem(e),this}withSystems(...e){for(const t of e)this.scene.addSystem(t);return this}build(){return this.scene}}class Ft{constructor(e,...t){this.component=new e(...t)}set(e,t){return this.component[e]=t,this}configure(e){return e(this.component),this}setIf(e,t,n){return e&&(this.component[t]=n),this}build(){return this.component}}class Ht{constructor(e){this.entities=e}addComponent(e){for(const t of this.entities)t.addComponent(e);return this}removeComponent(e){for(const t of this.entities)t.removeComponentByType(e);return this}setActive(e){for(const t of this.entities)t.active=e;return this}setTag(e){for(const t of this.entities)t.tag=e;return this}forEach(e){return this.entities.forEach(e),this}filter(e){return new Ht(this.entities.filter(e))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class Ut{constructor(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}createEntity(){return new oe(this.scene,this.scene.componentStorageManager)}createScene(){return new Wt}createComponent(e,...t){return new Ft(e,...t)}query(){return new we(this.querySystem)}find(...e){return this.querySystem.queryAll(...e).entities}findFirst(...e){const t=this.querySystem.queryAll(...e);return t.entities.length>0?t.entities[0]:null}findByName(e){return this.scene.findEntity(e)}findByTag(e){return this.scene.findEntitiesByTag(e)}emit(e,t){this.eventSystem.emitSync(e,t)}async emitAsync(e,t){await this.eventSystem.emit(e,t)}on(e,t){return this.eventSystem.on(e,t)}once(e,t){return this.eventSystem.once(e,t)}off(e,t){this.eventSystem.off(e,t)}batch(e){return new Ht(e)}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()}}}function qt(e,t,n){return new Ut(e,t,n)}const Gt=R("World");class jt{constructor(e={}){this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,...e},this.name=this._config.name,this._createdAt=Date.now()}createScene(e,t){if(this._scenes.has(e))throw new Error(`Scene ID '${e}' 已存在于World '${this.name}' 中`);if(this._scenes.size>=this._config.maxScenes)throw new Error(`World '${this.name}' 已达到最大Scene数量限制: ${this._config.maxScenes}`);const n=t||new $t;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),n}removeScene(e){const t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),Gt.info(`从World '${this.name}' 中移除Scene: ${e}`),!0)}getScene(e){return this._scenes.get(e)||null}getSceneIds(){return Array.from(this._scenes.keys())}getAllScenes(){return Array.from(this._scenes.values())}removeAllScenes(){const e=Array.from(this._scenes.keys());for(const t of e)this.removeScene(t);Gt.info(`从World '${this.name}' 中移除所有Scene`)}setSceneActive(e,t){const n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin&&n.begin(),Gt.debug(`在World '${this.name}' 中激活Scene: ${e}`)):(this._activeScenes.delete(e),Gt.debug(`在World '${this.name}' 中停用Scene: ${e}`)):Gt.warn(`Scene '${e}' 不存在于World '${this.name}' 中`)}isSceneActive(e){return this._activeScenes.has(e)}getActiveSceneCount(){return this._activeScenes.size}addGlobalSystem(e){return this._globalSystems.includes(e)||(this._globalSystems.push(e),e.initialize&&e.initialize(),Gt.debug(`在World '${this.name}' 中添加全局System: ${e.name}`)),e}removeGlobalSystem(e){const t=this._globalSystems.indexOf(e);return-1!==t&&(this._globalSystems.splice(t,1),e.reset&&e.reset(),Gt.debug(`从World '${this.name}' 中移除全局System: ${e.name}`),!0)}getGlobalSystem(e){for(const t of this._globalSystems)if(t instanceof e)return t;return null}start(){if(!this._isActive){this._isActive=!0;for(const e of this._globalSystems)e.initialize&&e.initialize();Gt.info(`启动World: ${this.name}`)}}stop(){if(this._isActive){for(const e of this._activeScenes)this.setSceneActive(e,!1);for(const e of this._globalSystems)e.reset&&e.reset();this._isActive=!1,Gt.info(`停止World: ${this.name}`)}}updateGlobalSystems(){if(this._isActive)for(const e of this._globalSystems)e.update&&e.update()}updateScenes(){if(this._isActive){for(const e of this._activeScenes){const t=this._scenes.get(e);t&&t.update&&t.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}}destroy(){Gt.info(`销毁World: ${this.name}`),this.stop();const e=Array.from(this._scenes.keys());for(const t of e)this.removeScene(t);for(const e of this._globalSystems)e.destroy?e.destroy():e.reset&&e.reset();this._globalSystems.length=0,this._scenes.clear(),this._activeScenes.clear()}getStatus(){return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:{...this._config},scenes:Array.from(this._scenes.keys()).map((e=>({id:e,isActive:this._activeScenes.has(e),name:this._scenes.get(e)?.name||e})))}}getStats(){const e={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}};for(const t of this._scenes.values())t.entities&&(e.totalEntities+=t.entities.count),t.systems&&(e.totalSystems+=t.systems.length);return e}shouldAutoCleanup(){const e=Date.now();for(const[t,n]of this._scenes)if(!this._activeScenes.has(t)&&n.entities&&0===n.entities.count&&e-this._createdAt>3e5)return!0;return!1}cleanup(){const e=Array.from(this._scenes.keys()),t=Date.now();for(const n of e){const e=this._scenes.get(n);e&&!this._activeScenes.has(n)&&e.entities&&0===e.entities.count&&t-this._createdAt>3e5&&(this.removeScene(n),Gt.debug(`自动清理空Scene: ${n} from World ${this.name}`))}}get isActive(){return this._isActive}get sceneCount(){return this._scenes.size}get createdAt(){return this._createdAt}}class Qt{constructor(e){this._nextScene=null,this._ecsAPI=null,this._logger=R("SceneManager"),this._performanceMonitor=null,this._defaultWorld=new jt({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}setSceneChangedCallback(e){this._onSceneChangedCallback=e}setScene(e){return this._defaultWorld.removeAllScenes(),this._performanceMonitor&&e.services.registerInstance(y,this._performanceMonitor),this._defaultWorld.createScene(Qt.DEFAULT_SCENE_ID,e),this._defaultWorld.setSceneActive(Qt.DEFAULT_SCENE_ID,!0),e.querySystem&&e.eventSystem?this._ecsAPI=qt(e,e.querySystem,e.eventSystem):this._ecsAPI=null,s.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info(`Scene changed to: ${e.name}`),e}loadScene(e){this._nextScene=e,this._logger.info(`Scheduled scene load: ${e.name}`)}get currentScene(){return this._defaultWorld.getScene(Qt.DEFAULT_SCENE_ID)}get api(){return this._ecsAPI}update(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()}destroy(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")}get hasScene(){return null!==this._defaultWorld.getScene(Qt.DEFAULT_SCENE_ID)}get hasPendingScene(){return null!==this._nextScene}dispose(){this.destroy()}}var Vt;Qt.DEFAULT_SCENE_ID="__main__",exports.DebugConfigService=class{constructor(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}setConfig(e){this._config=e}getConfig(){return this._config}isEnabled(){return this._config.enabled}dispose(){}},exports.DebugConfigService=e([c(),n("design:paramtypes",[])],exports.DebugConfigService),exports.DebugManager=class{constructor(e,t,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},this.config=n.getConfig(),this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new H,this.systemCollector=new U,this.performanceCollector=new q,this.componentCollector=new Q,this.sceneCollector=new V,this.webSocketManager=new Y(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const s=this.config.debugFrameRate||30;this.sendInterval=1e3/s,this.interceptConsole(),this.start()}start(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())}stop(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())}interceptConsole(){console.log=(...e)=>{this.sendLog("info",this.formatLogMessage(e)),this.originalConsole.log(...e)},console.debug=(...e)=>{this.sendLog("debug",this.formatLogMessage(e)),this.originalConsole.debug(...e)},console.info=(...e)=>{this.sendLog("info",this.formatLogMessage(e)),this.originalConsole.info(...e)},console.warn=(...e)=>{this.sendLog("warn",this.formatLogMessage(e)),this.originalConsole.warn(...e)},console.error=(...e)=>{this.sendLog("error",this.formatLogMessage(e)),this.originalConsole.error(...e)}}formatLogMessage(e){return e.map((e=>{if("string"==typeof e)return e;if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return this.safeStringify(e,6)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}safeStringify(e,t=6){const n=new WeakSet,s=(e,i)=>{if(null===e)return null;if(void 0===e)return;if("object"!=typeof e)return e;if(i>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){const t=e.map((e=>s(e,i+1)));return n.delete(e),t}const r={};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=s(e[t],i+1));return n.delete(e),r};return JSON.stringify(s(e,0))}sendLog(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}}updateConfig(e){this.config=e;const t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new Y(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())}update(e){if(!this.isRunning||!this.config.enabled)return;this.frameCounter++;const t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}onSceneChanged(){this.isRunning&&this.config.enabled&&this.sendDebugData()}handleMessage(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig({...this.config,...e.config});break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleExpandLazyObjectRequest(e){try{const{entityId:t,componentIndex:n,propertyPath:s,requestId:i}=e;if(void 0===t||void 0===n||!s)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});const r=this.sceneManager.currentScene,o=this.entityCollector.expandLazyObject(t,n,s,r);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,data:o})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetComponentPropertiesRequest(e){try{const{entityId:t,componentIndex:n,requestId:s}=e;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:s,error:"缺少必要参数"});const i=this.sceneManager.currentScene,r=this.entityCollector.getComponentProperties(t,n,i);this.webSocketManager.send({type:"get_component_properties_response",requestId:s,data:r})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetRawEntityListRequest(e){try{const{requestId:t}=e,n=this.sceneManager.currentScene,s=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:s})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetEntityDetailsRequest(e){try{const{entityId:t,requestId:n}=e;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});const s=this.sceneManager.currentScene,i=this.entityCollector.getEntityDetails(t,s);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:i})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleMemorySnapshotRequest(){try{const e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}}captureMemorySnapshot(){const e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,s=this.entityCollector.collectEntityDataWithMemory(n),i=n?.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},r=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=s.entitiesPerArchetype.reduce(((e,t)=>e+t.memory),0);return{timestamp:e,version:"2.0",summary:{totalEntities:s.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:i.totalMemory,systemMemory:r.totalMemory,poolMemory:o.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:s.totalEntities,archetypes:s.entitiesPerArchetype,largestEntities:s.topEntitiesByComponents},components:i,systems:r,pools:o,performance:a}}collectBaseMemoryInfo(){const e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{const t=performance;if(t.memory){const n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then((t=>{e.detailedMemory=t})).catch((()=>{}))}catch(e){}return e}collectComponentMemoryStats(e){const t=new Map;let n=0;const s=new Map;for(const t of e.buffer)if(t&&!t.destroyed&&t.components)for(const e of t.components){const t=T(e);s.set(t,(s.get(t)||0)+1)}for(const[i,r]of s.entries()){const s=this.componentCollector.calculateDetailedComponentMemory(i),o=s*r;n+=o;const a=[];let c=0;for(const t of e.buffer)if(t&&!t.destroyed&&t.components){for(const e of t.components)if(T(e)===i&&(a.push({entityId:t.id,entityName:t.name||`Entity_${t.id}`,memory:s}),c++,c>=100))break;if(c>=100)break}t.set(i,{count:r,totalMemory:o,instances:a.slice(0,10)})}const i=Array.from(t.entries()).map((([e,t])=>({typeName:e,instanceCount:t.count,totalMemory:t.totalMemory,averageMemory:t.totalMemory/t.count,percentage:n>0?t.totalMemory/n*100:0,largestInstances:t.instances.sort(((e,t)=>t.memory-e.memory)).slice(0,3)}))).sort(((e,t)=>t.totalMemory-e.totalMemory));return{totalMemory:n,componentTypes:t.size,totalInstances:Array.from(t.values()).reduce(((e,t)=>e+t.count),0),breakdown:i}}collectSystemMemoryStats(){const e=this.sceneManager.currentScene;let t=0;const n=[];try{const s=e?.systems;if(s){const e=new Map;for(const i of s){const s=A(i);let r;e.has(s)?r=e.get(s):(r=this.calculateQuickSystemSize(i),e.set(s,r)),t+=r,n.push({name:s,memory:r,enabled:!1!==i.enabled,updateOrder:i.updateOrder||0})}}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort(((e,t)=>t.memory-e.memory))}}calculateQuickSystemSize(e){if(!e||"object"!=typeof e)return 64;let t=128;try{const n=Object.keys(e);for(let s=0;s<Math.min(n.length,15);s++){const i=n[s];if("entities"===i||"scene"===i||"constructor"===i)continue;const r=e[i];t+=2*i.length,"string"==typeof r?t+=Math.min(2*r.length,100):"number"==typeof r?t+=8:"boolean"==typeof r?t+=4:Array.isArray(r)?t+=40+Math.min(8*r.length,200):"object"==typeof r&&null!==r&&(t+=64)}}catch(e){return 128}return Math.max(t,64)}collectPoolMemoryStats(){let e=0;const t=[];try{const n=j.getInstance().getPoolStats();for(const[s,i]of n.entries()){const n=i,r=32*n.maxSize;e+=r,t.push({typeName:s,maxSize:n.maxSize,currentSize:n.currentSize||0,estimatedMemory:r,utilization:n.currentSize?n.currentSize/n.maxSize*100:0})}}catch(e){}try{const n=_.getAllPoolStats();for(const[s,i]of Object.entries(n)){const n=i;e+=n.estimatedMemoryUsage,t.push({typeName:`Pool_${s}`,maxSize:n.maxSize,currentSize:n.size,estimatedMemory:n.estimatedMemoryUsage,utilization:n.size/n.maxSize*100,hitRate:100*n.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort(((e,t)=>t.estimatedMemory-e.estimatedMemory))}}collectPerformanceStats(){try{if(!this.performanceMonitor)return{enabled:!1};const e=this.performanceMonitor.getAllSystemStats(),t=this.performanceMonitor.getPerformanceWarnings();return{enabled:this.performanceMonitor.enabled??!1,systemCount:e.size,warnings:t.slice(0,10),topSystems:Array.from(e.entries()).map((e=>{const[t,n]=e;return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort(((e,t)=>t.averageTime-e.averageTime)).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}}getDebugData(){const e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:t?.name||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n}async connectWebSocket(){try{await this.webSocketManager.connect()}catch(e){}}sendDebugData(){if(this.webSocketManager.getConnectionStatus())try{const e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}}dispose(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error}},exports.DebugManager=e([c(),h(),t(0,l(Qt)),t(1,l(y)),t(2,l(exports.DebugConfigService)),n("design:paramtypes",[Qt,y,exports.DebugConfigService])],exports.DebugManager),exports.PluginState=void 0,(Vt=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Vt.Installed="installed",Vt.Failed="failed";const Yt=R("PluginManager");class Jt{constructor(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}initialize(e,t){this._core=e,this._services=t,Yt.info("PluginManager initialized")}async install(e){if(!this._core||!this._services)throw new Error("PluginManager not initialized. Call initialize() first.");if(this._plugins.has(e.name))return void Yt.warn(`Plugin ${e.name} is already installed`);e.dependencies&&e.dependencies.length>0&&this._checkDependencies(e);const t={name:e.name,version:e.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()};this._metadata.set(e.name,t);try{Yt.info(`Installing plugin: ${e.name} v${e.version}`),await e.install(this._core,this._services),this._plugins.set(e.name,e),t.state=exports.PluginState.Installed,Yt.info(`Plugin ${e.name} installed successfully`)}catch(n){throw t.state=exports.PluginState.Failed,t.error=n instanceof Error?n.message:String(n),Yt.error(`Failed to install plugin ${e.name}:`,n),n}}async uninstall(e){const t=this._plugins.get(e);if(!t)throw new Error(`Plugin ${e} is not installed`);this._checkDependents(e);try{Yt.info(`Uninstalling plugin: ${e}`),await t.uninstall(),this._plugins.delete(e),this._metadata.delete(e),Yt.info(`Plugin ${e} uninstalled successfully`)}catch(t){throw Yt.error(`Failed to uninstall plugin ${e}:`,t),t}}getPlugin(e){return this._plugins.get(e)}getMetadata(e){return this._metadata.get(e)}getAllPlugins(){return Array.from(this._plugins.values())}getAllMetadata(){return Array.from(this._metadata.values())}isInstalled(e){return this._plugins.has(e)}_checkDependencies(e){if(!e.dependencies)return;const t=[];for(const n of e.dependencies)this._plugins.has(n)||t.push(n);if(t.length>0)throw new Error(`Plugin ${e.name} has unmet dependencies: ${t.join(", ")}`)}_checkDependents(e){const t=[];for(const n of this._plugins.values())n.dependencies&&n.dependencies.includes(e)&&t.push(n.name);if(t.length>0)throw new Error(`Cannot uninstall plugin ${e}: it is required by ${t.join(", ")}`)}dispose(){const e=Array.from(this._plugins.values()).reverse();for(const t of e)try{Yt.info(`Disposing plugin: ${t.name}`),t.uninstall()}catch(e){Yt.error(`Error disposing plugin ${t.name}:`,e)}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,Yt.info("PluginManager disposed")}}const Zt=R("WorldManager");class Xt{constructor(e={}){this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config={maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1,...e},this._isRunning=!0,Zt.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}createWorld(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error(`World ID '${e}' 已存在`);if(this._worlds.size>=this._config.maxWorlds)throw new Error(`已达到最大World数量限制: ${this._config.maxWorlds}`);const n={name:e,debug:this._config.debug,...t},s=new jt(n);return this._worlds.set(e,s),s}removeWorld(e){const t=this._worlds.get(e);return!!t&&(this._activeWorlds.has(e)&&this.setWorldActive(e,!1),t.destroy(),this._worlds.delete(e),Zt.info(`移除World: ${e}`),!0)}getWorld(e){return this._worlds.get(e)||null}getWorldIds(){return Array.from(this._worlds.keys())}getAllWorlds(){return Array.from(this._worlds.values())}setWorldActive(e,t){const n=this._worlds.get(e);n?t?(this._activeWorlds.add(e),n.start(),Zt.debug(`激活World: ${e}`)):(this._activeWorlds.delete(e),n.stop(),Zt.debug(`停用World: ${e}`)):Zt.warn(`World '${e}' 不存在`)}isWorldActive(e){return this._activeWorlds.has(e)}updateAll(){if(this._isRunning)for(const e of this._activeWorlds){const t=this._worlds.get(e);t&&t.isActive&&(t.updateGlobalSystems(),t.updateScenes())}}getActiveWorlds(){const e=[];for(const t of this._activeWorlds){const n=this._worlds.get(t);n&&e.push(n)}return e}startAll(){this._isRunning=!0;for(const e of this._worlds.keys())this.setWorldActive(e,!0);Zt.info("启动所有World")}stopAll(){this._isRunning=!1;for(const e of this._activeWorlds)this.setWorldActive(e,!1);Zt.info("停止所有World")}findWorlds(e){const t=[];for(const n of this._worlds.values())e(n)&&t.push(n);return t}findWorldByName(e){for(const t of this._worlds.values())if(t.name===e)return t;return null}getStats(){const e={totalWorlds:this._worlds.size,activeWorlds:this._activeWorlds.size,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:{...this._config},worlds:[]};for(const[t,n]of this._worlds){const s=n.getStats();e.totalScenes+=s.totalSystems,e.totalEntities+=s.totalEntities,e.totalSystems+=s.totalSystems,e.worlds.push({id:t,name:n.name,isActive:this._activeWorlds.has(t),sceneCount:n.sceneCount,...s})}return e}getDetailedStatus(){return{...this.getStats(),worlds:Array.from(this._worlds.entries()).map((([e,t])=>({id:e,isActive:this._activeWorlds.has(e),status:t.getStatus()})))}}cleanup(){const e=[];for(const[t,n]of this._worlds)this.shouldCleanupWorld(n)&&e.push(t);for(const t of e)this.removeWorld(t);return e.length>0&&Zt.debug(`清理了 ${e.length} 个World`),e.length}destroy(){Zt.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();const e=Array.from(this._worlds.keys());for(const t of e)this.removeWorld(t);this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,Zt.info("WorldManager已销毁")}dispose(){this.destroy()}startCleanupTimer(){this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((()=>{this.cleanup()}),this._config.cleanupInterval),Zt.debug(`启动World清理定时器,间隔: ${this._config.cleanupInterval}ms`))}stopCleanupTimer(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Zt.debug("停止World清理定时器"))}shouldCleanupWorld(e){if(e.isActive)return!1;if(0===e.sceneCount){return Date.now()-e.createdAt>6e5}if(!e.getAllScenes().some((e=>e.entities&&e.entities.count>0))){return Date.now()-e.createdAt>6e5}return!1}get worldCount(){return this._worlds.size}get activeWorldCount(){return this._activeWorlds.size}get isRunning(){return this._isRunning}get config(){return{...this._config}}}class Kt{constructor(e={}){if(Kt._instance=this,this._config={debug:!0,enableEntitySystems:!0,...e},this._serviceContainer=new Lt,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new y,this._serviceContainer.registerInstance(y,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new S,this._serviceContainer.registerInstance(S,this._poolManager),this._sceneManager=new Qt(this._performanceMonitor),this._serviceContainer.registerInstance(Qt,this._sceneManager),this._sceneManager.setSceneChangedCallback((()=>{this._debugManager&&this._debugManager.onSceneChanged()})),this._worldManager=new Xt(this._config.worldManagerConfig),this._serviceContainer.registerInstance(Xt,this._worldManager),this._pluginManager=new Jt,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(Jt,this._pluginManager),Kt.entitySystemsEnabled=this._config.enableEntitySystems??!0,this.debug=this._config.debug??!0,this._config.debugConfig?.enabled){const e=new exports.DebugConfigService;e.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(exports.DebugConfigService,e),this._serviceContainer.registerSingleton(exports.DebugManager,(e=>d(exports.DebugManager,e))),this._debugManager=this._serviceContainer.resolve(exports.DebugManager)}this.initialize()}static get Instance(){return this._instance}static get services(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}static get worldManager(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager}static create(e=!0){if(null==this._instance){const t="boolean"==typeof e?{debug:e,enableEntitySystems:!0}:e;this._instance=new Kt(t)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance}static setScene(e){if(!this._instance)throw Kt._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(e)}static get scene(){return this._instance?this._instance._sceneManager.currentScene:null}static get ecsAPI(){return this._instance?this._instance._sceneManager.api:null}static loadScene(e){this._instance?this._instance._sceneManager.loadScene(e):Kt._logger.warn("Core实例未创建,请先调用Core.create()")}static update(e){this._instance?this._instance.updateInternal(e):Kt._logger.warn("Core实例未创建,请先调用Core.create()")}static schedule(e,t=!1,n,s){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!s)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,s)}static enableDebug(e){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(e);else{const t=new exports.DebugConfigService;t.setConfig(e),this._instance._serviceContainer.registerInstance(exports.DebugConfigService,t),this._instance._serviceContainer.registerSingleton(exports.DebugManager,(e=>d(exports.DebugManager,e))),this._instance._debugManager=this._instance._serviceContainer.resolve(exports.DebugManager)}this._instance._config.debugConfig=e}else Kt._logger.warn("Core实例未创建,请先调用Core.create()")}static disableDebug(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))}static getDebugData(){return this._instance?._debugManager?this._instance._debugManager.getDebugData():null}static get isDebugEnabled(){return this._instance?._config.debugConfig?.enabled||!1}static async installPlugin(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");await this._instance._pluginManager.install(e)}static async uninstallPlugin(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");await this._instance._pluginManager.uninstall(e)}static getPlugin(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)}static isPluginInstalled(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)}initialize(){Kt._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:Kt.entitySystemsEnabled,debugEnabled:this._config.debugConfig?.enabled||!1})}updateInternal(e){if(Kt.paused)return;const t=this._performanceMonitor.startMonitoring("Core.update");s.update(e),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(s.deltaTime);const n=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",n,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",t)}static destroy(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),Kt._logger.info("Core destroyed"),this._instance=null)}}Kt.paused=!1,Kt._instance=null,Kt._logger=R("Core");const en=R("DebugPlugin");exports.DebugPlugin=class{constructor(e){this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=e?.autoStart??!1,this.updateInterval=e?.updateInterval??1e3}async install(e,t){this.worldManager=t.resolve(Xt),en.info("ECS Debug Plugin installed"),this.autoStart&&this.start()}async uninstall(){this.stop(),this.worldManager=null,en.info("ECS Debug Plugin uninstalled")}dispose(){this.stop(),this.worldManager=null}start(){this.updateTimer?en.warn("Debug monitoring already started"):(en.info("Starting debug monitoring"),this.updateTimer=setInterval((()=>{this.logStats()}),this.updateInterval))}stop(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,en.info("Debug monitoring stopped"))}getStats(){if(!this.worldManager)throw new Error("Plugin not installed");const e=[];let t=0,n=0;const s=this.worldManager.getAllWorlds();for(const i of s)for(const s of i.getAllScenes()){const i=this.getSceneInfo(s);e.push(i),t+=i.entityCount,n+=i.systems.length}return{scenes:e,totalEntities:t,totalSystems:n,timestamp:Date.now()}}getSceneInfo(e){const t=e.entities.buffer,n=e.systems;return{name:e.name,entityCount:t.length,systems:n.map((e=>this.getSystemInfo(e))),entities:t.map((e=>this.getEntityInfo(e)))}}getSystemInfo(e){const t=e.getPerformanceStats();return{name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length,performance:t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0}}getEntityInfo(e){const t=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:t.length,components:t.map((e=>this.getComponentInfo(e)))}}getComponentInfo(e){const t=e.constructor.name,n={};for(const t of Object.keys(e))if(!t.startsWith("_")){const s=e[t];"function"!=typeof s&&(n[t]=s)}return{type:t,data:n}}queryEntities(e){if(!this.worldManager)throw new Error("Plugin not installed");const t=[],n=this.worldManager.getAllWorlds();for(const s of n)for(const n of s.getAllScenes())if(!e.sceneId||n.name===e.sceneId)for(const s of n.entities.buffer)if((void 0===e.tag||s.tag===e.tag)&&(!e.name||s.name.includes(e.name))){if(e.hasComponent){if(!s.components.some((t=>t.constructor.name===e.hasComponent)))continue}t.push(this.getEntityInfo(s))}return t}logStats(){const e=this.getStats();en.info("=== ECS Debug Stats ==="),en.info(`Total Entities: ${e.totalEntities}`),en.info(`Total Systems: ${e.totalSystems}`),en.info(`Scenes: ${e.scenes.length}`);for(const t of e.scenes){en.info(`\n[Scene: ${t.name}]`),en.info(` Entities: ${t.entityCount}`),en.info(` Systems: ${t.systems.length}`);for(const e of t.systems){const t=e.performance?` | Avg: ${e.performance.avgExecutionTime.toFixed(2)}ms, Max: ${e.performance.maxExecutionTime.toFixed(2)}ms`:"";en.info(` - ${e.name} (${e.enabled?"enabled":"disabled"}) | Entities: ${e.entityCount}${t}`)}}en.info("========================\n")}exportJSON(){const e=this.getStats();return JSON.stringify(e,null,2)}},exports.DebugPlugin=e([c(),n("design:paramtypes",[Object])],exports.DebugPlugin);class tn{constructor(e,t){this.func=e,this.context=t}}class nn{constructor(){this.entityId=null,this.id=nn._idGenerator++}onAddedToEntity(){}onRemovedFromEntity(){}}nn._idGenerator=0;class sn{constructor(){this.adapter=null,this.logger=R("PlatformManager")}static getInstance(){return sn.instance||(sn.instance=new sn),sn.instance}getAdapter(){if(!this.adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this.adapter}registerAdapter(e){this.adapter=e,this.logger.info(`平台适配器已注册: ${e.name}`,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})}hasAdapter(){return null!==this.adapter}getAdapterInfo(){return this.adapter?{name:this.adapter.name,version:this.adapter.version,config:this.adapter.getPlatformConfig()}:null}supportsFeature(e){if(!this.adapter)return!1;const t=this.adapter.getPlatformConfig();switch(e){case"worker":return this.adapter.isWorkerSupported();case"shared-array-buffer":return this.adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}}getBasicWorkerConfig(){if(!this.adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};const e=this.adapter.getPlatformConfig();return{platformSupportsWorker:this.adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this.adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}}async getFullPlatformConfig(){if(!this.adapter)throw new Error("平台适配器未注册");return"function"==typeof this.adapter.getPlatformConfigAsync?await this.adapter.getPlatformConfigAsync():this.adapter.getPlatformConfig()}}class rn{constructor(e,t=null){this.workers=[],this.taskQueue=[],this.busyWorkers=new Set,this.taskCounter=0,this.sharedBuffer=null,this.logger=R("PlatformWorkerPool"),this.sharedBuffer=t,this.workers=e;for(let n=0;n<e.length;n++){const s=e[n];s.onMessage((e=>this.handleWorkerMessage(n,e.data))),s.onError((e=>this.handleWorkerError(n,e))),t&&s.postMessage({type:"init",sharedBuffer:t})}}executeSharedBuffer(e){return new Promise(((t,n)=>{const s={id:"shared-task-"+ ++this.taskCounter,data:{...e,type:"shared"},resolve:()=>t(),reject:n};this.taskQueue.push(s),this.processQueue()}))}execute(e){return new Promise(((t,n)=>{const s={id:"task-"+ ++this.taskCounter,data:e,resolve:e=>{t(e)},reject:n};this.taskQueue.push(s),this.processQueue()}))}processQueue(){if(0!==this.taskQueue.length)for(let e=0;e<this.workers.length;e++)if(!this.busyWorkers.has(e)&&this.taskQueue.length>0){const t=this.taskQueue.shift();this.busyWorkers.add(e),this.workers[e].postMessage({id:t.id,...t.data}),this.workers[e]._currentTask=t}}handleWorkerMessage(e,t){const n=this.workers[e],s=n._currentTask;s&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?s.reject(new Error(t.error)):s.resolve(t.result),this.processQueue())}handleWorkerError(e,t){const n=this.workers[e],s=n._currentTask;s&&(this.busyWorkers.delete(e),n._currentTask=null,s.reject(new Error(t.message))),this.processQueue()}destroy(){for(const e of this.workers)e.terminate();this.workers.length=0,this.taskQueue.length=0,this.busyWorkers.clear()}}class on{static registerComponentMigration(e,t,n,s){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map);this.componentMigrations.get(e).set(t,s)}static registerSceneMigration(e,t,n){this.sceneMigrations.set(e,n)}static migrateComponent(e,t){const n=e.version;if(n===t)return e;const s=this.componentMigrations.get(e.type);if(!s)return console.warn(`No migration path found for component ${e.type}`),e;let i={...e},r=n;for(;r<t;){const t=s.get(r);if(!t){console.warn(`Missing migration from version ${r} to ${r+1} for ${e.type}`);break}i.data=t(i.data,r,r+1),r++}return i.version=r,i}static migrateScene(e,t){const n=e.version;if(n===t)return e;let s={...e},i=n;for(;i<t;){const e=this.sceneMigrations.get(i);if(!e){console.warn(`Missing scene migration from version ${i} to ${i+1}`);break}s=e(s,i,i+1),i++}return s.version=i,s=this.migrateSceneComponents(s),s}static migrateSceneComponents(e){const t={...e};return t.entities=e.entities.map((t=>({...t,components:t.components.map((t=>{const n=e.componentTypeRegistry.find((e=>e.typeName===t.type));return n&&n.version!==t.version?this.migrateComponent(t,n.version):t})),children:this.migrateEntitiesComponents(t.children,e.componentTypeRegistry)}))),t}static migrateEntitiesComponents(e,t){return e.map((e=>({...e,components:e.components.map((e=>{const n=t.find((t=>t.typeName===e.type));return n&&n.version!==e.version?this.migrateComponent(e,n.version):e})),children:this.migrateEntitiesComponents(e.children,t)})))}static clearMigrations(){this.componentMigrations.clear(),this.sceneMigrations.clear()}static getComponentMigrationPath(e){const t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort(((e,t)=>e-t)):[]}static getSceneMigrationPath(){return Array.from(this.sceneMigrations.keys()).sort(((e,t)=>e-t))}static canMigrateComponent(e,t,n){if(t===n)return!0;const s=this.componentMigrations.get(e);if(!s)return!1;for(let e=t;e<n;e++)if(!s.has(e))return!1;return!0}static canMigrateScene(e,t){if(e===t)return!0;for(let n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0}}on.componentMigrations=new Map,on.sceneMigrations=new Map;class an{constructor(e){this._entity=e}with(e){return this._entity.addComponent(e),this}withConfigured(e,t){return this._entity.addComponent(e),t(e),this}withTag(e){return this._entity.tag=e,this}withName(e){return this._entity.name=e,this}withActive(e){return this._entity.active=e,this}withEnabled(e){return this._entity.enabled=e,this}withUpdateOrder(e){return this._entity.updateOrder=e,this}withChild(e){return this._entity.addChild(e),this}build(){return this._entity}get entity(){return this._entity}}function cn(e){return"function"==typeof e&&e.prototype instanceof nn}exports.AutoTyped=function(e){return function(t,n){const s=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(s,e||{})}},exports.BinarySerializer=Ot,exports.BitMask64Utils=X,exports.Bits=de,exports.COMPONENT_TYPE_NAME=v,exports.Colors=I,exports.Component=nn,exports.ComponentDataCollector=Q,exports.ComponentPool=G,exports.ComponentPoolManager=j,exports.ComponentRegistry=te,exports.ComponentSerializer=Ne,exports.ComponentSparseSet=ge,exports.ComponentStorage=ne,exports.ConsoleLogger=x,exports.Core=Kt,exports.DeepCopy=function(e,t){const n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[v]=e,t}},exports.ECSFluentAPI=Ut,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[C]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=L,exports.EVENT_TYPES=Ae,exports.Emitter=class{constructor(){this._messageTable=new Map}addObserver(e,t,n){let s=this._messageTable.get(e);s||(s=[],this._messageTable.set(e,s)),this.hasObserver(e,t)||s.push(new tn(t,n))}removeObserver(e,t){let n=this._messageTable.get(e);if(n){let e=n.findIndex((e=>e.func==t));-1!=e&&n.splice(e,1)}}emit(e,...t){let n=this._messageTable.get(e);if(n)for(let e of n)e.func.call(e.context,...t)}hasObserver(e,t){let n=this._messageTable.get(e);return!!n&&n.some((e=>e.func===t))}removeAllObservers(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()}dispose(){this._messageTable.clear()}getEventTypeCount(){return this._messageTable.size}getObserverCount(e){const t=this._messageTable.get(e);return t?t.length:0}},exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=re,exports.EntityDataCollector=H,exports.EntityList=ae,exports.EntityProcessorList=ue,exports.EntityRef=function(){return function(e,t){const n=e.constructor;let s=n[L];s||(s={properties:new Set},n[L]=s);const i="symbol"==typeof t?t.toString():t;s.properties.add(i),Object.defineProperty(e,t,{get:function(){return W(this).get(i)||null},set:function(e){const t=W(this),n=t.get(i)||null;if(n===e)return;const s=null!==this.entityId?P(this.entityId):null;if(!s||!s.referenceTracker)return void t.set(i,e);const r=s.referenceTracker;if(n&&r.unregisterReference(n,this,i),e){if(e.scene!==s)return void B.error(`Cannot reference Entity from different Scene. Entity: ${e.name}, Scene: ${e.scene?.name||"null"}`);if(e.isDestroyed)return B.warn(`Cannot reference destroyed Entity: ${e.name}`),void t.set(i,null);r.registerReference(e,this,i)}t.set(i,e)},enumerable:!0,configurable:!0})}},exports.EntitySerializer=Be,exports.EntitySystem=le,exports.EventBus=Ie,exports.EventTypeValidator=Me,exports.Float32=function(e,t){const n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){const n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=tn,exports.GlobalEventBus=class{static getInstance(e=!1){return this.instance||(this.instance=new Ie(e)),this.instance}static reset(e=!1){return this.instance&&this.instance.clear(),this.instance=new Ie(e),this.instance}},exports.GlobalManager=class{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(e){this.setEnabled(e)}setEnabled(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}},exports.HighPrecision=function(e,t){const n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=ce,exports.IgnoreSerialization=function(){return function(e,t){const n=e.constructor;let s=n[ke];s||(s={options:{version:1},fields:new Map,ignoredFields:new Set},n[ke]=s),s.ignoredFields.add(t)}},exports.IncrementalSerializer=Pt,exports.Inject=l,exports.Injectable=c,exports.Int16=function(e,t){const n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){const n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){const n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=class extends le{constructor(e,t){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}onCheckProcessing(){return this.acc+=s.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}},exports.Logger=k,exports.LoggerManager=D,exports.Matcher=he,exports.MigrationBuilder=class{constructor(){this.fromVersion=1,this.toVersion=2}forComponent(e){return this.componentType=e,this}fromVersionToVersion(e,t){return this.fromVersion=e,this.toVersion=t,this}migrate(e){this.componentType?on.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):on.registerSceneMigration(this.fromVersion,this.toVersion,e)}},exports.NumberExtension=class{static toNumber(e){return null==e?0:Number(e)}},exports.PassiveSystem=class extends le{constructor(e){super(e)}process(e){}},exports.PerformanceDataCollector=q,exports.PerformanceMonitor=y,exports.PlatformDetector=class{static detect(){const e=[];let t,n="unknown",s=!1;return"undefined"!=typeof globalThis&&e.push("globalThis"),"undefined"!=typeof window&&e.push("window"),"undefined"!=typeof self&&e.push("self"),this.isNodeJS()?(n="nodejs",s=!0,t="NodeAdapter",e.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",s=!0,t="WeChatMiniGameAdapter",e.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",s=!0,t="ByteDanceMiniGameAdapter",e.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",s=!0,t="AlipayMiniGameAdapter",e.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",s=!0,t="BaiduMiniGameAdapter",e.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",s=!0,t="BrowserAdapter",e.push("browser")),"undefined"!=typeof Worker&&e.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&e.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&e.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&e.push("performance.now"),"undefined"!=typeof Blob&&e.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&e.push("URL.createObjectURL"),{platform:n,confident:s,features:e,adapterClass:t}}static isWeChatMiniGame(){if(void 0!==globalThis.wx){const e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1}static isByteDanceMiniGame(){if(void 0!==globalThis.tt){const e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1}static isNodeJS(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch{return!1}}static isAlipayMiniGame(){if(void 0!==globalThis.my){const e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1}static isBaiduMiniGame(){if(void 0!==globalThis.swan){const e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location}static getDetailedInfo(){const e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e}},exports.PlatformManager=sn,exports.PluginManager=Jt,exports.Pool=_,exports.PoolManager=S,exports.ProcessingSystem=class extends le{constructor(e){super(e)}process(e){this.processSystem()}},exports.QuerySystem=be,exports.ReactiveQuery=Ee,exports.ReferenceTracker=N,exports.SERIALIZABLE_METADATA=ke,exports.SERIALIZE_FIELD=Re,exports.SERIALIZE_OPTIONS=Oe,exports.SYSTEM_TYPE_NAME=C,exports.Scene=$t,exports.SceneDataCollector=V,exports.SceneManager=Qt,exports.SceneSerializer=zt,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");let n=t[ke];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[ke]=n),t}},exports.Serialize=ze,exports.SerializeArray=function(e,t){const n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){ze({serializer:e=>e instanceof Map?Array.from(e.entries()):null,deserializer:e=>Array.isArray(e)?new Map(e):new Map})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){ze({serializer:e=>e instanceof Set?Array.from(e):null,deserializer:e=>Array.isArray(e)?new Set(e):new Set})(e,t)}},exports.SerializeMap=function(e,t){const n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){const n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=Lt,exports.SoAStorage=ee,exports.SparseSet=pe,exports.SystemDataCollector=U,exports.Time=s,exports.Timer=i,exports.TypeInference=K,exports.TypeSafeEventSystem=Te,exports.TypeUtils=class{static getType(e){return e.constructor}},exports.TypedEntityBuilder=an,exports.TypedQueryBuilder=De,exports.TypedQueryResult=xe,exports.Uint16=function(e,t){const n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){const n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){const n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){const n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=h,exports.VersionMigrationManager=on,exports.WebSocketManager=Y,exports.WorkerEntitySystem=class extends le{constructor(e,t={}){super(e),this.workerPool=null,this.isProcessing=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.hasLoggedSyncMode=!1,this.platformAdapter=sn.getInstance().getAdapter();const n=t.workerCount??this.getMaxSystemWorkerCount(),s=this.getMaxSystemWorkerCount(),i=Math.min(n,s);n>s&&this.logger.warn(`请求 ${n} 个Worker,但系统最多支持 ${s} 个。实际使用 ${i} 个Worker。`),this.config={enableWorker:t.enableWorker??!0,workerCount:i,systemConfig:t.systemConfig,entitiesPerWorker:t.entitiesPerWorker,useSharedArrayBuffer:t.useSharedArrayBuffer??this.isSharedArrayBufferSupported(),entityDataSize:t.entityDataSize??this.getDefaultEntityDataSize(),maxEntities:t.maxEntities??1e4},this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())}isWorkerSupported(){return this.platformAdapter.isWorkerSupported()}isSharedArrayBufferSupported(){return this.platformAdapter.isSharedArrayBufferSupported()}getMaxSystemWorkerCount(){return this.platformAdapter.getPlatformConfig().maxWorkerCount}initializeSharedArrayBuffer(){try{if(!this.isSharedArrayBufferSupported())return this.logger.warn(`${this.systemName}: 平台不支持SharedArrayBuffer,降级到单Worker模式以保证数据处理完整性`),this.config.useSharedArrayBuffer=!1,void(this.config.workerCount=1);const e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer)),this.logger.info(`${this.systemName}: SharedArrayBuffer初始化成功 (${e} 字节)`)}catch(e){this.logger.warn(`${this.systemName}: SharedArrayBuffer初始化失败,降级到单Worker模式以保证数据处理完整性`,e),this.config.useSharedArrayBuffer=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.config.workerCount=1}}initializeWorkerPool(){try{const e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e;for(let e=0;e<this.config.workerCount;e++)try{const s=this.platformAdapter.createWorker(n,{name:`WorkerEntitySystem-${e}`});t.push(s)}catch(t){throw this.logger.error(`创建Worker ${e} 失败:`,t),t}this.workerPool=new rn(t,this.sharedBuffer)}catch(e){this.logger.error(`${this.systemName}: Worker池初始化失败`,e),this.config.enableWorker=!1}}createWorkerScript(){const e=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!e)throw new Error("无法解析workerProcess方法");const t=e[1],n=this.config.entityDataSize,s=this.getSharedArrayBufferProcessFunction?.()||null;let i="";if(s){const e=s.toString().match(/\{([\s\S]*)\}/);e&&(i=e[1])}return`\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = ${n};\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n\n try {\n // 处理SharedArrayBuffer初始化\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n // 处理SharedArrayBuffer数据\n if (type === 'shared' && sharedFloatArray) {\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null }); // SharedArrayBuffer不需要返回数据\n return;\n }\n\n // 传统处理方式\n if (entities) {\n // 定义处理函数\n function workerProcess(entities, deltaTime, systemConfig) {\n ${t}\n }\n\n // 执行处理\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n // 处理Promise返回值\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n // SharedArrayBuffer处理函数 - 由子类定义\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n\n ${i?`\n // 用户定义的处理函数\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n ${i}\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n `:""}\n }\n `}process(e){if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((()=>{this.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(`${this.systemName}: 本帧降级到传统Worker模式`),this.processWithWorker(e).finally((()=>{this.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(`${this.systemName}: Worker不可用,使用同步处理`),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(`${this.systemName}: 处理失败`,e),e}}}async processWithSharedArrayBuffer(e){if(!this.sharedFloatArray)throw new Error("SharedArrayBuffer not initialized");this.writeEntitiesToSharedBuffer(e);const t=this.createSharedArrayBufferTasks(e.length);await Promise.all(t),this.readResultsFromSharedBuffer(e)}async processWithWorker(e){const t=[];for(let n=0;n<e.length;n++)t[n]=this.extractEntityData(e[n]);const n=this.createBatches(t),i=s.deltaTime,r=n.map((e=>this.workerPool.execute({entities:e,deltaTime:i,systemConfig:this.config.systemConfig}))),o=await Promise.all(r);let a=0;for(const t of o)for(const n of t){if(a<e.length){const t=e[a];t&&n&&this.applyResult(t,n)}a++}}processSynchronously(e){const t=e.map((e=>this.extractEntityData(e))),n=s.deltaTime,i=this.workerProcess(t,n,this.config.systemConfig);i&&"function"==typeof i.then?i.then((t=>{e.forEach(((e,n)=>{this.applyResult(e,t[n])}))})):e.forEach(((e,t)=>{this.applyResult(e,i[t])}))}createBatches(e){const t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){const s=this.config.entitiesPerWorker;for(let t=0;t<e.length;t+=s){const i=Math.min(t+s,e.length);n.push(e.slice(t,i))}n.length>t&&this.logger.warn(`${this.systemName}: 创建了 ${n.length} 个批次,但只有 ${t} 个Worker。某些Worker将依次处理多个批次。`)}else{const s=Math.ceil(e.length/t);for(let i=0;i<t;i++){const t=i*s,r=Math.min(t+s,e.length);t<e.length&&n.push(e.slice(t,r))}}return n}writeEntitiesToSharedBuffer(e){if(this.sharedFloatArray)for(let t=0;t<e.length&&t<this.config.maxEntities;t++){const n=e[t],s=this.extractEntityData(n),i=t*this.config.entityDataSize;this.writeEntityToBuffer(s,i)}}createSharedArrayBufferTasks(e){const t=[];if(this.config.entitiesPerWorker){const n=this.config.entitiesPerWorker,i=Math.ceil(e/n),r=this.config.workerCount;i>r&&this.logger.warn(`${this.systemName}: 需要 ${i} 个任务处理 ${e} 个实体(每任务 ${n} 个),但只有 ${r} 个Worker。某些Worker将依次处理多个任务。`);for(let i=0;i<e;i+=n){const r=i,o=Math.min(i+n,e),a=this.workerPool.executeSharedBuffer({startIndex:r,endIndex:o,deltaTime:s.deltaTime,systemConfig:this.config.systemConfig});t.push(a)}}else{const n=Math.ceil(e/this.config.workerCount);for(let i=0;i<this.config.workerCount;i++){const r=i*n,o=Math.min(r+n,e);if(r<e){const e=this.workerPool.executeSharedBuffer({startIndex:r,endIndex:o,deltaTime:s.deltaTime,systemConfig:this.config.systemConfig});t.push(e)}}}return t}readResultsFromSharedBuffer(e){if(this.sharedFloatArray)for(let t=0;t<e.length&&t<this.config.maxEntities;t++){const n=e[t],s=t*this.config.entityDataSize,i=this.readEntityFromBuffer(s);i&&this.applyResult(n,i)}}updateConfig(e){const t={...this.config};if(void 0!==e.workerCount){const t=this.getMaxSystemWorkerCount(),n=Math.min(e.workerCount,t);e.workerCount>t&&this.logger.warn(`请求 ${e.workerCount} 个Worker,但系统最多支持 ${t} 个。实际使用 ${n} 个Worker。`),e.workerCount=n}Object.assign(this.config,e),t.useSharedArrayBuffer===this.config.useSharedArrayBuffer?t.workerCount===this.config.workerCount?(!this.config.enableWorker&&this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()):this.reinitializeWorkerPool():this.reinitializeWorkerSystem()}reinitializeWorkerSystem(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())}reinitializeWorkerPool(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()}getWorkerInfo(){let e="sync";return this.config.enableWorker&&this.workerPool&&(e=this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?"shared-buffer":"worker"),{enabled:this.config.enableWorker,workerCount:this.config.workerCount,entitiesPerWorker:this.config.entitiesPerWorker,maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:e}}onDestroy(){super.onDestroy(),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)}getLoggerName(){return A(this)}},exports.World=jt,exports.WorldManager=Xt,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new an(e)},exports.createECSAPI=qt,exports.createInstance=d,exports.createLogger=R,exports.createQuery=function(){return new De},exports.getBasicWorkerConfig=function(){return sn.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=T,exports.getComponentTypeName=b,exports.getComponents=function(e,...t){return t.map((t=>e.getComponent(t)))},exports.getCurrentAdapter=function(){return sn.getInstance().getAdapter()},exports.getEntityRefMetadata=F,exports.getFullPlatformConfig=function(){return sn.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){let s=e.getComponent(t);return s||(s=n(),e.addComponent(s)),s},exports.getSceneByEntityId=P,exports.getSerializationMetadata=Pe,exports.getSystemInstanceTypeName=A,exports.getSystemMetadata=E,exports.getSystemTypeName=w,exports.getUpdatableMetadata=g,exports.hasAdapter=function(){return sn.getInstance().hasAdapter()},exports.hasAnyComponent=function(e,...t){return t.some((t=>e.hasComponent(t)))},exports.hasComponents=function(e,...t){return t.every((t=>e.hasComponent(t)))},exports.hasEntityRef=function(e){return null!==F(e)},exports.isComponentArray=function(e){return e.every(cn)},exports.isComponentType=cn,exports.isSerializable=function(e){return null!==Pe(e)},exports.isUpdatable=m,exports.queryFor=function(e){return new De([e])},exports.queryForAll=function(...e){return new De(e)},exports.registerInjectable=function(e,t,n=!0){if(!u(t))throw new Error(`${t.name} is not marked as @Injectable(). Please add @Injectable() decorator to the class.`);const s=e=>d(t,e);n?e.registerSingleton(t,s):e.registerTransient(t,s)},exports.registerPlatformAdapter=function(e){return sn.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){const n=e.getComponent(t);if(!n)throw new Error(`Component ${t.name} not found on entity ${e.name} (id: ${e.id})`);return n},exports.resetLoggerColors=function(){D.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){D.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){D.getInstance().setGlobalColors(e)},exports.setLoggerFactory=function(e){D.getInstance().setLoggerFactory(e)},exports.supportsFeature=function(e){return sn.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){const n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){const s=e.getComponent(t);return!!s&&(Object.assign(s,n),!0)};
|
|
1
|
+
"use strict";function e(e,t,n,s){var i,r=arguments.length,o=r<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(r<3?i(o):r>3?i(t,n,o):i(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}function t(e,t){return function(n,s){t(n,s,e)}}function n(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;class s{static update(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++}static sceneChanged(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0}static checkEvery(e,t){return this.totalTime-t>=e}}s.deltaTime=0,s.unscaledDeltaTime=0,s.totalTime=0,s.unscaledTotalTime=0,s.timeScale=1,s.frameCount=0;class i{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}get isDone(){return this._isDone}get elapsedTime(){return this._elapsedTime}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+=s.deltaTime,this._isDone}initialize(e,t,n,s){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}const r=new WeakMap,o=new WeakMap,a=new WeakMap;function c(){return function(e){const t=r.get(e);r.set(e,{injectable:!0,dependencies:[],...t?.properties&&{properties:t.properties}})}}function h(e=0){return function(t){const n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error(`@Updatable() decorator requires class ${t.name} to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.`);a.set(t,{updatable:!0,priority:e})}}function l(e){return function(t,n,s){let i=o.get(t);i||(i=new Map,o.set(t,i)),i.set(s,e)}}function u(e){const t=r.get(e);return t?.injectable??!1}function d(e,t){const n=(s=e,o.get(s)||new Map);var s;const i=[],r=e.length;for(let s=0;s<r;s++){const r=n.get(s);if(r){if("string"==typeof r||"symbol"==typeof r)throw new Error(`String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for ${e.name} parameter ${s}`);i.push(t.resolve(r))}else i.push(void 0)}return new e(...i)}function p(e,t){const n=e.constructor,s=(i=n,r.get(i));var i;if(s?.properties&&0!==s.properties.size)for(const[n,i]of s.properties){const s=t.resolve(i);null!==s&&(e[n]=s)}}function m(e){const t=a.get(e);return t?.updatable??!1}function g(e){return a.get(e)}var y;exports.TimerManager=class{constructor(){this._timers=[]}update(){for(let e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))}schedule(e,t,n,s){const r=new i;return r.initialize(e,t,n,s),this._timers.push(r),r}dispose(){for(const e of this._timers)e.unload();this._timers=[]}},exports.TimerManager=e([h()],exports.TimerManager),exports.PerformanceWarningType=void 0,(y=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",y.HIGH_MEMORY_USAGE="high_memory_usage",y.HIGH_CPU_USAGE="high_cpu_usage",y.FREQUENT_GC="frequent_gc",y.LOW_FPS="low_fps",y.HIGH_ENTITY_COUNT="high_entity_count";class f{constructor(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(e){return this._isEnabled?performance.now():0}endMonitoring(e,t,n=0){if(!this._isEnabled||0===t)return;const s=performance.now(),i=s-t,r={name:e,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(e,r),this.updateStats(e,i)}updateStats(e,t){let n=this._systemStats.get(e);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(e,n)),n.totalTime+=t,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,t),n.maxTime=Math.max(n.maxTime,t),n.recentTimes.push(t),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(e){if(0===e.recentTimes.length)return;const t=e.recentTimes.reduce(((e,t)=>e+t),0)/e.recentTimes.length,n=e.recentTimes.reduce(((e,n)=>e+Math.pow(n-t,2)),0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);const s=[...e.recentTimes].sort(((e,t)=>e-t)),i=s.length;e.percentile95=s[Math.floor(.95*i)]||0,e.percentile99=s[Math.floor(.99*i)]||0}getSystemData(e){return this._systemData.get(e)}getSystemStats(e){return this._systemStats.get(e)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const e=[];e.push("=== ECS Performance Report ==="),e.push("");const t=Array.from(this._systemStats.entries()).sort(((e,t)=>t[1].averageTime-e[1].averageTime));for(const[n,s]of t){const t=this._systemData.get(n);e.push(`System: ${n}`),e.push(` Current: ${t?.executionTime.toFixed(2)}ms (${t?.entityCount} entities)`),e.push(` Average: ${s.averageTime.toFixed(2)}ms`),e.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),e.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),t?.averageTimePerEntity&&t.averageTimePerEntity>0&&e.push(` Per Entity: ${t.averageTimePerEntity.toFixed(4)}ms`),e.push("")}const n=Array.from(this._systemData.values()).reduce(((e,t)=>e+t.executionTime),0);return e.push(`Total Frame Time: ${n.toFixed(2)}ms`),e.push(`Systems Count: ${this._systemData.size}`),e.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(e){this._systemData.delete(e),this._systemStats.delete(e)}getPerformanceWarnings(e=16.67){const t=[];for(const[n,s]of this._systemData.entries())s.executionTime>e&&t.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${e}ms)`);return t}setMaxRecentSamples(e){this._maxRecentSamples=e;for(const t of this._systemStats.values())for(;t.recentTimes.length>e;)t.recentTimes.shift()}dispose(){this._systemData.clear(),this._systemStats.clear(),this._isEnabled=!1}}class _{constructor(e,t=100,n=1024){this._objects=[],this._createFn=e,this._maxSize=t,this._objectSize=n,this._stats={size:0,maxSize:t,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(e,t=100,n=1024){let s=this._pools.get(e);return s||(s=new _((()=>new e),t,n),this._pools.set(e,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const e of this._objects)e.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(e){const t=e??Math.floor(this._objects.length/2);for(;this._objects.length>t;){const e=this._objects.pop();e&&(e.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(e){const t=Math.min(e,this._maxSize-this._objects.length);for(let e=0;e<t;e++){const e=this._createFn();e.reset(),this._objects.push(e),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)}getAvailableCount(){return this._objects.length}isEmpty(){return 0===this._objects.length}isFull(){return this._objects.length>=this._maxSize}static getAllPoolTypes(){return Array.from(this._pools.keys())}static getAllPoolStats(){const e={};for(const[t,n]of this._pools){e[t.name||t.toString()]=n.getStats()}return e}static compactAllPools(){for(const e of this._pools.values())e.compact()}static clearAllPools(){for(const e of this._pools.values())e.clear();this._pools.clear()}static getGlobalStatsString(){const e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(const[n,s]of Object.entries(e))t.push(`${n}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Total Created: ${s.totalCreated}`),t.push(` Total Obtained: ${s.totalObtained}`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");return t.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}_._pools=new Map;class S{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}registerPool(e,t){this.pools.set(e,t)}getPool(e){return this.pools.get(e)||null}update(){const e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)}createPool(e,t,n=100,s=1024){let i=this.pools.get(e);return i||(i=new _(t,n,s),this.pools.set(e,i)),i}removePool(e){const t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const e of this.pools.values())e.compact()}clearAllPools(){for(const e of this.pools.values())e.clear()}getAllStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,n.getStats());return e}getGlobalStats(){let e=0,t=0,n=0,s=0,i=0,r=0;for(const o of this.pools.values()){const a=o.getStats();e+=a.size,t+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,r+=a.estimatedMemoryUsage}return{size:e,maxSize:t,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:r}}getStatsString(){const e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");const t=this.getGlobalStats();e.push(`Total Pools: ${this.pools.size}`),e.push(`Global Hit Rate: ${(100*t.hitRate).toFixed(1)}%`),e.push(`Global Memory Usage: ${(t.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");for(const[t,n]of this.pools){const s=n.getStats();e.push(`${t}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("")}return e.join("\n")}setAutoCompactInterval(e){this.autoCompactInterval=e}prewarmAllPools(){for(const e of this.pools.values()){const t=e.getStats(),n=Math.floor(.2*t.maxSize);e.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}dispose(){this.reset()}}const C=Symbol("ComponentTypeName"),v=Symbol("SystemTypeName");function E(e){return e.__systemMetadata__}function b(e){const t=e[C];return t||(e.name||"UnknownComponent")}function T(e){const t=e[v];return t||(e.name||"UnknownSystem")}function w(e){return b(e.constructor)}function A(e){return T(e.constructor)}const M="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||class{constructor(e){this._target=e}deref(){return this._target}},I=new Map;function x(e){const t=I.get(e);return t?.deref()||null}class D{constructor(){this._references=new Map}registerReference(e,t,n){const s=e.id;let i=this._references.get(s);i||(i=new Set,this._references.set(s,i));this._findRecord(i,t,n)||i.add({component:new M(t),propertyKey:n})}unregisterReference(e,t,n){const s=e.id,i=this._references.get(s);if(!i)return;const r=this._findRecord(i,t,n);r&&(i.delete(r),0===i.size&&this._references.delete(s))}clearReferencesTo(e){const t=this._references.get(e);if(!t)return;const n=[];for(const e of t){e.component.deref()&&n.push(e)}for(const e of n){const t=e.component.deref();t&&(t[e.propertyKey]=null)}this._references.delete(e)}clearComponentReferences(e){for(const[t,n]of this._references.entries()){const s=[];for(const t of n){const n=t.component.deref();n&&n!==e||s.push(t)}for(const e of s)n.delete(e);0===n.size&&this._references.delete(t)}}getReferencesTo(e){const t=this._references.get(e);if(!t)return[];const n=[];for(const e of t){e.component.deref()&&n.push(e)}return n}cleanup(){const e=[];for(const[t,n]of this._references.entries()){const s=[];for(const e of n)e.component.deref()||s.push(e);for(const e of s)n.delete(e);0===n.size&&e.push(t)}for(const t of e)this._references.delete(t)}registerEntityScene(e,t){I.set(e,new M(t))}unregisterEntityScene(e){I.delete(e)}getDebugInfo(){const e={};for(const[t,n]of this._references.entries()){const s=[];for(const e of n){const t=e.component.deref();t&&s.push({componentId:t.id,propertyKey:e.propertyKey})}s.length>0&&(e[`entity_${t}`]=s)}return e}_findRecord(e,t,n){for(const s of e){if(s.component.deref()===t&&s.propertyKey===n)return s}}}var k;exports.LogLevel=void 0,(k=exports.LogLevel||(exports.LogLevel={}))[k.Debug=0]="Debug",k[k.Info=1]="Info",k[k.Warn=2]="Warn",k[k.Error=3]="Error",k[k.Fatal=4]="Fatal",k[k.None=5]="None";const R={BLACK:"[30m",RED:"[31m",GREEN:"[32m",YELLOW:"[33m",BLUE:"[34m",MAGENTA:"[35m",CYAN:"[36m",WHITE:"[37m",BRIGHT_BLACK:"[90m",BRIGHT_RED:"[91m",BRIGHT_GREEN:"[92m",BRIGHT_YELLOW:"[93m",BRIGHT_BLUE:"[94m",BRIGHT_MAGENTA:"[95m",BRIGHT_CYAN:"[96m",BRIGHT_WHITE:"[97m",RESET:"[0m",BOLD:"[1m",UNDERLINE:"[4m"};class O{constructor(e={}){this._config={level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...e}}debug(e,...t){this.log(exports.LogLevel.Debug,e,...t)}info(e,...t){this.log(exports.LogLevel.Info,e,...t)}warn(e,...t){this.log(exports.LogLevel.Warn,e,...t)}error(e,...t){this.log(exports.LogLevel.Error,e,...t)}fatal(e,...t){this.log(exports.LogLevel.Fatal,e,...t)}setLevel(e){this._config.level=e}setColors(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors={...this._config.colors,...e}}setPrefix(e){this._config.prefix=e}log(e,t,...n){if(e<this._config.level)return;let s=t;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${exports.LogLevel[e].toUpperCase()}] ${s}`,this._config.output?this._config.output(e,s):this.outputToConsole(e,s,...n)}outputToConsole(e,t,...n){const s=this._config.enableColors?this.getColors():null;switch(e){case exports.LogLevel.Debug:s?console.debug(`${s.debug}${t}${s.reset}`,...n):console.debug(t,...n);break;case exports.LogLevel.Info:s?console.info(`${s.info}${t}${s.reset}`,...n):console.info(t,...n);break;case exports.LogLevel.Warn:s?console.warn(`${s.warn}${t}${s.reset}`,...n):console.warn(t,...n);break;case exports.LogLevel.Error:s?console.error(`${s.error}${t}${s.reset}`,...n):console.error(t,...n);break;case exports.LogLevel.Fatal:s?console.error(`${s.fatal}${t}${s.reset}`,...n):console.error(t,...n)}}getColors(){return{...{debug:R.BRIGHT_BLACK,info:R.GREEN,warn:R.YELLOW,error:R.RED,fatal:R.BRIGHT_RED,reset:R.RESET},...this._config.colors}}}class z{constructor(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info}get defaultLogger(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}createDefaultLogger(){return this._loggerFactory?this._loggerFactory():new O({level:this._defaultLevel})}static getInstance(){return z._instance||(z._instance=new z),z._instance}getLogger(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new O({prefix:e,level:this._defaultLevel})),this._loggers.get(e)):this.defaultLogger}setLogger(e,t){this._loggers.set(e,t)}setGlobalLevel(e){this._defaultLevel=e,this._defaultLogger instanceof O&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof O&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof O&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof O&&t.setColors(e)}resetColors(){this._defaultLogger instanceof O&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof O&&e.setColors({})}setLoggerFactory(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()}}const P=z.getInstance().getLogger();function N(e){return z.getInstance().getLogger(e)}const L=N("EntityRefDecorator"),B=Symbol("EntityRefMetadata"),$=Symbol("EntityRefValues");function W(e){let t=e[$];return t||(t=new Map,e[$]=t),t}function F(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[B]||null}class H{collectEntityData(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeData(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(e){if(!e)return[];const t=e.entities;return t?.buffer?t.buffer.map((e=>({id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),parentId:e.parent?.id||null,childIds:e.children?.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}))):[]}getEntityDetails(e,t){try{if(!t)return null;const n=t.entities;if(!n?.buffer)return null;const s=n.buffer.find((t=>t.id===e));if(!s)return null;const i=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t),r=this.extractComponentDetails(s.components),o=this.getSceneInfo(t);return{...i,scene:o.name,sceneName:o.name,sceneType:o.type,parentName:s.parent?.name||null,components:r||[],componentCount:s.components?.length||0,componentTypes:s.components?.map((e=>w(e)))||[]}}catch(e){return{error:`获取实体详情失败: ${e instanceof Error?e.message:String(e)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(e){let t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{const s=Object.getPrototypeOf(e)?.constructor?.name;s&&"Object"!==s&&(t=s,n=s)}}catch(e){t="场景名获取失败"}return{name:t,type:n}}collectEntityDataWithMemory(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeDataWithMemory(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:this.buildEntityHierarchyTree(t),entityDetailsMap:this.buildEntityDetailsMap(t,e)}}collectArchetypeData(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionFast(t),topEntities:this.getTopEntitiesByComponentsFast(t)}}getArchetypeDistributionFast(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>w(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);i?i.count++:t.set(s,{count:1,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:0}))).sort(((e,t)=>t.count-e.count)).slice(0,20)}getTopEntitiesByComponentsFast(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}collectArchetypeDataWithMemory(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionWithMemory(t),topEntities:this.getTopEntitiesByComponentsWithMemory(t)}}extractArchetypeStatistics(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;n.push({signature:t,count:i,memory:0}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}extractArchetypeStatisticsWithMemory(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;let r=0;if(e.entities&&e.entities.length>0){const t=Math.min(5,e.entities.length);let n=0;for(let s=0;s<t;s++)n+=this.estimateEntityMemoryUsage(e.entities[s]);r=n/t*i}n.push({signature:t,count:i,memory:r}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}getArchetypeDistributionWithMemory(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>w(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);let r=this.estimateEntityMemoryUsage(e);(isNaN(r)||r<0)&&(r=0),i?(i.count++,i.memory+=r):t.set(s,{count:1,memory:r,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:isNaN(t.memory)?0:t.memory}))).sort(((e,t)=>t.count-e.count))}getTopEntitiesByComponentsWithMemory(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}getEmptyEntityDebugData(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}calculateFallbackEntityStats(e){const t=e.buffer||[],n=t.filter((e=>e.enabled&&!e.isDestroyed));return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce(((e,t)=>e+(t.components?.length||0)),0)/n.length:0}}estimateEntityMemoryUsage(e){try{let t=0;const n=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(n)&&n>0&&(t+=n),e.components&&Array.isArray(e.components)&&e.components.forEach((e=>{const n=this.calculateObjectSize(e,["entity"]);!isNaN(n)&&n>0&&(t+=n)})),isNaN(t)||t<0?0:t}catch(e){return 0}}calculateObjectSize(e,t=[]){if(!e||"object"!=typeof e)return 0;const n=new WeakSet,s=(e,i=0)=>{if(!e||"object"!=typeof e||i>=2)return 0;if(n.has(e))return 0;n.add(e);let r=32;try{const n=Object.keys(e),o=Math.min(n.length,20);for(let a=0;a<o;a++){const o=n[a];if(!o||t.includes(o)||"constructor"===o||"__proto__"===o||o.startsWith("_cc_")||o.startsWith("__"))continue;const c=e[o];r+=2*o.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:Array.isArray(c)?r+=40+Math.min(8*c.length,160):"object"==typeof c&&null!==c&&(r+=s(c,i+1))}}catch(e){return 64}return r};try{const t=s(e);return Math.max(t,32)}catch(e){return 64}}buildEntityHierarchyTree(e){if(!e?.buffer)return[];const t=[];return e.buffer.forEach((e=>{if(!e.parent){const n=this.buildEntityHierarchyNode(e);t.push(n)}})),t.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:e.id-t.id)),t}buildEntityHierarchyNode(e){let t={id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),parentId:e.parent?.id||null,children:[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0};if(e.children&&e.children.length>0&&(t.children=e.children.map((e=>this.buildEntityHierarchyNode(e)))),"function"==typeof e.getDebugInfo){const n=e.getDebugInfo();t={...t,...n}}return e.components&&e.components.length>0&&(t.componentDetails=this.extractComponentDetails(e.components)),t}buildEntityDetailsMap(e,t){if(!e?.buffer)return{};const n={},s=e.buffer;for(let e=0;e<s.length;e+=100){s.slice(e,e+100).forEach((e=>{const s=e.getDebugInfo?e.getDebugInfo():this.buildFallbackEntityInfo(e,t),i=e.getComponentCacheStats?e.getComponentCacheStats():null,r=this.extractComponentDetails(e.components);n[e.id]={...s,parentName:e.parent?.name||null,components:r,componentTypes:s.componentTypes||r.map((e=>e.typeName)),cachePerformance:i?{hitRate:i.cacheStats.hitRate,size:i.cacheStats.size,maxSize:i.cacheStats.maxSize}:null}}))}return n}buildFallbackEntityInfo(e,t){const n=this.getSceneInfo(t);return{name:e.name||`Entity_${e.id}`,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:!1!==e.activeInHierarchy,destroyed:e.isDestroyed||!1,scene:n.name,sceneName:n.name,sceneType:n.type,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),componentMask:e.componentMask?.toString()||"0",parentId:e.parent?.id||null,childCount:e.children?.length||0,childIds:e.children.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}}extractComponentDetails(e){return e.map((e=>{const t=w(e),n={};try{Object.keys(e).forEach((t=>{if(!t.startsWith("_")&&"entity"!==t&&"constructor"!==t){const s=e[t];null!=s&&(n[t]=this.formatPropertyValue(s))}})),0===Object.keys(n).length&&(n._info="该组件没有公开属性",n._componentId=w(e))}catch(t){n._error="属性提取失败",n._componentId=w(e)}return{typeName:t,properties:n}}))}getComponentProperties(e,t,n){try{if(!n)return{};const s=n.entities;if(!s?.buffer)return{};const i=s.buffer.find((t=>t.id===e));if(!i||t>=i.components.length)return{};const r=i.components[t],o={};return Object.keys(r).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e){const t=r[e];null!=t&&(o[e]=this.formatPropertyValue(t))}})),o}catch(e){return{_error:"属性提取失败"}}}formatPropertyValue(e,t=0){return null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?`[长字符串: ${e.length}字符] ${e.substring(0,100)}...`:e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)}formatObjectFirstLevel(e){try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){const t=e.slice(0,3).map((e=>this.formatPropertyValue(e,1)));return{_isLazyArray:!0,_arrayLength:e.length,_sample:t,_summary:`数组[${e.length}个元素]`}}return e.map((e=>this.formatPropertyValue(e,1)))}const t=Object.keys(e);if(0===t.length)return{};const n={};let s=0;const i=15;for(const r of t){if(s>=i){n._hasMoreProperties=!0,n._totalProperties=t.length,n._hiddenCount=t.length-s;break}if(!r.startsWith("_")&&!r.startsWith("$")&&"function"!=typeof e[r])try{const t=e[r];null!=t&&(n[r]=this.formatPropertyValue(t,1),s++)}catch(e){n[r]=`[访问失败: ${e instanceof Error?e.message:String(e)}]`,s++}}return n}catch(e){return`[对象解析失败: ${e instanceof Error?e.message:String(e)}]`}}createLazyLoadPlaceholder(e){try{const t=e.constructor?.name||"Object";return{_isLazyObject:!0,_typeName:t,_summary:this.getObjectSummary(e,t),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:`无法分析的对象: ${e instanceof Error?e.message:String(e)}`,_objectId:Math.random().toString(36).substr(2,9)}}}getObjectSummary(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){const n=void 0!==e.z?e.z:"";return`${t}(${e.x}, ${e.y}${n?", "+n:""})`}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){const n=void 0!==e.a?e.a:1;return`${t}(${e.r}, ${e.g}, ${e.b}, ${n})`}if(t.toLowerCase().includes("node")){return`${t}: ${e.name||e._name||"未命名"}`}if(t.toLowerCase().includes("component")){const n=e.node?.name||e.node?._name||"";return`${t}${n?` on ${n}`:""}`}const n=Object.keys(e);return 0===n.length?`${t} (空对象)`:`${t} (${n.length}个属性)`}catch(e){return`${t} (无法分析)`}}generateObjectId(e){try{return void 0!==e.id?`obj_${e.id}`:void 0!==e._id?`obj_${e._id}`:void 0!==e.uuid?`obj_${e.uuid}`:void 0!==e._uuid?`obj_${e._uuid}`:`obj_${Math.random().toString(36).substr(2,9)}`}catch{return`obj_${Math.random().toString(36).substr(2,9)}`}}expandLazyObject(e,t,n,s){try{if(!s)return null;const i=s.entities;if(!i?.buffer)return null;const r=i.buffer.find((t=>t.id===e));if(!r)return null;if(t>=r.components.length)return null;const o=r.components[t],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:`展开失败: ${e instanceof Error?e.message:String(e)}`}}}getObjectByPath(e,t){if(!t)return e;const n=t.split(".");let s=e;for(const e of n){if(null==s)return null;if(e.includes("[")&&e.includes("]")){const t=e.substring(0,e.indexOf("[")),n=parseInt(e.substring(e.indexOf("[")+1,e.indexOf("]")));if(t&&(s=s[t]),!(Array.isArray(s)&&n>=0&&n<s.length))return null;s=s[n]}else s=s[e]}return s}}class U{collectSystemData(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};const n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};const s=n.processors||[];let i=new Map,r=new Map;if(e)try{i=e.getAllSystemStats(),r=e.getAllSystemData()}catch(e){}return{totalSystems:s.length,systemsInfo:s.map((e=>{const t=e.systemName||A(e),n=i.get(t),s=r.get(t);return{name:t,type:A(e),entityCount:e.entities?.length||0,executionTime:n?.averageTime||s?.executionTime||0,minExecutionTime:n?.minTime===Number.MAX_VALUE?0:n?.minTime||0,maxExecutionTime:n?.maxTime||0,executionTimeHistory:n?.recentTimes||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:s?.lastUpdateTime||0}}))}}}class q{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(e){const t=s.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,a=n>0?o/n*100:0;let c=0;performance.memory&&(c=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const h=this.frameTimeHistory.filter((e=>e>=0));return{frameTime:o,engineFrameTime:n,ecsPercentage:a,memoryUsage:c,fps:i,averageFrameTime:h.length>0?h.reduce(((e,t)=>e+t),0)/h.length:o,minFrameTime:h.length>0?Math.min(...h):o,maxFrameTime:h.length>0?Math.max(...h):o,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{let t=0;const n=[],s=e.getAllSystemStats();if(0===s.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[e,i]of s.entries()){const s=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;t+=s,n.push({systemName:e,executionTime:s,percentage:0})}return n.forEach((e=>{e.percentage=t>0?e.executionTime/t*100:0})),n.sort(((e,t)=>t.executionTime-e.executionTime)),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(e){if(!e)return[];try{const t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map((([e,t])=>{const s=n.get(e);return{systemName:e,averageTime:t.averageTime||0,maxTime:t.maxTime||0,minTime:t.minTime===Number.MAX_VALUE?0:t.minTime||0,samples:t.executionCount||0,percentage:0,entityCount:s?.entityCount||0,lastExecutionTime:s?.executionTime||0}}))}catch(e){return[]}}getMemoryDetails(){const e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){const t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0){this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++}this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e}updateGCCount(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}}}class G{constructor(e,t,n=1e3,s=10){this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,t&&(this.resetFn=t),this.maxSize=n,this.minSize=Math.max(1,s)}acquire(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())}release(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))}prewarm(e){const t=Math.min(e,this.maxSize);for(let e=this.pool.length;e<t;e++){const e=this.createFn();this.resetFn&&this.resetFn(e),this.pool.push(e),this.stats.totalCreated++}}shrink(){for(;this.pool.length>this.minSize;)this.pool.pop()}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}getStats(){const e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}}}class j{constructor(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}static getInstance(){return j.instance||(j.instance=new j),j.instance}registerPool(e,t,n,s,i){this.pools.set(e,new G(t,n,s,i)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})}acquireComponent(e){const t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null}releaseComponent(e,t){const n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)}trackUsage(e,t){let n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()}update(){const e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(const[t,n]of this.usageTracker.entries()){if(e-n.lastAccessTime>12e4){const e=this.pools.get(t);e&&e.shrink()}}this.lastCleanupTime=e}}getHotComponents(e=100){return Array.from(this.usageTracker.entries()).filter((([t,n])=>n.createCount>e)).map((([e])=>e))}prewarmAll(e=100){for(const t of this.pools.values())t.prewarm(e)}clearAll(){for(const e of this.pools.values())e.clear()}reset(){this.pools.clear(),this.usageTracker.clear()}getGlobalStats(){const e=[];for(const[t,n]of this.pools.entries())e.push({componentName:t,poolStats:n.getStats(),usage:this.usageTracker.get(t)});return e}getPoolStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return e}getPoolUtilization(){const e=new Map;for(const[t,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),r=i-s,o=i>0?r/i*100:0;e.set(t,{used:r,total:i,utilization:o})}return e}getComponentUtilization(e){const t=this.pools.get(e);if(!t)return 0;const n=t.getAvailableCount(),s=t.getMaxSize();return s>0?(s-n)/s*100:0}}class Q{collectComponentData(e){if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};const t=e.entities;if(!t?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const n=new Map;let s=0;t.buffer.forEach((e=>{e.components&&e.components.forEach((e=>{const t=w(e),i=n.get(t)||{count:0,entities:0};i.count++,s++,n.set(t,i)}))}));const i=new Map,r=new Map;try{const e=j.getInstance(),t=e.getPoolStats(),n=e.getPoolUtilization();for(const[e,n]of t.entries())r.set(e,n.maxSize);for(const[e,t]of n.entries())i.set(e,t.utilization)}catch(e){}return{componentTypes:n.size,componentInstances:s,componentStats:Array.from(n.entries()).map((([n,s])=>{const o=r.get(n)||0,a=i.get(n)||0,c=this.getEstimatedComponentSize(n,e);return{typeName:n,instanceCount:s.count,memoryPerInstance:c,totalMemory:s.count*c,poolSize:o,poolUtilization:a,averagePerEntity:s.count/t.buffer.length}}))}}getEstimatedComponentSize(e,t){if(Q.componentSizeCache.has(e))return Q.componentSizeCache.get(e);if(!t)return 64;const n=t.entities;if(!n?.buffer)return 64;let s=64;try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>w(t)===e));if(n){s=this.calculateQuickObjectSize(n);break}}}catch(e){s=64}return Q.componentSizeCache.set(e,s),s}calculateQuickObjectSize(e){if(!e||"object"!=typeof e)return 8;let t=32;const n=new WeakSet,s=(e,t=0)=>{if(!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);let i=0;try{const n=Object.keys(e);for(let r=0;r<Math.min(n.length,20);r++){const o=n[r];if(!o||"entity"===o||"_entity"===o||"constructor"===o)continue;const a=e[o];i+=2*o.length,"string"==typeof a?i+=Math.min(2*a.length,200):"number"==typeof a?i+=8:"boolean"==typeof a?i+=4:"object"==typeof a&&null!==a&&(i+=s(a,t+1))}}catch(e){return 32}return i};return t+=s(e),Math.max(t,32)}calculateDetailedComponentMemory(e,t){if(!t)return this.getEstimatedComponentSize(e,t);const n=t.entities;if(!n?.buffer)return this.getEstimatedComponentSize(e,t);try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>w(t)===e));if(n)return this.estimateObjectSize(n)}}catch(e){}return this.getEstimatedComponentSize(e,t)}estimateObjectSize(e,t=new WeakSet,n=0){if(null==e||n>10)return 0;if(t.has(e))return 0;let s=0;switch(typeof e){case"boolean":s=4;break;case"number":default:s=8;break;case"string":s=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){s=40+8*e.length;const i=Math.min(e.length,50);for(let r=0;r<i;r++)s+=this.estimateObjectSize(e[r],t,n+1)}else{s=32;try{const i=Object.getOwnPropertyNames(e),r=Math.min(i.length,30);for(let o=0;o<r;o++){const r=i[o];if(r&&("constructor"!==r&&"__proto__"!==r&&"entity"!==r&&"_entity"!==r&&!r.startsWith("_cc_")&&!r.startsWith("__")))try{s+=16+2*r.length;const i=e[r];null!=i&&(s+=this.estimateObjectSize(i,t,n+1))}catch(e){continue}}}catch(e){s=128}}}return 8*Math.ceil(s/8)}static clearCache(){Q.componentSizeCache.clear()}}Q.componentSizeCache=new Map;class V{constructor(){this.sceneStartTime=Date.now()}collectSceneData(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};const t=(Date.now()-this.sceneStartTime)/1e3,n=e.entities,s=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:t,sceneEntityCount:n?.buffer?.length||0,sceneSystemCount:s?.processors?.length||0,sceneMemory:0,sceneUptime:t}}setSceneStartTime(e){this.sceneStartTime=e}}class Y{constructor(e,t=!0){this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.url=e,this.autoReconnect=t}setMessageHandler(e){this.messageHandler=e}connect(){return new Promise(((e,t)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=t=>{this.handleOpen(t),e()},this.ws.onclose=e=>{this.handleClose(e)},this.ws.onerror=e=>{this.handleError(e),t(e)},this.ws.onmessage=e=>{this.handleMessage(e)}}catch(e){this.handleConnectionFailure(e),t(e)}}))}disconnect(){this.ws&&(this.autoReconnect=!1,this.ws.close(),delete this.ws),this.isConnected=!1}send(e){if(this.isConnected&&this.ws)try{const t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}}getConnectionStatus(){return this.isConnected}setMaxReconnectAttempts(e){this.maxReconnectAttempts=e}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((()=>{this.connect().catch((e=>{this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}))}),e)}handleMessage(e){try{const t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}}handleOpen(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)}handleClose(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}handleError(e){this.onError&&this.onError(e)}handleConnectionFailure(e){this.onError&&this.onError(e)}}var J,Z;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(J||(J={}));class X{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0]};return X.setBit(t,e),t}static fromNumber(e){return{base:[e>>>0,0]}}static hasAny(e,t){const n=t.base,s=e.base,i=t.segments,r=e.segments,o=0!==(s[J.LOW]&n[J.LOW])||0!==(s[J.HIGH]&n[J.HIGH]);return!o&&i&&r?r.some(((e,t)=>{const n=i[t];return n&&(0!==(e[J.LOW]&n[J.LOW])||0!==(e[J.HIGH]&n[J.HIGH]))})):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[J.LOW]&s[J.LOW])===s[J.LOW]&&(n[J.HIGH]&s[J.HIGH])===s[J.HIGH];if(!o||!r)return o;const a=i?.length??0;if(i)for(let e=0;e<Math.min(a,r.length);e++){const t=i[e],n=r[e];if((t[J.LOW]&n[J.LOW])!==n[J.LOW]||(t[J.HIGH]&n[J.HIGH])!==n[J.HIGH])return!1}for(let e=a;e<r.length;e++){const t=r[e];if(0!==t[J.LOW]||0!==t[J.HIGH])return!1}return!0}static hasNone(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=0===(n[J.LOW]&s[J.LOW])&&0===(n[J.HIGH]&s[J.HIGH]);return i&&o&&r?i.every(((e,t)=>{const n=r[t];return!n||0===(e[J.LOW]&n[J.LOW])&&0===(e[J.HIGH]&n[J.HIGH])})):o}static isZero(e){const t=0===e.base[J.LOW]&&0===e.base[J.HIGH];return e.segments&&t?e.segments.every((e=>0===e[J.LOW]&&0===e[J.HIGH])):t}static equals(e,t){const n=e.base[J.LOW]===t.base[J.LOW]&&e.base[J.HIGH]===t.base[J.HIGH];if(!n||!e.segments&&!t.segments)return n;const s=e.segments??[],i=t.segments??[];for(let e=0;e<Math.max(s.length,i.length);e++){const t=s[e],n=i[e];if(t&&!n){if(0!==t[J.LOW]||0!==t[J.HIGH])return!1}else if(!t&&n){if(0!==n[J.LOW]||0!==n[J.HIGH])return!1}else if(t&&n&&(t[J.LOW]!==n[J.LOW]||t[J.HIGH]!==n[J.HIGH]))return!1}return!0}static setBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t),s=63&t;s<32?n[J.LOW]|=1<<s:n[J.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[J.LOW]&1<<s):!!(n[J.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[J.LOW]&=~(1<<s):n[J.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[J.LOW]|=t.base[J.LOW],e.base[J.HIGH]|=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++){const s=t[e],i=n[e];s[J.LOW]|=i[J.LOW],s[J.HIGH]|=i[J.HIGH]}}}static andInPlace(e,t){e.base[J.LOW]&=t.base[J.LOW],e.base[J.HIGH]&=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++){const s=t[e],i=n[e];s[J.LOW]&=i[J.LOW],s[J.HIGH]&=i[J.HIGH]}}}static xorInPlace(e,t){e.base[J.LOW]^=t.base[J.LOW],e.base[J.HIGH]^=t.base[J.HIGH];const n=t.segments;if(!n||0==n.length)return;e.segments||(e.segments=[]);const s=e.segments;for(;s.length<n.length;)s.push([0,0]);for(let e=0;e<n.length;e++){const t=s[e],i=n[e];t[J.LOW]^=i[J.LOW],t[J.HIGH]^=i[J.HIGH]}}static clear(e){if(e.base[J.LOW]=0,e.base[J.HIGH]=0,e.segments)for(let t=0;t<e.segments.length;t++){const n=e.segments[t];n[J.LOW]=0,n[J.HIGH]=0}}static copy(e,t){if(X.clear(t),t.base[J.LOW]=e.base[J.LOW],t.base[J.HIGH]=e.base[J.HIGH],!e.segments||0==e.segments.length)return;if(!t.segments)return void(t.segments=e.segments.map((e=>[...e])));const n=e.segments.length-t.segments.length;for(let e=0;e<n;e++)t.segments.push([0,0]);const s=t.segments,i=e.segments;for(let e=0;e<i.length;e++){const t=s[e],n=i[e];t[J.LOW]=n[J.LOW],t[J.HIGH]=n[J.HIGH]}}static clone(e){return{base:e.base.slice(),...e.segments&&{segments:e.segments.map((e=>[...e]))}}}static toString(e,t=2,n=!1){2!=t&&16!=t&&(t=2);const s=e.segments?.length??0;let i="";if(n){let e=0;e=2===t?66:19;for(let t=0;t<=s;t++){i+=(0===t?"0 (Base):":`${t} (${64*t}):`).toString().padEnd(e)}i+="\n"}for(let r=-1;r<s;r++){let s="";const o=-1==r?e.base:e.segments[r],a=o[J.HIGH],c=o[J.LOW];if(2==t){s=a.toString(2).padStart(32,"0")+"_"+c.toString(2).padStart(32,"0")}else{let e=a?a.toString(16).toUpperCase():"";n&&(e=e.padStart(8,"0"));let t=c.toString(16).toUpperCase();e&&(t=t.padStart(8,"0")),s="0x"+e+t}i+=-1===r?s:" "+s}return i}static popCount(e){let t=0;for(let n=-1;n<(e.segments?.length??0);n++){const s=-1==n?e.base:e.segments[n];let i=s[J.LOW],r=s[J.HIGH];for(;i;)i&=i-1,t++;for(;r;)r&=r-1,t++}return t}static getSegmentByBitIndex(e,t,n=!0){if(t<=63)return e.base;{let s=e.segments;if(!s){if(!n)return null;s=e.segments=[]}const i=(t>>6)-1;if(s.length<=i){if(!n)return null;const e=i-s.length+1;for(let t=0;t<e;t++)s.push([0,0])}return s[i]??null}}}X.ZERO={base:[0,0]};class K{static inferOptimalType(e,t={}){const n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";const{minValue:s,maxValue:i,precision:r,signed:o}=t;if(!0===r)return Math.abs(e)>34028235e31||void 0!==s&&Math.abs(s)>34028235e31||void 0!==i&&Math.abs(i)>34028235e31?"float64":"float32";if(!1===r||Number.isInteger(e)){const t=void 0!==s?s:e,n=void 0!==i?i:e;return!1!==o&&(t<0||e<0)?t>=-128&&n<=127?"int8":t>=-32768&&n<=32767?"int16":t>=-2147483648&&n<=2147483647?"int32":"float64":n<=255?"uint8":n<=65535?"uint16":n<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"}static getTypedArrayConstructor(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}}}class ee{constructor(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}initializeFields(e){const t=new e,n=e.__highPrecisionFields||new Set,s=e.__float64Fields||new Set,i=e.__float32Fields||new Set,r=e.__int32Fields||new Set,o=e.__uint32Fields||new Set,a=e.__int16Fields||new Set,c=e.__uint16Fields||new Set,h=e.__int8Fields||new Set,l=e.__uint8Fields||new Set,u=e.__uint8ClampedFields||new Set,d=e.__autoTypedFields||new Map,p=e.__serializeMapFields||new Set,m=e.__serializeSetFields||new Set,g=e.__serializeArrayFields||new Set;for(const e in t)if(t.hasOwnProperty(e)&&"id"!==e){const y=t[e],f=typeof y;if("number"===f)if(n.has(e));else if(d.has(e)){const t=d.get(e),n=K.inferOptimalType(y,t),s=K.getTypedArrayConstructor(n);this.fields.set(e,new s(this._capacity)),ee._logger.info(`字段 ${e} 自动推断为 ${n} 类型,值: ${y}, 选项:`,t)}else s.has(e)?this.fields.set(e,new Float64Array(this._capacity)):r.has(e)?this.fields.set(e,new Int32Array(this._capacity)):o.has(e)?this.fields.set(e,new Uint32Array(this._capacity)):a.has(e)?this.fields.set(e,new Int16Array(this._capacity)):c.has(e)?this.fields.set(e,new Uint16Array(this._capacity)):h.has(e)?this.fields.set(e,new Int8Array(this._capacity)):l.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):u.has(e)?this.fields.set(e,new Uint8ClampedArray(this._capacity)):(i.has(e),this.fields.set(e,new Float32Array(this._capacity)));else"boolean"===f?l.has(e)||!i.has(e)&&!s.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):this.fields.set(e,new Float32Array(this._capacity)):"string"===f?this.stringFields.set(e,new Array(this._capacity)):"object"===f&&null!==y&&(p.has(e)||m.has(e)||g.has(e))&&this.serializedFields.set(e,new Array(this._capacity))}}addComponent(e,t){if(this.entityToIndex.has(e)){const n=this.entityToIndex.get(e);return void this.updateComponentAtIndex(n,t)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(e,n),this.indexToEntity[n]=e,this.updateComponentAtIndex(n,t),this._size++}updateComponentAtIndex(e,t){const n=this.indexToEntity[e],s=new Map,i=this.type.__highPrecisionFields||new Set,r=this.type.__serializeMapFields||new Set,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(const n in t)if(t.hasOwnProperty(n)&&"id"!==n){const h=t[n],l=typeof h;if("number"===l)if(i.has(n)||!this.fields.has(n))s.set(n,h);else{this.fields.get(n)[e]=h}else if("boolean"===l&&this.fields.has(n)){this.fields.get(n)[e]=h?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[e]=String(h)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[e]=this.serializeValue(h,n,r,o,a)}else c.has(n)?s.set(n,this.deepClone(h)):s.set(n,h)}s.size>0&&this.complexFields.set(n,s)}serializeValue(e,t,n,s,i){try{return n.has(t)&&e instanceof Map?JSON.stringify(Array.from(e.entries())):s.has(t)&&e instanceof Set?JSON.stringify(Array.from(e)):(i.has(t)&&Array.isArray(e),JSON.stringify(e))}catch(e){return ee._logger.warn(`SoA序列化字段 ${t} 失败:`,e),"{}"}}deserializeValue(e,t,n,s,i){try{const r=JSON.parse(e);return n.has(t)?new Map(r):s.has(t)?new Set(r):(i.has(t),r)}catch(e){return ee._logger.warn(`SoA反序列化字段 ${t} 失败:`,e),null}}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map((e=>this.deepClone(e)));if(e instanceof Map){const t=new Map;for(const[n,s]of e.entries())t.set(n,this.deepClone(s));return t}if(e instanceof Set){const t=new Set;for(const n of e.values())t.add(this.deepClone(n));return t}const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}getComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=new this.type,s=this.type.__serializeMapFields||new Set,i=this.type.__serializeSetFields||new Set,r=this.type.__serializeArrayFields||new Set;for(const[e,s]of this.fields.entries()){const i=s[t],r=this.getFieldType(e);n[e]="boolean"===r?1===i:i}for(const[e,s]of this.stringFields.entries())n[e]=s[t];for(const[e,o]of this.serializedFields.entries()){const a=o[t];a&&(n[e]=this.deserializeValue(a,e,s,i,r))}const o=this.complexFields.get(e);if(o)for(const[e,t]of o.entries())n[e]=t;return n}getFieldType(e){return typeof(new this.type)[e]}hasComponent(e){return this.entityToIndex.has(e)}removeComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n}resize(e){for(const[t,n]of this.fields.entries()){let s;n instanceof Float32Array?s=new Float32Array(e):n instanceof Float64Array?s=new Float64Array(e):n instanceof Int32Array?s=new Int32Array(e):n instanceof Uint32Array?s=new Uint32Array(e):n instanceof Int16Array?s=new Int16Array(e):n instanceof Uint16Array?s=new Uint16Array(e):n instanceof Int8Array?s=new Int8Array(e):n instanceof Uint8Array?s=new Uint8Array(e):n instanceof Uint8ClampedArray?s=new Uint8ClampedArray(e):(s=new Float32Array(e),ee._logger.warn(`未知的TypedArray类型用于字段 ${t},回退到Float32Array`)),s.set(n),this.fields.set(t,s)}for(const[t,n]of this.stringFields.entries()){const s=new Array(e);for(let e=0;e<n.length;e++)s[e]=n[e];this.stringFields.set(t,s)}for(const[t,n]of this.serializedFields.entries()){const s=new Array(e);for(let e=0;e<n.length;e++)s[e]=n[e];this.serializedFields.set(t,s)}this._capacity=e}getActiveIndices(){return Array.from(this.entityToIndex.values())}getFieldArray(e){return this.fields.get(e)||null}getTypedFieldArray(e){return this.fields.get(String(e))||null}getEntityIndex(e){return this.entityToIndex.get(e)}getEntityIdByIndex(e){return this.indexToEntity[e]}size(){return this._size}clear(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(const e of this.fields.values())e.fill(0);for(const e of this.stringFields.values())for(let t=0;t<e.length;t++)e[t]=void 0;for(const e of this.serializedFields.values())for(let t=0;t<e.length;t++)e[t]=void 0}compact(){if(0===this.freeIndices.length)return;const e=Array.from(this.entityToIndex.entries()).sort(((e,t)=>e[1]-t[1])),t=new Map,n=[];for(let s=0;s<e.length;s++){const i=e[s];if(!i)continue;const[r,o]=i;if(t.set(r,s),n[s]=r,s!==o){for(const[,e]of this.fields.entries()){const t=e[o];void 0!==t&&(e[s]=t)}for(const[,e]of this.stringFields.entries()){const t=e[o];void 0!==t&&(e[s]=t)}for(const[,e]of this.serializedFields.entries()){const t=e[o];void 0!==t&&(e[s]=t)}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}getStats(){let e=0;const t=new Map;for(const[n,s]of this.fields.entries()){let i,r;s instanceof Float32Array?(i=4,r="float32"):s instanceof Float64Array?(i=8,r="float64"):s instanceof Int32Array?(i=4,r="int32"):s instanceof Uint32Array?(i=4,r="uint32"):s instanceof Int16Array?(i=2,r="int16"):s instanceof Uint16Array?(i=2,r="uint16"):s instanceof Int8Array?(i=1,r="int8"):s instanceof Uint8Array?(i=1,r="uint8"):s instanceof Uint8ClampedArray?(i=1,r="uint8clamped"):(i=4,r="unknown");const o=s.length*i;e+=o,t.set(n,{size:this._size,capacity:s.length,type:r,memory:o})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:e,fieldStats:t}}performVectorizedOperation(e){const t=this.getActiveIndices();e(this.fields,t)}}ee._logger=N("SoAStorage");class te{static register(e){const t=b(e);if(this.componentTypes.has(e)){return this.componentTypes.get(e)}const n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n}static getBitMask(e){const t=this.componentTypes.get(e);if(void 0===t){const t=b(e);throw new Error(`Component type ${t} is not registered`)}return X.create(t)}static getBitIndex(e){const t=this.componentTypes.get(e);if(void 0===t){const t=b(e);throw new Error(`Component type ${t} is not registered`)}return t}static isRegistered(e){return this.componentTypes.has(e)}static getTypeByBitIndex(e){return this.bitIndexToType.get(e)||null}static getRegisteredCount(){return this.nextBitIndex}static getComponentType(e){return this.componentNameToType.get(e)||null}static getAllRegisteredTypes(){return new Map(this.componentTypes)}static getAllComponentNames(){return new Map(this.componentNameToType)}static getComponentId(e){return this.componentNameToId.get(e)}static registerComponentByName(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);const t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t}static createSingleComponentMask(e){const t=`single:${e}`;if(this.maskCache.has(t))return this.maskCache.get(t);const n=this.getComponentId(e);if(void 0===n)throw new Error(`Component type ${e} is not registered`);const s=X.create(n);return this.maskCache.set(t,s),s}static createComponentMask(e){const t=`multi:${[...e].sort().join(",")}`;if(this.maskCache.has(t))return this.maskCache.get(t);const n=X.clone(X.ZERO);for(const t of e){const e=this.getComponentId(t);if(void 0!==e){const t=X.create(e);X.orInPlace(n,t)}}return this.maskCache.set(t,n),n}static clearMaskCache(){this.maskCache.clear()}static reset(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0}}te._logger=N("ComponentStorage"),te.componentTypes=new Map,te.bitIndexToType=new Map,te.componentNameToType=new Map,te.componentNameToId=new Map,te.maskCache=new Map,te.nextBitIndex=0;class ne{constructor(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,te.isRegistered(e)||te.register(e)}addComponent(e,t){if(this.entityToIndex.has(e))throw new Error(`Entity ${e} already has component ${b(this.componentType)}`);const n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)}getComponent(e){const t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null}hasComponent(e){return this.entityToIndex.has(e)}removeComponent(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=this.dense[t],s=this.dense.length-1;if(t!==s){const e=this.dense[s],n=this.entityIds[s];this.dense[t]=e,this.entityIds[t]=n,this.entityToIndex.set(n,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n}forEach(e){for(let t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)}getDenseArray(){return{components:[...this.dense],entityIds:[...this.entityIds]}}clear(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()}get size(){return this.dense.length}get type(){return this.componentType}getStats(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}}}class se{constructor(){this.storages=new Map}isSoAStorage(e){return this.storages.get(e)instanceof ee}getSoAStorage(e){const t=this.getStorage(e);return t instanceof ee?t:null}getFieldArray(e,t){const n=this.getSoAStorage(e);return n?n.getFieldArray(t):null}getTypedFieldArray(e,t){const n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null}getActiveIndices(e){const t=this.getSoAStorage(e);return t?t.getActiveIndices():[]}getEntityIndex(e,t){const n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0}getEntityIdByIndex(e,t){const n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0}getStorage(e){let t=this.storages.get(e);if(!t){e.__enableSoA?(t=new ee(e),se._logger.info(`为 ${b(e)} 启用SoA优化(适用于大规模批量操作)`)):t=new ne(e),this.storages.set(e,t)}return t}addComponent(e,t){const n=t.constructor;this.getStorage(n).addComponent(e,t)}getComponent(e,t){const n=this.storages.get(t);return n?n.getComponent(e):null}hasComponent(e,t){const n=this.storages.get(t);return!!n&&n.hasComponent(e)}removeComponent(e,t){const n=this.storages.get(t);return n?n.removeComponent(e):null}removeAllComponents(e){for(const t of this.storages.values())t.removeComponent(e)}getComponentMask(e){const t=X.clone(X.ZERO);for(const[n,s]of this.storages.entries())if(s.hasComponent(e)){const e=te.getBitMask(n);X.orInPlace(t,e)}return t}getAllStats(){const e=new Map;for(const[t,n]of this.storages.entries()){const s=b(t);e.set(s,n.getStats())}return e}clear(){for(const e of this.storages.values())e.clear();this.storages.clear()}}se._logger=N("ComponentStorage");class ie{compare(e,t){let n=e.updateOrder-t.updateOrder;return 0==n&&(n=e.id-t.id),n}}class re{constructor(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=X.clone(X.ZERO),this._componentCache=null,this.name=e,this.id=t}get isDestroyed(){return this._isDestroyed}setDestroyedState(e){this._isDestroyed=e}get components(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}_rebuildComponentCache(){const e=[];if(!this.scene?.componentStorageManager)return void(this._componentCache=e);const t=this._componentMask,n=te.getRegisteredCount();for(let s=0;s<n;s++)if(X.getBit(t,s)){const t=te.getTypeByBitIndex(s);if(t){const n=this.scene.componentStorageManager.getComponent(this.id,t);n&&e.push(n)}}this._componentCache=e}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(e){this._active!==e&&(this._active=e,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(e){this._tag=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get updateOrder(){return this._updateOrder}set updateOrder(e){this._updateOrder=e}get componentMask(){return this._componentMask}createComponent(e,...t){const n=new e(...t);return this.addComponent(n)}addComponentInternal(e){const t=e.constructor;te.isRegistered(t)||te.register(t);const n=te.getBitMask(t);return X.orInPlace(this._componentMask,n),this._componentCache=null,e}notifyQuerySystems(){this.scene&&this.scene.querySystem&&(this.scene.querySystem.updateEntity(this),this.scene.clearSystemEntityCaches())}addComponent(e){const t=e.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(t))throw new Error(`Entity ${this.name} already has component ${b(t)}`);return this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),e.onAddedToEntity(),this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("component:added",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:b(t),component:e}),this.notifyQuerySystems(),e}getComponent(e){if(!this.hasComponent(e))return null;if(!this.scene?.componentStorageManager)return null;return this.scene.componentStorageManager.getComponent(this.id,e)}hasComponent(e){if(!te.isRegistered(e))return!1;const t=te.getBitMask(e);return X.hasAny(this._componentMask,t)}getOrCreateComponent(e,...t){let n=this.getComponent(e);return n||(n=this.createComponent(e,...t)),n}removeComponent(e){const t=e.constructor;if(!te.isRegistered(t))return;const n=te.getBitIndex(t);X.clearBit(this._componentMask,n),this._componentCache=null,this.scene?.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),this.scene?.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(e),e.onRemovedFromEntity&&e.onRemovedFromEntity(),e.entityId=null,this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("component:removed",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:b(t),component:e}),this.notifyQuerySystems()}removeComponentByType(e){const t=this.getComponent(e);return t?(this.removeComponent(t),t):null}removeAllComponents(){const e=[...this.components];X.clear(this._componentMask),this._componentCache=null;for(const t of e){const e=t.constructor;this.scene?.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity()}this.notifyQuerySystems()}addComponents(e){const t=[];for(const n of e)try{t.push(this.addComponent(n))}catch(e){re._logger.warn(`添加组件失败 ${w(n)}:`,e)}return t}removeComponentsByTypes(e){const t=[];for(const n of e)t.push(this.removeComponentByType(n));return t}getComponents(e){const t=[];for(const n of this.components)n instanceof e&&t.push(n);return t}getComponentByType(e){for(const t of this.components)if(t instanceof e)return t;return null}addChild(e){if(e===this)throw new Error("Entity cannot be its own child");return e._parent===this||(e._parent&&e._parent.removeChild(e),e._parent=this,this._children.push(e),!e.scene&&this.scene&&(e.scene=this.scene,this.scene.addEntity(e))),e}removeChild(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e._parent=null,!0)}removeAllChildren(){const e=[...this._children];for(const t of e)this.removeChild(t)}findChild(e,t=!1){for(const t of this._children)if(t.name===e)return t;if(t)for(const t of this._children){const n=t.findChild(e,!0);if(n)return n}return null}findChildrenByTag(e,t=!1){const n=[];for(const t of this._children)t.tag===e&&n.push(t);if(t)for(const t of this._children)n.push(...t.findChildrenByTag(e,!0));return n}getRoot(){return this._parent?this._parent.getRoot():this}isAncestorOf(e){let t=e._parent;for(;t;){if(t===this)return!0;t=t._parent}return!1}isDescendantOf(e){return e.isAncestorOf(this)}getDepth(){let e=0,t=this._parent;for(;t;)e++,t=t._parent;return e}forEachChild(e,t=!1){this._children.forEach(((n,s)=>{e(n,s),t&&n.forEachChild(e,!0)}))}onActiveChanged(){for(const e of this.components)"onActiveChanged"in e&&"function"==typeof e.onActiveChanged&&e.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));const e=[...this._children];for(const t of e)t.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}destroyAllChildren(){if(0===this._children.length)return;const e=this.scene,t=[],n=e=>{for(const s of e._children)t.push(s),n(s)};n(this);for(const e of t)e.setDestroyedState(!0);for(const e of t)e.removeAllComponents();if(e){for(const n of t)e.entities.remove(n),e.querySystem.removeEntity(n);e.clearSystemEntityCaches()}this._children.length=0}compareTo(e){return ie.prototype.compare(this,e)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){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((e=>w(e))),componentMask:X.toString(this._componentMask,2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((e=>e.id)),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}}}re._logger=N("Entity"),re.entityComparer=new ie;class oe{constructor(e,t){this.scene=e,this.storageManager=t;const n=e.identifierPool.checkOut();this.entity=new re("",n),this.entity.scene=this.scene}named(e){return this.entity.name=e,this}tagged(e){return this.entity.tag=e,this}with(e){return this.entity.addComponent(e),this}withComponents(...e){for(const t of e)this.entity.addComponent(t);return this}withIf(e,t){return e&&this.entity.addComponent(t),this}withFactory(e){const t=e();return this.entity.addComponent(t),this}configure(e,t){const n=this.entity.getComponent(e);return n&&t(n),this}enabled(e=!0){return this.entity.enabled=e,this}active(e=!0){return this.entity.active=e,this}withChild(e){const t=e.build();return this.entity.addChild(t),this}withChildren(...e){for(const t of e){const e=t.build();this.entity.addChild(e)}return this}withChildFactory(e){const t=e(this.entity).build();return this.entity.addChild(t),this}withChildIf(e,t){if(e){const e=t.build();this.entity.addChild(e)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const e=new oe(this.scene,this.storageManager);return e.entity=this.entity,e}}class ae{get count(){return this.buffer.length}constructor(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}add(e){this.addImmediate(e)}addImmediate(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))}remove(e){this.removeImmediate(e)}removeImmediate(e){const t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))}removeAllEntities(){const e=[];for(let t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(const t of e)this._scene.identifierPool.checkIn(t);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 e of this._entitiesToAdd)this.addImmediate(e);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const e of this._entitiesToRemove)this.removeImmediate(e);this._entitiesToRemove.length=0}}update(){this.updateLists()}findEntity(e){const t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null}findEntitiesByName(e){return this._nameToEntities.get(e)||[]}findEntityById(e){return this._idToEntity.get(e)||null}findEntitiesByTag(e){const t=[];for(const n of this.buffer)n.tag===e&&t.push(n);return t}findEntitiesWithComponent(e){const t=[];for(const n of this.buffer)n.hasComponent(e)&&t.push(n);return t}forEach(e){for(const t of this.buffer)e(t)}forEachWhere(e,t){for(const n of this.buffer)e(n)&&t(n)}updateNameIndex(e,t){if(e.name)if(t){let t=this._nameToEntities.get(e.name);t||(t=[],this._nameToEntities.set(e.name,t)),t.push(e)}else{const t=this._nameToEntities.get(e.name);if(t){const n=t.indexOf(e);-1!==n&&(t.splice(n,1),0===t.length&&this._nameToEntities.delete(e.name))}}}getStats(){let e=0;for(const t of this.buffer)t.enabled&&!t.isDestroyed&&e++;return{totalEntities:this.buffer.length,activeEntities:e,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class ce{constructor(e=100,t=1024){this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}checkOut(){let e;if(this._processDelayedRecycle(),this._freeIndices.length>0)e=this._freeIndices.pop();else{if(this._nextAvailableIndex>ce.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${ce.MAX_INDEX})。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。`);e=this._nextAvailableIndex++,this._ensureGenerationCapacity(e)}const t=this._generations.get(e)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(e,t)}checkIn(e){const t=this._unpackIndex(e),n=this._unpackGeneration(e);if(!this._isValidId(t,n))return!1;return!this._pendingRecycle.some((e=>e.index===t&&e.generation===n))&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0)}isValid(e){const t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)}getStats(){let e=0,t=0;for(const[n,s]of this._generations)n<this._nextAvailableIndex&&(e+=s,t++);const n=t>0?e/t:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:ce.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*n)/100,generationStorageSize:this._generations.size}}forceProcessDelayedRecycle(){this._processDelayedRecycle(!0)}_processDelayedRecycle(e=!1){if(0===this._pendingRecycle.length)return;const t=Date.now(),n=[],s=[];for(const i of this._pendingRecycle)e||t-i.timestamp>=this._recycleDelay?n.push(i):s.push(i);for(const e of n)if(this._isValidId(e.index,e.generation)){let t=e.generation+1;t>ce.MAX_GENERATION&&(t=1),this._generations.set(e.index,t),this._freeIndices.push(e.index)}this._pendingRecycle=s}_preAllocateGenerations(e,t){for(let n=0;n<t;n++){const t=e+n;t<=ce.MAX_INDEX&&this._generations.set(t,1)}this._stats.memoryExpansions++}_ensureGenerationCapacity(e){if(!this._generations.has(e)){const t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}}_calculateMemoryUsage(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length}_packId(e,t){return t<<16|e}_unpackIndex(e){return 65535&e}_unpackGeneration(e){return e>>>16&65535}_isValidId(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;const n=this._generations.get(e);return void 0!==n&&n===t}}ce.MAX_INDEX=65535,ce.MAX_GENERATION=65535;class he{constructor(){this.condition={all:[],any:[],none:[]}}static all(...e){return(new he).all(...e)}static any(...e){return(new he).any(...e)}static none(...e){return(new he).none(...e)}static byTag(e){return(new he).withTag(e)}static byName(e){return(new he).withName(e)}static byComponent(e){return(new he).withComponent(e)}static complex(){return new he}static empty(){return new he}all(...e){return this.condition.all.push(...e),this}any(...e){return this.condition.any.push(...e),this}none(...e){return this.condition.none.push(...e),this}exclude(...e){return this.none(...e)}one(...e){return this.any(...e)}withTag(e){return this.condition.tag=e,this}withName(e){return this.condition.name=e,this}withComponent(e){return this.condition.component=e,this}withoutTag(){return delete this.condition.tag,this}withoutName(){return delete this.condition.name,this}withoutComponent(){return delete this.condition.component,this}getCondition(){return{all:[...this.condition.all],any:[...this.condition.any],none:[...this.condition.none],...void 0!==this.condition.tag&&{tag:this.condition.tag},...void 0!==this.condition.name&&{name:this.condition.name},...void 0!==this.condition.component&&{component:this.condition.component}}}isEmpty(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component}reset(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this}clone(){const e=new he;return e.condition.all.push(...this.condition.all),e.condition.any.push(...this.condition.any),e.condition.none.push(...this.condition.none),void 0!==this.condition.tag&&(e.condition.tag=this.condition.tag),void 0!==this.condition.name&&(e.condition.name=this.condition.name),void 0!==this.condition.component&&(e.condition.component=this.condition.component),e}toString(){const e=[];return this.condition.all.length>0&&e.push(`all(${this.condition.all.map((e=>b(e))).join(", ")})`),this.condition.any.length>0&&e.push(`any(${this.condition.any.map((e=>b(e))).join(", ")})`),this.condition.none.length>0&&e.push(`none(${this.condition.none.map((e=>b(e))).join(", ")})`),void 0!==this.condition.tag&&e.push(`tag(${this.condition.tag})`),void 0!==this.condition.name&&e.push(`name(${this.condition.name})`),void 0!==this.condition.component&&e.push(`component(${b(this.condition.component)})`),`Matcher[${e.join(" & ")}]`}}class le{constructor(){this._frameCache=null,this._persistentCache=null,this._trackedEntities=new Set}getFrame(){return this._frameCache}setFrame(e){this._frameCache=e}getPersistent(){return this._persistentCache}setPersistent(e){this._persistentCache=e}getTracked(){return this._trackedEntities}addTracked(e){this._trackedEntities.add(e)}removeTracked(e){this._trackedEntities.delete(e)}isTracked(e){return this._trackedEntities.has(e)}invalidate(){this._persistentCache=null}clearFrame(){this._frameCache=null}clearAll(){this._frameCache=null,this._persistentCache=null,this._trackedEntities.clear()}hasPersistent(){return null!==this._persistentCache}hasFrame(){return null!==this._frameCache}getStats(){return{hasFrame:null!==this._frameCache,hasPersistent:null!==this._persistentCache,trackedCount:this._trackedEntities.size,frameEntityCount:this._frameCache?.length??0,persistentEntityCount:this._persistentCache?.length??0}}}class ue{get entities(){const e=this._entityCache.getFrame();return null!==e?e:(this._entityCache.hasPersistent()||this._entityCache.setPersistent(this.queryEntities()),this._entityCache.getPersistent())}get updateOrder(){return this._updateOrder}set updateOrder(e){this.setUpdateOrder(e)}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get systemName(){return this._systemName}constructor(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=A(this),this._initialized=!1,this._matcher=e||he.empty(),this._eventListeners=[],this._scene=null,this._destroyed=!1,this._entityIdMap=null,this._entityIdMapVersion=-1,this.logger=N(this.getLoggerName()),this._entityCache=new le}get scene(){return this._scene}set scene(e){this._scene=e}setPerformanceMonitor(e){this._performanceMonitor=e}getPerformanceMonitor(){if(!this._performanceMonitor)throw new Error(`${this._systemName}: PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene`);return this._performanceMonitor}get matcher(){return this._matcher}setUpdateOrder(e){this._updateOrder!==e&&(this._updateOrder=e,this._scene?.markSystemsOrderDirty())}initialize(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())}onInitialize(){}clearEntityCache(){this._entityCache.invalidate()}reset(){this._destroyed||(this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this.destroy())}queryEntities(){if(!this.scene?.querySystem||!this._matcher)return[];const e=this._matcher.getCondition(),t=this.scene.querySystem;let n=[];return n=this._matcher.isEmpty()?t.getAllEntities():this.isSingleCondition(e)?this.executeSingleConditionQuery(e,t):this.executeComplexQuery(e,t),this.updateEntityTracking(n),n}isSingleCondition(e){const t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)}executeSingleConditionQuery(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll(...e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny(...e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone(...e.none).entities:[]}executeComplexQueryWithIdSets(e,t){let n=null;if(void 0!==e.tag){const s=t.queryByTag(e.tag);n=this.extractEntityIds(s.entities)}if(void 0!==e.name){const s=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,s):s}if(void 0!==e.component){const s=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,s):s}if(e.all.length>0){const s=this.extractEntityIds(t.queryAll(...e.all).entities);n=n?this.intersectIdSets(n,s):s}if(e.any.length>0){const s=this.extractEntityIds(t.queryAny(...e.any).entities);n=n?this.intersectIdSets(n,s):s}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));const s=t.queryAny(...e.none),i=this.extractEntityIds(s.entities);n=this.differenceIdSets(n,i)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]}extractEntityIds(e){const t=e.length,n=new Set;for(let s=0;s<t;s=s+1|0)n.add(0|e[s].id);return n}intersectIdSets(e,t){let n,s;e.size<=t.size?(n=e,s=t):(n=t,s=e);const i=new Set;for(const e of n)s.has(e)&&i.add(e);return i}differenceIdSets(e,t){const n=new Set;for(const s of e)t.has(s)||n.add(s);return n}getEntityIdMap(e){const t=this.scene?.querySystem?.version??0;return null!==this._entityIdMap&&this._entityIdMapVersion===t?this._entityIdMap:this.rebuildEntityIdMap(e,t)}rebuildEntityIdMap(e,t){let n=this._entityIdMap;n?n.clear():n=new Map;const s=e.length;for(let t=0;t<s;t=t+1|0){const s=e[t];n.set(0|s.id,s)}return this._entityIdMap=n,this._entityIdMapVersion=t,n}idSetToEntityArray(e,t){const n=this.getEntityIdMap(t),s=e.size,i=new Array(s);let r=0;for(const t of e){const e=n.get(t);void 0!==e&&(i[r]=e,r=r+1|0)}return r<s&&(i.length=r),i}executeComplexQuery(e,t){return this.executeComplexQueryWithIdSets(e,t)}update(){if(!this._enabled||!this.onCheckProcessing())return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName);let n=0;try{this.onBegin();const e=this.queryEntities();this._entityCache.setFrame(e),n=e.length,this.process(e)}finally{e.endMonitoring(this._systemName,t,n)}}lateUpdate(){if(!this._enabled||!this.onCheckProcessing())return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(`${this._systemName}_Late`);let n=0;try{const e=this._entityCache.getFrame()||[];n=e.length,this.lateProcess(e),this.onEnd()}finally{e.endMonitoring(`${this._systemName}_Late`,t,n),this._entityCache.clearFrame()}}onBegin(){}process(e){}lateProcess(e){}onEnd(){}onCheckProcessing(){return!0}getPerformanceData(){return this.getPerformanceMonitor().getSystemData(this._systemName)}getPerformanceStats(){return this.getPerformanceMonitor().getSystemStats(this._systemName)}resetPerformanceData(){this.getPerformanceMonitor().resetSystem(this._systemName)}toString(){const e=this.entities.length,t=this.getPerformanceData(),n=t?` (${t.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${e} entities]${n}`}updateEntityTracking(e){const t=new Set(e);let n=!1;for(const t of e)this._entityCache.isTracked(t)||(this._entityCache.addTracked(t),this.onAdded(t),n=!0);for(const e of this._entityCache.getTracked())t.has(e)||(this._entityCache.removeTracked(e),this.onRemoved(e),n=!0);n&&this._entityCache.invalidate()}onAdded(e){}onRemoved(e){}dispose(){this._destroyed||(this.cleanupManualEventListeners(),this.onDestroy(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this._destroyed=!0,this.logger.debug(`System ${this._systemName} disposed`))}addEventListener(e,t,n){if(!this.scene?.eventSystem)return this.logger.warn(`${this.systemName}: 无法添加事件监听器,scene.eventSystem 不可用`),null;const s=this.scene.eventSystem.on(e,t,n);return s&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,listenerRef:s}),s}removeEventListener(e,t){const n=this._eventListeners.findIndex((n=>n.eventType===e&&n.listenerRef===t));if(n>=0){const t=this._eventListeners[n];if(!t)return;t.eventSystem.off(e,t.listenerRef),this._eventListeners.splice(n,1)}}cleanupManualEventListeners(){for(const e of this._eventListeners)try{e.eventSystem.off(e.eventType,e.listenerRef)}catch(t){this.logger.warn(`${this.systemName}: 移除事件监听器失败 "${e.eventType}"`,t)}this._eventListeners.length=0}destroy(){this._destroyed||(this.cleanupManualEventListeners(),this._destroyed=!0,this.onDestroy())}getLoggerName(){return A(this)}onDestroy(){}requireComponent(e,t){const n=e.getComponent(t);if(!n)throw new Error(`Component ${t.name} not found on entity ${e.name} in ${this.systemName}`);return n}getComponents(e,...t){return t.map((t=>this.requireComponent(e,t)))}forEach(e,t){for(let n=0;n<e.length;n++)t(e[n],n)}filterEntities(e,t){return Array.from(e).filter(t)}mapEntities(e,t){return Array.from(e).map(t)}findEntity(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return e[n]}someEntity(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1}everyEntity(e,t){for(let n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0}}class de{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(e){this._processors.push(e),this.setDirty()}remove(e){const t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)}getProcessor(e){for(const t of this._processors)if(t instanceof e)return t;return null}begin(){this.sortProcessors()}end(){for(const e of this._processors)try{e.reset()}catch(t){de._logger.error(`Error in processor ${A(e)}:`,t)}this._isDirty=!1,this._processors.length=0}update(){this.sortProcessors();for(const e of this._processors)try{e.update()}catch(t){de._logger.error(`Error in processor ${A(e)}:`,t)}}lateUpdate(){for(const e of this._processors)e.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((e,t)=>e.updateOrder-t.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}de._logger=N("EntityProcessorList");class pe{constructor(e){if(e&&"object"==typeof e)this._value=X.clone(e);else if("number"==typeof e)this._value=X.fromNumber(e);else if("string"==typeof e){const t=parseInt(e,10);this._value=X.fromNumber(t)}else this._value=X.clone(X.ZERO)}set(e){if(e<0)throw new Error("Bit index cannot be negative");X.setBit(this._value,e)}clear(e){if(e<0)throw new Error("Bit index cannot be negative");X.clearBit(this._value,e)}get(e){return X.getBit(this._value,e)}containsAll(e){return X.hasAll(this._value,e._value)}intersects(e){return X.hasAny(this._value,e._value)}excludes(e){return X.hasNone(this._value,e._value)}clearAll(){X.clear(this._value)}isEmpty(){return X.isZero(this._value)}cardinality(){return X.popCount(this._value)}and(e){const t=new pe;return X.copy(this._value,t._value),X.andInPlace(t._value,e._value),t}or(e){const t=new pe;return X.copy(this._value,t._value),X.orInPlace(t._value,e._value),t}xor(e){const t=new pe;return X.copy(this._value,t._value),X.xorInPlace(t._value,e._value),t}not(e=64){e>64&&(e=64);const t=new pe;if(X.copy(this._value,t._value),e<=32){const n=(1<<e)-1;t._value.base[J.LOW]=~t._value.base[J.LOW]&n,t._value.base[J.HIGH]=0}else if(t._value.base[J.LOW]=~t._value.base[J.LOW],e<64){const n=(1<<e-32)-1;t._value.base[J.HIGH]=~t._value.base[J.HIGH]&n}else t._value.base[J.HIGH]=~t._value.base[J.HIGH];return t}copyFrom(e){X.copy(e._value,this._value)}clone(){return new pe(this._value)}getValue(){return this._value}setValue(e){if("object"==typeof e)X.copy(e,this._value);else if("number"==typeof e)this._value=X.fromNumber(e);else{const t=parseInt(e,10);this._value=X.fromNumber(t)}}toString(){const e=[];for(let t=0;t<64;t++)this.get(t)&&e.push(t.toString());return`Bits[${e.join(", ")}]`}toBinaryString(e=0){0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));let t="";for(let n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t}toHexString(){return X.toString(this._value,16)}static fromBinaryString(e){const t=e.replace(/\s/g,"");let n;if(t.length<=32){n={base:[parseInt(t,2)>>>0,0]}}else{const e=t.substring(t.length-32),s=t.substring(0,t.length-32);n={base:[parseInt(e,2)>>>0,parseInt(s,2)>>>0]}}return new pe(n)}static fromHexString(e){const t=e.replace(/^0x/i,"");let n;if(t.length<=8){n={base:[parseInt(t,16)>>>0,0]}}else{const e=t.substring(t.length-8),s=t.substring(0,t.length-8);n={base:[parseInt(e,16)>>>0,parseInt(s,16)>>>0]}}return new pe(n)}equals(e){return X.equals(this._value,e._value)}getHighestBitIndex(){if(X.isZero(this._value))return-1;if(0!==this._value.base[J.HIGH])for(let e=31;e>=0;e--)if(this._value.base[J.HIGH]&1<<e)return e+32;for(let e=31;e>=0;e--)if(this._value.base[J.LOW]&1<<e)return e;return-1}getLowestBitIndex(){if(X.isZero(this._value))return-1;for(let e=0;e<32;e++)if(this._value.base[J.LOW]&1<<e)return e;for(let e=0;e<32;e++)if(this._value.base[J.HIGH]&1<<e)return e+32;return-1}}class me{constructor(){this._dense=[],this._sparse=new Map}add(e){if(this._sparse.has(e))return!1;const t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0}remove(e){const t=this._sparse.get(e);if(void 0===t)return!1;const n=this._dense.length-1;if(t!==n){const e=this._dense[n];this._dense[t]=e,this._sparse.set(e,t)}return this._dense.pop(),this._sparse.delete(e),!0}has(e){return this._sparse.has(e)}getIndex(e){return this._sparse.get(e)}getByIndex(e){return this._dense[e]}get size(){return this._dense.length}get isEmpty(){return 0===this._dense.length}forEach(e){for(let t=0;t<this._dense.length;t++)e(this._dense[t],t)}map(e){const t=[];for(let n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t}filter(e){const t=[];for(let n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t}find(e){for(let t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]}some(e){for(let t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1}every(e){for(let t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0}getDenseArray(){return[...this._dense]}getDenseArrayUnsafe(){return this._dense}clear(){this._dense.length=0,this._sparse.clear()}toArray(){return[...this._dense]}toSet(){return new Set(this._dense)}getMemoryStats(){const e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}}validate(){if(this._dense.length!==this._sparse.size)return!1;for(let e=0;e<this._dense.length;e++){const t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(const[e,t]of this._sparse)if(t>=this._dense.length||this._dense[t]!==e)return!1;return!0}}class ge extends Set{constructor(...e){super()}reset(){this.clear()}}class ye{constructor(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new me}addEntity(e){this._entities.has(e)&&this.removeEntity(e);const t=X.clone(X.ZERO),n=new Set;for(const s of e.components){const e=s.constructor;n.add(e),te.isRegistered(e)||te.register(e);const i=te.getBitMask(e);X.orInPlace(t,i)}this._entities.add(e);const s=this._entities.getIndex(e);for(;this._componentMasks.length<=s;)this._componentMasks.push(X.clone(X.ZERO));this._componentMasks[s]=t,this.updateComponentMappings(e,n,!0)}removeEntity(e){const t=this._entities.getIndex(e);if(void 0===t)return;const n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);const s=this._componentMasks.length-1;t!==s&&(this._componentMasks[t]=this._componentMasks[s]),this._componentMasks.pop()}queryByComponent(e){const t=this._componentToEntities.get(e);return t?new Set(t):new Set}queryMultipleAnd(e){if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);const t=X.clone(X.ZERO);for(const n of e){if(!te.isRegistered(n))return new Set;const e=te.getBitMask(n);X.orInPlace(t,e)}const n=ye._entitySetPool.obtain();return this._entities.forEach(((e,s)=>{const i=this._componentMasks[s];X.hasAll(i,t)&&n.add(e)})),n}queryMultipleOr(e){if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);const t=X.clone(X.ZERO);for(const n of e)if(te.isRegistered(n)){const e=te.getBitMask(n);X.orInPlace(t,e)}if(X.equals(t,X.ZERO))return new Set;const n=ye._entitySetPool.obtain();return this._entities.forEach(((e,s)=>{const i=this._componentMasks[s];X.hasAny(i,t)&&n.add(e)})),n}hasComponent(e,t){const n=this._entities.getIndex(e);if(void 0===n)return!1;if(!te.isRegistered(t))return!1;const s=this._componentMasks[n],i=te.getBitMask(t);return X.hasAny(s,i)}getEntityMask(e){const t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]}getAllEntities(){return this._entities.toArray()}get size(){return this._entities.size}get isEmpty(){return this._entities.isEmpty}forEach(e){this._entities.forEach(((t,n)=>{e(t,this._componentMasks[n],n)}))}clear(){this._entities.clear(),this._componentMasks.length=0;for(const e of this._componentToEntities.values())ye._entitySetPool.release(e);this._componentToEntities.clear()}getMemoryStats(){const e=this._entities.getMemoryStats(),t=16*this._componentMasks.length;let n=16*this._componentToEntities.size;for(const e of this._componentToEntities.values())n+=8*e.size;return{entitiesMemory:e.totalMemory,masksMemory:t,mappingsMemory:n,totalMemory:e.totalMemory+t+n}}validate(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;const e=new Set;for(const t of this._componentToEntities.values())for(const n of t)e.add(n);for(const t of e)if(!this._entities.has(t))return!1;return!0}getEntityComponentTypes(e){const t=new Set;for(const n of e.components)t.add(n.constructor);return t}updateComponentMappings(e,t,n){for(const s of t){let t=this._componentToEntities.get(s);n?(t||(t=ye._entitySetPool.obtain(),this._componentToEntities.set(s,t)),t.add(e)):t&&(t.delete(e),0===t.size&&(this._componentToEntities.delete(s),ye._entitySetPool.release(t)))}}}ye._entitySetPool=_.getPool(ge,50,512);class fe{constructor(){this.buckets=new Map,this._size=0}get size(){return this._size}get innerBuckets(){return this.buckets}murmur32(e,t){let n=t>>>0;const s=e=>{e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n^=e,n=n<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(s(e.base[0]>>>0),s(e.base[1]>>>0),e.segments)for(const t of e.segments)s(t[0]>>>0),s(t[1]>>>0);return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,n^=n>>>16,n>>>0}getHashes(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]}set(e,t){const[n,s]=this.getHashes(e);let i=this.buckets.get(n);i||(i=[],this.buckets.set(n,i));for(let e=0;e<i.length;e++)if(i[e][0]===s)return i[e][1]=t,this;return i.push([s,t]),this._size++,this}get(e){const[t,n]=this.getHashes(e),s=this.buckets.get(t);if(s)for(let e=0;e<s.length;e++)if(s[e][0]===n)return s[e][1]}has(e){return void 0!==this.get(e)}delete(e){const[t,n]=this.getHashes(e),s=this.buckets.get(t);if(!s)return!1;for(let e=0;e<s.length;e++)if(s[e][0]===n)return s.splice(e,1),this._size--,0===s.length&&this.buckets.delete(t),!0;return!1}clear(){this.buckets.clear(),this._size=0}*entries(){for(const[e,t]of this.buckets)for(const[e,n]of t)yield[void 0,n]}*values(){for(const e of this.buckets.values())for(const[t,n]of e)yield n}}class _e{constructor(){this._archetypes=new fe,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}addEntity(e){const t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t);let s=this._archetypes.get(n);s||(s=this.createArchetype(t)),s.entities.add(e),this._entityToArchetype.set(e,s)}removeEntity(e){const t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))}updateEntity(e){const t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);const n=this.getEntityComponentTypes(e),s=this.generateArchetypeId(n);if(t&&t.id===s)return;t&&t.entities.delete(e);let i=this._archetypes.get(s);i||(i=this.createArchetype(n)),i.entities.add(e),this._entityToArchetype.set(e,i)}queryArchetypes(e,t="AND"){const n=[];let s=0;if("AND"===t){if(0===e.length){for(const e of this._allArchetypes)n.push(e),s+=e.entities.size;return{archetypes:n,totalEntities:s}}if(1===e.length){const t=this._componentToArchetypes.get(e[0]);if(t)for(const e of t)n.push(e),s+=e.entities.size;return{archetypes:n,totalEntities:s}}let t,i=1/0;for(const n of e){const e=this._componentToArchetypes.get(n);if(!e||0===e.size)return{archetypes:[],totalEntities:0};e.size<i&&(i=e.size,t=e)}const r=this.generateArchetypeId(e);if(t)for(const e of t)X.hasAll(e.id,r)&&(n.push(e),s+=e.entities.size)}else{const t=new Set;for(const n of e){const e=this._componentToArchetypes.get(n);if(e)for(const n of e)t.add(n)}for(const e of t)n.push(e),s+=e.entities.size}return{archetypes:n,totalEntities:s}}getEntityArchetype(e){return this._entityToArchetype.get(e)}getAllArchetypes(){return this._allArchetypes.slice()}getEntitiesByComponent(e){const t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];const n=[];for(const e of t)for(const t of e.entities)n.push(t);return n}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]}updateAllArchetypeArrays(){this._allArchetypes=[];for(const e of this._archetypes.values())this._allArchetypes.push(e)}getEntityComponentTypes(e){let t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((e=>e.constructor)),this._entityComponentTypesCache.set(e,t)),t}generateArchetypeId(e){const t=X.clone(X.ZERO);for(const n of e){te.isRegistered(n)||te.register(n);const e=te.getBitMask(n);X.orInPlace(t,e)}return t}createArchetype(e){const t=this.generateArchetypeId(e),n={id:t,componentTypes:[...e],entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(const t of e){let e=this._componentToArchetypes.get(t);e||(e=new Set,this._componentToArchetypes.set(t,e)),e.add(n)}return n}}!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Z||(Z={}));const Se=N("ReactiveQuery");var Ce;exports.ReactiveQueryChangeType=void 0,(Ce=exports.ReactiveQueryChangeType||(exports.ReactiveQueryChangeType={})).ADDED="added",Ce.REMOVED="removed",Ce.BATCH_UPDATE="batch_update";class ve{constructor(e,t={}){this._entities=[],this._entityIdSet=new Set,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:t.enableBatchMode??!0,batchDelay:t.batchDelay??16,debug:t.debug??!1},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&Se.debug(`创建ReactiveQuery: ${this._id}`)}generateQueryId(){return`${this._condition.type}:${this._condition.componentTypes.map((e=>e.name)).sort().join(",")}`}subscribe(e){if(!this._active)throw new Error(`Cannot subscribe to disposed ReactiveQuery ${this._id}`);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&Se.debug(`订阅ReactiveQuery: ${this._id}, 监听器数量: ${this._listeners.length}`),()=>{const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}unsubscribeAll(){this._listeners.length=0}getEntities(){return this._entities}get count(){return this._entities.length}matches(e){const t=e.componentMask;switch(this._condition.type){case Z.ALL:return X.hasAll(t,this._condition.mask);case Z.ANY:return X.hasAny(t,this._condition.mask);case Z.NONE:return X.hasNone(t,this._condition.mask);default:return!1}}notifyEntityAdded(e){this._active&&this.matches(e)&&(this._entityIdSet.has(e.id)||(this._entities.push(e),this._entityIdSet.add(e.id),this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.ADDED,entity:e}),this._config.debug&&Se.debug(`ReactiveQuery ${this._id}: 实体添加 ${e.name}(${e.id})`)))}notifyEntityRemoved(e){if(!this._active)return;if(!this._entityIdSet.has(e.id))return;const t=this._entities.indexOf(e);-1!==t&&this._entities.splice(t,1),this._entityIdSet.delete(e.id),this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.REMOVED,entity:e}),this._config.debug&&Se.debug(`ReactiveQuery ${this._id}: 实体移除 ${e.name}(${e.id})`)}notifyEntityChanged(e){if(!this._active)return;const t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}initializeWith(e){this._entities.length=0,this._entityIdSet.clear();for(const t of e)this.matches(t)&&(this._entities.push(t),this._entityIdSet.add(t.id));this._config.debug&&Se.debug(`ReactiveQuery ${this._id}: 初始化 ${this._entities.length} 个实体`)}addToBatch(e,t){"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout((()=>{this.flushBatchChanges()}),this._config.batchDelay))}flushBatchChanges(){if(0===this._batchChanges.added.length&&0===this._batchChanges.removed.length)return void(this._batchChanges.timer=null);const e=[...this._batchChanges.added],t=[...this._batchChanges.removed];this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:exports.ReactiveQueryChangeType.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&Se.debug(`ReactiveQuery ${this._id}: 批量更新 +${e.length} -${t.length}`)}notifyListeners(e){const t=[...this._listeners];for(const n of t)try{n(e)}catch(e){Se.error(`ReactiveQuery ${this._id}: 监听器执行出错`,e)}}pause(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0}resume(){this._active=!0}dispose(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._config.debug&&Se.debug(`ReactiveQuery ${this._id}: 已销毁`)}get condition(){return this._condition}get id(){return this._id}get active(){return this._active}get listenerCount(){return this._listeners.length}}class Ee{constructor(){this._logger=N("QuerySystem"),this._entities=[],this._version=0,this._queryCache=new Map,this._cacheMaxSize=1e3,this._cacheTimeout=5e3,this._componentMaskCache=new Map,this._queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this._entityIndex={byTag:new Map,byName:new Map},this._archetypeSystem=new _e}setEntities(e){this._entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()}addEntity(e,t=!1){this._entities.includes(e)||(this._entities.push(e),this.addEntityToIndexes(e),this._archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)}addEntities(e){if(0===e.length)return;const t=new Set(this._entities.map((e=>e.id)));let n=0;for(const s of e)t.has(s.id)||(this._entities.push(s),this.addEntityToIndexes(s),this._archetypeSystem.addEntity(s),t.add(s.id),n++);n>0&&this.clearQueryCache()}addEntitiesUnchecked(e){if(0!==e.length){for(const t of e)this._entities.push(t);for(const t of e)this.addEntityToIndexes(t),this._archetypeSystem.addEntity(t);this.clearQueryCache()}}removeEntity(e){const t=this._entities.indexOf(e);if(-1!==t){const n=[];for(const t of e.components)n.push(t.constructor);this._entities.splice(t,1),this.removeEntityFromIndexes(e),this._archetypeSystem.removeEntity(e),n.length>0?this.notifyReactiveQueriesEntityRemoved(e,n):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}}updateEntity(e){this._entities.includes(e)?(this.removeEntityFromIndexes(e),this._archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)}addEntityToIndexes(e){const t=e.tag;if(void 0!==t){(this._entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e)}const n=e.name;if(n){(this._entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)}}createAndSetTagIndex(e){const t=new Set;return this._entityIndex.byTag.set(e,t),t}createAndSetNameIndex(e){const t=new Set;return this._entityIndex.byName.set(e,t),t}removeEntityFromIndexes(e){if(void 0!==e.tag){const t=this._entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this._entityIndex.byTag.delete(e.tag))}if(e.name){const t=this._entityIndex.byName.get(e.name);t&&(t.delete(e),0===t.size&&this._entityIndex.byName.delete(e.name))}}rebuildIndexes(){this._entityIndex.byTag.clear(),this._entityIndex.byName.clear(),this._archetypeSystem.clear();for(const e of this._entities)this.addEntityToIndexes(e),this._archetypeSystem.addEntity(e)}queryAll(...e){const t=performance.now();this._queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.ALL,e).getEntities();return this._queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryAny(...e){const t=performance.now();this._queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.ANY,e).getEntities();return this._queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryNone(...e){const t=performance.now();this._queryStats.totalQueries++;const n=this.getOrCreateReactiveQuery(Z.NONE,e).getEntities();return this._queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-t,fromCache:!0}}queryByTag(e){const t=performance.now();this._queryStats.totalQueries++;const n=`tag:${e}`,s=this.getFromCache(n);if(s)return this._queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;const i=Array.from(this._entityIndex.byTag.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}queryByName(e){const t=performance.now();this._queryStats.totalQueries++;const n=`name:${e}`,s=this.getFromCache(n);if(s)return this._queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;const i=Array.from(this._entityIndex.byName.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}queryByComponent(e){const t=performance.now();this._queryStats.totalQueries++;const n=this.generateCacheKey("component",[e]),s=this.getFromCache(n);if(s)return this._queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;const i=this._archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}}getFromCache(e){const t=this._queryCache.get(e);return t?Date.now()-t.timestamp>this._cacheTimeout||t.version!==this._version?(this._queryCache.delete(e),null):(t.hitCount++,t.entities):null}addToCache(e,t){this._queryCache.size>=this._cacheMaxSize&&this.cleanupCache(),this._queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})}cleanupCache(){const e=Date.now();for(const[t,n]of this._queryCache.entries())e-n.timestamp>this._cacheTimeout&&this._queryCache.delete(t);if(this._queryCache.size>=this._cacheMaxSize){let e=1/0,t="",n=1/0;for(const[s,i]of this._queryCache.entries())(i.hitCount<e||i.hitCount===e&&i.timestamp<n)&&(e=i.hitCount,t=s,n=i.timestamp);t&&this._queryCache.delete(t)}}clearQueryCache(){this._queryCache.clear(),this._componentMaskCache.clear()}clearReactiveQueries(){for(const e of this._reactiveQueries.values())e.dispose();this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()}generateCacheKey(e,t){if(1===t.length){return`${e}:${b(t[0])}`}return`${e}:${t.map((e=>b(e))).sort().join(",")}`}clearCache(){this.clearQueryCache(),this.clearReactiveQueries()}createReactiveQuery(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");const n=this.createComponentMask(e),s={type:Z.ALL,componentTypes:e,mask:n},i=new ve(s,t),r=this.executeTraditionalQuery(Z.ALL,e);i.initializeWith(r);const o=this.generateCacheKey("all",e);this._reactiveQueries.set(o,i);for(const t of e){let e=this._reactiveQueriesByComponent.get(t);e||(e=new Set,this._reactiveQueriesByComponent.set(t,e)),e.add(i)}return i}destroyReactiveQuery(e){if(!e)return;const t=e.id;this._reactiveQueries.delete(t);for(const t of e.condition.componentTypes){const n=this._reactiveQueriesByComponent.get(t);n&&(n.delete(e),0===n.size&&this._reactiveQueriesByComponent.delete(t))}e.dispose()}createComponentMask(e){const t=e.map((e=>b(e))).sort().join(","),n=this._componentMaskCache.get(t);if(n)return n;const s=X.clone(X.ZERO);for(const t of e){te.isRegistered(t)||te.register(t);const e=te.getBitMask(t);X.orInPlace(s,e)}return this._componentMaskCache.set(t,s),s}get version(){return this._version}getAllEntities(){return this._entities}getStats(){return{entityCount:this._entities.length,indexStats:{componentIndexSize:this._archetypeSystem.getAllArchetypes().length,tagIndexSize:this._entityIndex.byTag.size,nameIndexSize:this._entityIndex.byName.size},queryStats:{...this._queryStats,cacheHitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{archetypeSystem:this._archetypeSystem.getAllArchetypes().map((e=>({id:e.id,componentTypes:e.componentTypes.map((e=>b(e))),entityCount:e.entities.size})))},cacheStats:{size:this._reactiveQueries.size,hitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}getEntityArchetype(e){return this._archetypeSystem.getEntityArchetype(e)}getOrCreateReactiveQuery(e,t){const n=this.generateCacheKey(e,t);let s=this._reactiveQueries.get(n);if(!s){const i=this.createComponentMask(t);s=new ve({type:e,componentTypes:t,mask:i},{enableBatchMode:!1,debug:!1});const r=this.executeTraditionalQuery(e,t);s.initializeWith(r),this._reactiveQueries.set(n,s);for(const e of t){let t=this._reactiveQueriesByComponent.get(e);t||(t=new Set,this._reactiveQueriesByComponent.set(e,t)),t.add(s)}this._logger.debug(`创建内部响应式查询缓存: ${n}`)}return s}executeTraditionalQuery(e,t){switch(e){case Z.ALL:{const e=this._archetypeSystem.queryArchetypes(t,"AND"),n=[];for(const t of e.archetypes)for(const e of t.entities)n.push(e);return n}case Z.ANY:{const e=this._archetypeSystem.queryArchetypes(t,"OR"),n=[];for(const t of e.archetypes)for(const e of t.entities)n.push(e);return n}case Z.NONE:{const e=this.createComponentMask(t);return this._entities.filter((t=>X.hasNone(t.componentMask,e)))}default:return[]}}notifyReactiveQueriesEntityAdded(e){if(0===this._reactiveQueries.size)return;const t=new Set;for(const n of e.components){const s=n.constructor,i=this._reactiveQueriesByComponent.get(s);if(i)for(const n of i)t.has(n)||(n.notifyEntityAdded(e),t.add(n))}}notifyReactiveQueriesEntityRemoved(e,t){if(0===this._reactiveQueries.size)return;const n=new Set;for(const s of t){const t=this._reactiveQueriesByComponent.get(s);if(t)for(const s of t)n.has(s)||(s.notifyEntityRemoved(e),n.add(s))}}notifyReactiveQueriesEntityRemovedFallback(e){if(0!==this._reactiveQueries.size)for(const t of this._reactiveQueries.values())t.notifyEntityRemoved(e)}notifyReactiveQueriesEntityChanged(e){if(0===this._reactiveQueries.size)return;const t=new Set;for(const n of e.components){const s=n.constructor,i=this._reactiveQueriesByComponent.get(s);if(i)for(const n of i)t.has(n)||(n.notifyEntityChanged(e),t.add(n))}for(const n of this._reactiveQueries.values())t.has(n)||n.notifyEntityChanged(e)}}class be{constructor(e){this._logger=N("QueryBuilder"),this.conditions=[],this.querySystem=e}withAll(...e){return this.conditions.push({type:Z.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this}withAny(...e){return this.conditions.push({type:Z.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this}without(...e){return this.conditions.push({type:Z.NONE,componentTypes:e,mask:this.createComponentMask(e)}),this}execute(){const e=performance.now();if(1===this.conditions.length){const e=this.conditions[0];switch(e.type){case Z.ALL:return this.querySystem.queryAll(...e.componentTypes);case Z.ANY:return this.querySystem.queryAny(...e.componentTypes);case Z.NONE:return this.querySystem.queryNone(...e.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-e,fromCache:!1}}createComponentMask(e){const t=X.clone(X.ZERO);for(const n of e)try{const e=te.getBitMask(n);X.orInPlace(t,e)}catch(e){this._logger.warn(`组件类型 ${b(n)} 未注册,跳过`)}return t}reset(){return this.conditions=[],this}}class Te{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(e,t,n={}){return this.addListener(e,t,n)}once(e,t,n={}){return this.addListener(e,t,{...n,once:!0})}onAsync(e,t,n={}){return this.addListener(e,t,{...n,async:!0})}off(e,t){const n=this.listeners.get(e);if(!n)return!1;const s=n.findIndex((e=>e.id===t));return-1!==s&&(n.splice(s,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)}offAll(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)}async emit(e,t){if(!this.isEnabled)return;const n=this.batchConfigs.get(e);n?.enabled?this.addToBatch(e,t):await this.executeEvent(e,t)}emitSync(e,t){if(!this.isEnabled)return;const n=this.listeners.get(e);if(!n||0===n.length)return;const s=performance.now(),i=[],r=this.sortListenersByPriority(n);for(const n of r)if(!n.config.async)try{n.config.thisArg?n.handler.call(n.config.thisArg,t):n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`事件处理器执行错误 ${e}:`,t)}this.removeListeners(e,i),this.updateStats(e,performance.now()-s)}setBatchConfig(e,t){this.batchConfigs.set(e,t)}flushBatch(e){const t=this.batchQueue.get(e);if(!t||0===t.length)return;const n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}getStats(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)}resetStats(e){e?this.stats.delete(e):this.stats.clear()}setEnabled(e){this.isEnabled=e}hasListeners(e){const t=this.listeners.get(e);return!!t&&t.length>0}getListenerCount(e){const t=this.listeners.get(e);return t?t.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(e){this.maxListeners=e}addListener(e,t,n){let s=this.listeners.get(e);if(s||(s=[],this.listeners.set(e,s)),s.length>=this.maxListeners)return Te._logger.warn(`事件类型 ${e} 的监听器数量超过最大限制 (${this.maxListeners})`),"";const i="listener_"+this.nextListenerId++,r={handler:t,config:{priority:0,...n},id:i};return s.push(r),this.stats.has(e)||this.stats.set(e,this.createEmptyStats(e)),i}async executeEvent(e,t){const n=this.listeners.get(e);if(!n||0===n.length)return;const s=performance.now(),i=[],r=this.sortListenersByPriority(n),o=r.filter((e=>!e.config.async)),a=r.filter((e=>e.config.async));for(const n of o)try{n.config.thisArg?n.handler.call(n.config.thisArg,t):n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`同步事件处理器执行错误 ${e}:`,t)}const c=a.map((async n=>{try{n.config.thisArg?await n.handler.call(n.config.thisArg,t):await n.handler(t),n.config.once&&i.push(n.id)}catch(t){Te._logger.error(`异步事件处理器执行错误 ${e}:`,t)}}));await Promise.all(c),this.removeListeners(e,i),this.updateStats(e,performance.now()-s)}sortListenersByPriority(e){return e.slice().sort(((e,t)=>(t.config.priority||0)-(e.config.priority||0)))}removeListeners(e,t){if(0===t.length)return;const n=this.listeners.get(e);if(n){for(const e of t){const t=n.findIndex((t=>t.id===e));-1!==t&&n.splice(t,1)}0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}addToBatch(e,t){let n=this.batchQueue.get(e);n||(n=[],this.batchQueue.set(e,n)),n.push(t);const s=this.batchConfigs.get(e);if(n.length>=s.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){const t=setTimeout((()=>{this.flushBatch(e)}),s.delay);this.batchTimers.set(e,t)}}async processBatch(e,t){const n={type:e,events:t,count:t.length,timestamp:Date.now()};await this.executeEvent(`${e}:batch`,n)}clearBatch(e){this.batchQueue.delete(e);const t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))}clearAllBatches(){this.batchQueue.clear();for(const e of this.batchTimers.values())clearTimeout(e);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(e,t){let n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)}createEmptyStats(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}Te._logger=N("EventSystem");class we{constructor(e,t){this._entities=e,this._componentTypes=t}get entities(){return this._entities}get length(){return this._entities.length}forEach(e){this._entities.forEach(e)}map(e){return this._entities.map(e)}filter(e){return new we(this._entities.filter(e),this._componentTypes)}find(e){return this._entities.find(e)}some(e){return this._entities.some(e)}every(e){return this._entities.every(e)}get(e){return this._entities[e]}get first(){return this._entities[0]}get last(){return this._entities[this._entities.length-1]}get isEmpty(){return 0===this._entities.length}toArray(){return[...this._entities]}getComponentTypes(){return this._componentTypes}[Symbol.iterator](){return this._entities[Symbol.iterator]()}}class Ae{constructor(e,t,n,s,i){this._all=e||[],this._any=t||[],this._none=n||[],void 0!==s&&(this._tag=s),void 0!==i&&(this._name=i)}withAll(...e){return new Ae([...this._all,...e],this._any,this._none,this._tag,this._name)}withAny(...e){return new Ae(this._all,[...this._any,...e],this._none,this._tag,this._name)}withNone(...e){return new Ae(this._all,this._any,[...this._none,...e],this._tag,this._name)}withTag(e){return new Ae(this._all,this._any,this._none,e,this._name)}withName(e){return new Ae(this._all,this._any,this._none,this._tag,e)}buildMatcher(){let e=he.complex();return this._all.length>0&&(e=e.all(...this._all)),this._any.length>0&&(e=e.any(...this._any)),this._none.length>0&&(e=e.none(...this._none)),void 0!==this._tag&&(e=e.withTag(this._tag)),void 0!==this._name&&(e=e.withName(this._name)),e}getCondition(){return{all:[...this._all],any:[...this._any],none:[...this._none],...void 0!==this._tag&&{tag:this._tag},...void 0!==this._name&&{name:this._name}}}getRequiredTypes(){return this._all}clone(){return new Ae([...this._all],[...this._any],[...this._none],this._tag,this._name)}}const Me=Symbol("SerializableMetadata"),Ie=Symbol("SerializeField"),xe=Symbol("SerializeOptions");function De(e){return function(t,n){const s=t.constructor;let i=s[Me];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},s[Me]=i),i.fields.set(n,e||{})}}function ke(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Me]||null}class Re{static serialize(e){const t=ke(e);if(!t)return null;const n=e.constructor,s=t.options.typeId||b(n),i={};for(const[n,s]of t.fields){const r="symbol"==typeof n?n.toString():n,o=e[n];if(t.ignoredFields.has(n))continue;const a=s.serializer?s.serializer(o):this.serializeValue(o);i[s.alias||r]=a}return{type:s,version:t.options.version,data:i}}static deserialize(e,t){const n=t.get(e.type);if(!n)return console.warn(`未找到组件类型: ${e.type}`),null;const s=ke(n);if(!s)return console.warn(`组件 ${e.type} 不可序列化`),null;const i=new n;for(const[t,n]of s.fields){const s="symbol"==typeof t?t.toString():t,r=n.alias||s,o=e.data[r];if(void 0===o)continue;const a=n.deserializer?n.deserializer(o):this.deserializeValue(o);i[t]=a}return i}static serializeComponents(e){const t=[];for(const n of e){const e=this.serialize(n);e&&t.push(e)}return t}static deserializeComponents(e,t){const n=[];for(const s of e){const e=this.deserialize(s,t);e&&n.push(e)}return n}static serializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((e=>this.serializeValue(e)));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===t&&"object"==typeof e&&!Array.isArray(e)){const t={},n=e;for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=this.serializeValue(n[e]));return t}}static deserializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if("object"===t&&"object"==typeof e&&"__type"in e){const t=e;switch(t.__type){case"Date":return{__type:"Date",value:"string"==typeof t.value?t.value:String(t.value)};case"Map":return{__type:"Map",value:t.value};case"Set":return{__type:"Set",value:t.value}}}if(Array.isArray(e))return e.map((e=>this.deserializeValue(e)));if("object"===t&&"object"==typeof e&&!Array.isArray(e)){const t={},n=e;for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=this.deserializeValue(n[e]));return t}return e}static validateVersion(e,t){return e.version===t}static getSerializationInfo(e){const t=ke(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};const n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||b(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((e=>"symbol"==typeof e?e.toString():e)),ignoredFields:Array.from(t.ignoredFields).map((e=>"symbol"==typeof e?e.toString():e)),isSerializable:!0}}}class Oe{static serialize(e,t=!0){const n=Re.serializeComponents(Array.from(e.components)),s={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(s.parentId=e.parent.id),t)for(const t of e.children)s.children.push(this.serialize(t,!0));return s}static deserialize(e,t,n,s=!1,i){const r=s?e.id:n(),o=new re(e.name,r);i&&(o.scene=i),o.tag=e.tag,o.active=e.active,o.enabled=e.enabled,o.updateOrder=e.updateOrder;const a=Re.deserializeComponents(e.components,t);for(const e of a)o.addComponent(e);for(const r of e.children){const e=this.deserialize(r,t,n,s,i);o.addChild(e)}return o}static serializeEntities(e,t=!0){const n=[];for(const s of e)s.parent&&t||n.push(this.serialize(s,t));return n}static deserializeEntities(e,t,n,s=!1,i){const r=[];for(const o of e){const e=this.deserialize(o,t,n,s,i);r.push(e)}return r}static clone(e,t,n){const s=this.serialize(e,!0);return this.deserialize(s,t,n,!1)}}class ze{static stringToUtf8(e){const t=e.length;let n=0;const s=[];for(let i=0;i<t;i++){let r=e.charCodeAt(i);if(r>=55296&&r<=56319&&i+1<t){const t=r,n=e.charCodeAt(i+1);n>=56320&&n<=57343&&(r=65536+(t-55296<<10)+(n-56320),i++)}r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r<65536?(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return new Uint8Array(s)}static utf8ToString(e){const t=e.length;let n="",s=0;for(;s<t;){const t=e[s++];if(void 0===t)break;if(t<128)n+=String.fromCharCode(t);else if(192==(224&t)){const i=e[s++];if(void 0===i)break;n+=String.fromCharCode((31&t)<<6|63&i)}else if(224==(240&t)){const i=e[s++],r=e[s++];if(void 0===i||void 0===r)break;n+=String.fromCharCode((15&t)<<12|(63&i)<<6|63&r)}else if(240==(248&t)){const i=e[s++],r=e[s++],o=e[s++];if(void 0===i||void 0===r||void 0===o)break;let a=(7&t)<<18|(63&i)<<12|(63&r)<<6|63&o;a-=65536,n+=String.fromCharCode(55296+(a>>10),56320+(1023&a))}}return n}static encode(e){const t=JSON.stringify(e);return this.stringToUtf8(t)}static decode(e){const t=this.utf8ToString(e);return JSON.parse(t)}}class Pe{static serialize(e,t){const n={systems:!1,format:"json",pretty:!0,includeMetadata:!0,...t},s=this.filterEntities(e,n),i=Oe.serializeEntities(s,!0),r=this.buildComponentTypeRegistry(s),o=this.serializeSceneData(e.sceneData),a={name:e.name,version:this.SERIALIZATION_VERSION,entities:i,componentTypeRegistry:r};return o&&Object.keys(o).length>0&&(a.sceneData=o),n.includeMetadata&&(a.timestamp=Date.now(),a.metadata={entityCount:i.length,componentTypeCount:r.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(a,null,2):JSON.stringify(a):ze.encode(a)}static deserialize(e,t,n){const s={strategy:"replace",preserveIds:!1,...n};let i;try{i="string"==typeof t?JSON.parse(t):ze.decode(t)}catch(e){throw new Error(`Failed to parse save data: ${e}`)}s.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=s.migration(i.version,this.SERIALIZATION_VERSION,i));const r=s.componentRegistry||this.getGlobalComponentRegistry();"replace"===s.strategy&&e.destroyAllEntities();const o=Oe.deserializeEntities(i.entities,r,(()=>e.identifierPool.checkOut()),s.preserveIds||!1,e);for(const t of o)e.addEntity(t,!0),this.addChildrenRecursively(t,e);e.querySystem.clearCache(),e.clearSystemEntityCaches(),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData)}static addChildrenRecursively(e,t){for(const n of e.children)t.addEntity(n,!0),this.addChildrenRecursively(n,t)}static serializeSceneData(e){const t={};for(const[n,s]of e)t[n]=this.serializeValue(s);return t}static deserializeSceneData(e,t){t.clear();for(const[n,s]of Object.entries(e))t.set(n,this.deserializeValue(s))}static serializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((e=>this.serializeValue(e)));if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.serializeValue(e[n]));return t}}static deserializeValue(e){if(null==e)return e;const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if("object"===t&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((e=>this.deserializeValue(e)));if("object"===t){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deserializeValue(e[n]));return t}return e}static filterEntities(e,t){const n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){const e=new Set(t.components);return n.filter((t=>Array.from(t.components).some((t=>e.has(t.constructor)))))}return n}static buildComponentTypeRegistry(e){const t=new Map;for(const n of e)for(const e of n.components){const n=b(e.constructor),s=ke(e);s&&!t.has(n)&&t.set(n,s.options.version)}return Array.from(t.entries()).map((([e,t])=>({typeName:e,version:t})))}static getGlobalComponentRegistry(){return te.getAllComponentNames()}static validate(e){const t=[];try{const n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,...t.length>0&&{errors:t}}}catch(e){return{valid:!1,errors:[`JSON parse error: ${e}`]}}}static getInfo(e){try{const t=JSON.parse(e);return{name:t.name,version:t.version,...void 0!==t.timestamp&&{timestamp:t.timestamp},entityCount:t.metadata?.entityCount||t.entities.length,componentTypeCount:t.componentTypeRegistry.length}}catch(e){return null}}}var Ne;Pe.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(Ne=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",Ne.EntityRemoved="entity_removed",Ne.EntityUpdated="entity_updated",Ne.ComponentAdded="component_added",Ne.ComponentRemoved="component_removed",Ne.ComponentUpdated="component_updated",Ne.SceneDataUpdated="scene_data_updated";class Le{static createSnapshot(e,t){const n={deepComponentComparison:!0,trackSceneData:!0,...t},s={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map};for(const t of e.entities.buffer)if(s.entityIds.add(t.id),s.entities.set(t.id,{name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,...t.parent&&{parentId:t.parent.id}}),n.deepComponentComparison){const e=new Map;for(const n of t.components){const t=Re.serialize(n);t&&e.set(t.type,JSON.stringify(t.data))}e.size>0&&s.components.set(t.id,e)}if(n.trackSceneData)for(const[t,n]of e.sceneData)s.sceneData.set(t,JSON.stringify(n));return s}static computeIncremental(e,t,n){const s={deepComponentComparison:!0,trackSceneData:!0,...n},i={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},r=new Set;for(const n of e.entities.buffer)if(r.add(n.id),t.entityIds.has(n.id)){const e=t.entities.get(n.id);(e.name!==n.name||e.tag!==n.tag||e.active!==n.active||e.enabled!==n.enabled||e.updateOrder!==n.updateOrder||e.parentId!==n.parent?.id)&&i.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:n.id,entityData:{name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,...n.parent&&{parentId:n.parent.id}}}),s.deepComponentComparison&&this.detectComponentChanges(n,t,i.componentChanges)}else{i.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:n.id,entityName:n.name,entityData:{id:n.id,name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,...n.parent&&{parentId:n.parent.id},components:[],children:[]}});for(const e of n.components){const t=Re.serialize(e);t&&i.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:n.id,componentType:t.type,componentData:t})}}for(const e of t.entityIds)r.has(e)||i.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:e});return s.trackSceneData&&this.detectSceneDataChanges(e,t,i.sceneDataChanges),i}static detectComponentChanges(e,t,n){const s=t.components.get(e.id),i=new Map;for(const t of e.components){const e=Re.serialize(t);e&&i.set(e.type,e)}for(const[t,r]of i){const i=JSON.stringify(r.data);s&&s.has(t)?s.get(t)!==i&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:t,componentData:r}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:t,componentData:r})}if(s)for(const t of s.keys())i.has(t)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:t})}static detectSceneDataChanges(e,t,n){const s=new Set;for(const[i,r]of e.sceneData){s.add(i);const e=JSON.stringify(r),o=t.sceneData.get(i);o&&o===e||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:i,value:r})}for(const e of t.sceneData.keys())s.has(e)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:e,value:void 0,deleted:!0})}static applyIncremental(e,t,n){for(const n of t.entityChanges)switch(n.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,n);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,n);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,n)}for(const s of t.componentChanges)switch(s.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,s,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,s,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,s,n)}for(const n of t.sceneDataChanges)n.deleted?e.sceneData.delete(n.key):e.sceneData.set(n.key,n.value)}static applyEntityAdded(e,t){if(!t.entityData)return;const n=new re(t.entityName||"Entity",t.entityId);n.tag=t.entityData.tag||0,n.active=t.entityData.active??!0,n.enabled=t.entityData.enabled??!0,n.updateOrder=t.entityData.updateOrder||0,e.addEntity(n)}static applyEntityRemoved(e,t){const n=e.entities.findEntityById(t.entityId);n&&n.destroy()}static applyEntityUpdated(e,t){if(!t.entityData)return;const n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){const s=e.entities.findEntityById(t.entityData.parentId);s&&n.parent!==s&&(n.parent&&n.parent.removeChild(n),s.addChild(n))}else n.parent&&n.parent.removeChild(n)}static applyComponentAdded(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=Re.deserialize(t.componentData,n);i&&s.addComponent(i)}static applyComponentRemoved(e,t,n){const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=n.get(t.componentType);i&&s.removeComponentByType(i)}static applyComponentUpdated(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=n.get(t.componentType);if(!i)return;s.removeComponentByType(i);const r=Re.deserialize(t.componentData,n);r&&s.addComponent(r)}static serializeIncremental(e,t){const n={format:"json",pretty:!1,...t};return"binary"===n.format?ze.encode(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}static deserializeIncremental(e){return"string"==typeof e?JSON.parse(e):ze.decode(e)}static getIncrementalStats(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityAdded)).length,removedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityRemoved)).length,updatedEntities:e.entityChanges.filter((e=>e.operation===exports.ChangeOperation.EntityUpdated)).length,addedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentAdded)).length,removedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentRemoved)).length,updatedComponents:e.componentChanges.filter((e=>e.operation===exports.ChangeOperation.ComponentUpdated)).length}}static resetVersion(){this.snapshotVersion=0}}Le.snapshotVersion=0;const Be=N("ServiceContainer");var $e;exports.ServiceLifetime=void 0,($e=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",$e.Transient="transient";class We{constructor(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}registerSingleton(e,t){this._services.has(e)?Be.warn(`Service ${e.name} is already registered`):(this._services.set(e,{type:e,...t&&{factory:t},lifetime:exports.ServiceLifetime.Singleton}),Be.debug(`Registered singleton service: ${e.name}`))}registerTransient(e,t){this._services.has(e)?Be.warn(`Service ${e.name} is already registered`):(this._services.set(e,{type:e,...t&&{factory:t},lifetime:exports.ServiceLifetime.Transient}),Be.debug(`Registered transient service: ${e.name}`))}registerInstance(e,t){if(this._services.has(e))Be.warn(`Service ${e.name} is already registered`);else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),m(e)){const n=g(e),s=n?.priority??0;this._updatableServices.push({instance:t,priority:s}),this._updatableServices.sort(((e,t)=>e.priority-t.priority)),Be.debug(`Service ${e.name} is updatable (priority: ${s}), added to update list`)}Be.debug(`Registered service instance: ${e.name}`)}}resolve(e){const t=this._services.get(e);if(!t)throw new Error(`Service ${e.name} is not registered`);if(this._resolving.has(e)){const t=Array.from(this._resolving).map((e=>e.name)).join(" -> ");throw new Error(`Circular dependency detected: ${t} -> ${e.name}`)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{let n;if(n=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=n,m(t.type))){const s=g(t.type),i=s?.priority??0;this._updatableServices.push({instance:n,priority:i}),this._updatableServices.sort(((e,t)=>e.priority-t.priority)),Be.debug(`Service ${e.name} is updatable (priority: ${i}), added to update list`)}return n}finally{this._resolving.delete(e)}}tryResolve(e){try{return this.resolve(e)}catch{return null}}isRegistered(e){return this._services.has(e)}unregister(e){const t=this._services.get(e);if(!t)return!1;if(t.instance){const e=this._updatableServices.findIndex((e=>e.instance===t.instance));-1!==e&&this._updatableServices.splice(e,1),t.instance.dispose()}return this._services.delete(e),Be.debug(`Unregistered service: ${e.name}`),!0}clear(){for(const[,e]of this._services)e.instance&&e.instance.dispose();this._services.clear(),this._updatableServices=[],Be.debug("Cleared all services")}getRegisteredServices(){return Array.from(this._services.keys())}updateAll(e){for(const{instance:t}of this._updatableServices)t.update(e)}getUpdatableCount(){return this._updatableServices.length}getAll(){const e=[];for(const t of this._services.values())t.instance&&e.push(t.instance);return e}}class Fe{get systems(){return!this._systemsOrderDirty&&this._cachedSystems||(this._cachedSystems=this._rebuildSystemsCache(),this._systemsOrderDirty=!1),this._cachedSystems}_rebuildSystemsCache(){const e=this._services.getAll(),t=this._filterEntitySystems(e);return this._sortSystemsByUpdateOrder(t)}_filterEntitySystems(e){return e.filter((e=>e instanceof ue))}_sortSystemsByUpdateOrder(e){return e.sort(((e,t)=>e.updateOrder-t.updateOrder))}getSystem(e){return this._services.tryResolve(e)}markSystemsOrderDirty(){this._systemsOrderDirty=!0}get services(){return this._services}constructor(e){this.name="",this.sceneData=new Map,this._performanceMonitor=null,this._didSceneBegin=!1,this._cachedSystems=null,this._systemsOrderDirty=!0,this._systemErrorCount=new Map,this._maxErrorCount=10,this.entities=new ae(this),this.identifierPool=new ce,this.componentStorageManager=new se,this.querySystem=new Ee,this.eventSystem=new Te,this.referenceTracker=new D,this._services=new We,this.logger=N("Scene"),e?.name&&(this.name=e.name)}get performanceMonitor(){return this._performanceMonitor||(this._performanceMonitor=this._services.tryResolve(f)??new f),this._performanceMonitor}initialize(){}onStart(){}unload(){}begin(){this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.unload(),this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this._cachedSystems=null,this._systemsOrderDirty=!0}update(){j.getInstance().update(),this.entities.updateLists();const e=this.systems;for(const t of e)if(t.enabled)try{t.update()}catch(e){this._handleSystemError(t,"update",e)}for(const t of e)if(t.enabled)try{t.lateUpdate()}catch(e){this._handleSystemError(t,"lateUpdate",e)}}_handleSystemError(e,t,n){const s=(this._systemErrorCount.get(e)||0)+1;this._systemErrorCount.set(e,s),this.logger.error(`Error in system ${e.constructor.name}.${t}() [${s}/${this._maxErrorCount}]:`,n),s>=this._maxErrorCount&&(e.enabled=!1,this.logger.error(`System ${e.constructor.name} has been disabled due to excessive errors (${s} errors)`))}createEntity(e){const t=new re(e,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)}clearSystemEntityCaches(){for(const e of this.systems)e.clearEntityCache()}addEntity(e,t=!1){return this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e}createEntities(e,t="Entity"){const n=[];for(let s=0;s<e;s++){const e=new re(`${t}_${s}`,this.identifierPool.checkOut());e.scene=this,n.push(e)}for(const e of n)this.entities.add(e);return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n}destroyEntities(e){if(0!==e.length){for(const t of e)t.setDestroyedState(!0);for(const t of e)t.removeAllComponents();for(const t of e)this.entities.remove(t),this.querySystem.removeEntity(t);this.querySystem.clearCache(),this.clearSystemEntityCaches()}}destroyAllEntities(){this.entities.removeAllEntities(),this.querySystem.setEntities([])}findEntity(e){return this.entities.findEntity(e)}findEntityById(e){return this.entities.findEntityById(e)}findEntitiesByTag(e){const t=[];for(const n of this.entities.buffer)n.tag===e&&t.push(n);return t}getEntityByName(e){return this.findEntity(e)}getEntitiesByTag(e){return this.findEntitiesByTag(e)}queryAll(...e){return this.querySystem.queryAll(...e)}queryAny(...e){return this.querySystem.queryAny(...e)}queryNone(...e){return this.querySystem.queryNone(...e)}query(){return new Ae}addEntityProcessor(e){let t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n)){const e=this._services.resolve(n);return this.logger.debug(`System ${n.name} already registered, returning existing instance`),e}t=u(n)?d(n,this._services):new n}else if(t=e,n=t.constructor,this._services.isRegistered(n)){const e=this._services.resolve(n);return e===t?(this.logger.debug(`System ${n.name} instance already registered, returning it`),t):(this.logger.warn(`Attempting to register a different instance of ${n.name}, but type is already registered. Returning existing instance.`),e)}t.scene=this,t.setPerformanceMonitor(this.performanceMonitor);const s=E(n);return void 0!==s?.updateOrder&&t.setUpdateOrder(s.updateOrder),void 0!==s?.enabled&&(t.enabled=s.enabled),this._services.registerInstance(n,t),this.markSystemsOrderDirty(),p(t,this._services),t.initialize(),this.logger.debug(`System ${n.name} registered and initialized`),t}registerSystems(e){const t=[];for(const n of e){const e=this.addEntityProcessor(n);t.push(e)}return t}addSystem(e){return this.addEntityProcessor(e)}removeEntityProcessor(e){const t=e.constructor;this._services.unregister(t),this.markSystemsOrderDirty(),e.reset()}removeSystem(e){this.removeEntityProcessor(e)}getEntityProcessor(e){return this._services.tryResolve(e)}getStats(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}}getDebugInfo(){const e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((e=>({name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e)))}))),processors:e.map((e=>({name:A(e),updateOrder:e.updateOrder,entityCount:e.entities.length}))),componentStats:this.componentStorageManager.getAllStats()}}serialize(e){return Pe.serialize(this,e)}deserialize(e,t){Pe.deserialize(this,e,t)}createIncrementalSnapshot(e){this._incrementalBaseSnapshot=Le.createSnapshot(this,e)}serializeIncremental(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Le.computeIncremental(this,this._incrementalBaseSnapshot,e)}applyIncremental(e,t){const n="string"==typeof e||e instanceof Uint8Array?Le.deserializeIncremental(e):e,s=t||te.getAllComponentNames();Le.applyIncremental(this,n,s)}updateIncrementalSnapshot(e){this.createIncrementalSnapshot(e)}clearIncrementalSnapshot(){this._incrementalBaseSnapshot=void 0}hasIncrementalSnapshot(){return void 0!==this._incrementalBaseSnapshot}}class He{constructor(){this.scene=new Fe}named(e){return this.scene.name=e,this}withEntity(e){return this.scene.addEntity(e),this}withEntityBuilder(e){const t=e(new oe(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this}withEntities(...e){for(const t of e)this.scene.addEntity(t);return this}withSystem(e){return this.scene.addSystem(e),this}withSystems(...e){for(const t of e)this.scene.addSystem(t);return this}build(){return this.scene}}class Ue{constructor(e,...t){this.component=new e(...t)}set(e,t){return this.component[e]=t,this}configure(e){return e(this.component),this}setIf(e,t,n){return e&&(this.component[t]=n),this}build(){return this.component}}class qe{constructor(e){this.entities=e}addComponent(e){for(const t of this.entities)t.addComponent(e);return this}removeComponent(e){for(const t of this.entities)t.removeComponentByType(e);return this}setActive(e){for(const t of this.entities)t.active=e;return this}setTag(e){for(const t of this.entities)t.tag=e;return this}forEach(e){return this.entities.forEach(e),this}filter(e){return new qe(this.entities.filter(e))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class Ge{constructor(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}createEntity(){return new oe(this.scene,this.scene.componentStorageManager)}createScene(){return new He}createComponent(e,...t){return new Ue(e,...t)}query(){return new be(this.querySystem)}find(...e){return this.querySystem.queryAll(...e).entities}findFirst(...e){const t=this.querySystem.queryAll(...e);return t.entities.length>0?t.entities[0]:null}findByName(e){return this.scene.findEntity(e)}findByTag(e){return this.scene.findEntitiesByTag(e)}emit(e,t){this.eventSystem.emitSync(e,t)}async emitAsync(e,t){await this.eventSystem.emit(e,t)}on(e,t){return this.eventSystem.on(e,t)}once(e,t){return this.eventSystem.once(e,t)}off(e,t){this.eventSystem.off(e,t)}batch(e){return new qe(e)}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()}}}function je(e,t,n){return new Ge(e,t,n)}const Qe=N("World");class Ve{constructor(e={}){this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,...e},this.name=this._config.name,this._createdAt=Date.now(),this._services=new We}get services(){return this._services}createScene(e,t){if(this._scenes.has(e))throw new Error(`Scene ID '${e}' 已存在于World '${this.name}' 中`);if(this._scenes.size>=this._config.maxScenes)throw new Error(`World '${this.name}' 已达到最大Scene数量限制: ${this._config.maxScenes}`);const n=t||new Fe;if(this._config.debug){const e=new f;e.enable(),n.services.registerInstance(f,e)}return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),n}removeScene(e){const t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),Qe.info(`从World '${this.name}' 中移除Scene: ${e}`),!0)}getScene(e){return this._scenes.get(e)||null}getSceneIds(){return Array.from(this._scenes.keys())}getAllScenes(){return Array.from(this._scenes.values())}removeAllScenes(){const e=Array.from(this._scenes.keys());for(const t of e)this.removeScene(t);Qe.info(`从World '${this.name}' 中移除所有Scene`)}setSceneActive(e,t){const n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin&&n.begin(),Qe.debug(`在World '${this.name}' 中激活Scene: ${e}`)):(this._activeScenes.delete(e),Qe.debug(`在World '${this.name}' 中停用Scene: ${e}`)):Qe.warn(`Scene '${e}' 不存在于World '${this.name}' 中`)}isSceneActive(e){return this._activeScenes.has(e)}getActiveSceneCount(){return this._activeScenes.size}addGlobalSystem(e){return this._globalSystems.includes(e)||(this._globalSystems.push(e),e.initialize&&e.initialize(),Qe.debug(`在World '${this.name}' 中添加全局System: ${e.name}`)),e}removeGlobalSystem(e){const t=this._globalSystems.indexOf(e);return-1!==t&&(this._globalSystems.splice(t,1),e.reset&&e.reset(),Qe.debug(`从World '${this.name}' 中移除全局System: ${e.name}`),!0)}getGlobalSystem(e){for(const t of this._globalSystems)if(t instanceof e)return t;return null}start(){if(!this._isActive){this._isActive=!0;for(const e of this._globalSystems)e.initialize&&e.initialize();Qe.info(`启动World: ${this.name}`)}}stop(){if(this._isActive){for(const e of this._activeScenes)this.setSceneActive(e,!1);for(const e of this._globalSystems)e.reset&&e.reset();this._isActive=!1,Qe.info(`停止World: ${this.name}`)}}updateGlobalSystems(){if(this._isActive)for(const e of this._globalSystems)e.update&&e.update()}updateScenes(){if(this._isActive){for(const e of this._activeScenes){const t=this._scenes.get(e);t&&t.update&&t.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}}destroy(){Qe.info(`销毁World: ${this.name}`),this.stop();const e=Array.from(this._scenes.keys());for(const t of e)this.removeScene(t);for(const e of this._globalSystems)e.destroy?e.destroy():e.reset&&e.reset();this._globalSystems.length=0,this._services.clear(),this._scenes.clear(),this._activeScenes.clear()}getStatus(){return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:{...this._config},scenes:Array.from(this._scenes.keys()).map((e=>({id:e,isActive:this._activeScenes.has(e),name:this._scenes.get(e)?.name||e})))}}getStats(){const e={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}};for(const t of this._scenes.values())t.entities&&(e.totalEntities+=t.entities.count),t.systems&&(e.totalSystems+=t.systems.length);return e}shouldAutoCleanup(){const e=Date.now();for(const[t,n]of this._scenes)if(!this._activeScenes.has(t)&&n.entities&&0===n.entities.count&&e-this._createdAt>3e5)return!0;return!1}cleanup(){const e=Array.from(this._scenes.keys()),t=Date.now();for(const n of e){const e=this._scenes.get(n);e&&!this._activeScenes.has(n)&&e.entities&&0===e.entities.count&&t-this._createdAt>3e5&&(this.removeScene(n),Qe.debug(`自动清理空Scene: ${n} from World ${this.name}`))}}get isActive(){return this._isActive}get sceneCount(){return this._scenes.size}get createdAt(){return this._createdAt}}class Ye{constructor(e){this._nextScene=null,this._ecsAPI=null,this._logger=N("SceneManager"),this._performanceMonitor=null,this._defaultWorld=new Ve({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}setSceneChangedCallback(e){this._onSceneChangedCallback=e}setScene(e){return this._defaultWorld.removeAllScenes(),this._performanceMonitor&&e.services.registerInstance(f,this._performanceMonitor),this._defaultWorld.createScene(Ye.DEFAULT_SCENE_ID,e),this._defaultWorld.setSceneActive(Ye.DEFAULT_SCENE_ID,!0),e.querySystem&&e.eventSystem?this._ecsAPI=je(e,e.querySystem,e.eventSystem):this._ecsAPI=null,s.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info(`Scene changed to: ${e.name}`),e}loadScene(e){this._nextScene=e,this._logger.info(`Scheduled scene load: ${e.name}`)}get currentScene(){return this._defaultWorld.getScene(Ye.DEFAULT_SCENE_ID)}get api(){return this._ecsAPI}update(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()}destroy(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")}get hasScene(){return null!==this._defaultWorld.getScene(Ye.DEFAULT_SCENE_ID)}get hasPendingScene(){return null!==this._nextScene}dispose(){this.destroy()}}var Je;Ye.DEFAULT_SCENE_ID="__main__",exports.DebugConfigService=class{constructor(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}setConfig(e){this._config=e}getConfig(){return this._config}isEnabled(){return this._config.enabled}dispose(){}},exports.DebugConfigService=e([c(),n("design:paramtypes",[])],exports.DebugConfigService),exports.DebugManager=class{constructor(e,t,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},this.config=n.getConfig(),this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new H,this.systemCollector=new U,this.performanceCollector=new q,this.componentCollector=new Q,this.sceneCollector=new V,this.webSocketManager=new Y(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const s=this.config.debugFrameRate||30;this.sendInterval=1e3/s,this.interceptConsole(),this.start()}start(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())}stop(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())}interceptConsole(){console.log=(...e)=>{this.sendLog("info",this.formatLogMessage(e)),this.originalConsole.log(...e)},console.debug=(...e)=>{this.sendLog("debug",this.formatLogMessage(e)),this.originalConsole.debug(...e)},console.info=(...e)=>{this.sendLog("info",this.formatLogMessage(e)),this.originalConsole.info(...e)},console.warn=(...e)=>{this.sendLog("warn",this.formatLogMessage(e)),this.originalConsole.warn(...e)},console.error=(...e)=>{this.sendLog("error",this.formatLogMessage(e)),this.originalConsole.error(...e)}}formatLogMessage(e){return e.map((e=>{if("string"==typeof e)return e;if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return this.safeStringify(e,6)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}safeStringify(e,t=6){const n=new WeakSet,s=(e,i)=>{if(null===e)return null;if(void 0===e)return;if("object"!=typeof e)return e;if(i>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){const t=e.map((e=>s(e,i+1)));return n.delete(e),t}const r={};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=s(e[t],i+1));return n.delete(e),r};return JSON.stringify(s(e,0))}sendLog(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}}updateConfig(e){this.config=e;const t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new Y(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())}update(e){if(!this.isRunning||!this.config.enabled)return;this.frameCounter++;const t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}onSceneChanged(){this.isRunning&&this.config.enabled&&this.sendDebugData()}handleMessage(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig({...this.config,...e.config});break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleExpandLazyObjectRequest(e){try{const{entityId:t,componentIndex:n,propertyPath:s,requestId:i}=e;if(void 0===t||void 0===n||!s)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});const r=this.sceneManager.currentScene,o=this.entityCollector.expandLazyObject(t,n,s,r);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,data:o})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetComponentPropertiesRequest(e){try{const{entityId:t,componentIndex:n,requestId:s}=e;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:s,error:"缺少必要参数"});const i=this.sceneManager.currentScene,r=this.entityCollector.getComponentProperties(t,n,i);this.webSocketManager.send({type:"get_component_properties_response",requestId:s,data:r})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetRawEntityListRequest(e){try{const{requestId:t}=e,n=this.sceneManager.currentScene,s=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:s})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleGetEntityDetailsRequest(e){try{const{entityId:t,requestId:n}=e;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});const s=this.sceneManager.currentScene,i=this.entityCollector.getEntityDetails(t,s);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:i})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleMemorySnapshotRequest(){try{const e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}}captureMemorySnapshot(){const e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,s=this.entityCollector.collectEntityDataWithMemory(n),i=n?.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},r=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=s.entitiesPerArchetype.reduce(((e,t)=>e+t.memory),0);return{timestamp:e,version:"2.0",summary:{totalEntities:s.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:i.totalMemory,systemMemory:r.totalMemory,poolMemory:o.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:s.totalEntities,archetypes:s.entitiesPerArchetype,largestEntities:s.topEntitiesByComponents},components:i,systems:r,pools:o,performance:a}}collectBaseMemoryInfo(){const e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{const t=performance;if(t.memory){const n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then((t=>{e.detailedMemory=t})).catch((()=>{}))}catch(e){}return e}collectComponentMemoryStats(e){const t=new Map;let n=0;const s=new Map;for(const t of e.buffer)if(t&&!t.destroyed&&t.components)for(const e of t.components){const t=w(e);s.set(t,(s.get(t)||0)+1)}for(const[i,r]of s.entries()){const s=this.componentCollector.calculateDetailedComponentMemory(i),o=s*r;n+=o;const a=[];let c=0;for(const t of e.buffer)if(t&&!t.destroyed&&t.components){for(const e of t.components)if(w(e)===i&&(a.push({entityId:t.id,entityName:t.name||`Entity_${t.id}`,memory:s}),c++,c>=100))break;if(c>=100)break}t.set(i,{count:r,totalMemory:o,instances:a.slice(0,10)})}const i=Array.from(t.entries()).map((([e,t])=>({typeName:e,instanceCount:t.count,totalMemory:t.totalMemory,averageMemory:t.totalMemory/t.count,percentage:n>0?t.totalMemory/n*100:0,largestInstances:t.instances.sort(((e,t)=>t.memory-e.memory)).slice(0,3)}))).sort(((e,t)=>t.totalMemory-e.totalMemory));return{totalMemory:n,componentTypes:t.size,totalInstances:Array.from(t.values()).reduce(((e,t)=>e+t.count),0),breakdown:i}}collectSystemMemoryStats(){const e=this.sceneManager.currentScene;let t=0;const n=[];try{const s=e?.systems;if(s){const e=new Map;for(const i of s){const s=A(i);let r;e.has(s)?r=e.get(s):(r=this.calculateQuickSystemSize(i),e.set(s,r)),t+=r,n.push({name:s,memory:r,enabled:!1!==i.enabled,updateOrder:i.updateOrder||0})}}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort(((e,t)=>t.memory-e.memory))}}calculateQuickSystemSize(e){if(!e||"object"!=typeof e)return 64;let t=128;try{const n=Object.keys(e);for(let s=0;s<Math.min(n.length,15);s++){const i=n[s];if(!i||"entities"===i||"scene"===i||"constructor"===i)continue;const r=e[i];t+=2*i.length,"string"==typeof r?t+=Math.min(2*r.length,100):"number"==typeof r?t+=8:"boolean"==typeof r?t+=4:Array.isArray(r)?t+=40+Math.min(8*r.length,200):"object"==typeof r&&null!==r&&(t+=64)}}catch(e){return 128}return Math.max(t,64)}collectPoolMemoryStats(){let e=0;const t=[];try{const n=j.getInstance().getPoolStats();for(const[s,i]of n.entries()){const n=i,r=32*n.maxSize;e+=r,t.push({typeName:s,maxSize:n.maxSize,currentSize:n.currentSize||0,estimatedMemory:r,utilization:n.currentSize?n.currentSize/n.maxSize*100:0})}}catch(e){}try{const n=_.getAllPoolStats();for(const[s,i]of Object.entries(n)){const n=i;e+=n.estimatedMemoryUsage,t.push({typeName:`Pool_${s}`,maxSize:n.maxSize,currentSize:n.size,estimatedMemory:n.estimatedMemoryUsage,utilization:n.size/n.maxSize*100,hitRate:100*n.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort(((e,t)=>t.estimatedMemory-e.estimatedMemory))}}collectPerformanceStats(){try{if(!this.performanceMonitor)return{enabled:!1};const e=this.performanceMonitor.getAllSystemStats(),t=this.performanceMonitor.getPerformanceWarnings();return{enabled:this.performanceMonitor.enabled??!1,systemCount:e.size,warnings:t.slice(0,10),topSystems:Array.from(e.entries()).map((e=>{const[t,n]=e;return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort(((e,t)=>t.averageTime-e.averageTime)).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}}getDebugData(){const e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:t?.name||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n}async connectWebSocket(){try{await this.webSocketManager.connect()}catch(e){}}sendDebugData(){if(this.webSocketManager.getConnectionStatus())try{const e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}}dispose(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error}},exports.DebugManager=e([c(),h(),t(0,l(Ye)),t(1,l(f)),t(2,l(exports.DebugConfigService)),n("design:paramtypes",[Ye,f,exports.DebugConfigService])],exports.DebugManager),exports.PluginState=void 0,(Je=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Je.Installed="installed",Je.Failed="failed";const Ze=N("PluginManager");class Xe{constructor(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}initialize(e,t){this._core=e,this._services=t,Ze.info("PluginManager initialized")}async install(e){if(!this._core||!this._services)throw new Error("PluginManager not initialized. Call initialize() first.");if(this._plugins.has(e.name))return void Ze.warn(`Plugin ${e.name} is already installed`);e.dependencies&&e.dependencies.length>0&&this._checkDependencies(e);const t={name:e.name,version:e.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()};this._metadata.set(e.name,t);try{Ze.info(`Installing plugin: ${e.name} v${e.version}`),await e.install(this._core,this._services),this._plugins.set(e.name,e),t.state=exports.PluginState.Installed,Ze.info(`Plugin ${e.name} installed successfully`)}catch(n){throw t.state=exports.PluginState.Failed,t.error=n instanceof Error?n.message:String(n),Ze.error(`Failed to install plugin ${e.name}:`,n),n}}async uninstall(e){const t=this._plugins.get(e);if(!t)throw new Error(`Plugin ${e} is not installed`);this._checkDependents(e);try{Ze.info(`Uninstalling plugin: ${e}`),await t.uninstall(),this._plugins.delete(e),this._metadata.delete(e),Ze.info(`Plugin ${e} uninstalled successfully`)}catch(t){throw Ze.error(`Failed to uninstall plugin ${e}:`,t),t}}getPlugin(e){return this._plugins.get(e)}getMetadata(e){return this._metadata.get(e)}getAllPlugins(){return Array.from(this._plugins.values())}getAllMetadata(){return Array.from(this._metadata.values())}isInstalled(e){return this._plugins.has(e)}_checkDependencies(e){if(!e.dependencies)return;const t=[];for(const n of e.dependencies)this._plugins.has(n)||t.push(n);if(t.length>0)throw new Error(`Plugin ${e.name} has unmet dependencies: ${t.join(", ")}`)}_checkDependents(e){const t=[];for(const n of this._plugins.values())n.dependencies&&n.dependencies.includes(e)&&t.push(n.name);if(t.length>0)throw new Error(`Cannot uninstall plugin ${e}: it is required by ${t.join(", ")}`)}dispose(){const e=Array.from(this._plugins.values()).reverse();for(const t of e)try{Ze.info(`Disposing plugin: ${t.name}`),t.uninstall()}catch(e){Ze.error(`Error disposing plugin ${t.name}:`,e)}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,Ze.info("PluginManager disposed")}}const Ke=N("WorldManager");class et{constructor(e={}){this._worlds=new Map,this._isRunning=!1,this._framesSinceCleanup=0,this._config={maxWorlds:50,autoCleanup:!0,cleanupFrameInterval:1800,debug:!1,...e},this._isRunning=!0,Ke.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupFrameInterval:this._config.cleanupFrameInterval})}createWorld(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error(`World ID '${e}' 已存在`);if(this._worlds.size>=this._config.maxWorlds)throw new Error(`已达到最大World数量限制: ${this._config.maxWorlds}`);const n={name:e,debug:t?.debug??this._config.debug??!1,...void 0!==t?.maxScenes&&{maxScenes:t.maxScenes},...void 0!==t?.autoCleanup&&{autoCleanup:t.autoCleanup}},s=new Ve(n);return this._worlds.set(e,s),s}removeWorld(e){const t=this._worlds.get(e);return!!t&&(t.destroy(),this._worlds.delete(e),Ke.info(`移除World: ${e}`),!0)}getWorld(e){return this._worlds.get(e)||null}getWorldIds(){return Array.from(this._worlds.keys())}getAllWorlds(){return Array.from(this._worlds.values())}setWorldActive(e,t){const n=this._worlds.get(e);n?t?(n.start(),Ke.debug(`激活World: ${e}`)):(n.stop(),Ke.debug(`停用World: ${e}`)):Ke.warn(`World '${e}' 不存在`)}isWorldActive(e){const t=this._worlds.get(e);return t?.isActive??!1}updateAll(){if(this._isRunning){for(const e of this._worlds.values())e.isActive&&(e.updateGlobalSystems(),e.updateScenes());this._config.autoCleanup&&(this._framesSinceCleanup++,this._framesSinceCleanup>=this._config.cleanupFrameInterval&&(this.cleanup(),this._framesSinceCleanup=0,this._config.debug&&Ke.debug(`执行定期清理World (间隔: ${this._config.cleanupFrameInterval} 帧)`)))}}getActiveWorlds(){const e=[];for(const t of this._worlds.values())t.isActive&&e.push(t);return e}startAll(){this._isRunning=!0;for(const e of this._worlds.values())e.start();Ke.info("启动所有World")}stopAll(){this._isRunning=!1;for(const e of this._worlds.values())e.stop();Ke.info("停止所有World")}findWorlds(e){const t=[];for(const n of this._worlds.values())e(n)&&t.push(n);return t}findWorldByName(e){for(const t of this._worlds.values())if(t.name===e)return t;return null}getStats(){const e={totalWorlds:this._worlds.size,activeWorlds:this.activeWorldCount,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:{...this._config},worlds:[]};for(const[t,n]of this._worlds){const s=n.getStats();e.totalScenes+=s.totalSystems,e.totalEntities+=s.totalEntities,e.totalSystems+=s.totalSystems,e.worlds.push({id:t,name:n.name,isActive:n.isActive,sceneCount:n.sceneCount,...s})}return e}getDetailedStatus(){return{...this.getStats(),worlds:Array.from(this._worlds.entries()).map((([e,t])=>({id:e,isActive:t.isActive,status:t.getStatus()})))}}cleanup(){const e=[];for(const[t,n]of this._worlds)this.shouldCleanupWorld(n)&&e.push(t);for(const t of e)this.removeWorld(t);return e.length>0&&Ke.debug(`清理了 ${e.length} 个World`),e.length}destroy(){Ke.info("正在销毁WorldManager..."),this.stopAll();const e=Array.from(this._worlds.keys());for(const t of e)this.removeWorld(t);this._worlds.clear(),this._isRunning=!1,Ke.info("WorldManager已销毁")}dispose(){this.destroy()}shouldCleanupWorld(e){if(e.isActive)return!1;const t=Date.now()-e.createdAt>6e5;if(0===e.sceneCount)return t;return!e.getAllScenes().some((e=>e.entities&&e.entities.count>0))&&t}get worldCount(){return this._worlds.size}get activeWorldCount(){let e=0;for(const t of this._worlds.values())t.isActive&&e++;return e}get isRunning(){return this._isRunning}get config(){return{...this._config}}}class tt{constructor(e={}){if(tt._instance=this,this._config={debug:!0,enableEntitySystems:!0,...e},this._serviceContainer=new We,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new f,this._serviceContainer.registerInstance(f,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new S,this._serviceContainer.registerInstance(S,this._poolManager),this._sceneManager=new Ye(this._performanceMonitor),this._serviceContainer.registerInstance(Ye,this._sceneManager),this._sceneManager.setSceneChangedCallback((()=>{this._debugManager&&this._debugManager.onSceneChanged()})),this._worldManager=new et({debug:!!this._config.debug,...this._config.worldManagerConfig}),this._serviceContainer.registerInstance(et,this._worldManager),this._pluginManager=new Xe,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(Xe,this._pluginManager),tt.entitySystemsEnabled=this._config.enableEntitySystems??!0,this.debug=this._config.debug??!0,this._config.debugConfig?.enabled){const e=new exports.DebugConfigService;e.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(exports.DebugConfigService,e),this._serviceContainer.registerSingleton(exports.DebugManager,(e=>d(exports.DebugManager,e))),this._debugManager=this._serviceContainer.resolve(exports.DebugManager)}this.initialize()}static get Instance(){return this._instance}static get services(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}static get worldManager(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager}static create(e=!0){if(null==this._instance){const t="boolean"==typeof e?{debug:e,enableEntitySystems:!0}:e;this._instance=new tt(t)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance}static setScene(e){if(!this._instance)throw tt._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(e)}static get scene(){return this._instance?this._instance._sceneManager.currentScene:null}static get ecsAPI(){return this._instance?this._instance._sceneManager.api:null}static loadScene(e){this._instance?this._instance._sceneManager.loadScene(e):tt._logger.warn("Core实例未创建,请先调用Core.create()")}static update(e){this._instance?this._instance.updateInternal(e):tt._logger.warn("Core实例未创建,请先调用Core.create()")}static schedule(e,t=!1,n,s){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!s)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,s)}static enableDebug(e){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(e);else{const t=new exports.DebugConfigService;t.setConfig(e),this._instance._serviceContainer.registerInstance(exports.DebugConfigService,t),this._instance._serviceContainer.registerSingleton(exports.DebugManager,(e=>d(exports.DebugManager,e))),this._instance._debugManager=this._instance._serviceContainer.resolve(exports.DebugManager)}this._instance._config.debugConfig=e}else tt._logger.warn("Core实例未创建,请先调用Core.create()")}static disableDebug(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),delete this._instance._debugManager),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))}static getDebugData(){return this._instance?._debugManager?this._instance._debugManager.getDebugData():null}static get isDebugEnabled(){return this._instance?._config.debugConfig?.enabled||!1}static async installPlugin(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");await this._instance._pluginManager.install(e)}static async uninstallPlugin(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");await this._instance._pluginManager.uninstall(e)}static getPlugin(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)}static isPluginInstalled(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)}initialize(){tt._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:tt.entitySystemsEnabled,debugEnabled:this._config.debugConfig?.enabled||!1})}updateInternal(e){if(tt.paused)return;const t=this._performanceMonitor.startMonitoring("Core.update");s.update(e),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(s.deltaTime);const n=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",n,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",t)}static destroy(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),tt._logger.info("Core destroyed"),this._instance=null)}}tt.paused=!1,tt._instance=null,tt._logger=N("Core");const nt=N("DebugPlugin");exports.DebugPlugin=class{constructor(e){this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=e?.autoStart??!1,this.updateInterval=e?.updateInterval??1e3}async install(e,t){this.worldManager=t.resolve(et),nt.info("ECS Debug Plugin installed"),this.autoStart&&this.start()}async uninstall(){this.stop(),this.worldManager=null,nt.info("ECS Debug Plugin uninstalled")}dispose(){this.stop(),this.worldManager=null}start(){this.updateTimer?nt.warn("Debug monitoring already started"):(nt.info("Starting debug monitoring"),this.updateTimer=setInterval((()=>{this.logStats()}),this.updateInterval))}stop(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,nt.info("Debug monitoring stopped"))}getStats(){if(!this.worldManager)throw new Error("Plugin not installed");const e=[];let t=0,n=0;const s=this.worldManager.getAllWorlds();for(const i of s)for(const s of i.getAllScenes()){const i=this.getSceneInfo(s);e.push(i),t+=i.entityCount,n+=i.systems.length}return{scenes:e,totalEntities:t,totalSystems:n,timestamp:Date.now()}}getSceneInfo(e){const t=e.entities.buffer,n=e.systems;return{name:e.name,entityCount:t.length,systems:n.map((e=>this.getSystemInfo(e))),entities:t.map((e=>this.getEntityInfo(e)))}}getSystemInfo(e){const t=e.getPerformanceStats(),n=t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0;return{name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length,...void 0!==n&&{performance:n}}}getEntityInfo(e){const t=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:t.length,components:t.map((e=>this.getComponentInfo(e)))}}getComponentInfo(e){const t=e.constructor.name,n={};for(const t of Object.keys(e))if(!t.startsWith("_")){const s=e[t];"function"!=typeof s&&(n[t]=s)}return{type:t,data:n}}queryEntities(e){if(!this.worldManager)throw new Error("Plugin not installed");const t=[],n=this.worldManager.getAllWorlds();for(const s of n)for(const n of s.getAllScenes())if(!e.sceneId||n.name===e.sceneId)for(const s of n.entities.buffer)if((void 0===e.tag||s.tag===e.tag)&&(!e.name||s.name.includes(e.name))){if(e.hasComponent){if(!s.components.some((t=>t.constructor.name===e.hasComponent)))continue}t.push(this.getEntityInfo(s))}return t}logStats(){const e=this.getStats();nt.info("=== ECS Debug Stats ==="),nt.info(`Total Entities: ${e.totalEntities}`),nt.info(`Total Systems: ${e.totalSystems}`),nt.info(`Scenes: ${e.scenes.length}`);for(const t of e.scenes){nt.info(`\n[Scene: ${t.name}]`),nt.info(` Entities: ${t.entityCount}`),nt.info(` Systems: ${t.systems.length}`);for(const e of t.systems){const t=e.performance?` | Avg: ${e.performance.avgExecutionTime.toFixed(2)}ms, Max: ${e.performance.maxExecutionTime.toFixed(2)}ms`:"";nt.info(` - ${e.name} (${e.enabled?"enabled":"disabled"}) | Entities: ${e.entityCount}${t}`)}}nt.info("========================\n")}exportJSON(){const e=this.getStats();return JSON.stringify(e,null,2)}},exports.DebugPlugin=e([c(),n("design:paramtypes",[Object])],exports.DebugPlugin);class st{constructor(e,t){this.func=e,this.context=t}}class it{constructor(){this.entityId=null,this.id=it.idGenerator++}onAddedToEntity(){}onRemovedFromEntity(){}}var rt,ot;it.idGenerator=0,exports.ECSEventType=void 0,(rt=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",rt.ENTITY_DESTROYED="entity:destroyed",rt.ENTITY_ENABLED="entity:enabled",rt.ENTITY_DISABLED="entity:disabled",rt.ENTITY_TAG_ADDED="entity:tag:added",rt.ENTITY_TAG_REMOVED="entity:tag:removed",rt.ENTITY_NAME_CHANGED="entity:name:changed",rt.COMPONENT_ADDED="component:added",rt.COMPONENT_REMOVED="component:removed",rt.COMPONENT_MODIFIED="component:modified",rt.COMPONENT_ENABLED="component:enabled",rt.COMPONENT_DISABLED="component:disabled",rt.SYSTEM_ADDED="system:added",rt.SYSTEM_REMOVED="system:removed",rt.SYSTEM_ENABLED="system:enabled",rt.SYSTEM_DISABLED="system:disabled",rt.SYSTEM_PROCESSING_START="system:processing:start",rt.SYSTEM_PROCESSING_END="system:processing:end",rt.SYSTEM_ERROR="system:error",rt.SCENE_CREATED="scene:created",rt.SCENE_DESTROYED="scene:destroyed",rt.SCENE_ACTIVATED="scene:activated",rt.SCENE_DEACTIVATED="scene:deactivated",rt.SCENE_PAUSED="scene:paused",rt.SCENE_RESUMED="scene:resumed",rt.QUERY_EXECUTED="query:executed",rt.QUERY_CACHE_HIT="query:cache:hit",rt.QUERY_CACHE_MISS="query:cache:miss",rt.QUERY_OPTIMIZED="query:optimized",rt.PERFORMANCE_WARNING="performance:warning",rt.PERFORMANCE_CRITICAL="performance:critical",rt.MEMORY_USAGE_HIGH="memory:usage:high",rt.FRAME_RATE_DROP="frame:rate:drop",rt.INDEX_CREATED="index:created",rt.INDEX_UPDATED="index:updated",rt.INDEX_OPTIMIZED="index:optimized",rt.ARCHETYPE_CREATED="archetype:created",rt.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",rt.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",rt.DIRTY_MARK_ADDED="dirty:mark:added",rt.DIRTY_BATCH_PROCESSED="dirty:batch:processed",rt.ERROR_OCCURRED="error:occurred",rt.WARNING_ISSUED="warning:issued",rt.FRAMEWORK_INITIALIZED="framework:initialized",rt.FRAMEWORK_SHUTDOWN="framework:shutdown",rt.DEBUG_INFO="debug:info",rt.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(ot=exports.EventPriority||(exports.EventPriority={}))[ot.LOWEST=0]="LOWEST",ot[ot.LOW=25]="LOW",ot[ot.NORMAL=50]="NORMAL",ot[ot.HIGH=75]="HIGH",ot[ot.HIGHEST=100]="HIGHEST",ot[ot.CRITICAL=200]="CRITICAL";const at={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}};class ct{static isValid(e){return this.validTypes.has(e)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(e){this.validTypes.add(e)}static removeCustomType(e){this.validTypes.delete(e)}}ct.validTypes=new Set([...Object.values(exports.ECSEventType),...Object.values(at.ENTITY),...Object.values(at.COMPONENT),...Object.values(at.SYSTEM),...Object.values(at.PERFORMANCE)]);class ht{constructor(){this.adapter=null,this.logger=N("PlatformManager")}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}getAdapter(){if(!this.adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this.adapter}registerAdapter(e){this.adapter=e,this.logger.info(`平台适配器已注册: ${e.name}`,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})}hasAdapter(){return null!==this.adapter}getAdapterInfo(){return this.adapter?{name:this.adapter.name,version:this.adapter.version,config:this.adapter.getPlatformConfig()}:null}supportsFeature(e){if(!this.adapter)return!1;const t=this.adapter.getPlatformConfig();switch(e){case"worker":return this.adapter.isWorkerSupported();case"shared-array-buffer":return this.adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}}getBasicWorkerConfig(){if(!this.adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};const e=this.adapter.getPlatformConfig();return{platformSupportsWorker:this.adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this.adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}}async getFullPlatformConfig(){if(!this.adapter)throw new Error("平台适配器未注册");return"function"==typeof this.adapter.getPlatformConfigAsync?await this.adapter.getPlatformConfigAsync():this.adapter.getPlatformConfig()}}class lt{constructor(e){this.workers=[],this.taskQueue=[],this.busyWorkers=new Set,this.taskCounter=0,this.workers=e;for(let t=0;t<e.length;t++){const n=e[t];n&&(n.onMessage((e=>this.handleWorkerMessage(t,e.data))),n.onError((e=>this.handleWorkerError(t,e))))}}executeSharedBuffer(e){return new Promise(((t,n)=>{const s={id:"shared-task-"+ ++this.taskCounter,data:{...e,type:"shared"},resolve:()=>t(),reject:n};this.taskQueue.push(s),this.processQueue()}))}execute(e){return new Promise(((t,n)=>{const s={id:"task-"+ ++this.taskCounter,data:e,resolve:e=>{t(e)},reject:n};this.taskQueue.push(s),this.processQueue()}))}processQueue(){if(0!==this.taskQueue.length)for(let e=0;e<this.workers.length;e++)if(!this.busyWorkers.has(e)&&this.taskQueue.length>0){const t=this.taskQueue.shift();this.busyWorkers.add(e);const n=this.workers[e];n.postMessage({id:t.id,...t.data}),n._currentTask=t}}handleWorkerMessage(e,t){const n=this.workers[e],s=n._currentTask;s&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?s.reject(new Error(t.error)):s.resolve(t.result),this.processQueue())}handleWorkerError(e,t){const n=this.workers[e],s=n._currentTask;s&&(this.busyWorkers.delete(e),n._currentTask=null,s.reject(new Error(t.message))),this.processQueue()}destroy(){for(const e of this.workers)e.terminate();this.workers.length=0,this.taskQueue.length=0,this.busyWorkers.clear()}}class ut{constructor(e=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new Te,this.isDebugMode=e}emit(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&ut._logger.info(`发射事件: ${e}`,s),this.eventSystem.emitSync(e,s)}async emitAsync(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&ut._logger.info(`发射异步事件: ${e}`,s),await this.eventSystem.emit(e,s)}on(e,t,n={}){this.validateEventType(e);const s={once:n.once||!1,priority:n.priority||exports.EventPriority.NORMAL,async:n.async||!1};return n.thisArg&&(s.thisArg=n.thisArg),this.isDebugMode&&ut._logger.info(`添加监听器: ${e}`,s),this.eventSystem.on(e,t,s)}once(e,t,n={}){return this.on(e,t,{...n,once:!0})}onAsync(e,t,n={}){return this.on(e,t,{...n,async:!0})}off(e,t){return this.isDebugMode&&ut._logger.info(`移除监听器: ${t} 事件: ${e}`),this.eventSystem.off(e,t)}offAll(e){this.isDebugMode&&ut._logger.info(`移除所有监听器: ${e}`),this.eventSystem.offAll(e)}hasListeners(e){return this.eventSystem.hasListeners(e)}getStats(e){const t=this.eventSystem.getStats(e);if(t instanceof Map){const e=new Map;return t.forEach(((t,n)=>{e.set(n,this.convertEventStats(t))})),e}return this.convertEventStats(t)}clear(){this.isDebugMode&&ut._logger.info("清空所有监听器"),this.eventSystem.clear()}setEnabled(e){this.eventSystem.setEnabled(e)}setDebugMode(e){this.isDebugMode=e}setMaxListeners(e){this.eventSystem.setMaxListeners(e)}getListenerCount(e){return this.eventSystem.getListenerCount(e)}setBatchConfig(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})}flushBatch(e){this.eventSystem.flushBatch(e)}resetStats(e){this.eventSystem.resetStats(e)}emitEntityCreated(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)}emitEntityDestroyed(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)}emitComponentAdded(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)}emitComponentRemoved(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)}emitSystemAdded(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)}emitSystemRemoved(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)}emitSceneChanged(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)}emitPerformanceWarning(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)}onEntityCreated(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)}onComponentAdded(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)}onSystemError(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)}onPerformanceWarning(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)}validateEventType(e){this.isDebugMode&&(ct.isValid(e)||(ut._logger.warn(`未知事件类型: ${e}`),ct.addCustomType(e)))}enhanceEventData(e,t){if(null==t)return{timestamp:Date.now(),eventId:`${e}_${++this.eventIdCounter}`,source:"EventBus"};const n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=`${e}_${++this.eventIdCounter}`),n.source||(n.source="EventBus"),n}convertEventStats(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}}}ut._logger=N("EventBus");class dt{static registerComponentMigration(e,t,n,s){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map);this.componentMigrations.get(e).set(t,s)}static registerSceneMigration(e,t,n){this.sceneMigrations.set(e,n)}static migrateComponent(e,t){const n=e.version;if(n===t)return e;const s=this.componentMigrations.get(e.type);if(!s)return console.warn(`No migration path found for component ${e.type}`),e;const i={...e};let r=n;for(;r<t;){const t=s.get(r);if(!t){console.warn(`Missing migration from version ${r} to ${r+1} for ${e.type}`);break}i.data=t(i.data,r,r+1),r++}return i.version=r,i}static migrateScene(e,t){const n=e.version;if(n===t)return e;let s={...e},i=n;for(;i<t;){const e=this.sceneMigrations.get(i);if(!e){console.warn(`Missing scene migration from version ${i} to ${i+1}`);break}s=e(s,i,i+1),i++}return s.version=i,s=this.migrateSceneComponents(s),s}static migrateSceneComponents(e){const t={...e};return t.entities=e.entities.map((t=>({...t,components:t.components.map((t=>{const n=e.componentTypeRegistry.find((e=>e.typeName===t.type));return n&&n.version!==t.version?this.migrateComponent(t,n.version):t})),children:this.migrateEntitiesComponents(t.children,e.componentTypeRegistry)}))),t}static migrateEntitiesComponents(e,t){return e.map((e=>({...e,components:e.components.map((e=>{const n=t.find((t=>t.typeName===e.type));return n&&n.version!==e.version?this.migrateComponent(e,n.version):e})),children:this.migrateEntitiesComponents(e.children,t)})))}static clearMigrations(){this.componentMigrations.clear(),this.sceneMigrations.clear()}static getComponentMigrationPath(e){const t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort(((e,t)=>e-t)):[]}static getSceneMigrationPath(){return Array.from(this.sceneMigrations.keys()).sort(((e,t)=>e-t))}static canMigrateComponent(e,t,n){if(t===n)return!0;const s=this.componentMigrations.get(e);if(!s)return!1;for(let e=t;e<n;e++)if(!s.has(e))return!1;return!0}static canMigrateScene(e,t){if(e===t)return!0;for(let n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0}}dt.componentMigrations=new Map,dt.sceneMigrations=new Map;class pt{constructor(e){this._entity=e}with(e){return this._entity.addComponent(e),this}withConfigured(e,t){return this._entity.addComponent(e),t(e),this}withTag(e){return this._entity.tag=e,this}withName(e){return this._entity.name=e,this}withActive(e){return this._entity.active=e,this}withEnabled(e){return this._entity.enabled=e,this}withUpdateOrder(e){return this._entity.updateOrder=e,this}withChild(e){return this._entity.addChild(e),this}build(){return this._entity}get entity(){return this._entity}}function mt(e){return"function"==typeof e&&e.prototype instanceof it}exports.AutoTyped=function(e){return function(t,n){const s=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(s,e||{})}},exports.BinarySerializer=ze,exports.BitMask64Utils=X,exports.Bits=pe,exports.COMPONENT_TYPE_NAME=C,exports.Colors=R,exports.Component=it,exports.ComponentDataCollector=Q,exports.ComponentPool=G,exports.ComponentPoolManager=j,exports.ComponentRegistry=te,exports.ComponentSerializer=Re,exports.ComponentSparseSet=ye,exports.ComponentStorage=ne,exports.ConsoleLogger=O,exports.Core=tt,exports.DeepCopy=function(e,t){const n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[C]=e,t}},exports.ECSFluentAPI=Ge,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[v]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=B,exports.EVENT_TYPES=at,exports.Emitter=class{constructor(){this._messageTable=new Map}addObserver(e,t,n){let s=this._messageTable.get(e);s||(s=[],this._messageTable.set(e,s)),this.hasObserver(e,t)||s.push(new st(t,n))}removeObserver(e,t){const n=this._messageTable.get(e);if(n){const e=n.findIndex((e=>e.func==t));-1!=e&&n.splice(e,1)}}emit(e,...t){const n=this._messageTable.get(e);if(n)for(const e of n)e.func.call(e.context,...t)}hasObserver(e,t){const n=this._messageTable.get(e);return!!n&&n.some((e=>e.func===t))}removeAllObservers(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()}dispose(){this._messageTable.clear()}getEventTypeCount(){return this._messageTable.size}getObserverCount(e){const t=this._messageTable.get(e);return t?t.length:0}},exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=re,exports.EntityDataCollector=H,exports.EntityList=ae,exports.EntityProcessorList=de,exports.EntityRef=function(){return function(e,t){const n=e.constructor;let s=n[B];s||(s={properties:new Set},n[B]=s);const i="symbol"==typeof t?t.toString():t;s.properties.add(i),Object.defineProperty(e,t,{get:function(){return W(this).get(i)||null},set:function(e){const t=W(this),n=t.get(i)||null;if(n===e)return;const s=null!==this.entityId?x(this.entityId):null;if(!s||!s.referenceTracker)return void t.set(i,e);const r=s.referenceTracker;if(n&&r.unregisterReference(n,this,i),e){if(e.scene!==s)return void L.error(`Cannot reference Entity from different Scene. Entity: ${e.name}, Scene: ${e.scene?.name||"null"}`);if(e.isDestroyed)return L.warn(`Cannot reference destroyed Entity: ${e.name}`),void t.set(i,null);r.registerReference(e,this,i)}t.set(i,e)},enumerable:!0,configurable:!0})}},exports.EntitySerializer=Oe,exports.EntitySystem=ue,exports.EventBus=ut,exports.EventTypeValidator=ct,exports.Float32=function(e,t){const n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){const n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=st,exports.GlobalEventBus=class{static getInstance(e=!1){return this.instance||(this.instance=new ut(e)),this.instance}static reset(e=!1){return this.instance&&this.instance.clear(),this.instance=new ut(e),this.instance}},exports.GlobalManager=class{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(e){this.setEnabled(e)}setEnabled(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}},exports.HighPrecision=function(e,t){const n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=ce,exports.IgnoreSerialization=function(){return function(e,t){const n=e.constructor;let s=n[Me];s||(s={options:{version:1},fields:new Map,ignoredFields:new Set},n[Me]=s),s.ignoredFields.add(t)}},exports.IncrementalSerializer=Le,exports.Inject=l,exports.Injectable=c,exports.Int16=function(e,t){const n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){const n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){const n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=class extends ue{constructor(e,t){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}onCheckProcessing(){return this.acc+=s.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}},exports.Logger=P,exports.LoggerManager=z,exports.Matcher=he,exports.MigrationBuilder=class{constructor(){this.fromVersion=1,this.toVersion=2}forComponent(e){return this.componentType=e,this}fromVersionToVersion(e,t){return this.fromVersion=e,this.toVersion=t,this}migrate(e){this.componentType?dt.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):dt.registerSceneMigration(this.fromVersion,this.toVersion,e)}},exports.NumberExtension=class{static toNumber(e){return null==e?0:Number(e)}},exports.PassiveSystem=class extends ue{constructor(e){super(e)}process(e){}},exports.PerformanceDataCollector=q,exports.PerformanceMonitor=f,exports.PlatformDetector=class{static detect(){const e=[];let t,n="unknown",s=!1;return"undefined"!=typeof globalThis&&e.push("globalThis"),"undefined"!=typeof window&&e.push("window"),"undefined"!=typeof self&&e.push("self"),this.isNodeJS()?(n="nodejs",s=!0,t="NodeAdapter",e.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",s=!0,t="WeChatMiniGameAdapter",e.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",s=!0,t="ByteDanceMiniGameAdapter",e.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",s=!0,t="AlipayMiniGameAdapter",e.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",s=!0,t="BaiduMiniGameAdapter",e.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",s=!0,t="BrowserAdapter",e.push("browser")),"undefined"!=typeof Worker&&e.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&e.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&e.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&e.push("performance.now"),"undefined"!=typeof Blob&&e.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&e.push("URL.createObjectURL"),{platform:n,confident:s,features:e,...t&&{adapterClass:t}}}static isWeChatMiniGame(){if(void 0!==globalThis.wx){const e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1}static isByteDanceMiniGame(){if(void 0!==globalThis.tt){const e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1}static isNodeJS(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch{return!1}}static isAlipayMiniGame(){if(void 0!==globalThis.my){const e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1}static isBaiduMiniGame(){if(void 0!==globalThis.swan){const e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location}static getDetailedInfo(){const e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e}},exports.PlatformManager=ht,exports.PluginManager=Xe,exports.Pool=_,exports.PoolManager=S,exports.ProcessingSystem=class extends ue{constructor(e){super(e)}process(e){this.processSystem()}},exports.QuerySystem=Ee,exports.ReactiveQuery=ve,exports.ReferenceTracker=D,exports.SERIALIZABLE_METADATA=Me,exports.SERIALIZE_FIELD=Ie,exports.SERIALIZE_OPTIONS=xe,exports.SYSTEM_TYPE_NAME=v,exports.Scene=Fe,exports.SceneDataCollector=V,exports.SceneManager=Ye,exports.SceneSerializer=Pe,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");let n=t[Me];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[Me]=n),t}},exports.Serialize=De,exports.SerializeArray=function(e,t){const n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){De({serializer:e=>e instanceof Map?Array.from(e.entries()):null,deserializer:e=>Array.isArray(e)?new Map(e):new Map})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){De({serializer:e=>e instanceof Set?Array.from(e):null,deserializer:e=>Array.isArray(e)?new Set(e):new Set})(e,t)}},exports.SerializeMap=function(e,t){const n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){const n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=We,exports.SoAStorage=ee,exports.SparseSet=me,exports.SystemDataCollector=U,exports.Time=s,exports.Timer=i,exports.TypeInference=K,exports.TypeSafeEventSystem=Te,exports.TypeUtils=class{static getType(e){return e.constructor}},exports.TypedEntityBuilder=pt,exports.TypedQueryBuilder=Ae,exports.TypedQueryResult=we,exports.Uint16=function(e,t){const n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){const n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){const n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){const n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=h,exports.VersionMigrationManager=dt,exports.WebSocketManager=Y,exports.WorkerEntitySystem=class extends ue{constructor(e,t={}){super(e),this.workerPool=null,this.isProcessing=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.hasLoggedSyncMode=!1,this.platformAdapter=ht.getInstance().getAdapter();const n=t.workerCount??this.getMaxSystemWorkerCount(),s=this.getMaxSystemWorkerCount(),i=Math.min(n,s);n>s&&this.logger.warn(`请求 ${n} 个Worker,但系统最多支持 ${s} 个。实际使用 ${i} 个Worker。`),this.config={enableWorker:t.enableWorker??!0,workerCount:i,systemConfig:t.systemConfig,...void 0!==t.entitiesPerWorker&&{entitiesPerWorker:t.entitiesPerWorker},useSharedArrayBuffer:t.useSharedArrayBuffer??this.isSharedArrayBufferSupported(),entityDataSize:t.entityDataSize??this.getDefaultEntityDataSize(),maxEntities:t.maxEntities??1e4},this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())}isWorkerSupported(){return this.platformAdapter.isWorkerSupported()}isSharedArrayBufferSupported(){return this.platformAdapter.isSharedArrayBufferSupported()}getMaxSystemWorkerCount(){return this.platformAdapter.getPlatformConfig().maxWorkerCount}initializeSharedArrayBuffer(){try{if(!this.isSharedArrayBufferSupported())return this.logger.warn(`${this.systemName}: 平台不支持SharedArrayBuffer,降级到单Worker模式以保证数据处理完整性`),this.config.useSharedArrayBuffer=!1,void(this.config.workerCount=1);const e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer)),this.logger.info(`${this.systemName}: SharedArrayBuffer初始化成功 (${e} 字节)`)}catch(e){this.logger.warn(`${this.systemName}: SharedArrayBuffer初始化失败,降级到单Worker模式以保证数据处理完整性`,e),this.config.useSharedArrayBuffer=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.config.workerCount=1}}initializeWorkerPool(){try{const e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e;for(let e=0;e<this.config.workerCount;e++)try{const s=this.platformAdapter.createWorker(n,{name:`WorkerEntitySystem-${e}`});t.push(s)}catch(t){throw this.logger.error(`创建Worker ${e} 失败:`,t),t}this.workerPool=new lt(t)}catch(e){this.logger.error(`${this.systemName}: Worker池初始化失败`,e),this.config.enableWorker=!1}}createWorkerScript(){const e=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!e)throw new Error("无法解析workerProcess方法");const t=e[1],n=this.config.entityDataSize,s=this.getSharedArrayBufferProcessFunction?.()||null;let i="";if(s){const e=s.toString().match(/\{([\s\S]*)\}/);e&&(i=e[1]??"")}return`\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = ${n};\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n\n try {\n // 处理SharedArrayBuffer初始化\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n // 处理SharedArrayBuffer数据\n if (type === 'shared' && sharedFloatArray) {\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null }); // SharedArrayBuffer不需要返回数据\n return;\n }\n\n // 传统处理方式\n if (entities) {\n // 定义处理函数\n function workerProcess(entities, deltaTime, systemConfig) {\n ${t}\n }\n\n // 执行处理\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n // 处理Promise返回值\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n // SharedArrayBuffer处理函数 - 由子类定义\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n\n ${i?`\n // 用户定义的处理函数\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n ${i}\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n `:""}\n }\n `}process(e){if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((()=>{this.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(`${this.systemName}: 本帧降级到传统Worker模式`),this.processWithWorker(e).finally((()=>{this.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(`${this.systemName}: Worker不可用,使用同步处理`),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(`${this.systemName}: 处理失败`,e),e}}}async processWithSharedArrayBuffer(e){if(!this.sharedFloatArray)throw new Error("SharedArrayBuffer not initialized");this.writeEntitiesToSharedBuffer(e);const t=this.createSharedArrayBufferTasks(e.length);await Promise.all(t),this.readResultsFromSharedBuffer(e)}async processWithWorker(e){const t=[];for(let n=0;n<e.length;n++)t[n]=this.extractEntityData(e[n]);const n=this.createBatches(t),i=s.deltaTime,r=n.map((e=>this.workerPool.execute({entities:e,deltaTime:i,systemConfig:this.config.systemConfig}))),o=await Promise.all(r);let a=0;for(const t of o)for(const n of t){if(a<e.length){const t=e[a];t&&n&&this.applyResult(t,n)}a++}}processSynchronously(e){const t=e.map((e=>this.extractEntityData(e))),n=s.deltaTime,i=this.workerProcess(t,n,this.config.systemConfig);i&&"function"==typeof i.then?i.then((t=>{e.forEach(((e,n)=>{this.applyResult(e,t[n])}))})):e.forEach(((e,t)=>{this.applyResult(e,i[t])}))}createBatches(e){const t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){const s=this.config.entitiesPerWorker;for(let t=0;t<e.length;t+=s){const i=Math.min(t+s,e.length);n.push(e.slice(t,i))}n.length>t&&this.logger.warn(`${this.systemName}: 创建了 ${n.length} 个批次,但只有 ${t} 个Worker。某些Worker将依次处理多个批次。`)}else{const s=Math.ceil(e.length/t);for(let i=0;i<t;i++){const t=i*s,r=Math.min(t+s,e.length);t<e.length&&n.push(e.slice(t,r))}}return n}writeEntitiesToSharedBuffer(e){if(this.sharedFloatArray)for(let t=0;t<e.length&&t<this.config.maxEntities;t++){const n=e[t],s=this.extractEntityData(n),i=t*this.config.entityDataSize;this.writeEntityToBuffer(s,i)}}createSharedArrayBufferTasks(e){const t=[];if(this.config.entitiesPerWorker){const n=this.config.entitiesPerWorker,i=Math.ceil(e/n),r=this.config.workerCount;i>r&&this.logger.warn(`${this.systemName}: 需要 ${i} 个任务处理 ${e} 个实体(每任务 ${n} 个),但只有 ${r} 个Worker。某些Worker将依次处理多个任务。`);for(let i=0;i<e;i+=n){const r=i,o=Math.min(i+n,e),a=this.workerPool.executeSharedBuffer({startIndex:r,endIndex:o,deltaTime:s.deltaTime,systemConfig:this.config.systemConfig});t.push(a)}}else{const n=Math.ceil(e/this.config.workerCount);for(let i=0;i<this.config.workerCount;i++){const r=i*n,o=Math.min(r+n,e);if(r<e){const e=this.workerPool.executeSharedBuffer({startIndex:r,endIndex:o,deltaTime:s.deltaTime,systemConfig:this.config.systemConfig});t.push(e)}}}return t}readResultsFromSharedBuffer(e){if(this.sharedFloatArray)for(let t=0;t<e.length&&t<this.config.maxEntities;t++){const n=e[t],s=t*this.config.entityDataSize,i=this.readEntityFromBuffer(s);i&&this.applyResult(n,i)}}updateConfig(e){const t={...this.config};if(void 0!==e.workerCount){const t=this.getMaxSystemWorkerCount(),n=Math.min(e.workerCount,t);e.workerCount>t&&this.logger.warn(`请求 ${e.workerCount} 个Worker,但系统最多支持 ${t} 个。实际使用 ${n} 个Worker。`),e.workerCount=n}Object.assign(this.config,e),t.useSharedArrayBuffer===this.config.useSharedArrayBuffer?t.workerCount===this.config.workerCount?(!this.config.enableWorker&&this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()):this.reinitializeWorkerPool():this.reinitializeWorkerSystem()}reinitializeWorkerSystem(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())}reinitializeWorkerPool(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()}getWorkerInfo(){let e="sync";return this.config.enableWorker&&this.workerPool&&(e=this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?"shared-buffer":"worker"),{enabled:this.config.enableWorker,workerCount:this.config.workerCount,...void 0!==this.config.entitiesPerWorker&&{entitiesPerWorker:this.config.entitiesPerWorker},maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:e}}onDestroy(){super.onDestroy(),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)}getLoggerName(){return A(this)}},exports.World=Ve,exports.WorldManager=et,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new pt(e)},exports.createECSAPI=je,exports.createInstance=d,exports.createLogger=N,exports.createQuery=function(){return new Ae},exports.getBasicWorkerConfig=function(){return ht.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=w,exports.getComponentTypeName=b,exports.getComponents=function(e,...t){return t.map((t=>e.getComponent(t)))},exports.getCurrentAdapter=function(){return ht.getInstance().getAdapter()},exports.getEntityRefMetadata=F,exports.getFullPlatformConfig=function(){return ht.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){let s=e.getComponent(t);return s||(s=n(),e.addComponent(s)),s},exports.getSceneByEntityId=x,exports.getSerializationMetadata=ke,exports.getSystemInstanceTypeName=A,exports.getSystemMetadata=E,exports.getSystemTypeName=T,exports.getUpdatableMetadata=g,exports.hasAdapter=function(){return ht.getInstance().hasAdapter()},exports.hasAnyComponent=function(e,...t){return t.some((t=>e.hasComponent(t)))},exports.hasComponents=function(e,...t){return t.every((t=>e.hasComponent(t)))},exports.hasEntityRef=function(e){return null!==F(e)},exports.isComponentArray=function(e){return e.every(mt)},exports.isComponentType=mt,exports.isSerializable=function(e){return null!==ke(e)},exports.isUpdatable=m,exports.queryFor=function(e){return new Ae([e])},exports.queryForAll=function(...e){return new Ae(e)},exports.registerInjectable=function(e,t,n=!0){if(!u(t))throw new Error(`${t.name} is not marked as @Injectable(). Please add @Injectable() decorator to the class.`);const s=e=>d(t,e);n?e.registerSingleton(t,s):e.registerTransient(t,s)},exports.registerPlatformAdapter=function(e){return ht.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){const n=e.getComponent(t);if(!n)throw new Error(`Component ${t.name} not found on entity ${e.name} (id: ${e.id})`);return n},exports.resetLoggerColors=function(){z.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){z.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){z.getInstance().setGlobalColors(e)},exports.setLoggerFactory=function(e){z.getInstance().setLoggerFactory(e)},exports.supportsFeature=function(e){return ht.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){const n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){const s=e.getComponent(t);return!!s&&(Object.assign(s,n),!0)};
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|