@esengine/ecs-framework
Version:
用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架
1 lines • 145 kB
JavaScript
class GlobalManager{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(t){this.setEnabled(t)}setEnabled(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}}class Time{static update(t){this.unscaledDeltaTime=t,this.deltaTime=t*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(t,e){return this.totalTime-e>=t}}Time.deltaTime=0,Time.unscaledDeltaTime=0,Time.totalTime=0,Time.unscaledTotalTime=0,Time.timeScale=1,Time.frameCount=0;class Timer{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+=Time.deltaTime,this._isDone}initialize(t,e,n,s){this._timeInSeconds=t,this._repeats=e,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}class TimerManager extends GlobalManager{constructor(){super(...arguments),this._timers=[]}update(){for(let t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))}schedule(t,e,n,s){let i=new Timer;return i.initialize(t,e,n,s),this._timers.push(i),i}}var PerformanceWarningType,LogLevel;!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(PerformanceWarningType||(PerformanceWarningType={}));class PerformanceMonitor{static get instance(){return PerformanceMonitor._instance||(PerformanceMonitor._instance=new PerformanceMonitor),PerformanceMonitor._instance}constructor(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(t){return this._isEnabled?performance.now():0}endMonitoring(t,e,n=0){if(!this._isEnabled||0===e)return;const s=performance.now(),i=s-e,o={name:t,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let n=this._systemStats.get(t);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,n)),n.totalTime+=e,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,e),n.maxTime=Math.max(n.maxTime,e),n.recentTimes.push(e),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,n=t.recentTimes.reduce(((t,n)=>t+Math.pow(n-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(n);const s=[...t.recentTimes].sort(((t,e)=>t-e)),i=s.length;t.percentile95=s[Math.floor(.95*i)]||0,t.percentile99=s[Math.floor(.99*i)]||0}getSystemData(t){return this._systemData.get(t)}getSystemStats(t){return this._systemStats.get(t)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const t=[];t.push("=== ECS Performance Report ==="),t.push("");const e=Array.from(this._systemStats.entries()).sort(((t,e)=>e[1].averageTime-t[1].averageTime));for(const[n,s]of e){const e=this._systemData.get(n);t.push(`System: ${n}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${s.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),t.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const n=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${n.toFixed(2)}ms`),t.push(`Systems Count: ${this._systemData.size}`),t.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(t){this._systemData.delete(t),this._systemStats.delete(t)}getPerformanceWarnings(t=16.67){const e=[];for(const[n,s]of this._systemData.entries())s.executionTime>t&&e.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${t}ms)`);return e}setMaxRecentSamples(t){this._maxRecentSamples=t;for(const e of this._systemStats.values())for(;e.recentTimes.length>t;)e.recentTimes.shift()}}class Pool{constructor(t,e=100,n=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=n,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,n=1024){let s=this._pools.get(t);return s||(s=new Pool((()=>new t),e,n),this._pools.set(t,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(t){t&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const t of this._objects)t.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(t){const e=t??Math.floor(this._objects.length/2);for(;this._objects.length>e;){const t=this._objects.pop();t&&(t.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(t){const e=Math.min(t,this._maxSize-this._objects.length);for(let t=0;t<e;t++){const t=this._createFn();t.reset(),this._objects.push(t),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(t){this._maxSize=t,this._stats.maxSize=t,this._objects.length>t&&this.compact(t)}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 t={};for(const[e,n]of this._pools){t[e.name||e.toString()]=n.getStats()}return t}static compactAllPools(){for(const t of this._pools.values())t.compact()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getGlobalStatsString(){const t=this.getAllPoolStats(),e=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(t).length)return e.push("No pools registered"),e.join("\n");for(const[n,s]of Object.entries(t))e.push(`${n}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Total Created: ${s.totalCreated}`),e.push(` Total Obtained: ${s.totalObtained}`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}Pool._pools=new Map;class PoolManager{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return PoolManager.instance||(PoolManager.instance=new PoolManager),PoolManager.instance}registerPool(t,e){this.pools.set(t,e)}getPool(t){return this.pools.get(t)||null}update(){const t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)}createPool(t,e,n=100,s=1024){let i=this.pools.get(t);return i||(i=new Pool(e,n,s),this.pools.set(t,i)),i}removePool(t){const e=this.pools.get(t);return!!e&&(e.clear(),this.pools.delete(t),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const t of this.pools.values())t.compact()}clearAllPools(){for(const t of this.pools.values())t.clear()}getAllStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,n.getStats());return t}getGlobalStats(){let t=0,e=0,n=0,s=0,i=0,o=0;for(const r of this.pools.values()){const a=r.getStats();t+=a.size,e+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,o+=a.estimatedMemoryUsage}return{size:t,maxSize:e,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:o}}getStatsString(){const t=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return t.push("No pools registered"),t.join("\n");const e=this.getGlobalStats();t.push(`Total Pools: ${this.pools.size}`),t.push(`Global Hit Rate: ${(100*e.hitRate).toFixed(1)}%`),t.push(`Global Memory Usage: ${(e.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");for(const[e,n]of this.pools){const s=n.getStats();t.push(`${e}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("")}return t.join("\n")}setAutoCompactInterval(t){this.autoCompactInterval=t}prewarmAllPools(){for(const t of this.pools.values()){const e=t.getStats(),n=Math.floor(.2*e.maxSize);t.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}}class NativeBigInt{constructor(t){this.value=t}valueOf(){return Number(this.value)}toString(t){if(void 0!==t&&10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");const e=this.value.toString(t);return 16===t?e.toUpperCase():e}and(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value&e)}or(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value|e)}xor(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value^e)}not(t=64){const e=(BigInt(1)<<BigInt(t))-BigInt(1);return new NativeBigInt(~this.value&e)}shiftLeft(t){return new NativeBigInt(this.value<<BigInt(t))}shiftRight(t){return new NativeBigInt(this.value>>BigInt(t))}equals(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return this.value===e}isZero(){return this.value===BigInt(0)}clone(){return new NativeBigInt(this.value)}}class ArrayBigInt{constructor(t=0){this.chunks=[],"number"==typeof t?this.fromNumber(t):"string"==typeof t?this.fromString(t):this.chunks=t.slice(),this.normalize()}fromNumber(t){if(this.chunks=[],t<0&&(t=Math.abs(t)),0!==t)for(;t>0;)this.chunks.push(t&ArrayBigInt.CHUNK_MASK),t=Math.floor(t/ArrayBigInt.CHUNK_MAX);else this.chunks=[0]}fromString(t){(t=t.trim()).startsWith("0x")||t.startsWith("0X")?this.fromHexString(t.substring(2)):t.startsWith("0b")||t.startsWith("0B")?this.fromBinaryString(t.substring(2)):this.fromDecimalString(t)}fromHexString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=8){const n=Math.max(0,e-7),s=parseInt(t.substring(n,e+1),16);this.chunks.push(s)}this.normalize()}fromBinaryString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=32){const n=Math.max(0,e-31),s=parseInt(t.substring(n,e+1),2);this.chunks.push(s)}this.normalize()}fromDecimalString(t){const e=parseInt(t,10);this.fromNumber(e)}normalize(){for(;this.chunks.length>1&&0===this.chunks[this.chunks.length-1];)this.chunks.pop();0===this.chunks.length&&(this.chunks=[0])}valueOf(){let t=0,e=1;for(const n of this.chunks)if(t+=n*e,e*=ArrayBigInt.CHUNK_MAX,e>Number.MAX_SAFE_INTEGER)break;return t}toString(t=10){if(10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");if(this.isZero())return"0";if(10===t)return this.valueOf().toString(10);if(16===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(16);t+=e===this.chunks.length-1?n:n.padStart(8,"0")}return t.toUpperCase()}if(2===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(2);t+=e===this.chunks.length-1?n:n.padStart(32,"0")}return t}return this.valueOf().toString(t)}and(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n&i)}return new ArrayBigInt(s)}or(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n|i)}return new ArrayBigInt(s)}xor(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n^i)}return new ArrayBigInt(s)}not(t=64){const e=Math.ceil(t/ArrayBigInt.CHUNK_SIZE),n=[];for(let s=0;s<e;s++){const i=s<this.chunks.length?this.chunks[s]:0;if(s===e-1){const e=t%ArrayBigInt.CHUNK_SIZE;if(e>0){const t=(1<<e)-1;n.push(~i&t)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}return new ArrayBigInt(n)}shiftLeft(t){if(0===t)return this.clone();if(t<0)return this.shiftRight(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE,s=new Array(e).fill(0);if(0===n)s.push(...this.chunks);else{let t=0;for(const e of this.chunks){const i=e<<n|t;s.push(i&ArrayBigInt.CHUNK_MASK),t=e>>>ArrayBigInt.CHUNK_SIZE-n}t>0&&s.push(t)}return new ArrayBigInt(s)}shiftRight(t){if(0===t)return this.clone();if(t<0)return this.shiftLeft(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE;if(e>=this.chunks.length)return new ArrayBigInt(0);const s=[];if(0===n)for(let t=e;t<this.chunks.length;t++)s.push(this.chunks[t]);else{let t=0;for(let i=this.chunks.length-1;i>=e;i--){const e=this.chunks[i],o=t<<ArrayBigInt.CHUNK_SIZE-n|e>>>n;s.unshift(o),t=e&(1<<n)-1}}return new ArrayBigInt(s.length>0?s:[0])}equals(t){if(!(t instanceof ArrayBigInt))return!1;if(this.chunks.length!==t.chunks.length)return!1;for(let e=0;e<this.chunks.length;e++)if(this.chunks[e]!==t.chunks[e])return!1;return!0}isZero(){return 1===this.chunks.length&&0===this.chunks[0]}clone(){return new ArrayBigInt(this.chunks.slice())}}ArrayBigInt.CHUNK_SIZE=32,ArrayBigInt.CHUNK_MASK=4294967295,ArrayBigInt.CHUNK_MAX=4294967296;class BigIntFactory{static isNativeSupported(){return null===this._supportsBigInt&&(this._supportsBigInt=this.detectBigIntSupport()),this._supportsBigInt}static detectBigIntSupport(){try{if("undefined"==typeof BigInt)return!1;const test1=BigInt(1),test2=BigInt(2),result=test1|test2,literal=eval("1n");if("bigint"!=typeof result||"bigint"!=typeof literal)return!1;const shifted=test1<<BigInt(1),compared=test1===BigInt(1);return"bigint"==typeof shifted&&!0===compared}catch(t){return!1}}static create(t=0){if(this.isNativeSupported()){let e;return e="bigint"==typeof t?t:BigInt(t),new NativeBigInt(e)}{let e;return e="bigint"==typeof t?t.toString():t,new ArrayBigInt(e)}}static zero(){return this._cachedZero||(this._cachedZero=this.create(0)),this._cachedZero}static one(){return this._cachedOne||(this._cachedOne=this.create(1)),this._cachedOne}static fromBinaryString(t){if(this.isNativeSupported()){const e=BigInt("0b"+t);return new NativeBigInt(e)}return new ArrayBigInt("0b"+t)}static fromHexString(t){if(this.isNativeSupported()){const e=t.replace(/^0x/i,""),n=BigInt("0x"+e);return new NativeBigInt(n)}return new ArrayBigInt(t)}static getEnvironmentInfo(){return{supportsBigInt:this.isNativeSupported(),environment:this.detectEnvironment(),jsEngine:this.detectJSEngine()}}static detectEnvironment(){if("undefined"!=typeof window){if("undefined"!=typeof navigator){const t=navigator.userAgent;if(t.includes("Chrome")){const e=t.match(/Chrome\/(\d+)/);return`Chrome ${e?parseInt(e[1]):0}`}if(t.includes("Firefox")){const e=t.match(/Firefox\/(\d+)/);return`Firefox ${e?parseInt(e[1]):0}`}if(t.includes("Safari")&&!t.includes("Chrome")){const e=t.match(/Version\/(\d+)/);return`Safari ${e?parseInt(e[1]):0}`}return"Browser (Unknown)"}return"Browser"}return"undefined"!=typeof global?"undefined"!=typeof process&&process.version?`Node.js ${process.version}`:"Node.js":void 0!==globalThis.wx?"WeChat MiniProgram":void 0!==globalThis.cc?"Cocos Creator":void 0!==globalThis.Laya?"Laya Engine":"Unknown"}static detectJSEngine(){try{return"undefined"!=typeof process&&process.versions&&process.versions.v8?`V8 ${process.versions.v8}`:void 0!==globalThis.Components?"SpiderMonkey":"undefined"!=typeof window&&void 0!==window.safari?"JavaScriptCore":"Unknown"}catch{return"Unknown"}}}BigIntFactory._supportsBigInt=null,BigIntFactory._cachedZero=null,BigIntFactory._cachedOne=null,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal",t[t.None=5]="None"}(LogLevel||(LogLevel={}));class ConsoleLogger{constructor(t={}){this._config={level:LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...t}}debug(t,...e){this.log(LogLevel.Debug,t,...e)}info(t,...e){this.log(LogLevel.Info,t,...e)}warn(t,...e){this.log(LogLevel.Warn,t,...e)}error(t,...e){this.log(LogLevel.Error,t,...e)}fatal(t,...e){this.log(LogLevel.Fatal,t,...e)}setLevel(t){this._config.level=t}setPrefix(t){this._config.prefix=t}log(t,e,...n){if(t<this._config.level)return;let s=e;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${LogLevel[t].toUpperCase()}] ${s}`,this._config.output?this._config.output(t,s):this.outputToConsole(t,s,...n)}outputToConsole(t,e,...n){const s=this._config.enableColors?this.getColors():null;switch(t){case LogLevel.Debug:s?console.debug(`${s.gray}${e}${s.reset}`,...n):console.debug(e,...n);break;case LogLevel.Info:s?console.info(`${s.blue}${e}${s.reset}`,...n):console.info(e,...n);break;case LogLevel.Warn:s?console.warn(`${s.yellow}${e}${s.reset}`,...n):console.warn(e,...n);break;case LogLevel.Error:case LogLevel.Fatal:s?console.error(`${s.red}${e}${s.reset}`,...n):console.error(e,...n)}}getColors(){return{reset:"[0m",red:"[31m",yellow:"[33m",blue:"[34m",gray:"[90m"}}}class LoggerManager{constructor(){this._loggers=new Map,this._defaultLogger=new ConsoleLogger}static getInstance(){return LoggerManager._instance||(LoggerManager._instance=new LoggerManager),LoggerManager._instance}getLogger(t){if(!t)return this._defaultLogger;if(!this._loggers.has(t)){const e=new ConsoleLogger({prefix:t,level:LogLevel.Info});this._loggers.set(t,e)}return this._loggers.get(t)}setLogger(t,e){this._loggers.set(t,e)}setGlobalLevel(t){this._defaultLogger instanceof ConsoleLogger&&this._defaultLogger.setLevel(t);for(const e of this._loggers.values())e instanceof ConsoleLogger&&e.setLevel(t)}createChildLogger(t,e){const n=`${t}.${e}`;return this.getLogger(n)}}const Logger=LoggerManager.getInstance().getLogger();function createLogger(t){return LoggerManager.getInstance().getLogger(t)}function setGlobalLogLevel(t){LoggerManager.getInstance().setGlobalLevel(t)}function EnableSoA(t){return t.__enableSoA=!0,t}function HighPrecision(t,e){const n=String(e);t.constructor.__highPrecisionFields||(t.constructor.__highPrecisionFields=new Set),t.constructor.__highPrecisionFields.add(n)}function Float64(t,e){const n=String(e);t.constructor.__float64Fields||(t.constructor.__float64Fields=new Set),t.constructor.__float64Fields.add(n)}function Float32(t,e){const n=String(e);t.constructor.__float32Fields||(t.constructor.__float32Fields=new Set),t.constructor.__float32Fields.add(n)}function Int32(t,e){const n=String(e);t.constructor.__int32Fields||(t.constructor.__int32Fields=new Set),t.constructor.__int32Fields.add(n)}function SerializeMap(t,e){const n=String(e);t.constructor.__serializeMapFields||(t.constructor.__serializeMapFields=new Set),t.constructor.__serializeMapFields.add(n)}class SoAStorage{constructor(t){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=t,this.initializeFields(t)}initializeFields(t){const e=new t,n=t.__highPrecisionFields||new Set,s=t.__float64Fields||new Set,i=t.__float32Fields||new Set,o=t.__int32Fields||new Set,r=t.__serializeMapFields||new Set,a=t.__serializeSetFields||new Set,c=t.__serializeArrayFields||new Set;for(const t in e)if(e.hasOwnProperty(t)&&"id"!==t){const h=e[t],l=typeof h;"number"===l?n.has(t)||(s.has(t)?this.fields.set(t,new Float64Array(this._capacity)):o.has(t)?this.fields.set(t,new Int32Array(this._capacity)):(i.has(t),this.fields.set(t,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(t,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(t,new Array(this._capacity)):"object"===l&&null!==h&&(r.has(t)||a.has(t)||c.has(t))&&this.serializedFields.set(t,new Array(this._capacity))}}addComponent(t,e){if(this.entityToIndex.has(t)){const n=this.entityToIndex.get(t);return void this.updateComponentAtIndex(n,e)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(t,n),this.indexToEntity[n]=t,this.updateComponentAtIndex(n,e),this._size++}updateComponentAtIndex(t,e){const n=this.indexToEntity[t],s=new Map,i=this.type.__highPrecisionFields||new Set,o=this.type.__serializeMapFields||new Set,r=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(const n in e)if(e.hasOwnProperty(n)&&"id"!==n){const h=e[n],l=typeof h;if("number"===l)if(i.has(n)||!this.fields.has(n))s.set(n,h);else{this.fields.get(n)[t]=h}else if("boolean"===l&&this.fields.has(n)){this.fields.get(n)[t]=h?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[t]=String(h)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[t]=this.serializeValue(h,n,o,r,a)}else c.has(n)?s.set(n,this.deepClone(h)):s.set(n,h)}s.size>0&&this.complexFields.set(n,s)}serializeValue(t,e,n,s,i){try{return n.has(e)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):s.has(e)&&t instanceof Set?JSON.stringify(Array.from(t)):(i.has(e)&&Array.isArray(t),JSON.stringify(t))}catch(t){return SoAStorage._logger.warn(`SoA序列化字段 ${e} 失败:`,t),"{}"}}deserializeValue(t,e,n,s,i){try{const o=JSON.parse(t);return n.has(e)?new Map(o):s.has(e)?new Set(o):(i.has(e),o)}catch(t){return SoAStorage._logger.warn(`SoA反序列化字段 ${e} 失败:`,t),null}}deepClone(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((t=>this.deepClone(t)));if(t instanceof Map){const e=new Map;for(const[n,s]of t.entries())e.set(n,this.deepClone(s));return e}if(t instanceof Set){const e=new Set;for(const n of t.values())e.add(this.deepClone(n));return e}const e={};for(const n in t)t.hasOwnProperty(n)&&(e[n]=this.deepClone(t[n]));return e}getComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=new this.type,s=this.type.__serializeMapFields||new Set,i=this.type.__serializeSetFields||new Set,o=this.type.__serializeArrayFields||new Set;for(const[t,s]of this.fields.entries()){const i=s[e],o=this.getFieldType(t);n[t]="boolean"===o?1===i:i}for(const[t,s]of this.stringFields.entries())n[t]=s[e];for(const[t,r]of this.serializedFields.entries()){const a=r[e];a&&(n[t]=this.deserializeValue(a,t,s,i,o))}const r=this.complexFields.get(t);if(r)for(const[t,e]of r.entries())n[t]=e;return n}getFieldType(t){return typeof(new this.type)[t]}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.getComponent(t);return this.complexFields.delete(t),this.entityToIndex.delete(t),this.freeIndices.push(e),this._size--,n}resize(t){for(const[e,n]of this.fields.entries()){let s;s=n instanceof Float32Array?new Float32Array(t):n instanceof Float64Array?new Float64Array(t):new Int32Array(t),s.set(n),this.fields.set(e,s)}for(const[e,n]of this.stringFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.stringFields.set(e,s)}for(const[e,n]of this.serializedFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.serializedFields.set(e,s)}this._capacity=t}getActiveIndices(){return Array.from(this.entityToIndex.values())}getFieldArray(t){return this.fields.get(t)||null}size(){return this._size}clear(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(const t of this.fields.values())t.fill(0);for(const t of this.stringFields.values())for(let e=0;e<t.length;e++)t[e]=void 0;for(const t of this.serializedFields.values())for(let e=0;e<t.length;e++)t[e]=void 0}compact(){if(0===this.freeIndices.length)return;const t=Array.from(this.entityToIndex.entries()).sort(((t,e)=>t[1]-e[1])),e=new Map,n=[];for(let s=0;s<t.length;s++){const[i,o]=t[s];if(e.set(i,s),n[s]=i,s!==o){for(const[,t]of this.fields.entries())t[s]=t[o];for(const[,t]of this.stringFields.entries())t[s]=t[o];for(const[,t]of this.serializedFields.entries())t[s]=t[o]}}this.entityToIndex=e,this.indexToEntity=n,this.freeIndices=[],this._size=t.length}getStats(){let t=0;const e=new Map;for(const[n,s]of this.fields.entries()){let i,o;s instanceof Float32Array?(i=4,o="float32"):s instanceof Float64Array?(i=8,o="float64"):(i=4,o="int32");const r=s.length*i;t+=r,e.set(n,{size:this._size,capacity:s.length,type:o,memory:r})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:t,fieldStats:e}}performVectorizedOperation(t){const e=this.getActiveIndices();t(this.fields,e)}}SoAStorage._logger=createLogger("SoAStorage");class ComponentRegistry{static register(t){if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentTypes.set(t,e),this.componentNameToType.set(t.name,t),this.componentNameToId.set(t.name,e),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return BigIntFactory.one().shiftLeft(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getComponentType(t){return this.componentNameToType.get(t)||null}static getAllRegisteredTypes(){return new Map(this.componentTypes)}static getAllComponentNames(){return new Map(this.componentNameToType)}static getComponentId(t){return this.componentNameToId.get(t)}static registerComponentByName(t){if(this.componentNameToId.has(t))return this.componentNameToId.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentNameToId.set(t,e),e}static createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const n=this.getComponentId(t);if(void 0===n)throw new Error(`Component type ${t} is not registered`);const s=BigIntFactory.one().shiftLeft(n);return this.maskCache.set(e,s),s}static createComponentMask(t){const e=`multi:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let n=BigIntFactory.zero();for(const e of t){const t=this.getComponentId(e);void 0!==t&&(n=n.or(BigIntFactory.one().shiftLeft(t)))}return this.maskCache.set(e,n),n}static clearMaskCache(){this.maskCache.clear()}static reset(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0}}ComponentRegistry._logger=createLogger("ComponentStorage"),ComponentRegistry.componentTypes=new Map,ComponentRegistry.componentNameToType=new Map,ComponentRegistry.componentNameToId=new Map,ComponentRegistry.maskCache=new Map,ComponentRegistry.nextBitIndex=0,ComponentRegistry.maxComponents=64;class ComponentStorage{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,ComponentRegistry.isRegistered(t)||ComponentRegistry.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${this.componentType.name}`);let n;this.freeIndices.length>0?(n=this.freeIndices.pop(),this.components[n]=e,this.indexToEntity[n]=t):(n=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,n),this._size++}getComponent(t){const e=this.entityToIndex.get(t);return void 0!==e?this.components[e]:null}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,n}forEach(t){for(let e=0;e<this.components.length;e++){const n=this.components[e];n&&t(n,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let n=0;n<this.components.length;n++){const s=this.components[n];s&&(t.push(s),e.push(this.indexToEntity[n]))}return{components:t,entityIds:e}}clear(){this.components.length=0,this.entityToIndex.clear(),this.indexToEntity.length=0,this.freeIndices.length=0,this._size=0}get size(){return this._size}get type(){return this.componentType}compact(){if(0===this.freeIndices.length)return;const t=[],e=[],n=new Map;let s=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[s]=o,e[s]=this.indexToEntity[i],n.set(this.indexToEntity[i],s),s++)}this.components=t,this.indexToEntity=e,this.entityToIndex=n,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,n=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:n,fragmentation:t>0?n/t:0}}}class ComponentStorageManager{constructor(){this.storages=new Map}getStorage(t){let e=this.storages.get(t);if(!e){t.__enableSoA?(e=new SoAStorage(t),ComponentStorageManager._logger.info(`为 ${t.name} 启用SoA优化(适用于大规模批量操作)`)):e=new ComponentStorage(t),this.storages.set(t,e)}return e}addComponent(t,e){const n=e.constructor;this.getStorage(n).addComponent(t,e)}getComponent(t,e){const n=this.storages.get(e);return n?n.getComponent(t):null}hasComponent(t,e){const n=this.storages.get(e);return!!n&&n.hasComponent(t)}removeComponent(t,e){const n=this.storages.get(e);return n?n.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigIntFactory.zero();for(const[n,s]of this.storages.entries())if(s.hasComponent(t)){const t=ComponentRegistry.getBitMask(n);e=e.or(t)}return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,n]of this.storages.entries()){const s=e.name||"Unknown";t.set(s,n.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}ComponentStorageManager._logger=createLogger("ComponentStorage");class EntityComparer{compare(t,e){let n=t.updateOrder-e.updateOrder;return 0==n&&(n=t.id-e.id),n}}class Entity{constructor(t,e){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=BigIntFactory.zero(),this._componentTypeToIndex=new Map,this.name=t,this.id=e}get isDestroyed(){return this._isDestroyed}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(t){this._active!==t&&(this._active=t,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(t){this._tag=t}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}get componentMask(){return this._componentMask}createComponent(t,...e){const n=new t(...e);return this.addComponent(n)}addComponentInternal(t){const e=t.constructor;ComponentRegistry.isRegistered(e)||ComponentRegistry.register(e),t.entity=this;const n=this.components.length;this.components.push(t),this._componentTypeToIndex.set(e,n);const s=ComponentRegistry.getBitMask(e);return this._componentMask=this._componentMask.or(s),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${e.name}`);return this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),Entity.eventBus&&Entity.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this)),t}getComponent(t){if(!ComponentRegistry.isRegistered(t))return null;const e=ComponentRegistry.getBitMask(t);if(this._componentMask.and(e).isZero())return null;const n=this._componentTypeToIndex.get(t);if(void 0!==n&&n<this.components.length){const e=this.components[n];if(e&&e.constructor===t)return e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this.rebuildComponentIndex(),e}for(let e=0;e<this.components.length;e++){const n=this.components[e];if(n instanceof t)return this._componentTypeToIndex.set(t,e),n}return null}rebuildComponentIndex(){this._componentTypeToIndex.clear();for(let t=0;t<this.components.length;t++){const e=this.components[t].constructor;this._componentTypeToIndex.set(e,t)}}hasComponent(t){if(!ComponentRegistry.isRegistered(t))return!1;const e=ComponentRegistry.getBitMask(t);return!this._componentMask.and(e).isZero()}getOrCreateComponent(t,...e){let n=this.getComponent(t);return n||(n=this.createComponent(t,...e)),n}removeComponent(t){const e=t.constructor,n=this.components.indexOf(t);if(-1!==n&&(this.components.splice(n,1),this.rebuildComponentIndex()),ComponentRegistry.isRegistered(e)){const t=ComponentRegistry.getBitMask(e);this._componentMask=this._componentMask.and(t.not())}this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity&&t.onRemovedFromEntity(),Entity.eventBus&&Entity.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),t.entity=null,this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this))}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentTypeToIndex.clear(),this._componentMask=BigIntFactory.zero();for(const e of t){const t=e.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),e.onRemovedFromEntity(),e.entity=null}this.components.length=0}addComponents(t){const e=[];for(const n of t)try{e.push(this.addComponent(n))}catch(t){Entity._logger.warn(`添加组件失败 ${n.constructor.name}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const n of t)e.push(this.removeComponentByType(n));return e}getComponents(t){const e=[];for(const n of this.components)n instanceof t&&e.push(n);return e}addChild(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)}removeAllChildren(){const t=[...this._children];for(const e of t)this.removeChild(e)}findChild(t,e=!1){for(const e of this._children)if(e.name===t)return e;if(e)for(const e of this._children){const n=e.findChild(t,!0);if(n)return n}return null}findChildrenByTag(t,e=!1){const n=[];for(const e of this._children)e.tag===t&&n.push(e);if(e)for(const e of this._children)n.push(...e.findChildrenByTag(t,!0));return n}getRoot(){let t=this;for(;t._parent;)t=t._parent;return t}isAncestorOf(t){let e=t._parent;for(;e;){if(e===this)return!0;e=e._parent}return!1}isDescendantOf(t){return t.isAncestorOf(this)}getDepth(){let t=0,e=this._parent;for(;e;)t++,e=e._parent;return t}forEachChild(t,e=!1){this._children.forEach(((n,s)=>{t(n,s),e&&n.forEachChild(t,!0)}))}onActiveChanged(){for(const t of this.components)"onActiveChanged"in t&&"function"==typeof t.onActiveChanged&&t.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}update(){if(this.activeInHierarchy&&!this._isDestroyed){for(const t of this.components)t.enabled&&t.update();for(const t of this._children)t.update()}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const t=[...this._children];for(const e of t)e.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}compareTo(t){return EntityComparer.prototype.compare(this,t)}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((t=>t.constructor.name)),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),indexMappingSize:this._componentTypeToIndex.size}}}Entity._logger=createLogger("Entity"),Entity.entityComparer=new EntityComparer,Entity.eventBus=null;class EntityBuilder{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new Entity("",t.identifierPool.checkOut())}named(t){return this.entity.name=t,this}tagged(t){return this.entity.tag=t,this}with(t){return this.entity.addComponent(t),this}withComponents(...t){for(const e of t)this.entity.addComponent(e);return this}withIf(t,e){return t&&this.entity.addComponent(e),this}withFactory(t){const e=t();return this.entity.addComponent(e),this}configure(t,e){const n=this.entity.getComponent(t);return n&&e(n),this}enabled(t=!0){return this.entity.enabled=t,this}active(t=!0){return this.entity.active=t,this}withChild(t){const e=t.build();return this.entity.addChild(e),this}withChildren(...t){for(const e of t){const t=e.build();this.entity.addChild(t)}return this}withChildFactory(t){const e=t(this.entity).build();return this.entity.addChild(e),this}withChildIf(t,e){if(t){const t=e.build();this.entity.addChild(t)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const t=new EntityBuilder(this.scene,this.storageManager);return t.entity=this.entity,t}}class EntityList{get count(){return this.buffer.length}constructor(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}add(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)}addImmediate(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))}remove(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)}removeImmediate(t){const e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(t.id))}removeAllEntities(){const t=[];for(let e=this.buffer.length-1;e>=0;e--)t.push(this.buffer[e].id),this.buffer[e].destroy();if(this._scene&&this._scene.identifierPool)for(const e of t)this._scene.identifierPool.checkIn(e);this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0}updateLists(){if(this._entitiesToAdd.length>0){for(const t of this._entitiesToAdd)this.addImmediate(t);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const t of this._entitiesToRemove)this.removeImmediate(t);this._entitiesToRemove.length=0}}update(){this._isUpdating=!0;try{for(let t=0;t<this.buffer.length;t++){const e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()}findEntity(t){const e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null}findEntitiesByName(t){return this._nameToEntities.get(t)||[]}findEntityById(t){return this._idToEntity.get(t)||null}findEntitiesByTag(t){const e=[];for(const n of this.buffer)n.tag===t&&e.push(n);return e}findEntitiesWithComponent(t){const e=[];for(const n of this.buffer)n.hasComponent(t)&&e.push(n);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const n of this.buffer)t(n)&&e(n)}updateNameIndex(t,e){if(t.name)if(e){let e=this._nameToEntities.get(t.name);e||(e=[],this._nameToEntities.set(t.name,e)),e.push(t)}else{const e=this._nameToEntities.get(t.name);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._nameToEntities.delete(t.name))}}}getStats(){let t=0;for(const e of this.buffer)e.enabled&&!e.isDestroyed&&t++;return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class EntityProcessorList{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(t){this._processors.push(t),this.setDirty()}remove(t){const e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)}getProcessor(t){for(const e of this._processors)if(e instanceof t)return e;return null}begin(){this.sortProcessors()}end(){}update(){this.sortProcessors();for(const t of this._processors)try{t.update()}catch(e){EntityProcessorList._logger.error(`Error in processor ${t.constructor.name}:`,e)}}lateUpdate(){for(const t of this._processors)t.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((t,e)=>t.updateOrder-e.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}EntityProcessorList._logger=createLogger("EntityProcessorList");class IdentifierPool{constructor(t=100,e=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=t,this._expansionBlockSize=e,this._preAllocateGenerations(0,this._expansionBlockSize)}checkOut(){let t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>IdentifierPool.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。`);t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}const e=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,e)}checkIn(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);if(!this._isValidId(e,n))return!1;return!this._pendingRecycle.some((t=>t.index===e&&t.generation===n))&&(this._pendingRecycle.push({index:e,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0)}isValid(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);return this._isValidId(e,n)}getStats(){let t=0,e=0;for(const[n,s]of this._generations)n<this._nextAvailableIndex&&(t+=s,e++);const n=e>0?t/e:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:IdentifierPool.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(t=!1){if(0===this._pendingRecycle.length)return;const e=Date.now(),n=[],s=[];for(const i of this._pendingRecycle)t||e-i.timestamp>=this._recycleDelay?n.push(i):s.push(i);for(const t of n)if(this._isValidId(t.index,t.generation)){let e=t.generation+1;e>IdentifierPool.MAX_GENERATION&&(e=1),this._generations.set(t.index,e),this._freeIndices.push(t.index)}this._pendingRecycle=s}_preAllocateGenerations(t,e){for(let n=0;n<e;n++){const e=t+n;e<=IdentifierPool.MAX_INDEX&&this._generations.set(e,1)}this._stats.memoryExpansions++}_ensureGenerationCapacity(t){if(!this._generations.has(t)){const e=Math.floor(t/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(e,this._expansionBlockSize)}}_calculateMemoryUsage(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length}_packId(t,e){return e<<16|t}_unpackIndex(t){return 65535&t}_unpackGeneration(t){return t>>>16&65535}_isValidId(t,e){if(t<0||t>=this._nextAvailableIndex)return!1;const n=this._generations.get(t);return void 0!==n&&n===e}}IdentifierPool.MAX_INDEX=65535,IdentifierPool.MAX_GENERATION=65535;class ComponentPool{constructor(t,e,n=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=n}acquire(){return this.pool.length>0?this.pool.pop():this.createFn()}release(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))}prewarm(t){for(let e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}}class ComponentPoolManager{constructor(){this.pools=new Map}static getInstance(){return ComponentPoolManager.instance||(ComponentPoolManager.instance=new ComponentPoolManager),ComponentPoolManager.instance}registerPool(t,e,n,s){this.pools.set(t,new ComponentPool(e,n,s))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const n=this.pools.get(t);n&&n.release(e)}prewarmAll(t=100){for(const e of this.pools.values())e.prewarm(t)}clearAll(){for(const t of this.pools.values())t.clear()}reset(){this.pools.clear()}getPoolStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return t}getPoolUtilization(){const t=new Map;for(const[e,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),o=i-s,r=i>0?o/i*100:0;t.set(e,{used:o,total:i,utilization:r})}return t}getComponentUtilization(t){const e=this.pools.get(t);if(!e)return 0;const n=e.getAvailableCount(),s=e.getMaxSize();return s>0?(s-n)/s*100:0}}var IndexType,DirtyFlag,QueryConditionType,ECSEventType,EventPriority;!function(t){t.HASH="hash",t.BITMAP="bitmap",t.SORTED="sorted"}(IndexType||(IndexType={}));class HashComponentIndex{constructor(){this.type=IndexType.HASH,this._componentToEntities=new Map,this._entityToComponents=new Map,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._setPool=[],this._componentTypeSetPool=[]}addEntity(t){if(0===t.components.length){const e=this._componentTypeSetPool.pop()||new Set;return e.clear(),this._entityToComponents.set(t,e),void(this._lastUpdated=Date.now())}const e=this._componentTypeSetPool.pop()||new Set;e.clear();for(const n of t.components){const s=n.constructor;e.add(s);let i=this._componentToEntities.get(s);i||(i=this._setPool.pop()||new Set,i.clear(),this._componentToEntities.set(s,i)),i.add(t)}this._entityToComponents.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToComponents.get(t);if(e){for(const n of e){const e=this._componentToEntities.get(n);e&&(e.delete(t),0===e.size&&(this._componentToEntities.delete(n),this._setPool.length<50&&(e.clear(),this._setPool.push(e))))}this._entityToComponents.delete(t),this._componentTypeSetPool.length<50&&(e.clear(),this._componentTypeSetPool.push(e)),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),n=this._componentToEntities.get(t),s=n?new Set(n):new Set;return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const n=performance.now();if(0===t.length)return new Set;if(1===t.length)return this.query(t[0]);let s;if("AND"===e){let e,i=1/0;for(const s of t){const t=this._componentToEntities.get(s);if(!t||0===t.size)return this._queryCount++,this._totalQueryTime+=performance.now()-n,new Set;t.size<i&&(i=t.siz