@esengine/ecs-framework 2.7.0 → 2.7.1

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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- 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){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class n{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}}n.deltaTime=0,n.unscaledDeltaTime=0,n.totalTime=0,n.unscaledTotalTime=0,n.timeScale=1,n.frameCount=0;class s{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+=n.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 i=new WeakMap,r=new WeakMap;function o(){return function(e){const t=i.get(e);i.set(e,{injectable:!0,dependencies:[],...t?.properties&&{properties:t.properties}})}}function a(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.`);r.set(t,{updatable:!0,priority:e})}}function c(e){return function(t,n){let s=i.get(t.constructor);s||(s={injectable:!0,dependencies:[]},i.set(t.constructor,s)),s.properties||(s.properties=new Map),s.properties.set(n,e)}}function h(e){const t=i.get(e);return t?.injectable??!1}function l(e){const t=i.get(e);return t?.properties||new Map}function d(e,t){const n=new e;return u(n,t),n}function u(e,t){const n=e.constructor,s=(r=n,i.get(r));var r;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=r.get(e);return t?.updatable??!1}function p(e){return r.get(e)}function f(e,t,n=!0){if(!h(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)}let g=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,i){const r=new s;return r.initialize(e,t,n,i),this._timers.push(r),r}dispose(){for(const e of this._timers)e.unload();this._timers=[]}};var y;g=e([a()],g),function(e){e.HIGH_EXECUTION_TIME="high_execution_time",e.HIGH_MEMORY_USAGE="high_memory_usage",e.HIGH_CPU_USAGE="high_cpu_usage",e.FREQUENT_GC="frequent_gc",e.LOW_FPS="low_fps",e.HIGH_ENTITY_COUNT="high_entity_count"}(y||(y={}));class _{constructor(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}updateFPS(e){}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 S{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 S(()=>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}}S._pools=new Map;class C{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 S(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"),E=Symbol("ComponentDependencies"),b=Symbol("ComponentEditorOptions");function T(e){return void 0!==e[v]}function w(e){const t=e[v];return t||(e.name||"UnknownComponent")}function I(e){return w(e.constructor)}function M(e){return e[E]}function A(e){return e[b]}function k(e){return A(e.constructor)}function D(e){const t=A(e);return t?.hideInInspector??!1}function x(e){return D(e.constructor)}var O,P;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(O||(O={}));class R{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0]};return R.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[O.LOW]&n[O.LOW])||0!==(s[O.HIGH]&n[O.HIGH]);return!o&&i&&r?r.some((e,t)=>{const n=i[t];return n&&(0!==(e[O.LOW]&n[O.LOW])||0!==(e[O.HIGH]&n[O.HIGH]))}):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[O.LOW]&s[O.LOW])===s[O.LOW]&&(n[O.HIGH]&s[O.HIGH])===s[O.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[O.LOW]&n[O.LOW])!==n[O.LOW]||(t[O.HIGH]&n[O.HIGH])!==n[O.HIGH])return!1}for(let e=a;e<r.length;e++){const t=r[e];if(0!==t[O.LOW]||0!==t[O.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[O.LOW]&s[O.LOW])&&0===(n[O.HIGH]&s[O.HIGH]);return i&&o&&r?i.every((e,t)=>{const n=r[t];return!n||0===(e[O.LOW]&n[O.LOW])&&0===(e[O.HIGH]&n[O.HIGH])}):o}static isZero(e){const t=0===e.base[O.LOW]&&0===e.base[O.HIGH];return e.segments&&t?e.segments.every(e=>0===e[O.LOW]&&0===e[O.HIGH]):t}static equals(e,t){const n=e.base[O.LOW]===t.base[O.LOW]&&e.base[O.HIGH]===t.base[O.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[O.LOW]||0!==t[O.HIGH])return!1}else if(!t&&n){if(0!==n[O.LOW]||0!==n[O.HIGH])return!1}else if(t&&n&&(t[O.LOW]!==n[O.LOW]||t[O.HIGH]!==n[O.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=R.getSegmentByBitIndex(e,t),s=63&t;s<32?n[O.LOW]|=1<<s:n[O.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=R.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[O.LOW]&1<<s):!!(n[O.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=R.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[O.LOW]&=~(1<<s):n[O.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[O.LOW]|=t.base[O.LOW],e.base[O.HIGH]|=t.base[O.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[O.LOW]|=i[O.LOW],s[O.HIGH]|=i[O.HIGH]}}}static andInPlace(e,t){e.base[O.LOW]&=t.base[O.LOW],e.base[O.HIGH]&=t.base[O.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[O.LOW]&=i[O.LOW],s[O.HIGH]&=i[O.HIGH]}}}static xorInPlace(e,t){e.base[O.LOW]^=t.base[O.LOW],e.base[O.HIGH]^=t.base[O.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[O.LOW]^=i[O.LOW],t[O.HIGH]^=i[O.HIGH]}}static clear(e){if(e.base[O.LOW]=0,e.base[O.HIGH]=0,e.segments)for(let t=0;t<e.segments.length;t++){const n=e.segments[t];n[O.LOW]=0,n[O.HIGH]=0}}static copy(e,t){if(R.clear(t),t.base[O.LOW]=e.base[O.LOW],t.base[O.HIGH]=e.base[O.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[O.LOW]=n[O.LOW],t[O.HIGH]=n[O.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[O.HIGH],c=o[O.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[O.LOW],r=s[O.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}}}R.ZERO={base:[0,0]},function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error",e[e.Fatal=4]="Fatal",e[e.None=5]="None"}(P||(P={}));const z={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""};class N{constructor(e={}){this._config={level:P.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...e}}debug(e,...t){this.log(P.Debug,e,...t)}info(e,...t){this.log(P.Info,e,...t)}warn(e,...t){this.log(P.Warn,e,...t)}error(e,...t){this.log(P.Error,e,...t)}fatal(e,...t){this.log(P.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=`[${P[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 P.Debug:s?console.debug(`${s.debug}${t}${s.reset}`,...n):console.debug(t,...n);break;case P.Info:s?console.info(`${s.info}${t}${s.reset}`,...n):console.info(t,...n);break;case P.Warn:s?console.warn(`${s.warn}${t}${s.reset}`,...n):console.warn(t,...n);break;case P.Error:s?console.error(`${s.error}${t}${s.reset}`,...n):console.error(t,...n);break;case P.Fatal:s?console.error(`${s.fatal}${t}${s.reset}`,...n):console.error(t,...n)}}getColors(){return{...{debug:z.BRIGHT_BLACK,info:z.GREEN,warn:z.YELLOW,error:z.RED,fatal:z.BRIGHT_RED,reset:z.RESET},...this._config.colors}}}class F{constructor(){this._loggers=new Map,this._defaultLevel=P.Info}get defaultLogger(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}createDefaultLogger(){return this._loggerFactory?this._loggerFactory():new N({level:this._defaultLevel})}static getInstance(){return F._instance||(F._instance=new F),F._instance}getLogger(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new N({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 N&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof N&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof N&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof N&&t.setColors(e)}resetColors(){this._defaultLogger instanceof N&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof N&&e.setColors({})}setLoggerFactory(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()}}const B=F.getInstance().getLogger();function $(e){return F.getInstance().getLogger(e)}function L(e){F.getInstance().setGlobalColors(e)}function W(){F.getInstance().resetColors()}function H(e){F.getInstance().setGlobalLevel(e)}function U(e){F.getInstance().setLoggerFactory(e)}const G=$("ComponentRegistry");class q{constructor(){this._componentTypes=new Map,this._bitIndexToType=new Map,this._componentNameToType=new Map,this._componentNameToId=new Map,this._maskCache=new Map,this._nextBitIndex=0,this._hotReloadEnabled=!1,this._warnedComponents=new Set}register(e){const t=w(e);if(T(e)||this._warnedComponents.has(e)||(this._warnedComponents.add(e),G.warn(`Component "${t}" is missing @ECSComponent decorator. This may cause issues with serialization and code minification. Please add: @ECSComponent('${t}') | 组件 "${t}" 缺少 @ECSComponent 装饰器,可能导致序列化和代码压缩问题`)),this._componentTypes.has(e))return this._componentTypes.get(e);if(this._hotReloadEnabled&&this._componentNameToType.has(t)){const n=this._componentNameToType.get(t);if(n!==e){const s=this._componentTypes.get(n);return this._componentTypes.delete(n),this._componentTypes.set(e,s),this._bitIndexToType.set(s,e),this._componentNameToType.set(t,e),G.debug(`Hot reload: replaced component "${t}"`),s}}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}getBitMask(e){const t=this._componentTypes.get(e);if(void 0===t){const t=w(e);throw new Error(`Component type ${t} is not registered`)}return R.create(t)}getBitIndex(e){const t=this._componentTypes.get(e);if(void 0===t){const t=w(e);throw new Error(`Component type ${t} is not registered`)}return t}isRegistered(e){return this._componentTypes.has(e)}getTypeByBitIndex(e){return this._bitIndexToType.get(e)||null}getRegisteredCount(){return this._nextBitIndex}getComponentType(e){return this._componentNameToType.get(e)||null}getAllRegisteredTypes(){return new Map(this._componentTypes)}getAllComponentNames(){return new Map(this._componentNameToType)}getComponentId(e){return this._componentNameToId.get(e)}registerComponentByName(e){if(this._componentNameToId.has(e))return this._componentNameToId.get(e);const t=this._nextBitIndex++;return this._componentNameToId.set(e,t),t}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=R.create(n);return this._maskCache.set(t,s),s}createComponentMask(e){const t=`multi:${[...e].sort().join(",")}`;if(this._maskCache.has(t))return this._maskCache.get(t);const n=R.clone(R.ZERO);for(const t of e){const e=this.getComponentId(t);if(void 0!==e){const t=R.create(e);R.orInPlace(n,t)}}return this._maskCache.set(t,n),n}clearMaskCache(){this._maskCache.clear()}enableHotReload(){this._hotReloadEnabled=!0}disableHotReload(){this._hotReloadEnabled=!1}isHotReloadEnabled(){return this._hotReloadEnabled}unregister(e){const t=this._componentNameToType.get(e);if(!t)return;const n=this._componentTypes.get(t);this._componentTypes.delete(t),void 0!==n&&this._bitIndexToType.delete(n),this._componentNameToType.delete(e),this._componentNameToId.delete(e),this.clearMaskCache(),G.debug(`Component unregistered: ${e}`)}getRegisteredComponents(){const e=[];for(const[t,n]of this._componentNameToType){const s=this._componentTypes.get(n);void 0!==s&&e.push({name:t,type:n,bitIndex:s})}return e}reset(){this._componentTypes.clear(),this._bitIndexToType.clear(),this._componentNameToType.clear(),this._componentNameToId.clear(),this._maskCache.clear(),this._warnedComponents.clear(),this._nextBitIndex=0,this._hotReloadEnabled=!1}cloneFrom(e){const t=e.getAllRegisteredTypes();for(const[e,n]of t){this._componentTypes.set(e,n),this._bitIndexToType.set(n,e);const t=w(e);this._componentNameToType.set(t,e),this._componentNameToId.set(t,n)}this._nextBitIndex=e.getRegisteredCount(),this._hotReloadEnabled=e.isHotReloadEnabled()}}const j=new q;var V;!function(e){e[e.FULL=0]="FULL",e[e.DELTA=1]="DELTA",e[e.SPAWN=2]="SPAWN",e[e.DESPAWN=3]="DESPAWN"}(V||(V={}));const Q={boolean:1,int8:1,uint8:1,int16:2,uint16:2,int32:4,uint32:4,float32:4,float64:8,string:-1},Y=Symbol("SyncMetadata"),J=Symbol("ChangeTracker"),Z=Symbol("SystemTypeName");function X(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");const s=n;s[v]=e,t?.requires&&(s[E]=t.requires),t?.editor&&(s[b]=t.editor);const i=n[Y];return i&&(i.typeId=e),j.register(n),n}}function K(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");const s=n;return s[Z]=e,t&&(s.__systemMetadata__=t),n}}function ee(e){return e.__systemMetadata__}function te(e){return ee(e.constructor)}function ne(e){const t=e[Z];return t||(e.name||"UnknownSystem")}function se(e){return ne(e.constructor)}const ie="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}},re=new Map;function oe(e){const t=re.get(e);return t?.deref()||null}class ae{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 ie(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){re.set(e,new ie(t))}unregisterEntityScene(e){re.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 ce=$("EntityRefDecorator"),he=Symbol("EntityRefMetadata"),le=Symbol("EntityRefValues");function de(e){let t=e[le];return t||(t=new Map,e[le]=t),t}function ue(){return function(e,t){const n=e.constructor;let s=n[he];s||(s={properties:new Set},n[he]=s);const i="symbol"==typeof t?t.toString():t;s.properties.add(i),Object.defineProperty(e,t,{get:function(){return de(this).get(i)||null},set:function(e){const t=de(this),n=t.get(i)||null;if(n===e)return;const s=null!==this.entityId?oe(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 ce.error(`Cannot reference Entity from different Scene. Entity: ${e.name}, Scene: ${e.scene?.name||"null"}`);if(e.isDestroyed)return ce.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})}}function me(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[he]||null}function pe(e){return null!==me(e)}function fe(e,t){const n=me(e);return!!n&&n.properties.has(t)}function ge(e){const t=me(e);return t?Array.from(t.properties):[]}const ye=new WeakMap,_e=Symbol.for("@esengine/property:metadata");function Se(e){return(t,n)=>{const s=t.constructor,i=ye.get(s)||{};i[n]=e,ye.set(s,i)}}function Ce(e){return ye.get(e)}function ve(e){return ye.has(e)}const Ee=Symbol("schedulingMetadata");function be(e){const t=e;return t[Ee]||(t[Ee]={stage:"update",before:[],after:[],sets:[]}),t[Ee]}function Te(e){return function(t){return be(t.prototype).stage=e,t}}function we(...e){return function(t){return be(t.prototype).before.push(...e),t}}function Ie(...e){return function(t){return be(t.prototype).after.push(...e),t}}function Me(...e){return function(t){return be(t.prototype).sets.push(...e),t}}function Ae(e){let t=Object.getPrototypeOf(e);for(;t;){const e=t[Ee];if(e)return e;t=Object.getPrototypeOf(t)}}function ke(e){return void 0!==Ae(e)}function De(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@ServerOnly can only be applied to methods, not "+typeof s);return n.value=function(...e){if(this.scene?.isServer)return s.apply(this,e)},n}}function xe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@ClientOnly can only be applied to methods, not "+typeof s);return n.value=function(...e){if(this.scene?.isClient)return s.apply(this,e)},n}}function Oe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@NotClient can only be applied to methods, not "+typeof s);return n.value=function(...e){if(!this.scene?.isClient)return s.apply(this,e)},n}}function Pe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@NotServer can only be applied to methods, not "+typeof s);return n.value=function(...e){if(!this.scene?.isServer)return s.apply(this,e)},n}}class Re{static getConstructor(e){return this.TYPE_CONSTRUCTORS[e]||Float32Array}static getBytesPerElement(e){return this.TYPE_BYTES[e]||4}static getTypeName(e){return e instanceof Float32Array?"float32":e instanceof Float64Array?"float64":e instanceof Int32Array?"int32":e instanceof Uint32Array?"uint32":e instanceof Int16Array?"int16":e instanceof Uint16Array?"uint16":e instanceof Int8Array?"int8":e instanceof Uint8Array?"uint8":e instanceof Uint8ClampedArray?"uint8clamped":"float32"}static createSameType(e,t){const n=this.getTypeName(e);return new(this.getConstructor(n))(t)}static extractFieldMetadata(e){const t=new e,n=new Map,s=e,i=new Map,r=(e,t)=>{if(e)for(const n of e)i.set(n,t)};r(s.__float64Fields,"float64"),r(s.__float32Fields,"float32"),r(s.__int32Fields,"int32"),r(s.__uint32Fields,"uint32"),r(s.__int16Fields,"int16"),r(s.__uint16Fields,"uint16"),r(s.__int8Fields,"int8"),r(s.__uint8Fields,"uint8"),r(s.__uint8ClampedFields,"uint8clamped");const o=Object.keys(t).filter(e=>"id"!==e);for(const e of o){const r=typeof t[e];if("function"===r)continue;const o={name:e,type:r},a=i.get(e);a?o.arrayType=a:"number"===r?o.arrayType="float32":"boolean"===r&&(o.arrayType="uint8"),s.__serializeMapFields?.has(e)&&(o.isSerializedMap=!0),s.__serializeSetFields?.has(e)&&(o.isSerializedSet=!0),s.__serializeArrayFields?.has(e)&&(o.isSerializedArray=!0),s.__deepCopyFields?.has(e)&&(o.isDeepCopy=!0),n.set(e,o)}return n}}Re.TYPE_CONSTRUCTORS={float32:Float32Array,float64:Float64Array,int32:Int32Array,uint32:Uint32Array,int16:Int16Array,uint16:Uint16Array,int8:Int8Array,uint8:Uint8Array,uint8clamped:Uint8ClampedArray},Re.TYPE_BYTES={float32:4,float64:8,int32:4,uint32:4,int16:2,uint16:2,int8:1,uint8:1,uint8clamped:1};class ze{static serialize(e,t,n={}){try{return n.isMap&&e instanceof Map?JSON.stringify(Array.from(e.entries())):n.isSet&&e instanceof Set?JSON.stringify(Array.from(e)):(n.isArray&&Array.isArray(e),JSON.stringify(e))}catch(e){return this._logger.warn(`SoA序列化字段 ${t} 失败:`,e),"{}"}}static deserialize(e,t,n={}){try{const t=JSON.parse(e);return n.isMap?new Map(t):n.isSet?new Set(t):t}catch(e){return this._logger.warn(`SoA反序列化字段 ${t} 失败:`,e),null}}static deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))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)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=this.deepClone(e[n]));return t}}function Ne(e){return e.__enableSoA=!0,e}function Fe(e,t){const n=e.constructor;let s=n[t];return s||(s=new Set,n[t]=s),s}function Be(e,t){Fe(e,"__float64Fields").add(String(t))}function $e(e,t){Fe(e,"__float32Fields").add(String(t))}function Le(e,t){Fe(e,"__int32Fields").add(String(t))}function We(e,t){Fe(e,"__uint32Fields").add(String(t))}function He(e,t){Fe(e,"__int16Fields").add(String(t))}function Ue(e,t){Fe(e,"__uint16Fields").add(String(t))}function Ge(e,t){Fe(e,"__int8Fields").add(String(t))}function qe(e,t){Fe(e,"__uint8Fields").add(String(t))}function je(e,t){Fe(e,"__uint8ClampedFields").add(String(t))}function Ve(e,t){Fe(e,"__serializeMapFields").add(String(t))}function Qe(e,t){Fe(e,"__serializeSetFields").add(String(t))}function Ye(e,t){Fe(e,"__serializeArrayFields").add(String(t))}function Je(e,t){Fe(e,"__deepCopyFields").add(String(t))}ze._logger=$("SoASerializer");class Ze{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.fieldTypes=new Map,this.serializeMapFields=new Set,this.serializeSetFields=new Set,this.serializeArrayFields=new Set,this.type=e,this.initializeFields(e)}initializeFields(e){const t=new e,n=e,s=n.__float64Fields||new Set,i=n.__float32Fields||new Set,r=n.__int32Fields||new Set,o=n.__uint32Fields||new Set,a=n.__int16Fields||new Set,c=n.__uint16Fields||new Set,h=n.__int8Fields||new Set,l=n.__uint8Fields||new Set,d=n.__uint8ClampedFields||new Set;this.serializeMapFields=n.__serializeMapFields||new Set,this.serializeSetFields=n.__serializeSetFields||new Set,this.serializeArrayFields=n.__serializeArrayFields||new Set;const u=new Map;for(const e of s)u.set(e,"float64");for(const e of i)u.set(e,"float32");for(const e of r)u.set(e,"int32");for(const e of o)u.set(e,"uint32");for(const e of a)u.set(e,"int16");for(const e of c)u.set(e,"uint16");for(const e of h)u.set(e,"int8");for(const e of l)u.set(e,"uint8");for(const e of d)u.set(e,"uint8clamped");const m=Object.keys(t).filter(e=>"id"!==e);for(const e of m){const n=t[e],s=typeof n;if("function"===s)continue;const i=u.get(e),r=i?"number":s;if(this.fieldTypes.set(e,r),i){const t=Re.getConstructor(i);this.fields.set(e,new t(this._capacity))}else"number"===s?this.fields.set(e,new Float32Array(this._capacity)):"boolean"===s?this.fields.set(e,new Uint8Array(this._capacity)):"string"===s?this.stringFields.set(e,new Array(this._capacity)):"object"===s&&null!==n&&(this.serializeMapFields.has(e)||this.serializeSetFields.has(e)||this.serializeArrayFields.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,r=i.__highPrecisionFields||new Set,o=i.__serializeMapFields||new Set,a=i.__serializeSetFields||new Set,c=i.__serializeArrayFields||new Set,h=i.__deepCopyFields||new Set,l=t;for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&"id"!==n){const t=l[n],i=typeof t;if("number"===i){const i=t;if(r.has(n)||!this.fields.has(n))s.set(n,i);else{this.fields.get(n)[e]=i}}else if("boolean"===i&&this.fields.has(n)){this.fields.get(n)[e]=t?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[e]=String(t)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[e]=ze.serialize(t,n,{isMap:o.has(n),isSet:a.has(n),isArray:c.has(n)})}else h.has(n)?s.set(n,ze.deepClone(t)):s.set(n,t)}s.size>0&&this.complexFields.set(n,s)}getComponent(e){const t=this.entityToIndex.get(e);return void 0===t?null:this.createProxyView(e,t)}createProxyView(e,t){const n=this;return new Proxy({},{get(s,i){const r=String(i),o=n.fields.get(r);if(o){return"boolean"===n.getFieldType(r)?1===o[t]:o[t]}const a=n.stringFields.get(r);if(a)return a[t];const c=n.serializedFields.get(r);if(c){const e=c[t];return e?ze.deserialize(e,r,{isMap:n.serializeMapFields.has(r),isSet:n.serializeSetFields.has(r),isArray:n.serializeArrayFields.has(r)}):void 0}const h=n.complexFields.get(e);return h?.has(r)?h.get(r):void 0},set(s,i,r){const o=String(i);if("entityId"===o)return!1;const a=n.fields.get(o);if(a){const e=n.getFieldType(o);return a[t]="boolean"===e?r?1:0:r,!0}const c=n.stringFields.get(o);if(c)return c[t]=String(r),!0;if(n.serializedFields.has(o)){return n.serializedFields.get(o)[t]=ze.serialize(r,o,{isMap:n.serializeMapFields.has(o),isSet:n.serializeSetFields.has(o),isArray:n.serializeArrayFields.has(o)}),!0}let h=n.complexFields.get(e);return h||(h=new Map,n.complexFields.set(e,h)),h.set(o,r),!0},has(t,s){const i=String(s);return n.fields.has(i)||n.stringFields.has(i)||n.serializedFields.has(i)||n.complexFields.get(e)?.has(i)||!1},ownKeys(){const t=[];for(const e of n.fields.keys())t.push(e);for(const e of n.stringFields.keys())t.push(e);for(const e of n.serializedFields.keys())t.push(e);const s=n.complexFields.get(e);if(s)for(const e of s.keys())t.push(e);return t},getOwnPropertyDescriptor(t,s){const i=String(s);if(n.fields.has(i)||n.stringFields.has(i)||n.serializedFields.has(i)||n.complexFields.get(e)?.has(i))return{enumerable:!0,configurable:!0,writable:"entityId"!==i}}})}getComponentSnapshot(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=new this.type,s=n;for(const[e,n]of this.fields.entries()){const i=n[t],r=this.getFieldType(e);s[e]="boolean"===r?1===i:i}for(const[e,n]of this.stringFields.entries())s[e]=n[t];for(const[e,n]of this.serializedFields.entries()){const i=n[t];i&&(s[e]=ze.deserialize(i,e,{isMap:this.serializeMapFields.has(e),isSet:this.serializeSetFields.has(e),isArray:this.serializeArrayFields.has(e)}))}const i=this.complexFields.get(e);if(i)for(const[e,t]of i.entries())s[e]=t;return n}getFieldType(e){return this.fieldTypes.get(e)||"unknown"}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()){const s=Re.createSameType(n,e);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()){const i=Re.getTypeName(s),r=Re.getBytesPerElement(i),o=s.length*r;e+=o,t.set(n,{size:this._size,capacity:s.length,type:i,memory:o})}return{size:this._size,capacity:this._capacity,totalSlots:this._capacity,usedSlots:this._size,freeSlots:this._capacity-this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:e,fieldStats:t}}performVectorizedOperation(e){const t=this.getActiveIndices();e(this.fields,t)}}class Xe{get lastWriteEpoch(){return this._lastWriteEpoch}constructor(){this.entityId=null,this._lastWriteEpoch=0,this.id=Xe._idGenerator++}markDirty(e){this._lastWriteEpoch=e}onAddedToEntity(){}onRemovedFromEntity(){}onDeserialized(){}}Xe._idGenerator=0,e([Le,t("design:type",Object)],Xe.prototype,"entityId",void 0);const Ke=Symbol("SerializableMetadata"),et=Symbol("SerializeField"),tt=Symbol("SerializeOptions");function nt(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");let n;if(Object.prototype.hasOwnProperty.call(t,Ke))n=t[Ke],n.options=e;else{const s=t[Ke];n={options:e,fields:s?new Map(s.fields):new Map,ignoredFields:s?new Set(s.ignoredFields):new Set},t[Ke]=n}return t}}function st(e){return function(t,n){const s=t.constructor;let i;if(Object.prototype.hasOwnProperty.call(s,Ke))i=s[Ke];else{const e=s[Ke];i={options:e?{...e.options}:{version:1},fields:e?new Map(e.fields):new Map,ignoredFields:e?new Set(e.ignoredFields):new Set},s[Ke]=i}i.fields.set(n,e||{})}}function it(){return function(e,t){st({serializer:e=>e instanceof Map?Array.from(e.entries()):null,deserializer:e=>Array.isArray(e)?new Map(e):new Map})(e,t)}}function rt(){return function(e,t){st({serializer:e=>e instanceof Set?Array.from(e):null,deserializer:e=>Array.isArray(e)?new Set(e):new Set})(e,t)}}function ot(){return function(e,t){const n=e.constructor;let s;if(Object.prototype.hasOwnProperty.call(n,Ke))s=n[Ke];else{const e=n[Ke];s={options:e?{...e.options}:{version:1},fields:e?new Map(e.fields):new Map,ignoredFields:e?new Set(e.ignoredFields):new Set},n[Ke]=s}s.ignoredFields.add(t)}}function at(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Ke]||null}function ct(e){return null!==at(e)}let ht=class extends Xe{constructor(){super(...arguments),this.parentId=null,this.childIds=[],this.depth=0,this.bActiveInHierarchy=!0,this.bCacheDirty=!0}};e([st(),t("design:type",Object)],ht.prototype,"parentId",void 0),e([st(),t("design:type",Array)],ht.prototype,"childIds",void 0),ht=e([X("Hierarchy",{editor:{hideInInspector:!0}}),nt({version:1,typeId:"Hierarchy"})],ht);class lt{constructor(){this.condition={all:[],any:[],none:[]}}static all(...e){return(new lt).all(...e)}static any(...e){return(new lt).any(...e)}static none(...e){return(new lt).none(...e)}static byTag(e){return(new lt).withTag(e)}static byName(e){return(new lt).withName(e)}static byComponent(e){return(new lt).withComponent(e)}static complex(){return new lt}static empty(){return new lt}static nothing(){const e=new lt;return e.condition.matchNothing=!0,e}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},...this.condition.matchNothing&&{matchNothing:!0}}}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&&!this.condition.matchNothing}isNothing(){return!0===this.condition.matchNothing}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,delete this.condition.matchNothing,this}clone(){const e=new lt;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),this.condition.matchNothing&&(e.condition.matchNothing=!0),e}toString(){if(this.condition.matchNothing)return"Matcher[nothing]";const e=[];return this.condition.all.length>0&&e.push(`all(${this.condition.all.map(e=>w(e)).join(", ")})`),this.condition.any.length>0&&e.push(`any(${this.condition.any.map(e=>w(e)).join(", ")})`),this.condition.none.length>0&&e.push(`none(${this.condition.none.map(e=>w(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(${w(this.condition.component)})`),`Matcher[${e.join(" & ")}]`}}class dt{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 ut{constructor(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e}addComponent(e,t){if(this.entityToIndex.has(e))throw new Error(`Entity ${e} already has component ${w(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 mt{constructor(){this.storages=new Map}isSoAStorage(e){return this.storages.get(e)instanceof Ze}getSoAStorage(e){const t=this.getStorage(e);return t instanceof Ze?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 Ze(e),mt._logger.info(`为 ${w(e)} 启用SoA优化(适用于大规模批量操作)`)):t=new ut(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,t=j){const n=R.clone(R.ZERO);for(const[s,i]of this.storages.entries())if(i.hasComponent(e)){const e=t.getBitMask(s);R.orInPlace(n,e)}return n}getAllStats(){const e=new Map;for(const[t,n]of this.storages.entries()){const s=w(t);e.set(s,n.getStats())}return e}clear(){for(const e of this.storages.values())e.clear();this.storages.clear()}}mt._logger=$("ComponentStorage");const pt=$("CommandBuffer");var ft,gt;!function(e){e.ADD_COMPONENT="add_component",e.REMOVE_COMPONENT="remove_component",e.DESTROY_ENTITY="destroy_entity",e.SET_ENTITY_ACTIVE="set_entity_active"}(ft||(ft={}));class yt{constructor(e,t=!1){this._pending=new Map,this._commands=[],this._scene=null,this._debug=!1,this._useDeduplication=!0,this._scene=e??null,this._debug=t}setScene(e){this._scene=e}get scene(){return this._scene}setDeduplication(e){this._useDeduplication=e}get pendingCount(){if(this._useDeduplication){let e=0;for(const t of this._pending.values())t.bDestroy&&e++,void 0!==t.active&&e++,t.adds&&(e+=t.adds.size),t.removes&&(e+=t.removes.size);return e}return this._commands.length}get hasPending(){return this._useDeduplication?this._pending.size>0:this._commands.length>0}getPending(e){let t=this._pending.get(e);return t||(t={},this._pending.set(e,t)),t}getTypeId(e){return"function"==typeof e?j.getBitIndex(e):j.getBitIndex(e.constructor)}addComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略添加组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);if(n.removes?.delete(s),n.adds||(n.adds=new Map),n.adds.set(s,t),this._debug){const n=w(t.constructor);pt.debug(`CommandBuffer: 延迟添加组件 ${n} 到实体 ${e.name}`)}}else this._commands.push({type:ft.ADD_COMPONENT,entity:e,component:t})}removeComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略移除组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);n.adds?.delete(s),n.removes||(n.removes=new Set),n.removes.add(s),this._debug&&pt.debug(`CommandBuffer: 延迟移除组件 ${t.name} 从实体 ${e.name}`)}else this._commands.push({type:ft.REMOVE_COMPONENT,entity:e,componentType:t})}destroyEntity(e){if(this._useDeduplication){const t=this.getPending(e);t.adds?.clear(),t.removes?.clear(),delete t.active,t.bDestroy=!0,this._debug&&pt.debug(`CommandBuffer: 延迟销毁实体 ${e.name}`)}else this._commands.push({type:ft.DESTROY_ENTITY,entity:e})}setEntityActive(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略设置激活状态,实体 ${e.name} 已标记销毁`));n.active=t,this._debug&&pt.debug(`CommandBuffer: 延迟设置实体 ${e.name} 激活状态为 ${t}`)}else this._commands.push({type:ft.SET_ENTITY_ACTIVE,entity:e,value:t})}flush(){return this._useDeduplication?this.flushDeduplication():this.flushLegacy()}flushDeduplication(){if(0===this._pending.size)return 0;const e=this._pending.size;let t=0;this._debug&&pt.debug(`CommandBuffer: 开始执行 ${e} 个实体的延迟命令`);const n=this._pending;this._pending=new Map;for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.removes&&s.removes.size>0)for(const n of s.removes)try{const s=j.getTypeByBitIndex(n);s&&(e.removeComponentByType(s),t++)}catch(t){pt.error("CommandBuffer: 移除组件失败",{entity:e.name,typeId:n,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.adds&&s.adds.size>0)for(const n of s.adds.values())try{e.addComponent(n),t++}catch(t){const s=w(n.constructor);pt.error("CommandBuffer: 添加组件失败",{entity:e.name,component:s,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&void 0!==s.active)try{e.active=s.active,t++}catch(t){pt.error("CommandBuffer: 设置激活状态失败",{entity:e.name,error:t})}for(const[e,s]of n)if(s.bDestroy&&e.scene)try{e.destroy(),t++}catch(t){pt.error("CommandBuffer: 销毁实体失败",{entity:e.name,error:t})}return this._debug&&pt.debug(`CommandBuffer: 完成执行 ${t} 个延迟命令`),t}flushLegacy(){if(0===this._commands.length)return 0;const e=this._commands.length;this._debug&&pt.debug(`CommandBuffer: 开始执行 ${e} 个延迟命令`);const t=this._commands;this._commands=[];for(const e of t)this.executeCommand(e);return this._debug&&pt.debug(`CommandBuffer: 完成执行 ${e} 个延迟命令`),e}executeCommand(e){if(e.entity.scene)try{switch(e.type){case ft.ADD_COMPONENT:e.component&&e.entity.addComponent(e.component);break;case ft.REMOVE_COMPONENT:e.componentType&&e.entity.removeComponentByType(e.componentType);break;case ft.DESTROY_ENTITY:e.entity.destroy();break;case ft.SET_ENTITY_ACTIVE:void 0!==e.value&&(e.entity.active=e.value)}}catch(t){pt.error("CommandBuffer: 执行命令失败",{command:e,error:t})}else this._debug&&pt.debug(`CommandBuffer: 跳过命令,实体 ${e.entity.name} 已无效`)}clear(){if(this._debug){const e=this._useDeduplication?this._pending.size:this._commands.length;e>0&&pt.debug(`CommandBuffer: 清空 ${e} 个未执行的命令`)}this._pending.clear(),this._commands.length=0}dispose(){this.clear(),this._scene=null}}class _t{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 addOrder(){return this._addOrder}set addOrder(e){this._addOrder=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get systemName(){return this._systemName}constructor(e){this.commands=new yt,this._lastProcessEpoch=0,this._shouldProcessThisFrame=!1,this._updateOrder=0,this._addOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=se(this),this._initialized=!1,this._matcher=e||lt.empty(),this._eventListeners=[],this._scene=null,this._destroyed=!1,this._entityIdMap=null,this._entityIdMapVersion=-1,this.logger=$(this.getLoggerName()),this._entityCache=new dt;const t=Ae(this);this._schedulingMetadata=t?{...t}:{stage:"update",before:[],after:[],sets:[]}}get scene(){return this._scene}set scene(e){this._scene=e,this.commands.setScene(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())}stage(e){return this._schedulingMetadata.stage=e,this._scene?.markSystemsOrderDirty(),this}before(...e){return this._schedulingMetadata.before.push(...e),this._scene?.markSystemsOrderDirty(),this}after(...e){return this._schedulingMetadata.after.push(...e),this._scene?.markSystemsOrderDirty(),this}inSet(...e){return this._schedulingMetadata.sets.push(...e),this._scene?.markSystemsOrderDirty(),this}getStage(){return this._schedulingMetadata.stage}getBefore(){return this._schedulingMetadata.before}getAfter(){return this._schedulingMetadata.after}getSets(){return this._schedulingMetadata.sets}initialize(){if(!this._initialized){if(this._initialized=!0,this.scene){this._entityCache.invalidate();const e=this.queryEntities();for(const t of e)this.onAdded(t)}this.onInitialize()}}onInitialize(){}clearEntityCache(){this._entityCache.invalidate()}resetEntityTracking(){this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1}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 this._matcher.isNothing()?[]:(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._shouldProcessThisFrame=this._enabled&&this.onCheckProcessing(),!this._shouldProcessThisFrame)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._shouldProcessThisFrame)return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(`${this._systemName}_Late`);let n=0;try{const e=this.queryEntities();this._entityCache.setFrame(e),n=e.length,this.lateProcess(e),this.onEnd()}finally{e.endMonitoring(`${this._systemName}_Late`,t,n),this._entityCache.clearFrame()}}flushCommands(){return this.commands.flush()}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}`}matchesEntity(e){if(!this._matcher)return!1;if(this._matcher.isNothing())return!1;if(this._matcher.isEmpty())return!0;const t=this._matcher.getCondition();for(const n of t.all)if(!e.hasComponent(n))return!1;if(t.any.length>0){let n=!1;for(const s of t.any)if(e.hasComponent(s)){n=!0;break}if(!n)return!1}for(const n of t.none)if(e.hasComponent(n))return!1;return(void 0===t.tag||e.tag===t.tag)&&((void 0===t.name||e.name===t.name)&&!(void 0!==t.component&&!e.hasComponent(t.component)))}isTracking(e){return this._entityCache.isTracked(e)}handleEntityComponentChanged(e){if(!this._matcher||!this._enabled)return;const t=this._entityCache.isTracked(e),n=this.matchesEntity(e);!t&&n?(this._entityCache.addTracked(e),this._entityCache.invalidate(),this.onAdded(e)):t&&!n&&(this._entityCache.removeTracked(e),this._entityCache.invalidate(),this.onRemoved(e))}updateEntityTracking(e){const t=new Set(e);let n=!1;for(const t of e)this._entityCache.isTracked(t)||(this._entityCache.addTracked(t),n=!0);for(const e of this._entityCache.getTracked())t.has(e)||(this._entityCache.removeTracked(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.commands.dispose(),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 se(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}get lastProcessEpoch(){return this._lastProcessEpoch}get currentEpoch(){return this._scene?.epochManager?.current??0}saveEpoch(){this._lastProcessEpoch=this.currentEpoch}forEachChanged(e,t,n,s){const i=s??this._lastProcessEpoch;for(let s=0;s<e.length;s++){const r=e[s];let o=!1;for(const e of t){const t=r.getComponent(e);if(t&&t.lastWriteEpoch>i){o=!0;break}}o&&n(r,s)}this._lastProcessEpoch=this.currentEpoch}filterChanged(e,t,n){const s=n??this._lastProcessEpoch,i=[];for(let n=0;n<e.length;n++){const r=e[n];for(const e of t){const t=r.getComponent(e);if(t&&t.lastWriteEpoch>s){i.push(r);break}}}return i}hasChanged(e,t,n){const s=n??this._lastProcessEpoch;for(const n of t){const t=e.getComponent(n);if(t&&t.lastWriteEpoch>s)return!0}return!1}}class St extends _t{constructor(){super(lt.empty().all(ht)),this.dirtyEntities=new Set}get updateOrder(){return-1e3}process(e){if(0!==this.dirtyEntities.size){for(const e of this.dirtyEntities)e.scene&&this.updateHierarchyCache(e);this.dirtyEntities.clear()}}setParent(e,t){let n=e.getComponent(ht);n||(n=new ht,e.addComponent(n));const s=n.parentId;if(s!==(t?.id??null)){if(t&&this.isAncestorOf(e,t))throw new Error("Cannot set parent: would create circular reference");if(null!==s){const t=this.scene?.findEntityById(s);if(t){const n=t.getComponent(ht);if(n){const t=n.childIds.indexOf(e.id);-1!==t&&n.childIds.splice(t,1)}}}if(t){let s=t.getComponent(ht);s||(s=new ht,t.addComponent(s)),n.parentId=t.id,s.childIds.push(e.id)}else n.parentId=null;this.markCacheDirty(e)}}insertChildAt(e,t,n){let s=t.getComponent(ht),i=e.getComponent(ht);if(s||(s=new ht,t.addComponent(s)),i||(i=new ht,e.addComponent(i)),this.isAncestorOf(t,e))throw new Error("Cannot set parent: would create circular reference");if(null!==s.parentId&&s.parentId!==e.id){const e=this.scene?.findEntityById(s.parentId);if(e){const n=e.getComponent(ht);if(n){const e=n.childIds.indexOf(t.id);-1!==e&&n.childIds.splice(e,1)}}}s.parentId=e.id;const r=i.childIds.indexOf(t.id);-1!==r&&i.childIds.splice(r,1),n<0||n>=i.childIds.length?i.childIds.push(t.id):i.childIds.splice(n,0,t.id),this.markCacheDirty(t)}removeChild(e,t){const n=e.getComponent(ht),s=t.getComponent(ht);if(!n||!s)return!1;if(s.parentId!==e.id)return!1;const i=n.childIds.indexOf(t.id);return-1!==i&&n.childIds.splice(i,1),s.parentId=null,this.markCacheDirty(t),!0}removeAllChildren(e){const t=e.getComponent(ht);if(!t)return;const n=[...t.childIds];for(const t of n){const n=this.scene?.findEntityById(t);n&&this.removeChild(e,n)}}getParent(e){const t=e.getComponent(ht);return t&&null!==t.parentId?this.scene?.findEntityById(t.parentId)??null:null}getChildren(e){const t=e.getComponent(ht);if(!t)return[];const n=[];for(const e of t.childIds){const t=this.scene?.findEntityById(e);t&&n.push(t)}return n}getChildCount(e){const t=e.getComponent(ht);return t?.childIds.length??0}hasChildren(e){return this.getChildCount(e)>0}isAncestorOf(e,t){let n=this.getParent(t),s=0;for(;n&&s<St.MAX_DEPTH;){if(n.id===e.id)return!0;n=this.getParent(n),s++}return!1}isDescendantOf(e,t){return this.isAncestorOf(t,e)}getRoot(e){let t=e,n=this.getParent(t),s=0;for(;n&&s<St.MAX_DEPTH;)t=n,n=this.getParent(t),s++;return t}getDepth(e){const t=e.getComponent(ht);if(!t)return 0;if(!t.bCacheDirty)return t.depth;let n=0,s=this.getParent(e);for(;s&&n<St.MAX_DEPTH;)n++,s=this.getParent(s);return t.depth=n,n}isActiveInHierarchy(e){if(!e.active)return!1;const t=e.getComponent(ht);if(!t)return e.active;if(!t.bCacheDirty)return t.bActiveInHierarchy;const n=this.getParent(e);return t.bActiveInHierarchy=n?e.active&&this.isActiveInHierarchy(n):e.active,t.bActiveInHierarchy}getRootEntities(){const e=[];for(const t of this.entities){const n=t.getComponent(ht);n&&null===n.parentId&&e.push(t)}return e}findChild(e,t,n=!1){const s=this.getChildren(e);for(const e of s)if(e.name===t)return e;if(n)for(const e of s){const n=this.findChild(e,t,!0);if(n)return n}return null}findChildrenByTag(e,t,n=!1){const s=[],i=this.getChildren(e);for(const e of i)0!==(e.tag&t)&&s.push(e),n&&s.push(...this.findChildrenByTag(e,t,!0));return s}forEachChild(e,t,n=!1){const s=this.getChildren(e);for(const e of s)t(e),n&&this.forEachChild(e,t,!0)}flattenHierarchy(e){const t=[],n=(s,i)=>{const r=this.hasChildren(s),o=e.has(s.id);if(t.push({entity:s,depth:i,bHasChildren:r,bIsExpanded:o}),r&&o)for(const e of this.getChildren(s))n(e,i+1)};for(const e of this.getRootEntities())n(e,0);return t}markCacheDirty(e){const t=e.getComponent(ht);if(t&&!t.bCacheDirty){t.bCacheDirty=!0,this.dirtyEntities.add(e);for(const e of t.childIds){const t=this.scene?.findEntityById(e);t&&this.markCacheDirty(t)}}}updateHierarchyCache(e){const t=e.getComponent(ht);t&&(t.depth=this.getDepth(e),t.bActiveInHierarchy=this.isActiveInHierarchy(e),t.bCacheDirty=!1)}onAdded(e){const t=e.getComponent(ht);t&&t.bCacheDirty&&this.dirtyEntities.add(e)}onRemoved(e){this.dirtyEntities.delete(e);const t=e.getComponent(ht);if(t){if(null!==t.parentId){const n=this.scene?.findEntityById(t.parentId);if(n){const t=n.getComponent(ht);if(t){const n=t.childIds.indexOf(e.id);-1!==n&&t.childIds.splice(n,1)}}}for(const e of t.childIds){const t=this.scene?.findEntityById(e);if(t){const e=t.getComponent(ht);e&&(e.parentId=null,this.markCacheDirty(t))}}}}dispose(){this.dirtyEntities.clear()}}St.MAX_DEPTH=32;class Ct{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;if(!t?.buffer)return[];const n=e.getSystem(St);return t.buffer.map(e=>{const t=e.getComponent(ht),s=n?.isActiveInHierarchy(e)??e.active,i=n?.getDepth(e)??0;return{id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:s,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),parentId:t?.parentId??null,childIds:t?.childIds??[],depth:i,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=t.getSystem(St),r=i?.getParent(s),o=r?.name??null,a=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t,i),c=this.extractComponentDetails(s.components),h=this.getSceneInfo(t);return{...a,scene:h.name,sceneName:h.name,sceneType:h.type,parentName:o,components:c||[],componentCount:s.components?.length||0,componentTypes:s.components?.map(e=>I(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,e),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=>I(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=>I(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,t){if(!e?.buffer)return[];const n=t?.getSystem(St),s=[];return e.buffer.forEach(e=>{const t=e.getComponent(ht);if(null==t?.parentId){const t=this.buildEntityHierarchyNode(e,n);s.push(t)}}),s.sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:e.id-t.id),s}buildEntityHierarchyNode(e,t){const n=e.getComponent(ht),s=t?.isActiveInHierarchy(e)??e.active,i=t?.getDepth(e)??0;let r={id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:s,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),parentId:n?.parentId??null,children:[],depth:i,tag:e.tag||0,updateOrder:e.updateOrder||0};if(t){const n=t.getChildren(e);n.length>0&&(r.children=n.map(e=>this.buildEntityHierarchyNode(e,t)))}if("function"==typeof e.getDebugInfo){const t=e.getDebugInfo();r={...r,...t}}return e.components&&e.components.length>0&&(r.componentDetails=this.extractComponentDetails(e.components)),r}buildEntityDetailsMap(e,t){if(!e?.buffer)return{};const n=t?.getSystem(St),s={},i=e.buffer;for(let e=0;e<i.length;e+=100){i.slice(e,e+100).forEach(e=>{const i=e.getDebugInfo?e.getDebugInfo():this.buildFallbackEntityInfo(e,t,n),r=e.getComponentCacheStats?e.getComponentCacheStats():null,o=this.extractComponentDetails(e.components),a=n?.getParent(e),c=a?.name??null;s[e.id]={...i,parentName:c,components:o,componentTypes:i.componentTypes||o.map(e=>e.typeName),cachePerformance:r?{hitRate:r.cacheStats.hitRate,size:r.cacheStats.size,maxSize:r.cacheStats.maxSize}:null}})}return s}buildFallbackEntityInfo(e,t,n){const s=this.getSceneInfo(t),i=e.getComponent(ht),r=n?.isActiveInHierarchy(e)??e.active,o=n?.getDepth(e)??0;return{name:e.name||`Entity_${e.id}`,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:r,destroyed:e.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),componentMask:e.componentMask?.toString()||"0",parentId:i?.parentId??null,childCount:i?.childIds?.length??0,childIds:i?.childIds??[],depth:o,tag:e.tag||0,updateOrder:e.updateOrder||0}}extractComponentDetails(e){return e.map(e=>{const t=I(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=I(e))}catch(t){n._error="属性提取失败",n._componentId=I(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];if(!r)return{};const 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 vt{collectSystemData(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};const n=t.systems||[];let s=new Map,i=new Map;if(e)try{s=e.getAllSystemStats(),i=e.getAllSystemData()}catch(e){}return{totalSystems:n.length,systemsInfo:n.map(e=>{const t=e.systemName||se(e),n=s.get(t),r=i.get(t);return{name:t,type:se(e),entityCount:e.entities?.length||0,executionTime:n?.averageTime||r?.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:r?.lastUpdateTime||0}})}}}class Et{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(e){const t=n.deltaTime,s=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,a=s>0?o/s*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:s,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 bt{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 Tt{constructor(){this._pools=new Map,this._usageTracker=new Map,this._autoCleanupInterval=6e4,this._lastCleanupTime=0}static getInstance(){return Tt._instance||(Tt._instance=new Tt),Tt._instance}registerPool(e,t,n,s,i){this._pools.set(e,new bt(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 wt{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=I(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=Tt.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(wt.componentSizeCache.has(e))return wt.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=>I(t)===e);if(n){s=this.calculateQuickObjectSize(n);break}}}catch(e){s=64}return wt.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=>I(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(){wt.componentSizeCache.clear()}}wt.componentSizeCache=new Map;class It{constructor(){this.sceneStartTime=Date.now()}collectSceneData(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneUptime:0};const t=(Date.now()-this.sceneStartTime)/1e3,n=e.getStats();return{currentSceneName:e.name||"Unnamed Scene",isInitialized:!0,sceneRunTime:t,sceneEntityCount:n.entityCount,sceneSystemCount:n.processorCount,sceneUptime:t}}setSceneStartTime(e){this.sceneStartTime=e}}class Mt{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)}}!function(e){e.ECS="ECS",e.Rendering="Rendering",e.Physics="Physics",e.Audio="Audio",e.Network="Network",e.Script="Script",e.Memory="Memory",e.Animation="Animation",e.AI="AI",e.Input="Input",e.Loading="Loading",e.Custom="Custom"}(gt||(gt={}));const At={enabled:!1,maxFrameHistory:300,maxSampleDepth:32,collectMemory:!0,memorySampleInterval:100,detectLongTasks:!0,longTaskThreshold:50,enabledCategories:new Set(Object.values(gt))};let kt=0;class Dt{constructor(e){this.currentFrame=null,this.frameHistory=[],this.frameNumber=0,this.activeSamples=new Map,this.sampleStack=[],this.counters=new Map,this.callGraph=new Map,this.gcCount=0,this.previousHeapSize=0,this.longTasks=[],this.performanceObserver=null,this._config={...At,...e},this._config.detectLongTasks&&this._setupLongTaskObserver()}static getInstance(e){return Dt._instance||(Dt._instance=new Dt(e)),Dt._instance}static resetInstance(){Dt._instance&&(Dt._instance.dispose(),Dt._instance=null)}static beginSample(e,t=gt.Custom){return Dt.getInstance().beginSample(e,t)}static endSample(e){e&&Dt.getInstance().endSample(e)}static measure(e,t,n=gt.Custom){return Dt.getInstance().measure(e,t,n)}static async measureAsync(e,t,n=gt.Custom){return Dt.getInstance().measureAsync(e,t,n)}static beginFrame(){Dt.getInstance().beginFrame()}static endFrame(){Dt.getInstance().endFrame()}static incrementCounter(e,t=1,n=gt.Custom){Dt.getInstance().incrementCounter(e,t,n)}static setGauge(e,t,n=gt.Custom){Dt.getInstance().setGauge(e,t,n)}static setEnabled(e){Dt.getInstance().setEnabled(e)}static isEnabled(){return Dt.getInstance()._config.enabled}static getCurrentFrame(){return Dt.getInstance().currentFrame}static getFrameHistory(){return Dt.getInstance().frameHistory}static getReport(e){return Dt.getInstance().generateReport(e)}static reset(){Dt.getInstance().reset()}beginSample(e,t=gt.Custom){if(!this._config.enabled||!this._config.enabledCategories.has(t))return null;const n=this.sampleStack.length>0?this.sampleStack[this.sampleStack.length-1]:void 0;if(n&&this.sampleStack.length>=this._config.maxSampleDepth)return null;const s={id:`sample_${++kt}_${Date.now()}`,name:e,category:t,startTime:performance.now(),depth:this.sampleStack.length,parentId:n?.id};return this.activeSamples.set(s.id,s),this.sampleStack.push(s),s}endSample(e){if(!this._config.enabled||!this.activeSamples.has(e.id))return;const t=performance.now(),n=t-e.startTime,s=e.parentId?this.activeSamples.get(e.parentId):void 0,i={id:e.id,name:e.name,category:e.category,startTime:e.startTime,endTime:t,duration:n,selfTime:n,parentId:e.parentId,parentName:s?.name,depth:e.depth,callCount:1};this.currentFrame&&this.currentFrame.samples.push(i),this._updateCallGraph(e.name,e.category,n,s),this.activeSamples.delete(e.id);const r=this.sampleStack.indexOf(e);-1!==r&&this.sampleStack.splice(r,1)}measure(e,t,n=gt.Custom){const s=this.beginSample(e,n);try{return t()}finally{s&&this.endSample(s)}}async measureAsync(e,t,n=gt.Custom){const s=this.beginSample(e,n);try{return await t()}finally{s&&this.endSample(s)}}beginFrame(){this._config.enabled&&(this.frameNumber++,this.currentFrame={frameNumber:this.frameNumber,startTime:performance.now(),endTime:0,duration:0,samples:[],sampleStats:[],counters:new Map(this.counters),memory:this._captureMemory(),categoryStats:new Map},this._resetFrameCounters())}endFrame(){if(this._config.enabled&&this.currentFrame){for(this.currentFrame.endTime=performance.now(),this.currentFrame.duration=this.currentFrame.endTime-this.currentFrame.startTime,this._calculateSampleStats(),this._calculateCategoryStats(),this.frameHistory.push(this.currentFrame);this.frameHistory.length>this._config.maxFrameHistory;)this.frameHistory.shift();this.sampleStack=[],this.activeSamples.clear()}}incrementCounter(e,t=1,n=gt.Custom){if(!this._config.enabled)return;let s=this.counters.get(e);s||(s={name:e,category:n,value:0,type:"counter",history:[]},this.counters.set(e,s)),s.value+=t,s.history.push({time:performance.now(),value:s.value}),s.history.length>100&&s.history.shift()}setGauge(e,t,n=gt.Custom){if(!this._config.enabled)return;let s=this.counters.get(e);s||(s={name:e,category:n,value:0,type:"gauge",history:[]},this.counters.set(e,s)),s.value=t,s.history.push({time:performance.now(),value:t}),s.history.length>100&&s.history.shift()}setEnabled(e){this._config.enabled=e,e&&this._config.detectLongTasks&&!this.performanceObserver&&this._setupLongTaskObserver()}reset(){this.frameHistory=[],this.currentFrame=null,this.frameNumber=0,this.activeSamples.clear(),this.sampleStack=[],this.counters.clear(),this.callGraph.clear(),this.gcCount=0,this.longTasks=[]}generateReport(e){const t=e?this.frameHistory.slice(-e):this.frameHistory;if(0===t.length)return this._createEmptyReport();const n=t.map(e=>e.duration),s=[...n].sort((e,t)=>e-t),i=this._aggregateSampleStats(t).sort((e,t)=>t.inclusiveTime-e.inclusiveTime).slice(0,20),r=this._aggregateCategoryStats(t),o=this._buildCallGraphFromFrames(t),a=t[0],c=t[t.length-1];return{startTime:a?.startTime??0,endTime:c?.endTime??0,totalFrames:t.length,averageFrameTime:n.reduce((e,t)=>e+t,0)/n.length,minFrameTime:Math.min(...n),maxFrameTime:Math.max(...n),p95FrameTime:s[Math.floor(.95*s.length)]||0,p99FrameTime:s[Math.floor(.99*s.length)]||0,hotspots:i,callGraph:o,categoryBreakdown:r,memoryTrend:t.map(e=>e.memory),longTasks:[...this.longTasks]}}_buildCallGraphFromFrames(e){const t=new Map;for(const n of e)for(const e of n.samples){let n=t.get(e.name);if(n||(n={category:e.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},t.set(e.name,n)),n.callCount++,n.totalTime+=e.duration,e.parentName){const s=n.callers.get(e.parentName)||{count:0,totalTime:0};s.count++,s.totalTime+=e.duration,n.callers.set(e.parentName,s);let i=t.get(e.parentName);i||(i={category:e.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},t.set(e.parentName,i));const r=i.callees.get(e.name)||{count:0,totalTime:0};r.count++,r.totalTime+=e.duration,i.callees.set(e.name,r)}}const n=new Map;for(const[e,s]of t){const t=new Map;for(const[e,n]of s.callers)t.set(e,{count:n.count,totalTime:n.count>0?n.totalTime/n.count:0});const i=new Map;for(const[e,t]of s.callees)i.set(e,{count:t.count,totalTime:t.count>0?t.totalTime/t.count:0});n.set(e,{name:e,category:s.category,callCount:s.callCount,totalTime:s.callCount>0?s.totalTime/s.callCount:0,callers:t,callees:i})}return n}getCallGraph(){return new Map(this.callGraph)}getFunctionCallInfo(e){const t=this.callGraph.get(e);return t?{callers:Array.from(t.callers.entries()).map(([e,t])=>({name:e,...t})),callees:Array.from(t.callees.entries()).map(([e,t])=>({name:e,...t}))}:null}dispose(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.reset()}_captureMemory(){const e=performance.now();let t=0,n=0,s=0;const i=performance;return i.memory&&(t=i.memory.usedJSHeapSize||0,n=i.memory.totalJSHeapSize||0,s=i.memory.jsHeapSizeLimit||0,this.previousHeapSize>0&&t<this.previousHeapSize-1048576&&this.gcCount++,this.previousHeapSize=t),{timestamp:e,usedHeapSize:t,totalHeapSize:n,heapSizeLimit:s,utilizationPercent:s>0?t/s*100:0,gcCount:this.gcCount}}_resetFrameCounters(){for(const e of this.counters.values())"counter"===e.type&&(e.value=0)}_calculateSampleStats(){if(!this.currentFrame)return;const e=new Map;for(const t of this.currentFrame.samples){let n=e.get(t.name);n||(n={name:t.name,category:t.category,inclusiveTime:0,exclusiveTime:0,callCount:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,percentOfFrame:0,percentOfParent:0,children:[],depth:t.depth},e.set(t.name,n)),n.inclusiveTime+=t.duration,n.callCount+=1,n.minTime=Math.min(n.minTime,t.duration),n.maxTime=Math.max(n.maxTime,t.duration)}for(const t of this.currentFrame.samples)if(t.parentId){const n=this.currentFrame.samples.find(e=>e.id===t.parentId);if(n){const t=e.get(n.name);if(t){t.exclusiveTime=t.inclusiveTime;for(const e of this.currentFrame.samples)e.parentId===n.id&&(t.exclusiveTime-=e.duration)}}}const t=this.currentFrame.duration||1;for(const n of e.values())n.averageTime=n.inclusiveTime/n.callCount,n.percentOfFrame=n.inclusiveTime/t*100,0===n.exclusiveTime&&(n.exclusiveTime=n.inclusiveTime);this.currentFrame.sampleStats=Array.from(e.values()).sort((e,t)=>t.inclusiveTime-e.inclusiveTime)}_calculateCategoryStats(){if(!this.currentFrame)return;const e=new Map;for(const t of this.currentFrame.samples)if(0===t.depth){let n=e.get(t.category);n||(n={totalTime:0,sampleCount:0},e.set(t.category,n)),n.totalTime+=t.duration,n.sampleCount+=1}const t=this.currentFrame.duration||1;for(const[n,s]of e)this.currentFrame.categoryStats.set(n,{...s,percentOfFrame:s.totalTime/t*100})}_updateCallGraph(e,t,n,s){let i=this.callGraph.get(e);if(i||(i={name:e,category:t,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(e,i)),i.callCount++,i.totalTime+=n,s){const t=i.callers.get(s.name)||{count:0,totalTime:0};t.count++,t.totalTime+=n,i.callers.set(s.name,t);let r=this.callGraph.get(s.name);r||(r={name:s.name,category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(s.name,r));const o=r.callees.get(e)||{count:0,totalTime:0};o.count++,o.totalTime+=n,r.callees.set(e,o)}}_aggregateSampleStats(e){const t=new Map;for(const n of e)for(const e of n.sampleStats){let n=t.get(e.name);n?(n.inclusiveTime+=e.inclusiveTime,n.exclusiveTime+=e.exclusiveTime,n.callCount+=e.callCount,n.minTime=Math.min(n.minTime,e.minTime),n.maxTime=Math.max(n.maxTime,e.maxTime)):(n={...e,minTime:Number.MAX_VALUE},t.set(e.name,n))}const n=e.reduce((e,t)=>e+t.duration,0);for(const e of t.values())e.averageTime=e.inclusiveTime/e.callCount,e.percentOfFrame=e.inclusiveTime/n*100;return Array.from(t.values())}_aggregateCategoryStats(e){const t=new Map;for(const n of e)for(const[e,s]of n.categoryStats){let n=t.get(e);n||(n={totalTime:0,frameCount:0},t.set(e,n)),n.totalTime+=s.totalTime,n.frameCount++}const n=e.reduce((e,t)=>e+t.duration,0),s=new Map;for(const[e,i]of t)s.set(e,{totalTime:i.totalTime,averageTime:i.frameCount>0?i.totalTime/i.frameCount:0,percentOfTotal:n>0?i.totalTime/n*100:0});return s}_setupLongTaskObserver(){if("undefined"!=typeof PerformanceObserver)try{this.performanceObserver=new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>this._config.longTaskThreshold&&(this.longTasks.push({startTime:t.startTime,duration:t.duration,attribution:t.attribution?.map(e=>e.name)||[]}),this.longTasks.length>100&&this.longTasks.shift())}),this.performanceObserver.observe({entryTypes:["longtask"]})}catch{}}_createEmptyReport(){return{startTime:0,endTime:0,totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,hotspots:[],callGraph:new Map,categoryBreakdown:new Map,memoryTrend:[],longTasks:[]}}}Dt._instance=null;class xt{constructor(){this.selectedFunction=null,this.peakMemory=0}setSelectedFunction(e){this.selectedFunction=e}collectAdvancedData(e){const t=Dt.getFrameHistory(),n=Dt.getCurrentFrame(),s=Dt.getReport(300),i=n?.memory||this.getDefaultMemory();return i.usedHeapSize>this.peakMemory&&(this.peakMemory=i.usedHeapSize),{currentFrame:this.buildCurrentFrameData(n),frameTimeHistory:this.buildFrameTimeHistory(t),categoryStats:this.buildCategoryStats(n,e),hotspots:this.buildHotspots(s),callGraph:this.buildCallGraph(s),longTasks:s.longTasks,memoryTrend:this.buildMemoryTrend(s.memoryTrend),summary:this.buildSummary(s,i)}}collectFromLegacyMonitor(e){if(!e)return this.createEmptyData();const t=e.getAllSystemStats?.()||new Map,s=e.getAllSystemData?.()||new Map,i=1e3*n.deltaTime,r=i>0?Math.round(1e3/i):0,o=this.buildCategoryStatsFromLegacy(t,s,i),a=this.buildHotspotsFromLegacy(t,s,i);return{currentFrame:{frameNumber:0,frameTime:i,fps:r,memory:this.getCurrentMemory()},frameTimeHistory:[],categoryStats:o,hotspots:a,callGraph:{currentFunction:this.selectedFunction,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:i,minFrameTime:i,maxFrameTime:i,p95FrameTime:i,p99FrameTime:i,currentMemoryMB:this.getCurrentMemory().usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:0,longTaskCount:0}}}buildCurrentFrameData(e){if(!e){const e=1e3*n.deltaTime;return{frameNumber:0,frameTime:e,fps:e>0?Math.round(1e3/e):0,memory:this.getCurrentMemory()}}return{frameNumber:e.frameNumber,frameTime:e.duration,fps:e.duration>0?Math.round(1e3/e.duration):0,memory:e.memory}}buildFrameTimeHistory(e){return e.map(e=>({frameNumber:e.frameNumber,time:e.startTime,duration:e.duration}))}buildCategoryStats(e,t){const s=[];if(e&&e.categoryStats.size>0){const t=e.duration||1;for(const[n,i]of e.categoryStats){const r=e.sampleStats.filter(e=>e.category===n).map(e=>({name:e.name,inclusiveTime:e.inclusiveTime,exclusiveTime:e.exclusiveTime,callCount:e.callCount,percentOfCategory:i.totalTime>0?e.inclusiveTime/i.totalTime*100:0,percentOfFrame:e.inclusiveTime/t*100})).sort((e,t)=>t.inclusiveTime-e.inclusiveTime);s.push({category:n,totalTime:i.totalTime,percentOfFrame:i.percentOfFrame,sampleCount:i.sampleCount,items:r})}}if(t&&0===s.length){const e=t.getAllSystemStats?.()||new Map,s=t.getAllSystemData?.()||new Map,i=1e3*n.deltaTime||1;return this.buildCategoryStatsFromLegacy(e,s,i)}return s.sort((e,t)=>t.totalTime-e.totalTime)}buildCategoryStatsFromLegacy(e,t,n){const s=[];let i=0;for(const[r,o]of e.entries()){const e=t.get(r),a=e?.executionTime||o?.averageTime||0;i+=a,s.push({name:r,inclusiveTime:a,exclusiveTime:a,callCount:1,percentOfCategory:0,percentOfFrame:n>0?a/n*100:0})}for(const e of s)e.percentOfCategory=i>0?e.inclusiveTime/i*100:0;return s.sort((e,t)=>t.inclusiveTime-e.inclusiveTime),0===s.length?[]:[{category:gt.ECS,totalTime:i,percentOfFrame:n>0?i/n*100:0,sampleCount:s.length,items:s}]}buildHotspots(e){const t=e.hotspots.reduce((e,t)=>e+t.inclusiveTime,0)||1,n=new Set,s=new Set;for(const[t,i]of e.callGraph)if(0===i.callers.size)n.add(t);else{let r=!1;for(const n of i.callers.keys())if(e.callGraph.has(n)){r=!0,s.add(t);break}r||n.add(t)}const i=(n,s,r)=>{if(r.has(n))return null;r.add(n);const o=e.hotspots.find(e=>e.name===n),a=e.callGraph.get(n);if(!o&&!a)return null;const c=o?.inclusiveTime||a?.totalTime||0,h=o?.exclusiveTime||c,l=o?.callCount||a?.callCount||1,d=[];if(a&&s<5){for(const[e]of a.callees){const t=i(e,s+1,r);t&&d.push(t)}d.sort((e,t)=>t.inclusiveTime-e.inclusiveTime)}return{name:n,category:o?.category||a?.category||gt.Custom,inclusiveTime:c,inclusiveTimePercent:c/t*100,exclusiveTime:h,exclusiveTimePercent:h/t*100,callCount:l,avgCallTime:l>0?c/l:0,depth:s,children:d.length>0?d:void 0}},r=[],o=new Set;for(const e of n){const t=i(e,0,o);t&&r.push(t)}return r.sort((e,t)=>t.inclusiveTime-e.inclusiveTime),r.slice(0,50)}buildHotspotsFromLegacy(e,t,n){const s=[];for(const[i,r]of e.entries()){const e=t.get(i),o=e?.executionTime||r?.averageTime||0;s.push({name:i,category:gt.ECS,inclusiveTime:o,inclusiveTimePercent:n>0?o/n*100:0,exclusiveTime:o,exclusiveTimePercent:n>0?o/n*100:0,callCount:r?.executionCount||1,avgCallTime:r?.averageTime||o,depth:0})}return s.sort((e,t)=>t.inclusiveTime-e.inclusiveTime).slice(0,50)}buildCallGraph(e){if(!this.selectedFunction)return{currentFunction:null,callers:[],callees:[]};const t=e.callGraph.get(this.selectedFunction);if(!t)return{currentFunction:this.selectedFunction,callers:[],callees:[]};let n=0;for(const e of t.callers.values())n+=e.count;const s=Array.from(t.callers.entries()).map(([e,t])=>({name:e,callCount:t.count,totalTime:t.totalTime,percentOfCurrent:n>0?t.count/n*100:0})).sort((e,t)=>t.callCount-e.callCount),i=Array.from(t.callees.entries()).map(([e,n])=>({name:e,callCount:n.count,totalTime:n.totalTime,percentOfCurrent:t.totalTime>0?n.totalTime/t.totalTime*100:0})).sort((e,t)=>t.totalTime-e.totalTime);return{currentFunction:this.selectedFunction,callers:s,callees:i}}buildMemoryTrend(e){return e.map(e=>({time:e.timestamp,usedMB:e.usedHeapSize/1048576,totalMB:e.totalHeapSize/1048576,gcCount:e.gcCount}))}buildSummary(e,t){return{totalFrames:e.totalFrames,averageFrameTime:e.averageFrameTime,minFrameTime:e.minFrameTime,maxFrameTime:e.maxFrameTime,p95FrameTime:e.p95FrameTime,p99FrameTime:e.p99FrameTime,currentMemoryMB:t.usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:t.gcCount,longTaskCount:e.longTasks.length}}getCurrentMemory(){const e=performance,t=e.memory?.usedJSHeapSize||0,n=e.memory?.totalJSHeapSize||0,s=e.memory?.jsHeapSizeLimit||0;return{timestamp:performance.now(),usedHeapSize:t,totalHeapSize:n,heapSizeLimit:s,utilizationPercent:s>0?t/s*100:0,gcCount:0}}getDefaultMemory(){return{timestamp:performance.now(),usedHeapSize:0,totalHeapSize:0,heapSizeLimit:0,utilizationPercent:0,gcCount:0}}createEmptyData(){return{currentFrame:{frameNumber:0,frameTime:0,fps:0,memory:this.getDefaultMemory()},frameTimeHistory:[],categoryStats:[],hotspots:[],callGraph:{currentFunction:null,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,currentMemoryMB:0,peakMemoryMB:0,gcCount:0,longTaskCount:0}}}}function Ot(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}(e)}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}()}function Pt(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}const Rt="00000000-0000-0000-0000-000000000000",zt=28,Nt=20,Ft=268435455,Bt=1048575,$t=1<<28,Lt=1<<20,Wt=0;function Ht(e,t){return(t&Bt)*$t+(e&Ft)}function Ut(e){return e&Ft}function Gt(e){return Math.floor(e/$t)&Bt}function qt(e){return 0!==e}function jt(e,t){return e===t}function Vt(e){return 0===e?"Entity(NULL)":`Entity(idx=${Ut(e)}, gen=${Gt(e)})`}var Qt,Yt;!function(e){e.ENTITY_CREATED="entity:created",e.ENTITY_DESTROYED="entity:destroyed",e.ENTITY_ENABLED="entity:enabled",e.ENTITY_DISABLED="entity:disabled",e.ENTITY_TAG_ADDED="entity:tag:added",e.ENTITY_TAG_REMOVED="entity:tag:removed",e.ENTITY_NAME_CHANGED="entity:name:changed",e.COMPONENT_ADDED="component:added",e.COMPONENT_REMOVED="component:removed",e.COMPONENT_MODIFIED="component:modified",e.COMPONENT_ENABLED="component:enabled",e.COMPONENT_DISABLED="component:disabled",e.SYSTEM_ADDED="system:added",e.SYSTEM_REMOVED="system:removed",e.SYSTEM_ENABLED="system:enabled",e.SYSTEM_DISABLED="system:disabled",e.SYSTEM_PROCESSING_START="system:processing:start",e.SYSTEM_PROCESSING_END="system:processing:end",e.SYSTEM_ERROR="system:error",e.SCENE_CREATED="scene:created",e.SCENE_DESTROYED="scene:destroyed",e.SCENE_ACTIVATED="scene:activated",e.SCENE_DEACTIVATED="scene:deactivated",e.SCENE_PAUSED="scene:paused",e.SCENE_RESUMED="scene:resumed",e.QUERY_EXECUTED="query:executed",e.QUERY_CACHE_HIT="query:cache:hit",e.QUERY_CACHE_MISS="query:cache:miss",e.QUERY_OPTIMIZED="query:optimized",e.PERFORMANCE_WARNING="performance:warning",e.PERFORMANCE_CRITICAL="performance:critical",e.MEMORY_USAGE_HIGH="memory:usage:high",e.FRAME_RATE_DROP="frame:rate:drop",e.INDEX_CREATED="index:created",e.INDEX_UPDATED="index:updated",e.INDEX_OPTIMIZED="index:optimized",e.ARCHETYPE_CREATED="archetype:created",e.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",e.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",e.DIRTY_MARK_ADDED="dirty:mark:added",e.DIRTY_BATCH_PROCESSED="dirty:batch:processed",e.ERROR_OCCURRED="error:occurred",e.WARNING_ISSUED="warning:issued",e.FRAMEWORK_INITIALIZED="framework:initialized",e.FRAMEWORK_SHUTDOWN="framework:shutdown",e.DEBUG_INFO="debug:info",e.DEBUG_STATS_UPDATED="debug:stats:updated"}(Qt||(Qt={})),function(e){e[e.LOWEST=0]="LOWEST",e[e.LOW=25]="LOW",e[e.NORMAL=50]="NORMAL",e[e.HIGH=75]="HIGH",e[e.HIGHEST=100]="HIGHEST",e[e.CRITICAL=200]="CRITICAL"}(Yt||(Yt={}));const Jt={ENTITY:{CREATED:Qt.ENTITY_CREATED,DESTROYED:Qt.ENTITY_DESTROYED,ENABLED:Qt.ENTITY_ENABLED,DISABLED:Qt.ENTITY_DISABLED,TAG_ADDED:Qt.ENTITY_TAG_ADDED,TAG_REMOVED:Qt.ENTITY_TAG_REMOVED,NAME_CHANGED:Qt.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:Qt.COMPONENT_ADDED,REMOVED:Qt.COMPONENT_REMOVED,MODIFIED:Qt.COMPONENT_MODIFIED,ENABLED:Qt.COMPONENT_ENABLED,DISABLED:Qt.COMPONENT_DISABLED},SYSTEM:{ADDED:Qt.SYSTEM_ADDED,REMOVED:Qt.SYSTEM_REMOVED,ENABLED:Qt.SYSTEM_ENABLED,DISABLED:Qt.SYSTEM_DISABLED,PROCESSING_START:Qt.SYSTEM_PROCESSING_START,PROCESSING_END:Qt.SYSTEM_PROCESSING_END,ERROR:Qt.SYSTEM_ERROR},PERFORMANCE:{WARNING:Qt.PERFORMANCE_WARNING,CRITICAL:Qt.PERFORMANCE_CRITICAL,MEMORY_HIGH:Qt.MEMORY_USAGE_HIGH,FRAME_DROP:Qt.FRAME_RATE_DROP}};class Zt{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)}}Zt.validTypes=new Set([...Object.values(Qt),...Object.values(Jt.ENTITY),...Object.values(Jt.COMPONENT),...Object.values(Jt.SYSTEM),...Object.values(Jt.PERFORMANCE)]);class Xt{constructor(e,t,n){this._handle=0,this.scene=null,this._isDestroyed=!1,this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=R.clone(R.ZERO),this._componentCache=null,this._lifecyclePolicy=0,this.name=e,this.id=t,this.persistentId=n??Ot()}get lifecyclePolicy(){return this._lifecyclePolicy}get isPersistent(){return 1===this._lifecyclePolicy}get handle(){return this._handle}setHandle(e){this._handle=e}setPersistent(){return this._lifecyclePolicy=1,this}setSceneLocal(){return this._lifecyclePolicy=0,this}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=this.scene.componentRegistry,s=n.getRegisteredCount();for(let i=0;i<s;i++)if(R.getBit(t,i)){const t=n.getTypeByBitIndex(i);if(t){const n=this.scene.componentStorageManager.getComponent(this.id,t);n&&e.push(n)}}this._componentCache=e}get active(){return this._active}set active(e){this._active!==e&&(this._active=e,this.onActiveChanged())}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,n=(this.scene?.componentRegistry??j).getBitMask(t);return R.orInPlace(this._componentMask,n),this._componentCache=null,e}notifyQuerySystems(e){this.scene?.querySystem&&(this.scene.querySystem.updateEntity(this),this.scene.clearSystemEntityCaches(),this.scene.notifyEntityComponentChanged?.(this,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 ${w(t)}`);return this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,this.scene.referenceTracker?.registerEntityScene(this.id,this.scene),this.scene.isEditorMode?this.scene.queueDeferredComponentCallback(()=>e.onAddedToEntity()):e.onAddedToEntity(),this.scene.eventSystem&&this.scene.eventSystem.emitSync(Qt.COMPONENT_ADDED,{timestamp:Date.now(),source:"Entity",entity:this,entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:w(t),component:e}),this.notifyQuerySystems(t),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){const t=this.scene?.componentRegistry??j;if(!t.isRegistered(e))return!1;const n=t.getBitMask(e);return R.hasAny(this._componentMask,n)}getOrCreateComponent(e,...t){let n=this.getComponent(e);return n||(n=this.createComponent(e,...t)),n}markDirty(...e){if(!this.scene)return;const t=this.scene.epochManager.current;for(const n of e)n.markDirty(t)}removeComponent(e){const t=e.constructor,n=this.scene?.componentRegistry??j;if(!n.isRegistered(t))return;const s=n.getBitIndex(t);R.clearBit(this._componentMask,s),this._componentCache=null,this.scene?.componentStorageManager?.removeComponent(this.id,t),this.scene?.referenceTracker?.clearComponentReferences(e),e.onRemovedFromEntity?.(),e.entityId=null,this.scene?.eventSystem&&this.scene.eventSystem.emitSync(Qt.COMPONENT_REMOVED,{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:w(t),component:e}),this.notifyQuerySystems(t)}removeComponentByType(e){const t=this.getComponent(e);return t?(this.removeComponent(t),t):null}removeAllComponents(){const e=[...this.components];R.clear(this._componentMask),this._componentCache=null;for(const t of e){const e=t.constructor;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){Xt._logger.warn(`添加组件失败 ${I(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}onActiveChanged(){if(this.scene?.eventSystem){const e=this._active?Qt.ENTITY_ENABLED:Qt.ENTITY_DISABLED;this.scene.eventSystem.emitSync(e,{entity:this,scene:this.scene})}}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.scene?.eventSystem&&this.scene.eventSystem.emitSync(Qt.ENTITY_DESTROYED,{entity:this,entityId:this.id,scene:this.scene}),this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id)),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this)))}compareTo(e){return n=e,(t=this).updateOrder-n.updateOrder||t.id-n.id;var t,n}toString(){return`Entity[${this.name}:${this.id}:${this.persistentId.slice(0,8)}]`}getDebugInfo(){return{name:this.name,id:this.id,persistentId:this.persistentId,enabled:this._enabled,active:this._active,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map(e=>I(e)),componentMask:R.toString(this._componentMask,2),cacheBuilt:null!==this._componentCache}}}Xt._logger=$("Entity");class Kt{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();for(const t of this._entitiesToAdd)e.push(t.id),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))}}}reorderEntity(e,t){const n=this._idToEntity.get(e);if(!n)return;const s=this.buffer.indexOf(n);if(-1===s||s===t)return;const i=Math.max(0,Math.min(t,this.buffer.length-1));this.buffer.splice(s,1),this.buffer.splice(i,0,n)}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 en{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>en.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${en.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:en.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>en.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<=en.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}}en.MAX_INDEX=65535,en.MAX_GENERATION=65535;class tn{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){tn._logger.error(`Error in processor ${se(e)}:`,t)}this._isDirty=!1,this._processors.length=0}update(){this.sortProcessors();for(const e of this._processors)try{e.update()}catch(t){tn._logger.error(`Error in processor ${se(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}}tn._logger=$("EntityProcessorList");class nn{constructor(e){if(e&&"object"==typeof e)this._value=R.clone(e);else if("number"==typeof e)this._value=R.fromNumber(e);else if("string"==typeof e){const t=parseInt(e,10);this._value=R.fromNumber(t)}else this._value=R.clone(R.ZERO)}set(e){if(e<0)throw new Error("Bit index cannot be negative");R.setBit(this._value,e)}clear(e){if(e<0)throw new Error("Bit index cannot be negative");R.clearBit(this._value,e)}get(e){return R.getBit(this._value,e)}containsAll(e){return R.hasAll(this._value,e._value)}intersects(e){return R.hasAny(this._value,e._value)}excludes(e){return R.hasNone(this._value,e._value)}clearAll(){R.clear(this._value)}isEmpty(){return R.isZero(this._value)}cardinality(){return R.popCount(this._value)}and(e){const t=new nn;return R.copy(this._value,t._value),R.andInPlace(t._value,e._value),t}or(e){const t=new nn;return R.copy(this._value,t._value),R.orInPlace(t._value,e._value),t}xor(e){const t=new nn;return R.copy(this._value,t._value),R.xorInPlace(t._value,e._value),t}not(e=64){e>64&&(e=64);const t=new nn;if(R.copy(this._value,t._value),e<=32){const n=(1<<e)-1;t._value.base[O.LOW]=~t._value.base[O.LOW]&n,t._value.base[O.HIGH]=0}else if(t._value.base[O.LOW]=~t._value.base[O.LOW],e<64){const n=(1<<e-32)-1;t._value.base[O.HIGH]=~t._value.base[O.HIGH]&n}else t._value.base[O.HIGH]=~t._value.base[O.HIGH];return t}copyFrom(e){R.copy(e._value,this._value)}clone(){return new nn(this._value)}getValue(){return this._value}setValue(e){if("object"==typeof e)R.copy(e,this._value);else if("number"==typeof e)this._value=R.fromNumber(e);else{const t=parseInt(e,10);this._value=R.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 R.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 nn(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 nn(n)}equals(e){return R.equals(this._value,e._value)}getHighestBitIndex(){if(R.isZero(this._value))return-1;if(0!==this._value.base[O.HIGH])for(let e=31;e>=0;e--)if(this._value.base[O.HIGH]&1<<e)return e+32;for(let e=31;e>=0;e--)if(this._value.base[O.LOW]&1<<e)return e;return-1}getLowestBitIndex(){if(R.isZero(this._value))return-1;for(let e=0;e<32;e++)if(this._value.base[O.LOW]&1<<e)return e;for(let e=0;e<32;e++)if(this._value.base[O.HIGH]&1<<e)return e+32;return-1}}class sn{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 rn extends Set{constructor(...e){super()}reset(){this.clear()}}class on{constructor(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new sn}addEntity(e){this._entities.has(e)&&this.removeEntity(e);const t=R.clone(R.ZERO),n=new Set;for(const s of e.components){const e=s.constructor;n.add(e);const i=j.getBitMask(e);R.orInPlace(t,i)}this._entities.add(e);const s=this._entities.getIndex(e);for(;this._componentMasks.length<=s;)this._componentMasks.push(R.clone(R.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=R.clone(R.ZERO);for(const n of e){if(!j.isRegistered(n))return new Set;const e=j.getBitMask(n);R.orInPlace(t,e)}const n=on._entitySetPool.obtain();return this._entities.forEach((e,s)=>{const i=this._componentMasks[s];R.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=R.clone(R.ZERO);for(const n of e)if(j.isRegistered(n)){const e=j.getBitMask(n);R.orInPlace(t,e)}if(R.equals(t,R.ZERO))return new Set;const n=on._entitySetPool.obtain();return this._entities.forEach((e,s)=>{const i=this._componentMasks[s];R.hasAny(i,t)&&n.add(e)}),n}hasComponent(e,t){const n=this._entities.getIndex(e);if(void 0===n)return!1;if(!j.isRegistered(t))return!1;const s=this._componentMasks[n],i=j.getBitMask(t);return R.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())on._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=on._entitySetPool.obtain(),this._componentToEntities.set(s,t)),t.add(e)):t&&(t.delete(e),0===t.size&&(this._componentToEntities.delete(s),on._entitySetPool.release(t)))}}}on._entitySetPool=S.getPool(rn,50,512);class an{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 cn{constructor(){this._archetypes=new an,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)R.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=R.clone(R.ZERO);for(const n of e){const e=j.getBitMask(n);R.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}}var hn;!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(hn||(hn={}));const ln=$("ReactiveQuery");var dn;!function(e){e.ADDED="added",e.REMOVED="removed",e.BATCH_UPDATE="batch_update"}(dn||(dn={}));class un{constructor(e,t={}){this._entities=[],this._entityIdSet=new Set,this._snapshot=null,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&&ln.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&&ln.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 null!==this._snapshot||(this._snapshot=[...this._entities]),this._snapshot}get count(){return this._entities.length}matches(e){const t=e.componentMask;switch(this._condition.type){case hn.ALL:return R.hasAll(t,this._condition.mask);case hn.ANY:return R.hasAny(t,this._condition.mask);case hn.NONE:return R.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._snapshot=null,this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:dn.ADDED,entity:e}),this._config.debug&&ln.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._snapshot=null,this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:dn.REMOVED,entity:e}),this._config.debug&&ln.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(),this._snapshot=null;for(const t of e)this.matches(t)&&(this._entities.push(t),this._entityIdSet.add(t.id));this._config.debug&&ln.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:dn.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&ln.debug(`ReactiveQuery ${this._id}: 批量更新 +${e.length} -${t.length}`)}notifyListeners(e){const t=[...this._listeners];for(const n of t)try{n(e)}catch(e){ln.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._snapshot=null,this._config.debug&&ln.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 mn{constructor(e,...t){this._lastVersion=-1,this._cachedEntities=[],this._querySystem=e,this._componentTypes=t}get componentTypes(){return this._componentTypes}get entities(){return this._refreshCache(),this._cachedEntities}get count(){return this.entities.length}_refreshCache(){const e=this._querySystem.version;if(this._lastVersion!==e){const t=this._querySystem.queryAll(...this._componentTypes);this._cachedEntities=t.entities,this._lastVersion=e}}forEach(e){const t=this.entities,n=this._componentTypes,s=n.length;for(let i=0,r=t.length;i<r;i++){const r=t[i],o=new Array(s);for(let e=0;e<s;e++){const t=r.getComponent(n[e]);t&&(o[e]=t)}e(r,...o)}}forEachChanged(e,t){const n=this.entities,s=this._componentTypes,i=s.length;for(let r=0,o=n.length;r<o;r++){const o=n[r],a=new Array(i);let c=!1;for(let t=0;t<i;t++){const n=o.getComponent(s[t]);n&&(a[t]=n,n.lastWriteEpoch>e&&(c=!0))}c&&t(o,...a)}}first(){const e=this.entities;if(0===e.length)return null;const t=e[0],n=[];for(const e of this._componentTypes){const s=t.getComponent(e);if(!s)return null;n.push(s)}return[t,...n]}toArray(){const e=[];return this.forEach((t,...n)=>{e.push([t,...n])}),e}map(e){const t=[];return this.forEach((n,...s)=>{t.push(e(n,...s))}),t}filter(e){const t=[];return this.forEach((n,...s)=>{e(n,...s)&&t.push(n)}),t}find(e){const t=this.entities,n=this._componentTypes,s=n.length;for(let i=0,r=t.length;i<r;i++){const r=t[i],o=new Array(s);for(let e=0;e<s;e++){const t=r.getComponent(n[e]);t&&(o[e]=t)}if(e(r,...o))return r}}any(){return this.count>0}empty(){return 0===this.count}}class pn{constructor(){this._logger=$("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 cn}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(hn.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(hn.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(hn.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}}queryChangedSince(e,...t){const n=performance.now();this._queryStats.totalQueries++,this._queryStats.dirtyChecks++;const s=this.queryAll(...t),i=[];for(const n of s.entities){let s=!1;for(const i of t){const t=n.getComponent(i);if(t&&t.lastWriteEpoch>e){s=!0;break}}s&&i.push(n)}return{entities:i,count:i.length,executionTime:performance.now()-n,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}:${w(t[0])}`}return`${e}:${t.map(e=>w(e)).sort().join(",")}`}clearCache(){this.clearQueryCache(),this.clearReactiveQueries()}compile(...e){return new mn(this,...e)}createReactiveQuery(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");const n=this.createComponentMask(e),s={type:hn.ALL,componentTypes:e,mask:n},i=new un(s,t),r=this.executeTraditionalQuery(hn.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=>w(e)).sort().join(","),n=this._componentMaskCache.get(t);if(n)return n;const s=R.clone(R.ZERO);for(const t of e){const e=j.getBitMask(t);R.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=>w(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 un({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 hn.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 hn.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 hn.NONE:{const e=this.createComponentMask(t);return this._entities.filter(t=>R.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 fn{constructor(e){this._logger=$("QueryBuilder"),this.conditions=[],this.querySystem=e}withAll(...e){return this.conditions.push({type:hn.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this}withAny(...e){return this.conditions.push({type:hn.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this}without(...e){return this.conditions.push({type:hn.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 hn.ALL:return this.querySystem.queryAll(...e.componentTypes);case hn.ANY:return this.querySystem.queryAny(...e.componentTypes);case hn.NONE:return this.querySystem.queryNone(...e.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-e,fromCache:!1}}createComponentMask(e){const t=R.clone(R.ZERO);for(const n of e)try{const e=j.getBitMask(n);R.orInPlace(t,e)}catch(e){this._logger.warn(`组件类型 ${w(n)} 未注册,跳过`)}return t}reset(){return this.conditions=[],this}}class gn{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){gn._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 gn._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){gn._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){gn._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}}}gn._logger=$("EventSystem");class yn{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 yn(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 _n{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 _n([...this._all,...e],this._any,this._none,this._tag,this._name)}withAny(...e){return new _n(this._all,[...this._any,...e],this._none,this._tag,this._name)}withNone(...e){return new _n(this._all,this._any,[...this._none,...e],this._tag,this._name)}withTag(e){return new _n(this._all,this._any,this._none,e,this._name)}withName(e){return new _n(this._all,this._any,this._none,this._tag,e)}buildMatcher(){let e=lt.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 _n([...this._all],[...this._any],[...this._none],this._tag,this._name)}}function Sn(){return new _n}function Cn(e){return new _n([e])}function vn(...e){return new _n(e)}const En=new Map;function bn(e,t){En.set(e,t)}bn("Date",{check:e=>e instanceof Date,serialize:e=>({__type:"Date",value:e.toISOString()}),deserialize:e=>new Date(e.value)}),bn("Map",{check:e=>e instanceof Map,serialize:(e,t)=>({__type:"Map",value:[...e].map(([e,n])=>[t(e),t(n)])}),deserialize:e=>new Map(e.value)}),bn("Set",{check:e=>e instanceof Set,serialize:(e,t)=>({__type:"Set",value:[...e].map(t)}),deserialize:e=>new Set(e.value)});const Tn={serialize:function e(t,n=new WeakSet){if(null==t)return t;const s=typeof t;if("string"===s||"number"===s||"boolean"===s)return t;if("function"===s)return;const i=t;if(n.has(i))return;n.add(i);for(const[,s]of En)if(s.check(t))return s.serialize(t,t=>e(t,n));if(Array.isArray(t))return t.map(t=>e(t,n));const r={};for(const s of Object.keys(t))r[s]=e(t[s],n);return r},deserialize:function e(t){if(null==t)return t;const n=typeof t;if("string"===n||"number"===n||"boolean"===n)return t;if(function(e){if(null===e||"object"!=typeof e)return!1;return"__type"in e}(t)){const e=En.get(t.__type);return e?e.deserialize(t):t}if(Array.isArray(t))return t.map(e);const s={};for(const n of Object.keys(t))s[n]=e(t[n]);return s},register:bn},wn=$("ComponentSerializer");class In{static serialize(e){const t=at(e);if(!t)return null;const n=e.constructor,s=t.options.typeId||w(n),i={};for(const[n,s]of t.fields){if(t.ignoredFields.has(n))continue;const r="symbol"==typeof n?n.toString():n,o=e[n];let a;a=fe(e,r)?this.serializeEntityRef(o):s.serializer?s.serializer(o):Tn.serialize(o),i[s.alias||r]=a}return{type:s,version:t.options.version,data:i}}static deserialize(e,t,n){const s=t.get(e.type);if(!s)return wn.warn(`Component type not found: ${e.type} | 未找到组件类型: ${e.type}`),null;const i=at(s);if(!i)return wn.warn(`Component ${e.type} is not serializable | 组件 ${e.type} 不可序列化`),null;const r=new s;for(const[t,s]of i.fields){const i="symbol"==typeof t?t.toString():t,o=s.alias||i,a=e.data[o];if(void 0===a)continue;if(this.isSerializedEntityRef(a)){if(n){const e=a.__entityRef;n.registerPendingRef(r,i,e.id,e.guid)}r[t]=null;continue}const c=s.deserializer?s.deserializer(a):Tn.deserialize(a);r[t]=c}return r}static serializeComponents(e){return e.map(e=>this.serialize(e)).filter(e=>null!==e)}static deserializeComponents(e,t,n){return e.map(e=>this.deserialize(e,t,n)).filter(e=>null!==e)}static validateVersion(e,t){return e.version===t}static getSerializationInfo(e){const t=at(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||w(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}}static serializeEntityRef(e){return e?{__entityRef:{id:e.id,guid:e.persistentId}}:null}static isSerializedEntityRef(e){return"object"==typeof e&&null!==e&&"__entityRef"in e}}class Mn{static serialize(e,t=!0,n){const s=In.serializeComponents(Array.from(e.components)),i={id:e.id,guid:e.persistentId,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:s,children:[]},r=e.getComponent(ht);if(null!=r?.parentId&&(i.parentId=r.parentId),t&&r&&r.childIds.length>0){const t=n?.scene??e.scene;if(t)for(const e of r.childIds){const s=t.findEntityById(e);s&&i.children.push(this.serialize(s,!0,n))}}return i}static deserialize(e,t,n,s=!1,i,r,o,a){const c=s?e.id:n(),h=new Xt(e.name,c,e.guid);o?.set(h.id,h),a&&a.registerEntity(h,e.id,e.guid),i&&(h.scene=i),h.tag=e.tag,h.active=e.active,h.enabled=e.enabled,h.updateOrder=e.updateOrder;const l=In.deserializeComponents(e.components,t,a);for(const e of l)h.addComponent(e);const d=h.getComponent(ht);d&&(d.parentId=null,d.childIds=[]);for(const c of e.children){const e=this.deserialize(c,t,n,s,i,r,o,a);r?.setParent(e,h)}return h}static serializeEntities(e,t=!0,n){const s=[];for(const i of e){const e=i.getComponent(ht);null!=e?.parentId&&t||s.push(this.serialize(i,t,n))}return s}static deserializeEntities(e,t,n,s=!1,i,r,o){const a=[],c=new Map;for(const h of e){const e=this.deserialize(h,t,n,s,i,r,c,o);a.push(e)}return{rootEntities:a,allEntities:c}}static clone(e,t,n){const s=this.serialize(e,!0);return this.deserialize(s,t,n,!1)}}class An{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 kn{constructor(){this._idRemapping=new Map,this._guidLookup=new Map,this._pendingRefs=[],this._preserveIds=!1}setPreserveIds(e){this._preserveIds=e}get preserveIds(){return this._preserveIds}registerEntity(e,t,n){const s=n??e.persistentId;this._guidLookup.set(s,e),void 0!==t&&this._idRemapping.set(t,e)}getEntityById(e){return this._idRemapping.get(e)??null}getEntityByGuid(e){return this._guidLookup.get(e)??null}resolveEntityRef(e){if(!e)return null;if(e.guid){const t=this._guidLookup.get(e.guid);if(t)return t}if(void 0!==e.id){const t=this._idRemapping.get(e.id);if(t)return t}return null}registerPendingRef(e,t,n,s){this._pendingRefs.push({component:e,propertyKey:t,originalId:n,originalGuid:s})}resolveAllReferences(){let e=0;for(const t of this._pendingRefs){const n=this.resolveEntityRef({id:t.originalId,guid:t.originalGuid});n&&(t.component[t.propertyKey]=n,e++)}return e}getUnresolvedCount(){let e=0;for(const t of this._pendingRefs){this.resolveEntityRef({id:t.originalId,guid:t.originalGuid})||e++}return e}getPendingCount(){return this._pendingRefs.length}getRegisteredEntityCount(){return this._guidLookup.size}clear(){this._idRemapping.clear(),this._guidLookup.clear(),this._pendingRefs=[]}getDebugInfo(){return{registeredEntities:this._guidLookup.size,pendingRefs:this._pendingRefs.length,unresolvedRefs:this.getUnresolvedCount(),preserveIds:this._preserveIds}}}const Dn=$("SceneSerializer");class xn{static serialize(e,t){const n={systems:!1,format:"json",pretty:!0,includeMetadata:!0,...t},s=this.filterEntities(e,n),i=e.getSystem(St),r=Mn.serializeEntities(s,!0,i??void 0),o=this.buildComponentTypeRegistry(s),a=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:r,componentTypeRegistry:o};return a&&Object.keys(a).length>0&&(c.sceneData=a),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:r.length,componentTypeCount:o.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):An.encode(c)}static deserialize(e,t,n){const s={strategy:"replace",preserveIds:!1,...n};let i;try{i="string"==typeof t?JSON.parse(t):An.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=e.getSystem(St),a=new kn;a.setPreserveIds(s.preserveIds||!1);const{rootEntities:c,allEntities:h}=Mn.deserializeEntities(i.entities,r,()=>e.identifierPool.checkOut(),s.preserveIds||!1,e,o,a);for(const t of c)e.addEntity(t,!0),this.addChildrenRecursively(t,e,o,h);e.querySystem.clearCache(),e.clearSystemEntityCaches();const l=a.resolveAllReferences(),d=a.getUnresolvedCount();d>0&&Dn.warn(`${d} EntityRef(s) could not be resolved. Resolved: ${l}, Total pending: ${a.getPendingCount()} | ${d} 个实体引用无法解析`),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData);const u=[];for(const e of h.values())this.callOnDeserializedForEntity(e,u);u.length>0&&Promise.all(u).catch(e=>{Dn.error("Error in onDeserialized | onDeserialized 执行错误:",e)})}static callOnDeserializedForEntity(e,t){for(const n of e.components)try{const e=n.onDeserialized();e instanceof Promise&&t.push(e)}catch(e){const t=w(n.constructor);Dn.error(`Error calling onDeserialized on component ${t} | 调用组件 ${t} 的 onDeserialized 时出错:`,e)}}static addChildrenRecursively(e,t,n,s){const i=e.getComponent(ht);if(i&&0!==i.childIds.length)for(const e of i.childIds){const i=s?.get(e)??t.findEntityById(e);i&&(t.addEntity(i,!0),this.addChildrenRecursively(i,t,n,s))}}static serializeSceneData(e){const t={};for(const[n,s]of e)t[n]=Tn.serialize(s);return t}static deserializeSceneData(e,t){t.clear();for(const[n,s]of Object.entries(e))t.set(n,Tn.deserialize(s))}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=w(e.constructor),s=at(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 j.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 On;xn.SERIALIZATION_VERSION=1,function(e){e.EntityAdded="entity_added",e.EntityRemoved="entity_removed",e.EntityUpdated="entity_updated",e.ComponentAdded="component_added",e.ComponentRemoved="component_removed",e.ComponentUpdated="component_updated",e.SceneDataUpdated="scene_data_updated"}(On||(On={}));const Pn={deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1,format:"json",pretty:!1};class Rn{static createSnapshot(e,t){const n={...Pn,...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(n.entityFilter&&!n.entityFilter(t))continue;s.entityIds.add(t.id);const e=t.getComponent(ht),i=e?.parentId;if(s.entities.set(t.id,{name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,...null!=i&&{parentId:i}}),n.deepComponentComparison){const e=new Map;for(const n of t.components){const t=In.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={...Pn,...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(s.entityFilter&&!s.entityFilter(n))continue;r.add(n.id);const e=n.getComponent(ht),o=e?.parentId;if(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!==o)&&i.entityChanges.push({operation:On.EntityUpdated,entityId:n.id,entityData:{name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,...null!=o&&{parentId:o}}}),s.deepComponentComparison&&this.detectComponentChanges(n,t,i.componentChanges)}else{i.entityChanges.push({operation:On.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,...null!=o&&{parentId:o},components:[],children:[]}});for(const e of n.components){const t=In.serialize(e);t&&i.componentChanges.push({operation:On.ComponentAdded,entityId:n.id,componentType:t.type,componentData:t})}}}for(const e of t.entityIds)r.has(e)||i.entityChanges.push({operation:On.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=In.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:On.ComponentUpdated,entityId:e.id,componentType:t,componentData:r}):n.push({operation:On.ComponentAdded,entityId:e.id,componentType:t,componentData:r})}if(s)for(const t of s.keys())i.has(t)||n.push({operation:On.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:On.SceneDataUpdated,key:i,value:r})}for(const e of t.sceneData.keys())s.has(e)||n.push({operation:On.SceneDataUpdated,key:e,value:void 0,deleted:!0})}static applyIncremental(e,t,n){for(const n of t.entityChanges)switch(n.operation){case On.EntityAdded:this.applyEntityAdded(e,n);break;case On.EntityRemoved:this.applyEntityRemoved(e,n);break;case On.EntityUpdated:this.applyEntityUpdated(e,n)}for(const s of t.componentChanges)switch(s.operation){case On.ComponentAdded:this.applyComponentAdded(e,s,n);break;case On.ComponentRemoved:this.applyComponentRemoved(e,s,n);break;case On.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 Xt(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)return;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);const s=e.getSystem(St);if(s){const i=n.getComponent(ht),r=i?.parentId;if(void 0!==t.entityData.parentId){const i=e.entities.findEntityById(t.entityData.parentId);i&&r!==t.entityData.parentId&&s.setParent(n,i)}else null!=r&&s.setParent(n,null)}}static applyComponentAdded(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=In.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=In.deserialize(t.componentData,n);r&&s.addComponent(r)}static serializeIncremental(e,t){const n=t?.format??"json",s=t?.pretty??!1;return"binary"===n?An.encode(e):s?JSON.stringify(e,null,2):JSON.stringify(e)}static deserializeIncremental(e){return"string"==typeof e?JSON.parse(e):An.decode(e)}static getIncrementalStats(e){const t={added:0,removed:0,updated:0},n={added:0,removed:0,updated:0};for(const n of e.entityChanges)n.operation===On.EntityAdded?t.added++:n.operation===On.EntityRemoved?t.removed++:n.operation===On.EntityUpdated&&t.updated++;for(const t of e.componentChanges)t.operation===On.ComponentAdded?n.added++:t.operation===On.ComponentRemoved?n.removed++:t.operation===On.ComponentUpdated&&n.updated++;return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:t.added,removedEntities:t.removed,updatedEntities:t.updated,addedComponents:n.added,removedComponents:n.removed,updatedComponents:n.updated}}static resetVersion(){this.snapshotVersion=0}}Rn.snapshotVersion=0;const zn={enabled:!0,sampleInterval:10,minDuration:.1,trackAsync:!0,excludePatterns:[/^_/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/],maxBufferSize:1e4};class Nn{constructor(e){this.wrappedObjects=new WeakMap,this.samplingProfiler=null,this.registeredClasses=new Map,this._config={...zn,...e}}static getInstance(e){return Nn._instance||(Nn._instance=new Nn(e)),Nn._instance}static resetInstance(){Nn._instance&&(Nn._instance.dispose(),Nn._instance=null)}static setEnabled(e){Nn.getInstance().setEnabled(e)}static registerClass(e,t=gt.Custom,n){return Nn.getInstance().registerClass(e,t,n)}static wrapInstance(e,t,n=gt.Custom){return Nn.getInstance().wrapInstance(e,t,n)}static wrapFunction(e,t,n=gt.Custom){return Nn.getInstance().wrapFunction(e,t,n)}static startSampling(){Nn.getInstance().startSampling()}static stopSampling(){return Nn.getInstance().stopSampling()}setEnabled(e){this._config.enabled=e,!e&&this.samplingProfiler&&this.samplingProfiler.stop()}registerClass(e,t=gt.Custom,n){const s=n||e.name;this.registeredClasses.set(s,{constructor:e,category:t});const i=this;return new Proxy(e,{construct(e,n,r){const o=Reflect.construct(e,n,r);return i._config.enabled&&i.wrapInstance(o,s,t),o}})}wrapInstance(e,t,n=gt.Custom){if(!this._config.enabled)return e;if(this.wrappedObjects.has(e))return e;const s=new Map;this.wrappedObjects.set(e,s);const i=this._getAllMethodNames(e);for(const r of i){if(this._shouldExcludeMethod(r))continue;const i=this._getPropertyDescriptor(e,r);if(!i||"function"!=typeof i.value)continue;const o=i.value,a=this._createWrappedMethod(o,t,r,n);s.set(r,{className:t,methodName:r,category:n,original:o});try{e[r]=a}catch{}}return e}wrapFunction(e,t,n=gt.Custom){if(!this._config.enabled)return e;const s=this,i=function(...i){const r=Dt.beginSample(t,n);try{const t=e.apply(this,i);return s._config.trackAsync&&t instanceof Promise?t.finally(()=>{Dt.endSample(r)}):(Dt.endSample(r),t)}catch(e){throw Dt.endSample(r),e}};return Object.defineProperty(i,"name",{value:e.name||t}),Object.defineProperty(i,"length",{value:e.length}),i}startSampling(){this.samplingProfiler||(this.samplingProfiler=new Fn(this._config)),this.samplingProfiler.start()}stopSampling(){return this.samplingProfiler?this.samplingProfiler.stop():[]}dispose(){this.samplingProfiler&&(this.samplingProfiler.stop(),this.samplingProfiler=null),this.registeredClasses.clear()}_createWrappedMethod(e,t,n,s){const i=this,r=`${t}.${n}`,o=this._config.minDuration;return function(...t){if(!i._config.enabled||!Dt.isEnabled())return e.apply(this,t);const n=performance.now(),a=Dt.beginSample(r,s);try{const s=e.apply(this,t);if(i._config.trackAsync&&s instanceof Promise)return s.then(e=>(performance.now()-n>=o&&Dt.endSample(a),e),e=>{throw Dt.endSample(a),e});return performance.now()-n>=o&&Dt.endSample(a),s}catch(e){throw Dt.endSample(a),e}}}_getAllMethodNames(e){const t=new Set;let n=e;for(;n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))"constructor"!==e&&t.add(e);n=Object.getPrototypeOf(n)}return Array.from(t)}_getPropertyDescriptor(e,t){let n=e;for(;n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}_shouldExcludeMethod(e){if("constructor"===e||e.startsWith("__"))return!0;for(const t of this._config.excludePatterns)if(t.test(e))return!0;return!1}}Nn._instance=null;class Fn{constructor(e){this.samples=[],this.intervalId=null,this.isRunning=!1,this.config=e}start(){if(this.isRunning)return;this.isRunning=!0,this.samples=[];const e=()=>{if(!this.isRunning)return;const t=this.captureStack();t.length>0&&(this.samples.push({timestamp:performance.now(),stack:t}),this.samples.length>this.config.maxBufferSize&&this.samples.shift()),this.config.sampleInterval,this.intervalId=setTimeout(e,this.config.sampleInterval)};e()}stop(){return this.isRunning=!1,null!==this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),[...this.samples]}captureStack(){try{const e=new Error,t=(e.stack||"").split("\n").slice(3),n=[];for(const e of t){const t=this.parseStackFrame(e);t&&!this.isInternalFrame(t)&&n.push(t)}return n}catch{return[]}}parseStackFrame(e){let t=(e=e.trim()).match(/at\s+(.+?)\s+\(/);if(t&&t[1])return t[1];if(t=e.match(/at\s+(.+)/),t&&t[1]){const e=t[1];if(!e.includes("("))return e}return t=e.match(/^(.+?)@/),t&&t[1]?t[1]:null}isInternalFrame(e){return["SamplingProfiler","AutoProfiler","ProfilerSDK","setTimeout","setInterval","requestAnimationFrame","<anonymous>","eval"].some(t=>e.includes(t))}}function Bn(e,t=gt.Custom){return function(n,s,i){const r=i.value,o=e||`${n.constructor.name}.${String(s)}`;return i.value=function(...e){if(!Dt.isEnabled())return r.apply(this,e);const n=Dt.beginSample(o,t);try{const t=r.apply(this,e);return t instanceof Promise?t.finally(()=>{Dt.endSample(n)}):(Dt.endSample(n),t)}catch(e){throw Dt.endSample(n),e}},i}}function $n(e=gt.Custom){return function(t){return Nn.registerClass(t,e)}}const Ln=$("ServiceContainer");var Wn;!function(e){e.Singleton="singleton",e.Transient="transient"}(Wn||(Wn={}));class Hn{constructor(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}registerSingleton(e,t){this._services.has(e)?Ln.warn(`Service ${e.name} is already registered`):(this._services.set(e,{identifier:e,type:e,...t&&{factory:t},lifetime:Wn.Singleton}),Ln.debug(`Registered singleton service: ${e.name}`))}registerTransient(e,t){this._services.has(e)?Ln.warn(`Service ${e.name} is already registered`):(this._services.set(e,{identifier:e,type:e,...t&&{factory:t},lifetime:Wn.Transient}),Ln.debug(`Registered transient service: ${e.name}`))}registerInstance(e,t){if(this._services.has(e)){const t="symbol"==typeof e?e.description:e.name;return void Ln.warn(`Service ${t} is already registered`)}if(this._services.set(e,{identifier:e,instance:t,lifetime:Wn.Singleton}),"symbol"!=typeof e&&m(e)){const n=p(e),s=n?.priority??0;this._updatableServices.push({instance:t,priority:s}),this._updatableServices.sort((e,t)=>e.priority-t.priority),Ln.debug(`Service ${e.name} is updatable (priority: ${s}), added to update list`)}const n="symbol"==typeof e?e.description:e.name;Ln.debug(`Registered service instance: ${n}`)}resolve(e){const t=this._services.get(e),n="symbol"==typeof e?e.description:e.name;if(!t)throw new Error(`Service ${n} is not registered`);if(this._resolving.has(e)){const e=Array.from(this._resolving).map(e=>"symbol"==typeof e?e.description:e.name).join(" -> ");throw new Error(`Circular dependency detected: ${e} -> ${n}`)}if(t.lifetime===Wn.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{let e;if(t.factory)e=t.factory(this);else{if(!t.type)throw new Error(`Service ${n} has no factory or type to construct`);e=new t.type}if(t.lifetime===Wn.Singleton&&(t.instance=e,t.type&&m(t.type))){const s=p(t.type),i=s?.priority??0;this._updatableServices.push({instance:e,priority:i}),this._updatableServices.sort((e,t)=>e.priority-t.priority),Ln.debug(`Service ${n} is updatable (priority: ${i}), added to update list`)}return e}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()}this._services.delete(e);const n="symbol"==typeof e?e.description:e.name;return Ln.debug(`Unregistered service: ${n}`),!0}clear(){for(const[,e]of this._services)e.instance&&e.instance.dispose();this._services.clear(),this._updatableServices=[],Ln.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 Un extends Error{constructor(e){super(`[SystemDependencyGraph] 检测到循环依赖 | Cycle dependency detected: ${e.join(" -> ")}`),this.name="CycleDependencyError",this.involvedNodes=e,Object.setPrototypeOf(this,new.target.prototype)}}const Gn="set:";class qn{constructor(){this._nodes=new Map}addSystemNode(e){this.getOrCreateNode(e,!1)}addSetNode(e){const t=Gn+e;this.getOrCreateNode(t,!0)}addEdge(e,t){if(e===t)return;const n=this.getOrCreateNode(e,e.startsWith(Gn)),s=this.getOrCreateNode(t,t.startsWith(Gn));n.outEdges.add(t),s.inEdges.add(e)}buildFromSystems(e){this.clear();for(const t of e){this.addSystemNode(t.name);for(const e of t.sets)this.addSetNode(e)}for(const t of e){for(const e of t.sets){const n=Gn+e;this.addEdge(n,t.name)}for(const e of t.before){const n=this.resolveTargetId(e);this.addEdge(t.name,n)}for(const e of t.after){const n=this.resolveTargetId(e);this.addEdge(n,t.name)}}}topologicalSort(){const e=new Map;for(const[t,n]of this._nodes)e.set(t,n.inEdges.size);const t=[];for(const[n,s]of e)0===s&&t.push(n);const n=[];let s=0;for(;t.length>0;){const i=t.shift();s++;const r=this._nodes.get(i);if(r){r.bIsVirtual||n.push(i);for(const n of r.outEdges){const s=(e.get(n)??0)-1;e.set(n,s),0===s&&t.push(n)}}}if(s<this._nodes.size){const t=[];for(const[n,s]of e)s>0&&t.push(n);throw new Un(t)}return n}clear(){this._nodes.clear()}get size(){return this._nodes.size}getOrCreateNode(e,t){let n=this._nodes.get(e);return n||(n={id:e,bIsVirtual:t,inEdges:new Set,outEdges:new Set},this._nodes.set(e,n)),n}resolveTargetId(e){return e.startsWith(Gn),e}}const jn=$("SystemScheduler"),Vn=["startup","preUpdate","update","postUpdate","cleanup"];class Qn{constructor(){this._sortedByStage=new Map,this._dirty=!0,this._graph=new qn,this._useDependencySort=!0}setUseDependencySort(e){this._useDependencySort!==e&&(this._useDependencySort=e,this._dirty=!0)}markDirty(){this._dirty=!0}getSortedSystems(e,t){if(this.ensureBuilt(e),t)return this._sortedByStage.get(t)??[];const n=[];for(const e of Vn){const t=this._sortedByStage.get(e);t&&n.push(...t)}return n}getAllSortedSystems(e){return this.getSortedSystems(e)}ensureBuilt(e){this._dirty&&(this._sortedByStage.clear(),this._useDependencySort&&this.hasDependencies(e)?this.buildWithDependencyGraph(e):this.buildWithUpdateOrder(e),this._dirty=!1)}hasDependencies(e){for(const t of e){const e=this.getSchedulingMetadata(t);if(e.before.length>0||e.after.length>0||e.sets.length>0)return!0;if("update"!==e.stage)return!0}return!1}buildWithUpdateOrder(e){const t=[...e].sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder});this._sortedByStage.set("update",t)}buildWithDependencyGraph(e){const t=new Map;for(const e of Vn)t.set(e,[]);for(const n of e){const e=this.getSchedulingMetadata(n).stage,s=t.get(e);s?s.push(n):t.get("update").push(n)}for(const[e,n]of t){if(0===n.length){this._sortedByStage.set(e,[]);continue}const t=this.sortSystemsInStage(n);this._sortedByStage.set(e,t)}}sortSystemsInStage(e){const t=new Map,n=[];for(const s of e){const e=s.systemName;t.set(e,s);const i=this.getSchedulingMetadata(s);n.push({name:e,before:i.before,after:i.after,sets:i.sets})}this._graph.buildFromSystems(n);try{const e=this._graph.topologicalSort(),n=[];for(const s of e){const e=t.get(s);e&&n.push(e)}return this.stableSortByUpdateOrder(n)}catch(t){if(t instanceof Un)throw t;return jn.warn("Topological sort failed, falling back to updateOrder | 拓扑排序失败,回退到 updateOrder 排序",t),this.fallbackSort(e)}}stableSortByUpdateOrder(e){return e}fallbackSort(e){return[...e].sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})}getSchedulingMetadata(e){return{stage:e.getStage(),before:[...e.getBefore()],after:[...e.getAfter()],sets:[...e.getSets()]}}}class Yn{constructor(e=1024){this._freeList=[],this._nextIndex=1,this._aliveCount=0,this._capacity=e,this._generations=new Uint32Array(e),this._alive=new Uint8Array(e),this._enabled=new Uint8Array(e),this._alive[0]=0,this._enabled[0]=0}get aliveCount(){return this._aliveCount}get capacity(){return this._capacity}create(){let e;this._freeList.length>0?e=this._freeList.pop():(e=this._nextIndex++,e>=this._capacity&&this.grow(e));const t=this._generations[e];return this._alive[e]=1,this._enabled[e]=1,this._aliveCount++,Ht(e,t)}destroy(e){const t=Ut(e),n=Gt(e);if(t>=this._capacity||0===t)return!1;if(this._generations[t]!==n)return!1;if(1!==this._alive[t])return!1;this._alive[t]=0,this._enabled[t]=0,this._aliveCount--;const s=(n+1)%Lt;return this._generations[t]=s,this._freeList.push(t),!0}isAlive(e){const t=Ut(e),n=Gt(e);return!(t>=this._capacity||0===t)&&(1===this._alive[t]&&this._generations[t]===n)}isEnabled(e){if(!this.isAlive(e))return!1;const t=Ut(e);return 1===this._enabled[t]}setEnabled(e,t){if(!this.isAlive(e))return!1;const n=Ut(e);return this._enabled[n]=t?1:0,!0}validate(e){return this.isAlive(e)}grow(e){let t=this._capacity;for(;t<=e;)t<<=1;if(t>$t&&(t=$t,e>=t))throw new Error("EntityHandleManager: 超过最大实体数量 268435456");const n=new Uint32Array(t),s=new Uint8Array(t),i=new Uint8Array(t);n.set(this._generations),s.set(this._alive),i.set(this._enabled),this._generations=n,this._alive=s,this._enabled=i,this._capacity=t}reset(){this._generations.fill(0),this._alive.fill(0),this._enabled.fill(0),this._freeList.length=0,this._nextIndex=1,this._aliveCount=0}forEach(e){for(let t=1;t<this._nextIndex;t++)if(1===this._alive[t]){e(Ht(t,this._generations[t]))}}getAllAlive(){const e=[];return this.forEach(t=>e.push(t)),e}}class Jn{constructor(){this._current=1}get current(){return this._current}increment(){this._current++,this._current>=Number.MAX_SAFE_INTEGER&&(this._current=1)}reset(){this._current=1}isChangedSince(e,t){return e>t}}class Zn{get runtimeEnvironment(){if(this._runtimeEnvironmentOverride)return this._runtimeEnvironmentOverride;const{Core:e}=require("../Core");return e.runtimeEnvironment}get isServer(){return"server"===this.runtimeEnvironment}get isClient(){return"client"===this.runtimeEnvironment}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);try{return this._systemScheduler.markDirty(),this._systemScheduler.getAllSortedSystems(t)}catch(e){return e instanceof Un?this._logger.error("[Scene] 系统存在循环依赖,回退到 updateOrder 排序 | Cycle dependency detected, falling back to updateOrder sort",e.involvedNodes):this._logger.error("[Scene] 系统排序失败 | System sorting failed",e),this._sortSystemsByUpdateOrder(t)}}_filterEntitySystems(e){return e.filter(e=>e instanceof _t)}_sortSystemsByUpdateOrder(e){return e.sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})}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._handleToEntity=new Map,this.epochManager=new Jn,this._performanceMonitor=null,this._didSceneBegin=!1,this.isEditorMode=!1,this._deferredComponentCallbacks=[],this._cachedSystems=null,this._systemsOrderDirty=!0,this._systemErrorCount=new Map,this._systemAddCounter=0,this._systemScheduler=new Qn,this._componentIdToSystems=new Map,this._globalNotifySystems=new Set,this.entities=new Kt(this),this.identifierPool=new en,this.componentStorageManager=new mt,this.componentRegistry=new q,!1!==e?.inheritGlobalRegistry&&this.componentRegistry.cloneFrom(j),this.querySystem=new pn,this.eventSystem=new gn,this.referenceTracker=new ae,this.handleManager=new Yn,this._services=new Hn,this._logger=$("Scene"),this._maxErrorCount=e?.maxSystemErrorCount??10,e?.runtimeEnvironment&&(this._runtimeEnvironmentOverride=e.runtimeEnvironment),e?.name&&(this.name=e.name)}get performanceMonitor(){return this._performanceMonitor||(this._performanceMonitor=this._services.tryResolve(_)??new _),this._performanceMonitor}initialize(){}onStart(){}unload(){}queueDeferredComponentCallback(e){this._deferredComponentCallbacks.push(e)}begin(){if(this._didSceneBegin=!0,this._deferredComponentCallbacks.length>0){for(const e of this._deferredComponentCallbacks)try{e()}catch(e){this._logger.error("Error executing deferred component callback:",e)}this._deferredComponentCallbacks=[]}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,this._componentIdToSystems.clear(),this._globalNotifySystems.clear(),this._handleToEntity.clear(),this.handleManager.reset(),this.epochManager.reset()}update(){this.epochManager.increment(),Dt.beginFrame();const e=Dt.beginSample("Scene.update",gt.ECS);try{Tt.getInstance().update(),this.entities.updateLists();const e=this.systems;this._runSystemPhase(e,"update","Systems.update"),this._runSystemPhase(e,"lateUpdate","Systems.lateUpdate"),this.flushCommandBuffers(e)}finally{Dt.endSample(e),Dt.endFrame()}}_runSystemPhase(e,t,n){const s=Dt.beginSample(n,gt.ECS);try{for(const n of e){if(!this._shouldSystemRun(n))continue;const e="lateUpdate"===t?".late":"",s=Dt.beginSample(`${n.systemName}${e}`,gt.ECS);try{n[t]()}catch(e){this._handleSystemError(n,t,e)}finally{Dt.endSample(s)}}}finally{Dt.endSample(s)}}_shouldSystemRun(e){if(!e.enabled)return!1;if(!this.isEditorMode)return!0;const t=te(e);return!1!==t?.runInEditMode}flushCommandBuffers(e){const t=Dt.beginSample("Scene.flushCommandBuffers",gt.ECS);try{for(const t of e)try{t.flushCommands()}catch(e){this._logger.error(`Error flushing commands for system ${t.systemName}:`,e)}}finally{Dt.endSample(t)}}_handleSystemError(e,t,n){const s=(this._systemErrorCount.get(e)||0)+1;this._systemErrorCount.set(e,s);const i=e.systemName;this._logger.error(`Error in system ${i}.${t}() [${s}/${this._maxErrorCount}]:`,n),s>=this._maxErrorCount&&(e.enabled=!1,this._logger.error(`System ${i} has been disabled due to excessive errors (${s} errors)`))}createEntity(e){const t=new Xt(e,this.identifierPool.checkOut()),n=this.handleManager.create();return t.setHandle(n),this._handleToEntity.set(n,t),this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)}clearSystemEntityCaches(){for(const e of this.systems)e.clearEntityCache()}notifyEntityComponentChanged(e,t){const n=new Set;if(t&&this.componentRegistry.isRegistered(t)){const s=this.componentRegistry.getBitIndex(t),i=this._componentIdToSystems.get(s);if(i)for(const t of i)t.handleEntityComponentChanged(e),n.add(t)}for(const t of this._globalNotifySystems)n.has(t)||(t.handleEntityComponentChanged(e),n.add(t));if(!t)for(const t of this.systems)n.has(t)||t.handleEntityComponentChanged(e)}indexSystemByComponents(e){const t=e.matcher;if(!t)return;if(t.isNothing())return;const n=t.getCondition();if((n.none.length>0||void 0!==n.tag||void 0!==n.name)&&this._globalNotifySystems.add(e),t.isEmpty())this._globalNotifySystems.add(e);else{for(const t of n.all)this.addSystemToComponentIndex(t,e);for(const t of n.any)this.addSystemToComponentIndex(t,e);n.component&&this.addSystemToComponentIndex(n.component,e)}}addSystemToComponentIndex(e,t){const n=this.componentRegistry.getBitIndex(e);let s=this._componentIdToSystems.get(n);s||(s=new Set,this._componentIdToSystems.set(n,s)),s.add(t)}removeSystemFromIndex(e){this._globalNotifySystems.delete(e);for(const t of this._componentIdToSystems.values())t.delete(e)}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 Xt(`${t}_${s}`,this.identifierPool.checkOut());e.scene=this;const i=this.handleManager.create();e.setHandle(i),this._handleToEntity.set(i,e),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),qt(t.handle)&&(this._handleToEntity.delete(t.handle),this.handleManager.destroy(t.handle));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)}findEntityByHandle(e){return qt(e)&&this.handleManager.isAlive(e)?this._handleToEntity.get(e)??null:null}findEntitiesByTag(e){const t=[];for(const n of this.entities.buffer)n.tag===e&&t.push(n);return t}findPersistentEntities(){return this.entities.buffer.filter(e=>e.isPersistent)}extractPersistentEntities(){const e=this.findPersistentEntities();for(const t of e)this.entities.remove(t),this.querySystem.removeEntity(t),t.scene=null;return e}receiveMigratedEntities(e){for(const t of e){t.scene=this,this.entities.add(t),this.querySystem.addEntity(t);for(const e of t.components)this.componentStorageManager.addComponent(t.id,e),this.referenceTracker?.registerEntityScene(t.id,this)}e.length>0&&this.clearSystemEntityCaches()}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 _n}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=h(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.addOrder=this._systemAddCounter++,t.setPerformanceMonitor(this.performanceMonitor);const s=ee(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(),this.indexSystemByComponents(t),u(t,this._services),Dt.isEnabled()&&Nn.wrapInstance(t,t.systemName,gt.ECS),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(),this.removeSystemFromIndex(e),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=>I(e))})),processors:e.map(e=>({name:se(e),updateOrder:e.updateOrder,entityCount:e.entities.length})),componentStats:this.componentStorageManager.getAllStats()}}serialize(e){return xn.serialize(this,e)}deserialize(e,t){xn.deserialize(this,e,t)}createIncrementalSnapshot(e){this._incrementalBaseSnapshot=Rn.createSnapshot(this,e)}serializeIncremental(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Rn.computeIncremental(this,this._incrementalBaseSnapshot,e)}applyIncremental(e,t){const n="string"==typeof e||e instanceof Uint8Array?Rn.deserializeIncremental(e):e,s=t||this.componentRegistry.getAllComponentNames();Rn.applyIncremental(this,n,s)}updateIncrementalSnapshot(e){this.createIncrementalSnapshot(e)}clearIncrementalSnapshot(){this._incrementalBaseSnapshot=void 0}hasIncrementalSnapshot(){return void 0!==this._incrementalBaseSnapshot}}class Xn{constructor(e,t){this.scene=e,this.storageManager=t;const n=e.identifierPool.checkOut();this.entity=new Xt("",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(),n=this.scene.getSystem(St);return n?.setParent(t,this.entity),this}withChildren(...e){const t=this.scene.getSystem(St);for(const n of e){const e=n.build();t?.setParent(e,this.entity)}return this}withChildFactory(e){const t=e(this.entity).build(),n=this.scene.getSystem(St);return n?.setParent(t,this.entity),this}withChildIf(e,t){if(e){const e=t.build(),n=this.scene.getSystem(St);n?.setParent(e,this.entity)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const e=new Xn(this.scene,this.storageManager);return e.entity=this.entity,e}}class Kn{constructor(){this.scene=new Zn}named(e){return this.scene.name=e,this}withEntity(e){return this.scene.addEntity(e),this}withEntityBuilder(e){const t=e(new Xn(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 es{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 ts{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 ts(this.entities.filter(e))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class ns{constructor(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}createEntity(){return new Xn(this.scene,this.scene.componentStorageManager)}createScene(){return new Kn}createComponent(e,...t){return new es(e,...t)}query(){return new fn(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 ts(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 ss(e,t,n){return new ns(e,t,n)}const is=$("World"),rs={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,cleanupThresholdMs:3e5};class os{constructor(e={}){this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config={...rs,...e},this.name=this._config.name,this._createdAt=Date.now(),this._services=new Hn}get services(){return this._services}get isActive(){return this._isActive}get sceneCount(){return this._scenes.size}get createdAt(){return this._createdAt}createScene(e,t){this.validateSceneName(e);const n=t??new Zn;if(this._config.debug){const e=new _;e.enable(),n.services.registerInstance(_,e)}return n.id=e,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),is.info(`从World '${this.name}' 中移除Scene: ${e}`),!0)}removeAllScenes(){this._scenes.forEach((e,t)=>this.removeScene(t)),is.info(`从World '${this.name}' 中移除所有Scene`)}getScene(e){return this._scenes.get(e)??null}getSceneIds(){return Array.from(this._scenes.keys())}getAllScenes(){return Array.from(this._scenes.values())}setSceneActive(e,t){const n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin?.(),is.debug(`在World '${this.name}' 中激活Scene: ${e}`)):(this._activeScenes.delete(e),is.debug(`在World '${this.name}' 中停用Scene: ${e}`)):is.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?.(),is.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?.(),is.debug(`从World '${this.name}' 中移除全局System: ${e.name}`),!0)}getGlobalSystem(e){return this._globalSystems.find(t=>t instanceof e)??null}start(){this._isActive||(this._isActive=!0,this._globalSystems.forEach(e=>e.initialize?.()),is.info(`启动World: ${this.name}`))}stop(){this._isActive&&(this._activeScenes.forEach(e=>this.setSceneActive(e,!1)),this._globalSystems.forEach(e=>e.reset?.()),this._isActive=!1,is.info(`停止World: ${this.name}`))}destroy(){is.info(`销毁World: ${this.name}`),this.stop(),this.removeAllScenes(),this._globalSystems.forEach(e=>e.destroy?.()??e.reset?.()),this._globalSystems.length=0,this._services.clear(),this._scenes.clear(),this._activeScenes.clear()}updateGlobalSystems(){this._isActive&&this._globalSystems.forEach(e=>e.update?.())}updateScenes(){this._isActive&&(this._activeScenes.forEach(e=>{this._scenes.get(e)?.update?.()}),this._config.autoCleanup&&this.cleanup())}getStatus(){const e=[];return this._scenes.forEach((t,n)=>{e.push({id:n,name:t.name||n,isActive:this._activeScenes.has(n)})}),{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:e}}getStats(){let e=0,t=this._globalSystems.length;return this._scenes.forEach(n=>{e+=n.entities?.count??0,t+=n.systems?.length??0}),{totalEntities:e,totalSystems:t,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}}}validateSceneName(e){if(!e?.trim())throw new Error("Scene name不能为空");if(this._scenes.has(e))throw new Error(`Scene name '${e}' 已存在于World '${this.name}' 中`);if(this._scenes.size>=this._config.maxScenes)throw new Error(`World '${this.name}' 已达到最大Scene数量限制: ${this._config.maxScenes}`)}isCleanupCandidate(e,t){const n=Date.now()-this._createdAt;return!this._activeScenes.has(e)&&null!=t.entities&&0===t.entities.count&&n>this._config.cleanupThresholdMs}cleanup(){const e=[];this._scenes.forEach((t,n)=>{this.isCleanupCandidate(n,t)&&e.push(n)}),e.forEach(e=>{this.removeScene(e),is.debug(`自动清理空Scene: ${e} from World ${this.name}`)})}}class as{constructor(e){this._nextScene=null,this._ecsAPI=null,this._logger=$("SceneManager"),this._performanceMonitor=null,this._pendingPersistentEntities=[],this._defaultWorld=new os({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}setSceneChangedCallback(e){this._onSceneChangedCallback=e}setScene(e){const t=this.currentScene;return t&&t instanceof Zn&&(this._pendingPersistentEntities=t.extractPersistentEntities(),this._pendingPersistentEntities.length>0&&this._logger.debug(`Extracted ${this._pendingPersistentEntities.length} persistent entities for migration`)),this._defaultWorld.removeAllScenes(),this._performanceMonitor&&e.services.registerInstance(_,this._performanceMonitor),this._defaultWorld.createScene(as.DEFAULT_SCENE_ID,e),this._defaultWorld.setSceneActive(as.DEFAULT_SCENE_ID,!0),this._pendingPersistentEntities.length>0&&e instanceof Zn&&(e.receiveMigratedEntities(this._pendingPersistentEntities),this._logger.debug(`Migrated ${this._pendingPersistentEntities.length} persistent entities to new scene`),this._pendingPersistentEntities=[]),e.querySystem&&e.eventSystem?this._ecsAPI=ss(e,e.querySystem,e.eventSystem):this._ecsAPI=null,n.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(as.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(as.DEFAULT_SCENE_ID)}get hasPendingScene(){return null!==this._nextScene}dispose(){this.destroy()}}as.DEFAULT_SCENE_ID="__main__";let cs=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(){}};cs=e([o(),t("design:paramtypes",[])],cs);let hs=class{constructor(){this.frameCounter=0,this.lastSendTime=0,this.sendInterval=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)}}onInitialize(){this.config=this.configService.getConfig(),this.entityCollector=new Ct,this.systemCollector=new vt,this.performanceCollector=new Et,this.componentCollector=new wt,this.sceneCollector=new It,this.advancedProfilerCollector=new xt,Dt.setEnabled(!0),this.webSocketManager=new Mt(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const e=this.config.debugFrameRate||30;this.sendInterval=1e3/e,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 Mt(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"get_advanced_profiler_data":this.handleGetAdvancedProfilerDataRequest(e);break;case"set_profiler_selected_function":this.handleSetProfilerSelectedFunction(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)})}}handleGetAdvancedProfilerDataRequest(e){try{const{requestId:t}=e,n=Dt.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):this.advancedProfilerCollector.collectFromLegacyMonitor(this.performanceMonitor);this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:t,data:n})}catch(t){this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleSetProfilerSelectedFunction(e){try{const{functionName:t,requestId:n}=e;this.advancedProfilerCollector.setSelectedFunction(t||null),this.sendDebugData(),this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:n,success:!0})}catch(t){this.webSocketManager.send({type:"set_profiler_selected_function_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=I(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(I(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=se(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=Tt.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=S.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=this.getDebugData(),t=Dt.isEnabled(),n={type:"debug_data",data:e,advancedProfiler:t?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):null};this.webSocketManager.send(n)}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}};var ls;e([c(as),t("design:type",as)],hs.prototype,"sceneManager",void 0),e([c(_),t("design:type",_)],hs.prototype,"performanceMonitor",void 0),e([c(cs),t("design:type",cs)],hs.prototype,"configService",void 0),hs=e([o(),a()],hs),function(e){e.NotInstalled="not_installed",e.Installed="installed",e.Failed="failed"}(ls||(ls={}));const ds=$("PluginManager");class us{constructor(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}initialize(e,t){this._core=e,this._services=t,ds.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 ds.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:ls.NotInstalled,installedAt:Date.now()};this._metadata.set(e.name,t);try{ds.info(`Installing plugin: ${e.name} v${e.version}`),await e.install(this._core,this._services),this._plugins.set(e.name,e),t.state=ls.Installed,ds.info(`Plugin ${e.name} installed successfully`)}catch(n){throw t.state=ls.Failed,t.error=n instanceof Error?n.message:String(n),ds.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{ds.info(`Uninstalling plugin: ${e}`),await t.uninstall(),this._plugins.delete(e),this._metadata.delete(e),ds.info(`Plugin ${e} uninstalled successfully`)}catch(t){throw ds.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{ds.info(`Disposing plugin: ${t.name}`),t.uninstall()}catch(e){ds.error(`Error disposing plugin ${t.name}:`,e)}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,ds.info("PluginManager disposed")}}function ms(e){const t=`@esengine/service:${e}`;return{id:Symbol.for(t),name:e}}class ps{constructor(){this._services=new Map}register(e,t){this._services.set(e.id,t)}get(e){return this._services.get(e.id)}require(e){const t=this._services.get(e.id);if(void 0===t)throw new Error(`Service not found: ${e.name}`);return t}has(e){return this._services.has(e.id)}unregister(e){return this._services.delete(e.id)}clear(){this._services.clear()}dispose(){this.clear()}}const fs=$("WorldManager"),gs={maxWorlds:50,autoCleanup:!0,cleanupFrameInterval:1800,debug:!1};class ys{constructor(e={}){this._worlds=new Map,this._isRunning=!0,this._framesSinceCleanup=0,this._config={...gs,...e},fs.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupFrameInterval:this._config.cleanupFrameInterval})}get worldCount(){return this._worlds.size}get activeWorldCount(){let e=0;return this._worlds.forEach(t=>{t.isActive&&e++}),e}get isRunning(){return this._isRunning}get config(){return{...this._config}}createWorld(e,t){this.validateWorldName(e);const n={...t,name:e,debug:t?.debug??this._config.debug},s=new os(n);return this._worlds.set(e,s),s}removeWorld(e){const t=this._worlds.get(e);return!!t&&(t.destroy(),this._worlds.delete(e),fs.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(),fs.debug(`激活World: ${e}`)):(n.stop(),fs.debug(`停用World: ${e}`)):fs.warn(`World '${e}' 不存在`)}isWorldActive(e){return this._worlds.get(e)?.isActive??!1}getActiveWorlds(){const e=[];return this._worlds.forEach(t=>{t.isActive&&e.push(t)}),e}findWorlds(e){const t=[];return this._worlds.forEach(n=>{e(n)&&t.push(n)}),t}findWorldByName(e){let t=null;return this._worlds.forEach(n=>{n.name===e&&(t=n)}),t}startAll(){this._isRunning=!0,this._worlds.forEach(e=>e.start()),fs.info("启动所有World")}stopAll(){this._isRunning=!1,this._worlds.forEach(e=>e.stop()),fs.info("停止所有World")}destroy(){fs.info("正在销毁WorldManager..."),this.stopAll();Array.from(this._worlds.keys()).forEach(e=>this.removeWorld(e)),this._worlds.clear(),this._isRunning=!1,fs.info("WorldManager已销毁")}dispose(){this.destroy()}updateAll(){this._isRunning&&(this._worlds.forEach(e=>{e.isActive&&(e.updateGlobalSystems(),e.updateScenes())}),this.processAutoCleanup())}getStats(){let e=0,t=0,n=0;const s=[];return this._worlds.forEach((i,r)=>{const o=i.getStats();e+=i.sceneCount,t+=o.totalEntities,n+=o.totalSystems,s.push({id:r,name:i.name,isActive:i.isActive,sceneCount:i.sceneCount,...o})}),{totalWorlds:this._worlds.size,activeWorlds:this.activeWorldCount,totalScenes:e,totalEntities:t,totalSystems:n,memoryUsage:0,isRunning:this._isRunning,config:{...this._config},worlds:s}}getDetailedStatus(){const e=[];return this._worlds.forEach((t,n)=>{e.push({id:n,isActive:t.isActive,status:t.getStatus()})}),{...this.getStats(),worlds:e}}cleanup(){const e=[];return this._worlds.forEach((t,n)=>{this.isCleanupCandidate(t)&&e.push(n)}),e.forEach(e=>this.removeWorld(e)),e.length>0&&fs.debug(`清理了 ${e.length} 个World`),e.length}validateWorldName(e){if(!e?.trim())throw new Error("World name不能为空");if(this._worlds.has(e))throw new Error(`World name '${e}' 已存在`);if(this._worlds.size>=this._config.maxWorlds)throw new Error(`已达到最大World数量限制: ${this._config.maxWorlds}`)}processAutoCleanup(){this._config.autoCleanup&&(this._framesSinceCleanup++,this._framesSinceCleanup>=this._config.cleanupFrameInterval&&(this.cleanup(),this._framesSinceCleanup=0,this._config.debug&&fs.debug(`执行定期清理World (间隔: ${this._config.cleanupFrameInterval} 帧)`)))}isCleanupCandidate(e){if(e.isActive)return!1;if(Date.now()-e.createdAt<=6e5)return!1;if(0===e.sceneCount)return!0;return!e.getAllScenes().some(e=>e.entities&&e.entities.count>0)}}class _s{static get isServer(){return"server"===_s.runtimeEnvironment}static get isClient(){return"client"===_s.runtimeEnvironment}constructor(e={}){if(_s._instance=this,this._config={debug:!0,...e},this._serviceContainer=new Hn,e.runtimeEnvironment&&(_s.runtimeEnvironment=e.runtimeEnvironment),this._timerManager=new g,this._serviceContainer.registerInstance(g,this._timerManager),this._performanceMonitor=new _,this._serviceContainer.registerInstance(_,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new C,this._serviceContainer.registerInstance(C,this._poolManager),this._sceneManager=new as(this._performanceMonitor),this._serviceContainer.registerInstance(as,this._sceneManager),this._sceneManager.setSceneChangedCallback(()=>this._debugManager?.onSceneChanged()),this._worldManager=new ys({debug:!!this._config.debug,...this._config.worldManagerConfig}),this._serviceContainer.registerInstance(ys,this._worldManager),this._pluginManager=new us,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(us,this._pluginManager),this._pluginServiceRegistry=new ps,this._serviceContainer.registerInstance(ps,this._pluginServiceRegistry),this.debug=this._config.debug??!0,this._config.debugConfig?.enabled){const e=new cs;e.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(cs,e),this._serviceContainer.registerSingleton(hs,e=>d(hs,e)),this._debugManager=this._serviceContainer.resolve(hs),this._debugManager.onInitialize()}this.initialize()}static get Instance(){return this._instance}static get services(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}static get pluginServices(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._pluginServiceRegistry}static get worldManager(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._worldManager}static create(e=!0){if(null==this._instance){const t="boolean"==typeof e?{debug:e}:e;this._instance=new _s(t)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance}static setScene(e){if(!this._instance)throw _s._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):_s._logger.warn("Core实例未创建,请先调用Core.create()")}static update(e){this._instance?this._instance.updateInternal(e):_s._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 cs;t.setConfig(e),this._instance._serviceContainer.registerInstance(cs,t),this._instance._serviceContainer.registerSingleton(hs,e=>d(hs,e)),this._instance._debugManager=this._instance._serviceContainer.resolve(hs),this._instance._debugManager.onInitialize()}this._instance._config.debugConfig=e}else _s._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 get performanceMonitor(){return this._instance?._performanceMonitor||null}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(){_s._logger.info("Core initialized",{debug:this.debug,debugEnabled:this._config.debugConfig?.enabled||!1})}updateInternal(e){if(_s.paused)return;const t=this._performanceMonitor.startMonitoring("Core.update");n.update(e),this._performanceMonitor.updateFPS?.(n.deltaTime);const s=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",s,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?.stop(),this._instance._serviceContainer.clear(),_s._logger.info("Core destroyed"),this._instance=null)}}_s.paused=!1,_s.runtimeEnvironment="standalone",_s._instance=null,_s._logger=$("Core");const Ss=ms("runtimeMode");class Cs{constructor(e={}){this._callbacks=new Set,this._isEditor=e.isEditor??!1,this._isPlaying=e.isPlaying??!1,this._isPreview=e.isPreview??!1}get isEditor(){return this._isEditor}get isPlaying(){return this._isPlaying}get isPreview(){return this._isPreview}get isStandalone(){return!this._isEditor}onModeChanged(e){return this._callbacks.add(e),()=>{this._callbacks.delete(e)}}setEditorMode(e){this._isEditor!==e&&(this._isEditor=e,this._notifyChange())}setPlaying(e){this._isPlaying!==e&&(this._isPlaying=e,this._notifyChange())}setPreview(e){this._isPreview!==e&&(this._isPreview=e,this._notifyChange())}updateMode(e){let t=!1;void 0!==e.isEditor&&this._isEditor!==e.isEditor&&(this._isEditor=e.isEditor,t=!0),void 0!==e.isPlaying&&this._isPlaying!==e.isPlaying&&(this._isPlaying=e.isPlaying,t=!0),void 0!==e.isPreview&&this._isPreview!==e.isPreview&&(this._isPreview=e.isPreview,t=!0),t&&this._notifyChange()}_notifyChange(){for(const e of this._callbacks)try{e(this)}catch(e){Cs._logger.error("Callback error:",e)}}dispose(){this._callbacks.clear()}}function vs(){return new Cs({isEditor:!0,isPlaying:!1,isPreview:!1})}function Es(){return new Cs({isEditor:!1,isPlaying:!0,isPreview:!1})}Cs._logger=$("RuntimeModeService");const bs=$("DebugPlugin");let Ts=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(ys),bs.info("ECS Debug Plugin installed"),this.autoStart&&this.start()}async uninstall(){this.stop(),this.worldManager=null,bs.info("ECS Debug Plugin uninstalled")}dispose(){this.stop(),this.worldManager=null}start(){this.updateTimer?bs.warn("Debug monitoring already started"):(bs.info("Starting debug monitoring"),this.updateTimer=setInterval(()=>{this.logStats()},this.updateInterval))}stop(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,bs.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.sceneName||n.name===e.sceneName)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();bs.info("=== ECS Debug Stats ==="),bs.info(`Total Entities: ${e.totalEntities}`),bs.info(`Total Systems: ${e.totalSystems}`),bs.info(`Scenes: ${e.scenes.length}`);for(const t of e.scenes){bs.info(`\n[Scene: ${t.name}]`),bs.info(` Entities: ${t.entityCount}`),bs.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`:"";bs.info(` - ${e.name} (${e.enabled?"enabled":"disabled"}) | Entities: ${e.entityCount}${t}`)}}bs.info("========================\n")}exportJSON(){const e=this.getStats();return JSON.stringify(e,null,2)}};Ts=e([o(),t("design:paramtypes",[Object])],Ts);class ws{constructor(e,t){this.func=e,this.context=t}}class Is{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 ws(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}}class Ms{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(){}}class As extends _t{constructor(e){super(e)}process(e){this.processSystem()}}class ks extends _t{constructor(e){super(e)}process(e){}}class Ds extends _t{constructor(e,t){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}onCheckProcessing(){return this.acc+=n.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class xs{constructor(){this._adapter=null,this._logger=$("PlatformManager")}static getInstance(){return xs._instance||(xs._instance=new xs),xs._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()}}const Os="Worker pool has been destroyed";class Ps{constructor(e,t){this.workerStates=new Map,this.pendingTasks=new Map,this.taskQueue=[],this.taskCounter=0,this._isDestroyed=!1,this.workers=e,this.initializeWorkers(t)}get isDestroyed(){return this._isDestroyed}get workerCount(){return this.workers.length}get isReady(){if(this._isDestroyed)return!1;for(const e of this.workerStates.values())if(0===e)return!1;return this.workers.length>0}get hasPendingTasks(){return this.taskQueue.length>0||this.pendingTasks.size>0}executeSharedBuffer(e){return this.createTask("shared-"+ ++this.taskCounter,{...e,type:"shared"},()=>{})}execute(e){return this.createTask("task-"+ ++this.taskCounter,e,e=>e)}getStatus(){const e={idle:0,busy:0,initializing:0};for(const t of this.workerStates.values())1===t?e.idle++:2===t?e.busy++:0===t&&e.initializing++;return{total:this.workers.length,...e,queuedTasks:this.taskQueue.length}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const e=new Error(Os);for(const t of this.pendingTasks.values())t.reject(e);for(const t of this.taskQueue)t.reject(e);for(const e of this.workers)e.terminate();this.workers.length=0,this.taskQueue.length=0,this.pendingTasks.clear(),this.workerStates.clear()}initializeWorkers(e){for(let t=0;t<this.workers.length;t++){const n=this.workers[t];n&&(this.workerStates.set(t,e?0:1),n.onMessage(e=>this.handleMessage(t,e.data)),n.onError(e=>this.handleError(t,e)),e&&n.postMessage({type:"init",sharedBuffer:e}))}}createTask(e,t,n){return new Promise((s,i)=>{this._isDestroyed?i(new Error(Os)):this.enqueueTask({id:e,data:t,resolve:e=>s(n(e)),reject:i})})}enqueueTask(e){this.taskQueue.push(e),this.dispatchTasks()}dispatchTasks(){for(;this.taskQueue.length>0;){const e=this.findIdleWorker();if(-1===e)break;const t=this.taskQueue.shift();this.assignTask(e,t)}}findIdleWorker(){for(let e=0;e<this.workers.length;e++)if(1===this.workerStates.get(e))return e;return-1}assignTask(e,t){const n=this.workers[e];n&&(this.workerStates.set(e,2),this.pendingTasks.set(e,t),n.postMessage({id:t.id,...t.data}))}handleMessage(e,t){if("init"===t.type)return this.workerStates.set(e,1),void this.dispatchTasks();t.error?this.completeTask(e,new Error(t.error)):this.completeTask(e,void 0,t.result)}handleError(e,t){this.completeTask(e,new Error(t.message))}completeTask(e,t,n){const s=this.pendingTasks.get(e);s&&(this.pendingTasks.delete(e),this.workerStates.set(e,1),t?s.reject(t):s.resolve(n),this.dispatchTasks())}}class Rs extends _t{constructor(e,t={}){super(e),this.sharedBuffer=null,this.sharedFloatArray=null,this.workerPool=null,this.isProcessing=!1,this.hasLoggedSyncMode=!1,this.platformAdapter=xs.getInstance().getAdapter(),this.config=this.resolveConfig(t),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()}resolveConfig(e){const t=this.getMaxSystemWorkerCount(),n=e.workerCount??t,s=Math.min(n,t);return n>t&&this.logger.warn(`请求 ${n} 个 Worker,但系统最多支持 ${t} 个。实际使用 ${s} 个 Worker。`),{enableWorker:e.enableWorker??!0,workerCount:s,useSharedArrayBuffer:e.useSharedArrayBuffer??this.isSharedArrayBufferSupported(),entityDataSize:e.entityDataSize??this.getDefaultEntityDataSize(),maxEntities:e.maxEntities??1e4,systemConfig:e.systemConfig,...void 0!==e.entitiesPerWorker&&{entitiesPerWorker:e.entitiesPerWorker},...void 0!==e.workerScriptPath&&{workerScriptPath:e.workerScriptPath}}}isWorkerSupported(){return this.platformAdapter.isWorkerSupported()}isSharedArrayBufferSupported(){return this.platformAdapter.isSharedArrayBufferSupported()}getMaxSystemWorkerCount(){return this.platformAdapter.getPlatformConfig().maxWorkerCount}initializeWorkerSystem(){this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool()}initializeSharedArrayBuffer(){try{if(!this.isSharedArrayBufferSupported())return void this.fallbackToSingleWorker("平台不支持 SharedArrayBuffer");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} bytes)`))}catch(e){this.fallbackToSingleWorker("SharedArrayBuffer 初始化失败"),this.logger.warn(`${this.systemName}:`,e)}}fallbackToSingleWorker(e){this.logger.warn(`${this.systemName}: ${e},降级到单 Worker 模式`),this.config.useSharedArrayBuffer=!1,this.config.workerCount=1,this.sharedBuffer=null,this.sharedFloatArray=null}initializeWorkerPool(){try{const e=this.resolveWorkerScript();if(!e)return void(this.config.enableWorker=!1);const t=this.createWorkers(e);this.workerPool=new Ps(t,this.sharedBuffer)}catch(e){this.logger.error(`${this.systemName}: Worker 池初始化失败`,e),this.config.enableWorker=!1}}resolveWorkerScript(){const e=this.platformAdapter.getPlatformConfig();if(this.config.workerScriptPath)return this.logger.info(`${this.systemName}: 使用外部 Worker 文件: ${this.config.workerScriptPath}`),this.config.workerScriptPath;if(e.limitations?.noEval)return this.logger.error(`${this.systemName}: 当前平台不支持动态 Worker 脚本,请配置 workerScriptPath 指定预编译的 Worker 文件`),null;const t=this.createWorkerScript();return(e.workerScriptPrefix||"")+t}createWorkers(e){const t=[];for(let n=0;n<this.config.workerCount;n++){const s=this.platformAdapter.createWorker(e,{name:`${this.systemName}-Worker-${n}`});t.push(s)}return t}createWorkerScript(){const e=this.extractFunctionBody(this.workerProcess.toString()),t=this.getSharedProcessFunctionBody();return`\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = ${this.config.entityDataSize};\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n try {\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n if (type === 'shared') {\n if (!sharedFloatArray) {\n self.postMessage({ id, error: 'SharedArrayBuffer not initialized' });\n return;\n }\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null });\n return;\n }\n\n if (entities) {\n function workerProcess(entities, deltaTime, systemConfig) {\n ${e}\n }\n\n const result = workerProcess(entities, deltaTime, systemConfig);\n\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 function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n ${t}\n }\n `}extractFunctionBody(e){const t=e.match(/\{([\s\S]*)\}/);if(!t||void 0===t[1])throw new Error("无法解析 workerProcess 方法");return t[1]}getSharedProcessFunctionBody(){const e=this.getSharedArrayBufferProcessFunction?.();if(!e)return"";return`\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n ${this.extractFunctionBody(e.toString())}\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n `}process(e){if(this.isProcessing)return;this.isProcessing=!0;const t=this.getCurrentProcessingMode();try{switch(t){case"shared-buffer":this.processWithSharedArrayBuffer(e).finally(()=>{this.isProcessing=!1});break;case"worker":this.processWithWorker(e).finally(()=>{this.isProcessing=!1});break;default:this.processSynchronously(e),this.isProcessing=!1}}catch(e){throw this.isProcessing=!1,this.logger.error(`${this.systemName}: 处理失败`,e),e}}getCurrentProcessingMode(){return this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray?"shared-buffer":"worker":(this.hasLoggedSyncMode||(this.logger.info(`${this.systemName}: Worker 不可用,使用同步处理`),this.hasLoggedSyncMode=!0),"sync")}async processWithSharedArrayBuffer(e){if(!this.sharedFloatArray||!this.workerPool)return;this.writeEntitiesToBuffer(e);const t=this.createBatchTasks(e.length,!0);await Promise.all(t),this.readResultsFromBuffer(e)}async processWithWorker(e){if(!this.workerPool)return;const t=e.map(e=>this.extractEntityData(e)),s=this.createDataBatches(t),i=n.deltaTime,r=await Promise.all(s.map(e=>this.workerPool.execute({entities:e,deltaTime:i,systemConfig:this.config.systemConfig})));this.applyBatchResults(e,r)}processSynchronously(e){const t=e.map(e=>this.extractEntityData(e)),s=n.deltaTime,i=this.workerProcess(t,s,this.config.systemConfig);i&&"function"==typeof i.then?i.then(t=>{this.applyResults(e,t)}):this.applyResults(e,i)}createDataBatches(e){return this.splitIntoBatches(e.length,(t,n)=>e.slice(t,n))}createBatchTasks(e,t){return this.splitIntoBatches(e,(e,s)=>t?this.workerPool.executeSharedBuffer({startIndex:e,endIndex:s,deltaTime:n.deltaTime,systemConfig:this.config.systemConfig}):Promise.resolve())}splitIntoBatches(e,t){const n=[],{workerCount:s,entitiesPerWorker:i}=this.config;if(i)for(let s=0;s<e;s+=i){const r=Math.min(s+i,e);n.push(t(s,r))}else{const i=Math.ceil(e/s);for(let r=0;r<s;r++){const s=r*i,o=Math.min(s+i,e);s<e&&n.push(t(s,o))}}return n}applyBatchResults(e,t){let n=0;for(const s of t)for(const t of s)n<e.length&&t&&this.applyResult(e[n],t),n++}applyResults(e,t){for(let n=0;n<e.length&&n<t.length;n++)this.applyResult(e[n],t[n])}writeEntitiesToBuffer(e){if(!this.sharedFloatArray)return;const t=Math.min(e.length,this.config.maxEntities);for(let n=0;n<t;n++){const t=this.extractEntityData(e[n]),s=n*this.config.entityDataSize;this.writeEntityToBuffer(t,s)}}readResultsFromBuffer(e){if(!this.sharedFloatArray)return;const t=Math.min(e.length,this.config.maxEntities);for(let n=0;n<t;n++){const t=n*this.config.entityDataSize,s=this.readEntityFromBuffer(t);s&&this.applyResult(e[n],s)}}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?this.reinitializeSystem():t.workerCount!==this.config.workerCount?this.reinitializeWorkerPool():!this.config.enableWorker&&this.workerPool?this.destroyWorkerPool():this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()}reinitializeSystem(){this.destroyWorkerPool(),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()}reinitializeWorkerPool(){this.destroyWorkerPool(),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()}destroyWorkerPool(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)}getWorkerInfo(){return{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:this.getCurrentProcessingMode()}}onDestroy(){super.onDestroy(),this.destroyWorkerPool()}getLoggerName(){return se(this)}}let zs=class extends Xe{constructor(e="",t="",n=!1){super(),this.sourcePrefabGuid="",this.sourcePrefabPath="",this.isRoot=!1,this.rootInstanceEntityId=null,this.modifiedProperties=[],this.instantiatedAt=0,this.originalValues={},this.sourcePrefabGuid=e,this.sourcePrefabPath=t,this.isRoot=n,this.instantiatedAt=Date.now()}markPropertyModified(e,t){const n=`${e}.${t}`;this.modifiedProperties.includes(n)||this.modifiedProperties.push(n)}isPropertyModified(e,t){const n=`${e}.${t}`;return this.modifiedProperties.includes(n)}clearPropertyModified(e,t){const n=`${e}.${t}`,s=this.modifiedProperties.indexOf(n);-1!==s&&this.modifiedProperties.splice(s,1)}clearAllModifications(){this.modifiedProperties=[],this.originalValues={}}storeOriginalValue(e,t,n){const s=`${e}.${t}`;s in this.originalValues||(this.originalValues[s]=this.deepClone(n))}getOriginalValue(e){return this.originalValues[e]}hasOriginalValue(e,t){return`${e}.${t}`in this.originalValues}deepClone(e){if(null==e)return e;if("object"==typeof e)try{return JSON.parse(JSON.stringify(e))}catch{return e}return e}};e([st(),t("design:type",String)],zs.prototype,"sourcePrefabGuid",void 0),e([st(),t("design:type",String)],zs.prototype,"sourcePrefabPath",void 0),e([st(),t("design:type",Boolean)],zs.prototype,"isRoot",void 0),e([st(),t("design:type",Object)],zs.prototype,"rootInstanceEntityId",void 0),e([st(),t("design:type",Array)],zs.prototype,"modifiedProperties",void 0),e([st(),t("design:type",Number)],zs.prototype,"instantiatedAt",void 0),e([st(),t("design:type",Object)],zs.prototype,"originalValues",void 0),zs=e([X("PrefabInstance",{editor:{hideInInspector:!0}}),nt({version:1,typeId:"PrefabInstance"}),t("design:paramtypes",[String,String,Boolean])],zs);class Ns{constructor(e=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new gn,this.isDebugMode=e}emit(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&Ns._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&&Ns._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||Yt.NORMAL,async:n.async||!1};return n.thisArg&&(s.thisArg=n.thisArg),this.isDebugMode&&Ns._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&&Ns._logger.info(`移除监听器: ${t} 事件: ${e}`),this.eventSystem.off(e,t)}offAll(e){this.isDebugMode&&Ns._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&&Ns._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(Qt.ENTITY_CREATED,e)}emitEntityDestroyed(e){this.emit(Qt.ENTITY_DESTROYED,e)}emitComponentAdded(e){this.emit(Qt.COMPONENT_ADDED,e)}emitComponentRemoved(e){this.emit(Qt.COMPONENT_REMOVED,e)}emitSystemAdded(e){this.emit(Qt.SYSTEM_ADDED,e)}emitSystemRemoved(e){this.emit(Qt.SYSTEM_REMOVED,e)}emitSceneChanged(e){this.emit(Qt.SCENE_ACTIVATED,e)}emitPerformanceWarning(e){this.emit(Qt.PERFORMANCE_WARNING,e)}onEntityCreated(e,t){return this.on(Qt.ENTITY_CREATED,e,t)}onComponentAdded(e,t){return this.on(Qt.COMPONENT_ADDED,e,t)}onSystemError(e,t){return this.on(Qt.SYSTEM_ERROR,e,t)}onPerformanceWarning(e,t){return this.on(Qt.PERFORMANCE_WARNING,e,t)}validateEventType(e){this.isDebugMode&&(Zt.isValid(e)||(Ns._logger.warn(`未知事件类型: ${e}`),Zt.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}}}Ns._logger=$("EventBus");class Fs{static getInstance(e=!1){return this._instance||(this._instance=new Ns(e)),this._instance}static reset(e=!1){return this._instance&&this._instance.clear(),this._instance=new Ns(e),this._instance}}const Bs=$("VersionMigration");class $s{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 Bs.warn(`No migration path found for component ${e.type} | 未找到组件 ${e.type} 的迁移路径`),e;const i={...e};let r=n;for(;r<t;){const t=s.get(r);if(!t){Bs.warn(`Missing migration from version ${r} to ${r+1} for ${e.type} | 缺少组件 ${e.type} 从版本 ${r} 到 ${r+1} 的迁移`);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){Bs.warn(`Missing scene migration from version ${i} to ${i+1} | 缺少场景从版本 ${i} 到 ${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}}$s.componentMigrations=new Map,$s.sceneMigrations=new Map;class Ls{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?$s.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):$s.registerSceneMigration(this.fromVersion,this.toVersion,e)}}const Ws=1;class Hs{static createPrefab(e,t,n){const s=t.includeChildren??!0,i=Mn.serialize(e,s,n),r=this.toPrefabEntity(i,!0),{componentTypes:o,componentTypeRegistry:a}=this.collectComponentTypes(r),c=Date.now(),h={name:t.name,createdAt:c,modifiedAt:c,componentTypes:o,referencedAssets:[]};return t.description&&(h.description=t.description),t.tags&&(h.tags=t.tags),{version:1,metadata:h,root:r,componentTypeRegistry:a}}static instantiate(e,t,n,s={}){const{parentId:i,name:r,preserveIds:o=!1,trackInstance:a=!0}=s,c=t.getSystem(St)??null;let h=1;const{rootEntities:l,allEntities:d}=Mn.deserializeEntities([e.root],n,()=>{for(;t.findEntityById(h);)h++;return h++},o,t,c),u=l[0];if(!u)throw new Error("Failed to instantiate prefab: no root entity created");r&&(u.name=r);for(const e of d.values())t.entities.add(e);if(void 0!==i&&c){const e=t.findEntityById(i);e&&c.setParent(u,e)}if(a){const t=e.metadata.guid||"";this.addPrefabInstanceComponents(u,d,t,"",c)}return u}static toPrefabEntity(e,t){return{...e,isPrefabRoot:t,children:e.children.map(e=>this.toPrefabEntity(e,!1))}}static collectComponentTypes(e){const t=new Map,n=e=>{for(const n of e.components)t.has(n.type)||t.set(n.type,n.version);for(const t of e.children)n(t)};n(e);return{componentTypes:Array.from(t.keys()),componentTypeRegistry:Array.from(t.entries()).map(([e,t])=>({typeName:e,version:t}))}}static addPrefabInstanceComponents(e,t,n,s,i){const r=e.id,o=new zs(n,s,!0);o.rootInstanceEntityId=r,e.addComponent(o);for(const e of t.values()){if(e.id===r)continue;const t=new zs(n,s,!1);t.rootInstanceEntityId=r,e.addComponent(t)}}static isPrefabInstance(e){return e.hasComponent(zs)}static getSourcePrefabGuid(e){const t=e.getComponent(zs);return t?.sourcePrefabGuid||null}static getPrefabInstanceRoot(e){const t=e.getComponent(zs);if(!t||!t.rootInstanceEntityId)return null;const n=e.scene;return n&&n.findEntityById(t.rootInstanceEntityId)||null}static serialize(e,t=!0){return JSON.stringify(e,null,t?2:void 0)}static deserialize(e){const t=JSON.parse(e);if(!t.version||!t.metadata||!t.root)throw new Error("Invalid prefab data format");return t}static validate(e){const t=[];return"number"!=typeof e.version&&t.push("Invalid or missing version"),e.metadata?(e.metadata.name||t.push("Missing metadata.name"),Array.isArray(e.metadata.componentTypes)||t.push("Invalid metadata.componentTypes")):t.push("Missing metadata"),e.root?this.validateEntity(e.root,t,"root"):t.push("Missing root entity"),Array.isArray(e.componentTypeRegistry)||t.push("Invalid componentTypeRegistry"),t.length>0?{valid:!1,errors:t}:{valid:!0}}static validateEntity(e,t,n){"number"!=typeof e.id&&t.push(`${n}: Invalid or missing id`),"string"!=typeof e.name&&t.push(`${n}: Invalid or missing name`),Array.isArray(e.components)||t.push(`${n}: Invalid or missing components`),Array.isArray(e.children)?e.children.forEach((e,s)=>{this.validateEntity(e,t,`${n}.children[${s}]`)}):t.push(`${n}: Invalid or missing children`)}}const Us={NONE:0,FOLDER:4096,HIDDEN:8192,LOCKED:16384,EDITOR_ONLY:32768,PREFAB_INSTANCE:256,PREFAB_ROOT:512};function Gs(e,t){return 0!==(e&t)}function qs(e,t){return e|t}function js(e,t){return e&~t}function Vs(e){return Gs(e,Us.FOLDER)}function Qs(e){return Gs(e,Us.HIDDEN)}function Ys(e){return Gs(e,Us.LOCKED)}class Js{constructor(){this._dirtyFields=new Set,this._hasChanges=!1,this._lastSyncTime=0}setDirty(e){this._dirtyFields.add(e),this._hasChanges=!0}hasChanges(){return this._hasChanges}isDirty(e){return this._dirtyFields.has(e)}getDirtyFields(){return Array.from(this._dirtyFields)}getDirtyCount(){return this._dirtyFields.size}clear(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=Date.now()}clearField(e){this._dirtyFields.delete(e),0===this._dirtyFields.size&&(this._hasChanges=!1)}get lastSyncTime(){return this._lastSyncTime}markAllDirty(e){for(let t=0;t<e;t++)this._dirtyFields.add(t);this._hasChanges=e>0}reset(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=0}}function Zs(e){return function(t,n){const s=function(e){const t=e.constructor;if(Object.prototype.hasOwnProperty.call(t,Y))return t[Y];const n=t[Y],s={typeId:w(t),fields:n?[...n.fields]:[],fieldIndexMap:n?new Map(n.fieldIndexMap):new Map};return t[Y]=s,s}(t),i=s.fields.length,r={index:i,name:n,type:e};s.fields.push(r),s.fieldIndexMap.set(n,i);const o=`_sync_${n}`;Object.defineProperty(t,n,{get(){return this[o]},set(e){if(this[o]!==e){this[o]=e;const t=this[J];t&&t.setDirty(i)}},enumerable:!0,configurable:!0})}}function Xs(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Y]||null}function Ks(e){const t=Xs(e);return null!==t&&t.fields.length>0}function ei(e){return e&&e[J]||null}function ti(e){const t=Xs(e);if(!t)throw new Error("Component does not have sync metadata. Use @sync decorator on fields.");let n=e[J];return n||(n=new Js,e[J]=n),n.markAllDirty(t.fields.length),n}function ni(e){const t=ei(e);t&&t.clear()}function si(e){const t=ei(e);return!!t&&t.hasChanges()}const ii=Symbol("NetworkEntityMetadata");function ri(e,t){return function(n){const s={prefabType:e,autoSpawn:t?.autoSpawn??!0,autoDespawn:t?.autoDespawn??!0};return n[ii]=s,n}}function oi(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[ii]||null}function ai(e){return null!==oi(e)}function ci(e){if(e<0)throw new Error("Varint only supports non-negative integers");return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}function hi(e,t,n){if(e<0)throw new Error("Varint only supports non-negative integers");for(;e>=128;)t[n++]=127&e|128,e>>>=7;return t[n++]=e,n}function li(e,t){let n,s=0,i=0;do{if(t>=e.length)throw new Error("Varint decode: buffer overflow");n=e[t++],s|=(127&n)<<i,i+=7}while(n>=128);return[s,t]}function di(e){return e<<1^e>>31}function ui(e){return e>>>1^-(1&e)}function mi(e,t,n){return hi(di(e),t,n)}function pi(e,t){const[n,s]=li(e,t);return[ui(n),s]}const fi="undefined"!=typeof TextEncoder?new TextEncoder:null;class gi{constructor(e=256){this._offset=0,this._buffer=new Uint8Array(e),this._view=new DataView(this._buffer.buffer)}get offset(){return this._offset}toUint8Array(){return this._buffer.slice(0,this._offset)}reset(){this._offset=0}ensureCapacity(e){const t=this._offset+e;if(t>this._buffer.length){const e=Math.max(2*this._buffer.length,t),n=new Uint8Array(e);n.set(this._buffer),this._buffer=n,this._view=new DataView(this._buffer.buffer)}}writeUint8(e){this.ensureCapacity(1),this._buffer[this._offset++]=e}writeInt8(e){this.ensureCapacity(1),this._view.setInt8(this._offset++,e)}writeBoolean(e){this.writeUint8(e?1:0)}writeUint16(e){this.ensureCapacity(2),this._view.setUint16(this._offset,e,!0),this._offset+=2}writeInt16(e){this.ensureCapacity(2),this._view.setInt16(this._offset,e,!0),this._offset+=2}writeUint32(e){this.ensureCapacity(4),this._view.setUint32(this._offset,e,!0),this._offset+=4}writeInt32(e){this.ensureCapacity(4),this._view.setInt32(this._offset,e,!0),this._offset+=4}writeFloat32(e){this.ensureCapacity(4),this._view.setFloat32(this._offset,e,!0),this._offset+=4}writeFloat64(e){this.ensureCapacity(8),this._view.setFloat64(this._offset,e,!0),this._offset+=8}writeVarint(e){this.ensureCapacity(ci(e)),this._offset=hi(e,this._buffer,this._offset)}writeString(e){if(fi){const t=fi.encode(e);this.writeVarint(t.length),this.ensureCapacity(t.length),this._buffer.set(t,this._offset),this._offset+=t.length}else{const t=this.stringToUtf8Bytes(e);this.writeVarint(t.length),this.ensureCapacity(t.length),this._buffer.set(t,this._offset),this._offset+=t.length}}writeBytes(e){this.ensureCapacity(e.length),this._buffer.set(e,this._offset),this._offset+=e.length}stringToUtf8Bytes(e){const t=[];for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s>=55296&&s<=56319&&n+1<e.length){const t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),n++)}s<128?t.push(s):s<2048?(t.push(192|s>>6),t.push(128|63&s)):s<65536?(t.push(224|s>>12),t.push(128|s>>6&63),t.push(128|63&s)):(t.push(240|s>>18),t.push(128|s>>12&63),t.push(128|s>>6&63),t.push(128|63&s))}return new Uint8Array(t)}}const yi="undefined"!=typeof TextDecoder?new TextDecoder:null;class _i{constructor(e){this._offset=0,this._buffer=e,this._view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get offset(){return this._offset}set offset(e){this._offset=e}get remaining(){return this._buffer.length-this._offset}hasMore(){return this._offset<this._buffer.length}readUint8(){return this.checkBounds(1),this._buffer[this._offset++]}readInt8(){return this.checkBounds(1),this._view.getInt8(this._offset++)}readBoolean(){return 0!==this.readUint8()}readUint16(){this.checkBounds(2);const e=this._view.getUint16(this._offset,!0);return this._offset+=2,e}readInt16(){this.checkBounds(2);const e=this._view.getInt16(this._offset,!0);return this._offset+=2,e}readUint32(){this.checkBounds(4);const e=this._view.getUint32(this._offset,!0);return this._offset+=4,e}readInt32(){this.checkBounds(4);const e=this._view.getInt32(this._offset,!0);return this._offset+=4,e}readFloat32(){this.checkBounds(4);const e=this._view.getFloat32(this._offset,!0);return this._offset+=4,e}readFloat64(){this.checkBounds(8);const e=this._view.getFloat64(this._offset,!0);return this._offset+=8,e}readVarint(){const[e,t]=li(this._buffer,this._offset);return this._offset=t,e}readString(){const e=this.readVarint();this.checkBounds(e);const t=this._buffer.subarray(this._offset,this._offset+e);return this._offset+=e,yi?yi.decode(t):this.utf8BytesToString(t)}readBytes(e){this.checkBounds(e);const t=this._buffer.slice(this._offset,this._offset+e);return this._offset+=e,t}peekUint8(){return this.checkBounds(1),this._buffer[this._offset]}skip(e){this.checkBounds(e),this._offset+=e}checkBounds(e){if(this._offset+e>this._buffer.length)throw new Error(`BinaryReader: buffer overflow (offset=${this._offset}, size=${e}, bufferLength=${this._buffer.length})`)}utf8BytesToString(e){let t="",n=0;for(;n<e.length;){let s;const i=e[n++];if(i<128)s=i;else if(i<224){s=(31&i)<<6|63&e[n++]}else if(i<240){s=(15&i)<<12|(63&e[n++])<<6|63&e[n++]}else{s=(7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++],s>65535&&(s-=65536,t+=String.fromCharCode(55296+(s>>10)),s=56320+(1023&s))}t+=String.fromCharCode(s)}return t}}function Si(e,t,n){switch(n){case"boolean":e.writeBoolean(t);break;case"int8":e.writeInt8(t);break;case"uint8":e.writeUint8(t);break;case"int16":e.writeInt16(t);break;case"uint16":e.writeUint16(t);break;case"int32":e.writeInt32(t);break;case"uint32":e.writeUint32(t);break;case"float32":e.writeFloat32(t);break;case"float64":e.writeFloat64(t);break;case"string":e.writeString(t??"")}}function Ci(e,t,n){const s=t.fields;n.writeVarint(s.length);for(const t of s){n.writeUint8(t.index);Si(n,e[t.name],t.type)}}function vi(e,t,n,s){if(!n.hasChanges())return!1;const i=n.getDirtyFields();s.writeVarint(i.length);for(const n of i){const i=t.fields[n];if(i){s.writeUint8(i.index);Si(s,e[i.name],i.type)}}return i.length>0}function Ei(e,t,n=!1){t.writeUint32(e.id);const s=e.components,i=[];for(const e of s){const t=e.constructor[Y];if(t&&t.fields.length>0){const s=e[J];if(n&&s&&!s.hasChanges())continue;i.push({component:e,metadata:t,tracker:s})}}t.writeVarint(i.length);for(const{component:e,metadata:s,tracker:r}of i)t.writeString(s.typeId),n&&r?vi(e,s,r,t):Ci(e,s,t);return i.length}function bi(e,t=V.FULL){const n=new gi(1024);n.writeUint8(t),n.writeVarint(e.length);const s=t===V.DELTA;for(const t of e)Ei(t,n,s);return n.toUint8Array()}function Ti(e,t){const n=new gi(256);n.writeUint8(V.SPAWN),n.writeUint32(e.id),n.writeString(t||"");const s=e.components,i=[];for(const e of s){const t=e.constructor[Y];t&&t.fields.length>0&&i.push({component:e,metadata:t})}n.writeVarint(i.length);for(const{component:e,metadata:t}of i)n.writeString(t.typeId),Ci(e,t,n);return n.toUint8Array()}function wi(e){const t=new gi(8);return t.writeUint8(V.DESPAWN),t.writeUint32(e),t.toUint8Array()}function Ii(e){const t=new gi(8+4*e.length);t.writeUint8(V.DESPAWN),t.writeVarint(e.length);for(const n of e)t.writeUint32(n);return t.toUint8Array()}function Mi(e,t){switch(t){case"boolean":return e.readBoolean();case"int8":return e.readInt8();case"uint8":return e.readUint8();case"int16":return e.readInt16();case"uint16":return e.readUint16();case"int32":return e.readInt32();case"uint32":return e.readUint32();case"float32":return e.readFloat32();case"float64":return e.readFloat64();case"string":return e.readString()}}function Ai(e,t,n){const s=n.readVarint();for(let i=0;i<s;i++){const s=n.readUint8(),i=t.fields[s];if(i){const t=Mi(n,i.type);e[`_sync_${i.name}`]=t}else console.warn(`Unknown sync field index: ${s}`)}}function ki(e,t,n){const s=t.readUint32(),i=t.readVarint(),r=[];let o=n?.get(s),a=!1;o||(o=e.findEntityById(s)),o||(o=e.createEntity(`entity_${s}`),a=!0,n?.set(s,o));for(let e=0;e<i;e++){const e=t.readString();r.push(e);const n=j.getComponentType(e);if(!n){console.warn(`Unknown component type: ${e}`);const n=t.readVarint();for(let s=0;s<n;s++){t.readUint8(),console.error(`Cannot skip unknown component type: ${e}`);break}continue}const s=n[Y];if(!s){console.warn(`Component ${e} has no sync metadata`);continue}let i=o.getComponent(n);i||(i=o.addComponent(new n)),Ai(i,s,t)}return{entityId:s,isNew:a,componentTypes:r}}function Di(e,t,n){const s=new _i(t),i=s.readUint8(),r=s.readVarint(),o=[],a=n||new Map;for(let t=0;t<r;t++){const t=ki(e,s,a);o.push(t)}return{operation:i,entities:o}}function xi(e,t,n){const s=new _i(t);if(s.readUint8()!==V.SPAWN)return null;const i=s.readUint32(),r=s.readString(),o=s.readVarint(),a=[],c=e.createEntity(`entity_${i}`);n?.set(i,c);for(let e=0;e<o;e++){const e=s.readString();a.push(e);const t=j.getComponentType(e);if(!t){console.warn(`Unknown component type: ${e}`);const t=s.readVarint();for(let e=0;e<t;e++)s.readUint8();continue}const n=t[Y];if(!n)continue;Ai(c.addComponent(new t),n,s)}return{entity:c,prefabType:r,componentTypes:a}}function Oi(e){const t=new _i(e);if(t.readUint8()!==V.DESPAWN)return null;const n=[];if(4===t.remaining)n.push(t.readUint32());else{const e=t.readVarint();for(let s=0;s<e;s++)n.push(t.readUint32())}return{entityIds:n}}function Pi(e,t,n){const s=Oi(t);if(!s)return[];for(const t of s.entityIds){const s=n?.get(t)||e.findEntityById(t);s&&(s.destroy(),n?.delete(t))}return s.entityIds}function Ri(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}function zi(e,t){const n=e.getComponent(t);return null!==n?n:void 0}function Ni(e,...t){return t.map(t=>e.getComponent(t))}function Fi(e,...t){return t.every(t=>e.hasComponent(t))}function Bi(e,...t){return t.some(t=>e.hasComponent(t))}function $i(e,t,n){return e.addComponent(t),n(t),e}function Li(e,t,n){let s=e.getComponent(t);return s||(s=n(),e.addComponent(s)),s}function Wi(e,t,n){const s=e.getComponent(t);return!!s&&(Object.assign(s,n),!0)}class Hi{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){const t=this._entity.scene?.getSystem(St);return t?.setParent(e,this._entity),this}build(){return this._entity}get entity(){return this._entity}}function Ui(e){return new Hi(e)}class Gi{static getType(e){return e.constructor}}class qi{static toNumber(e){return null==e?0:Number(e)}}function ji(e){return"function"==typeof e&&e.prototype instanceof Xe}function Vi(e){return e.every(ji)}function Qi(){return globalThis}function Yi(){return performance}class Ji{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(){const e=this.miniGameGlobals.wx;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}static isByteDanceMiniGame(){const e=this.miniGameGlobals.tt;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}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(){const e=this.miniGameGlobals.my;return!!e&&!(!e.getSystemInfo||!e.createCanvas)}static isBaiduMiniGame(){const e=this.miniGameGlobals.swan;return!!e&&!(!e.getSystemInfo||!e.createCanvas)}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location}static isTauriEnvironment(){return"undefined"!=typeof window&&("__TAURI__"in window||"__TAURI_INTERNALS__"in window)}static isEditorEnvironment(){return"undefined"!=typeof window&&(!!this.isTauriEnvironment()||"__ESENGINE_EDITOR__"in window)}static getDetailedInfo(){const e={},t=this.miniGameGlobals;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!==t.wx,tt:void 0!==t.tt,my:void 0!==t.my,swan:void 0!==t.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}}function Zi(e){return xs.getInstance().registerAdapter(e)}function Xi(){return xs.getInstance().getAdapter()}function Ki(){return xs.getInstance().getBasicWorkerConfig()}function er(){return xs.getInstance().getFullPlatformConfig()}function tr(e){return xs.getInstance().supportsFeature(e)}function nr(){return xs.getInstance().hasAdapter()}Ji.miniGameGlobals=Qi();export{xt as AdvancedProfilerCollector,Ie as After,Nn as AutoProfiler,we as Before,_i as BinaryReader,An as BinarySerializer,gi as BinaryWriter,R as BitMask64Utils,nn as Bits,J as CHANGE_TRACKER,E as COMPONENT_DEPENDENCIES,b as COMPONENT_EDITOR_OPTIONS,v as COMPONENT_TYPE_NAME,On as ChangeOperation,Js as ChangeTracker,xe as ClientOnly,z as Colors,yt as CommandBuffer,ft as CommandType,mn as CompiledQuery,Xe as Component,wt as ComponentDataCollector,Tt as ComponentPoolManager,q as ComponentRegistry,In as ComponentSerializer,on as ComponentSparseSet,ut as ComponentStorage,N as ConsoleLogger,_s as Core,Un as CycleDependencyError,At as DEFAULT_PROFILER_CONFIG,Vn as DEFAULT_STAGE_ORDER,cs as DebugConfigService,hs as DebugManager,Ts as DebugPlugin,Je as DeepCopy,X as ECSComponent,Qt as ECSEventType,ns as ECSFluentAPI,K as ECSSystem,Rt as EMPTY_GUID,he as ENTITY_REF_METADATA,Jt as EVENT_TYPES,Is as Emitter,Ne as EnableSoA,Xt as Entity,Ct as EntityDataCollector,Yn as EntityHandleManager,Kt as EntityList,tn as EntityProcessorList,ue as EntityRef,Mn as EntitySerializer,_t as EntitySystem,Us as EntityTags,Jn as EpochManager,Ns as EventBus,Yt as EventPriority,Zt as EventTypeValidator,$e as Float32,Be as Float64,ws as FuncPack,Nt as GEN_BITS,Bt as GEN_MASK,j as GlobalComponentRegistry,Fs as GlobalEventBus,Ms as GlobalManager,ht as HierarchyComponent,St as HierarchySystem,zt as INDEX_BITS,Ft as INDEX_MASK,en as IdentifierPool,ot as IgnoreSerialization,Me as InSet,Rn as IncrementalSerializer,c as InjectProperty,o as Injectable,He as Int16,Le as Int32,Ge as Int8,Ds as IntervalSystem,P as LogLevel,B as Logger,F as LoggerManager,$t as MAX_ENTITIES,Lt as MAX_GENERATION,lt as Matcher,Ls as MigrationBuilder,ii as NETWORK_ENTITY_METADATA,Wt as NULL_HANDLE,ri as NetworkEntity,Oe as NotClient,Pe as NotServer,qi as NumberExtension,Ws as PREFAB_FORMAT_VERSION,_e as PROPERTY_METADATA,ks as PassiveSystem,Et as PerformanceDataCollector,_ as PerformanceMonitor,y as PerformanceWarningType,Ji as PlatformDetector,xs as PlatformManager,Ps as PlatformWorkerPool,us as PluginManager,ps as PluginServiceRegistry,ls as PluginState,S as Pool,C as PoolManager,zs as PrefabInstanceComponent,Hs as PrefabSerializer,As as ProcessingSystem,Bn as Profile,gt as ProfileCategory,$n as ProfileClass,Dt as ProfilerSDK,Se as Property,pn as QuerySystem,un as ReactiveQuery,dn as ReactiveQueryChangeType,ae as ReferenceTracker,Cs as RuntimeModeService,Ss as RuntimeModeToken,Ee as SCHEDULING_METADATA,Ke as SERIALIZABLE_METADATA,et as SERIALIZE_FIELD,tt as SERIALIZE_OPTIONS,Y as SYNC_METADATA,Z as SYSTEM_TYPE_NAME,Zn as Scene,It as SceneDataCollector,as as SceneManager,xn as SceneSerializer,nt as Serializable,kn as SerializationContext,st as Serialize,Ye as SerializeArray,it as SerializeAsMap,rt as SerializeAsSet,Ve as SerializeMap,Qe as SerializeSet,De as ServerOnly,Hn as ServiceContainer,Wn as ServiceLifetime,Ze as SoAStorage,sn as SparseSet,Te as Stage,V as SyncOperation,vt as SystemDataCollector,qn as SystemDependencyGraph,Qn as SystemScheduler,Q as TYPE_SIZES,n as Time,s as Timer,g as TimerManager,gn as TypeSafeEventSystem,Gi as TypeUtils,Hi as TypedEntityBuilder,_n as TypedQueryBuilder,yn as TypedQueryResult,Ue as Uint16,We as Uint32,qe as Uint8,je as Uint8Clamped,a as Updatable,Tn as ValueSerializer,$s as VersionMigrationManager,Mt as WebSocketManager,Rs as WorkerEntitySystem,os as World,ys as WorldManager,$i as addAndConfigure,qs as addEntityTag,Ui as buildEntity,ni as clearChanges,ss as createECSAPI,vs as createEditorModeService,d as createInstance,$ as createLogger,Sn as createQuery,ms as createServiceToken,Es as createStandaloneModeService,Ai as decodeComponent,Oi as decodeDespawn,ki as decodeEntity,pi as decodeSignedVarint,Di as decodeSnapshot,xi as decodeSpawn,li as decodeVarint,vi as encodeComponentDelta,Ci as encodeComponentFull,wi as encodeDespawn,Ii as encodeDespawnBatch,Ei as encodeEntity,mi as encodeSignedVarint,bi as encodeSnapshot,Ti as encodeSpawn,hi as encodeVarint,Gt as genOf,Ot as generateGUID,Ki as getBasicWorkerConfig,ei as getChangeTracker,M as getComponentDependencies,A as getComponentEditorOptions,k as getComponentInstanceEditorOptions,I as getComponentInstanceTypeName,w as getComponentTypeName,Ni as getComponents,Xi as getCurrentAdapter,me as getEntityRefMetadata,ge as getEntityRefProperties,er as getFullPlatformConfig,Qi as getGlobalWithMiniGame,oi as getNetworkEntityMetadata,Li as getOrAddComponent,Yi as getPerformanceWithMemory,l as getPropertyInjectMetadata,Ce as getPropertyMetadata,oe as getSceneByEntityId,Ae as getSchedulingMetadata,at as getSerializationMetadata,Xs as getSyncMetadata,te as getSystemInstanceMetadata,se as getSystemInstanceTypeName,ee as getSystemMetadata,ne as getSystemTypeName,p as getUpdatableMetadata,jt as handleEquals,Vt as handleToString,nr as hasAdapter,Bi as hasAnyComponent,si as hasChanges,Fi as hasComponents,T as hasECSComponentDecorator,pe as hasEntityRef,Gs as hasEntityTag,ve as hasPropertyMetadata,ke as hasSchedulingMetadata,Ks as hasSyncFields,Ut as indexOf,ti as initChangeTracker,u as injectProperties,Vi as isComponentArray,D as isComponentHiddenInInspector,x as isComponentInstanceHiddenInInspector,ji as isComponentType,fe as isEntityRefProperty,Vs as isFolder,Qs as isHidden,Ys as isLocked,ai as isNetworkEntity,ct as isSerializable,m as isUpdatable,Pt as isValidGUID,qt as isValidHandle,Ht as makeHandle,Pi as processDespawn,Cn as queryFor,vn as queryForAll,f as registerInjectable,Zi as registerPlatformAdapter,js as removeEntityTag,Ri as requireComponent,W as resetLoggerColors,H as setGlobalLogLevel,L as setLoggerColors,U as setLoggerFactory,tr as supportsFeature,Zs as sync,zi as tryGetComponent,Wi as updateComponent,ci as varintSize,ui as zigzagDecode,di as zigzagEncode};
1
+ 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){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class n{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}}n.deltaTime=0,n.unscaledDeltaTime=0,n.totalTime=0,n.unscaledTotalTime=0,n.timeScale=1,n.frameCount=0;class s{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+=n.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 i=new WeakMap,r=new WeakMap;function o(){return function(e){const t=i.get(e);i.set(e,{injectable:!0,dependencies:[],...t?.properties&&{properties:t.properties}})}}function a(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.`);r.set(t,{updatable:!0,priority:e})}}function c(e){return function(t,n){let s=i.get(t.constructor);s||(s={injectable:!0,dependencies:[]},i.set(t.constructor,s)),s.properties||(s.properties=new Map),s.properties.set(n,e)}}function h(e){const t=i.get(e);return t?.injectable??!1}function l(e){const t=i.get(e);return t?.properties||new Map}function d(e,t){const n=new e;return u(n,t),n}function u(e,t){const n=e.constructor,s=(r=n,i.get(r));var r;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=r.get(e);return t?.updatable??!1}function p(e){return r.get(e)}function f(e,t,n=!0){if(!h(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)}let g=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,i){const r=new s;return r.initialize(e,t,n,i),this._timers.push(r),r}dispose(){for(const e of this._timers)e.unload();this._timers=[]}};var y;g=e([a()],g),function(e){e.HIGH_EXECUTION_TIME="high_execution_time",e.HIGH_MEMORY_USAGE="high_memory_usage",e.HIGH_CPU_USAGE="high_cpu_usage",e.FREQUENT_GC="frequent_gc",e.LOW_FPS="low_fps",e.HIGH_ENTITY_COUNT="high_entity_count"}(y||(y={}));class _{constructor(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}updateFPS(e){}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 S{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 S(()=>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}}S._pools=new Map;class C{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 S(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"),E=Symbol("ComponentDependencies"),b=Symbol("ComponentEditorOptions");function T(e){return void 0!==e[v]}function w(e){const t=e[v];return t||(e.name||"UnknownComponent")}function I(e){return w(e.constructor)}function M(e){return e[E]}function A(e){return e[b]}function k(e){return A(e.constructor)}function D(e){const t=A(e);return t?.hideInInspector??!1}function x(e){return D(e.constructor)}var O,P;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(O||(O={}));class R{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0]};return R.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[O.LOW]&n[O.LOW])||0!==(s[O.HIGH]&n[O.HIGH]);return!o&&i&&r?r.some((e,t)=>{const n=i[t];return n&&(0!==(e[O.LOW]&n[O.LOW])||0!==(e[O.HIGH]&n[O.HIGH]))}):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[O.LOW]&s[O.LOW])===s[O.LOW]&&(n[O.HIGH]&s[O.HIGH])===s[O.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[O.LOW]&n[O.LOW])!==n[O.LOW]||(t[O.HIGH]&n[O.HIGH])!==n[O.HIGH])return!1}for(let e=a;e<r.length;e++){const t=r[e];if(0!==t[O.LOW]||0!==t[O.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[O.LOW]&s[O.LOW])&&0===(n[O.HIGH]&s[O.HIGH]);return i&&o&&r?i.every((e,t)=>{const n=r[t];return!n||0===(e[O.LOW]&n[O.LOW])&&0===(e[O.HIGH]&n[O.HIGH])}):o}static isZero(e){const t=0===e.base[O.LOW]&&0===e.base[O.HIGH];return e.segments&&t?e.segments.every(e=>0===e[O.LOW]&&0===e[O.HIGH]):t}static equals(e,t){const n=e.base[O.LOW]===t.base[O.LOW]&&e.base[O.HIGH]===t.base[O.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[O.LOW]||0!==t[O.HIGH])return!1}else if(!t&&n){if(0!==n[O.LOW]||0!==n[O.HIGH])return!1}else if(t&&n&&(t[O.LOW]!==n[O.LOW]||t[O.HIGH]!==n[O.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=R.getSegmentByBitIndex(e,t),s=63&t;s<32?n[O.LOW]|=1<<s:n[O.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=R.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[O.LOW]&1<<s):!!(n[O.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=R.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[O.LOW]&=~(1<<s):n[O.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[O.LOW]|=t.base[O.LOW],e.base[O.HIGH]|=t.base[O.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[O.LOW]|=i[O.LOW],s[O.HIGH]|=i[O.HIGH]}}}static andInPlace(e,t){e.base[O.LOW]&=t.base[O.LOW],e.base[O.HIGH]&=t.base[O.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[O.LOW]&=i[O.LOW],s[O.HIGH]&=i[O.HIGH]}}}static xorInPlace(e,t){e.base[O.LOW]^=t.base[O.LOW],e.base[O.HIGH]^=t.base[O.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[O.LOW]^=i[O.LOW],t[O.HIGH]^=i[O.HIGH]}}static clear(e){if(e.base[O.LOW]=0,e.base[O.HIGH]=0,e.segments)for(let t=0;t<e.segments.length;t++){const n=e.segments[t];n[O.LOW]=0,n[O.HIGH]=0}}static copy(e,t){if(R.clear(t),t.base[O.LOW]=e.base[O.LOW],t.base[O.HIGH]=e.base[O.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[O.LOW]=n[O.LOW],t[O.HIGH]=n[O.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[O.HIGH],c=o[O.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[O.LOW],r=s[O.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}}}R.ZERO={base:[0,0]},function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error",e[e.Fatal=4]="Fatal",e[e.None=5]="None"}(P||(P={}));const z={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""};class N{constructor(e={}){this._config={level:P.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...e}}debug(e,...t){this.log(P.Debug,e,...t)}info(e,...t){this.log(P.Info,e,...t)}warn(e,...t){this.log(P.Warn,e,...t)}error(e,...t){this.log(P.Error,e,...t)}fatal(e,...t){this.log(P.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=`[${P[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 P.Debug:s?console.debug(`${s.debug}${t}${s.reset}`,...n):console.debug(t,...n);break;case P.Info:s?console.info(`${s.info}${t}${s.reset}`,...n):console.info(t,...n);break;case P.Warn:s?console.warn(`${s.warn}${t}${s.reset}`,...n):console.warn(t,...n);break;case P.Error:s?console.error(`${s.error}${t}${s.reset}`,...n):console.error(t,...n);break;case P.Fatal:s?console.error(`${s.fatal}${t}${s.reset}`,...n):console.error(t,...n)}}getColors(){return{...{debug:z.BRIGHT_BLACK,info:z.GREEN,warn:z.YELLOW,error:z.RED,fatal:z.BRIGHT_RED,reset:z.RESET},...this._config.colors}}}class F{constructor(){this._loggers=new Map,this._defaultLevel=P.Info}get defaultLogger(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}createDefaultLogger(){return this._loggerFactory?this._loggerFactory():new N({level:this._defaultLevel})}static getInstance(){return F._instance||(F._instance=new F),F._instance}getLogger(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new N({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 N&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof N&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof N&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof N&&t.setColors(e)}resetColors(){this._defaultLogger instanceof N&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof N&&e.setColors({})}setLoggerFactory(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()}}const B=F.getInstance().getLogger();function $(e){return F.getInstance().getLogger(e)}function L(e){F.getInstance().setGlobalColors(e)}function W(){F.getInstance().resetColors()}function H(e){F.getInstance().setGlobalLevel(e)}function U(e){F.getInstance().setLoggerFactory(e)}const G=$("ComponentRegistry");class q{constructor(){this._componentTypes=new Map,this._bitIndexToType=new Map,this._componentNameToType=new Map,this._componentNameToId=new Map,this._maskCache=new Map,this._nextBitIndex=0,this._hotReloadEnabled=!1,this._warnedComponents=new Set}register(e){const t=w(e);if(T(e)||this._warnedComponents.has(e)||(this._warnedComponents.add(e),G.warn(`Component "${t}" is missing @ECSComponent decorator. This may cause issues with serialization and code minification. Please add: @ECSComponent('${t}') | 组件 "${t}" 缺少 @ECSComponent 装饰器,可能导致序列化和代码压缩问题`)),this._componentTypes.has(e))return this._componentTypes.get(e);if(this._hotReloadEnabled&&this._componentNameToType.has(t)){const n=this._componentNameToType.get(t);if(n!==e){const s=this._componentTypes.get(n);return this._componentTypes.delete(n),this._componentTypes.set(e,s),this._bitIndexToType.set(s,e),this._componentNameToType.set(t,e),G.debug(`Hot reload: replaced component "${t}"`),s}}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}getBitMask(e){const t=this._componentTypes.get(e);if(void 0===t){const t=w(e);throw new Error(`Component type ${t} is not registered`)}return R.create(t)}getBitIndex(e){const t=this._componentTypes.get(e);if(void 0===t){const t=w(e);throw new Error(`Component type ${t} is not registered`)}return t}isRegistered(e){return this._componentTypes.has(e)}getTypeByBitIndex(e){return this._bitIndexToType.get(e)||null}getRegisteredCount(){return this._nextBitIndex}getComponentType(e){return this._componentNameToType.get(e)||null}getAllRegisteredTypes(){return new Map(this._componentTypes)}getAllComponentNames(){return new Map(this._componentNameToType)}getComponentId(e){return this._componentNameToId.get(e)}registerComponentByName(e){if(this._componentNameToId.has(e))return this._componentNameToId.get(e);const t=this._nextBitIndex++;return this._componentNameToId.set(e,t),t}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=R.create(n);return this._maskCache.set(t,s),s}createComponentMask(e){const t=`multi:${[...e].sort().join(",")}`;if(this._maskCache.has(t))return this._maskCache.get(t);const n=R.clone(R.ZERO);for(const t of e){const e=this.getComponentId(t);if(void 0!==e){const t=R.create(e);R.orInPlace(n,t)}}return this._maskCache.set(t,n),n}clearMaskCache(){this._maskCache.clear()}enableHotReload(){this._hotReloadEnabled=!0}disableHotReload(){this._hotReloadEnabled=!1}isHotReloadEnabled(){return this._hotReloadEnabled}unregister(e){const t=this._componentNameToType.get(e);if(!t)return;const n=this._componentTypes.get(t);this._componentTypes.delete(t),void 0!==n&&this._bitIndexToType.delete(n),this._componentNameToType.delete(e),this._componentNameToId.delete(e),this.clearMaskCache(),G.debug(`Component unregistered: ${e}`)}getRegisteredComponents(){const e=[];for(const[t,n]of this._componentNameToType){const s=this._componentTypes.get(n);void 0!==s&&e.push({name:t,type:n,bitIndex:s})}return e}reset(){this._componentTypes.clear(),this._bitIndexToType.clear(),this._componentNameToType.clear(),this._componentNameToId.clear(),this._maskCache.clear(),this._warnedComponents.clear(),this._nextBitIndex=0,this._hotReloadEnabled=!1}cloneFrom(e){const t=e.getAllRegisteredTypes();for(const[e,n]of t){this._componentTypes.set(e,n),this._bitIndexToType.set(n,e);const t=w(e);this._componentNameToType.set(t,e),this._componentNameToId.set(t,n)}this._nextBitIndex=e.getRegisteredCount(),this._hotReloadEnabled=e.isHotReloadEnabled()}}const j=new q;var V;!function(e){e[e.FULL=0]="FULL",e[e.DELTA=1]="DELTA",e[e.SPAWN=2]="SPAWN",e[e.DESPAWN=3]="DESPAWN"}(V||(V={}));const Q={boolean:1,int8:1,uint8:1,int16:2,uint16:2,int32:4,uint32:4,float32:4,float64:8,string:-1},Y=Symbol("SyncMetadata"),J=Symbol("ChangeTracker"),Z=Symbol("SystemTypeName");function X(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");const s=n;s[v]=e,t?.requires&&(s[E]=t.requires),t?.editor&&(s[b]=t.editor);const i=n[Y];return i&&(i.typeId=e),j.register(n),n}}function K(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");const s=n;return s[Z]=e,t&&(s.__systemMetadata__=t),n}}function ee(e){return e.__systemMetadata__}function te(e){return ee(e.constructor)}function ne(e){const t=e[Z];return t||(e.name||"UnknownSystem")}function se(e){return ne(e.constructor)}const ie="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}},re=new Map;function oe(e){const t=re.get(e);return t?.deref()||null}class ae{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 ie(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){re.set(e,new ie(t))}unregisterEntityScene(e){re.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 ce=$("EntityRefDecorator"),he=Symbol("EntityRefMetadata"),le=Symbol("EntityRefValues");function de(e){let t=e[le];return t||(t=new Map,e[le]=t),t}function ue(){return function(e,t){const n=e.constructor;let s=n[he];s||(s={properties:new Set},n[he]=s);const i="symbol"==typeof t?t.toString():t;s.properties.add(i),Object.defineProperty(e,t,{get:function(){return de(this).get(i)||null},set:function(e){const t=de(this),n=t.get(i)||null;if(n===e)return;const s=null!==this.entityId?oe(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 ce.error(`Cannot reference Entity from different Scene. Entity: ${e.name}, Scene: ${e.scene?.name||"null"}`);if(e.isDestroyed)return ce.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})}}function me(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[he]||null}function pe(e){return null!==me(e)}function fe(e,t){const n=me(e);return!!n&&n.properties.has(t)}function ge(e){const t=me(e);return t?Array.from(t.properties):[]}const ye=new WeakMap,_e=Symbol.for("@esengine/property:metadata");function Se(e){return(t,n)=>{const s=t.constructor,i=ye.get(s)||{};i[n]=e,ye.set(s,i)}}function Ce(e){return ye.get(e)}function ve(e){return ye.has(e)}const Ee=Symbol("schedulingMetadata");function be(e){const t=e;return t[Ee]||(t[Ee]={stage:"update",before:[],after:[],sets:[]}),t[Ee]}function Te(e){return function(t){return be(t.prototype).stage=e,t}}function we(...e){return function(t){return be(t.prototype).before.push(...e),t}}function Ie(...e){return function(t){return be(t.prototype).after.push(...e),t}}function Me(...e){return function(t){return be(t.prototype).sets.push(...e),t}}function Ae(e){let t=Object.getPrototypeOf(e);for(;t;){const e=t[Ee];if(e)return e;t=Object.getPrototypeOf(t)}}function ke(e){return void 0!==Ae(e)}function De(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@ServerOnly can only be applied to methods, not "+typeof s);return n.value=function(...e){if(this.scene?.isServer)return s.apply(this,e)},n}}function xe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@ClientOnly can only be applied to methods, not "+typeof s);return n.value=function(...e){if(this.scene?.isClient)return s.apply(this,e)},n}}function Oe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@NotClient can only be applied to methods, not "+typeof s);return n.value=function(...e){if(!this.scene?.isClient)return s.apply(this,e)},n}}function Pe(){return function(e,t,n){const s=n.value;if("function"!=typeof s)throw new Error("@NotServer can only be applied to methods, not "+typeof s);return n.value=function(...e){if(!this.scene?.isServer)return s.apply(this,e)},n}}class Re{static getConstructor(e){return this.TYPE_CONSTRUCTORS[e]||Float32Array}static getBytesPerElement(e){return this.TYPE_BYTES[e]||4}static getTypeName(e){return e instanceof Float32Array?"float32":e instanceof Float64Array?"float64":e instanceof Int32Array?"int32":e instanceof Uint32Array?"uint32":e instanceof Int16Array?"int16":e instanceof Uint16Array?"uint16":e instanceof Int8Array?"int8":e instanceof Uint8Array?"uint8":e instanceof Uint8ClampedArray?"uint8clamped":"float32"}static createSameType(e,t){const n=this.getTypeName(e);return new(this.getConstructor(n))(t)}static extractFieldMetadata(e){const t=new e,n=new Map,s=e,i=new Map,r=(e,t)=>{if(e)for(const n of e)i.set(n,t)};r(s.__float64Fields,"float64"),r(s.__float32Fields,"float32"),r(s.__int32Fields,"int32"),r(s.__uint32Fields,"uint32"),r(s.__int16Fields,"int16"),r(s.__uint16Fields,"uint16"),r(s.__int8Fields,"int8"),r(s.__uint8Fields,"uint8"),r(s.__uint8ClampedFields,"uint8clamped");const o=Object.keys(t).filter(e=>"id"!==e);for(const e of o){const r=typeof t[e];if("function"===r)continue;const o={name:e,type:r},a=i.get(e);a?o.arrayType=a:"number"===r?o.arrayType="float32":"boolean"===r&&(o.arrayType="uint8"),s.__serializeMapFields?.has(e)&&(o.isSerializedMap=!0),s.__serializeSetFields?.has(e)&&(o.isSerializedSet=!0),s.__serializeArrayFields?.has(e)&&(o.isSerializedArray=!0),s.__deepCopyFields?.has(e)&&(o.isDeepCopy=!0),n.set(e,o)}return n}}Re.TYPE_CONSTRUCTORS={float32:Float32Array,float64:Float64Array,int32:Int32Array,uint32:Uint32Array,int16:Int16Array,uint16:Uint16Array,int8:Int8Array,uint8:Uint8Array,uint8clamped:Uint8ClampedArray},Re.TYPE_BYTES={float32:4,float64:8,int32:4,uint32:4,int16:2,uint16:2,int8:1,uint8:1,uint8clamped:1};class ze{static serialize(e,t,n={}){try{return n.isMap&&e instanceof Map?JSON.stringify(Array.from(e.entries())):n.isSet&&e instanceof Set?JSON.stringify(Array.from(e)):(n.isArray&&Array.isArray(e),JSON.stringify(e))}catch(e){return this._logger.warn(`SoA序列化字段 ${t} 失败:`,e),"{}"}}static deserialize(e,t,n={}){try{const t=JSON.parse(e);return n.isMap?new Map(t):n.isSet?new Set(t):t}catch(e){return this._logger.warn(`SoA反序列化字段 ${t} 失败:`,e),null}}static deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))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)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=this.deepClone(e[n]));return t}}function Ne(e){return e.__enableSoA=!0,e}function Fe(e,t){const n=e.constructor;let s=n[t];return s||(s=new Set,n[t]=s),s}function Be(e,t){Fe(e,"__float64Fields").add(String(t))}function $e(e,t){Fe(e,"__float32Fields").add(String(t))}function Le(e,t){Fe(e,"__int32Fields").add(String(t))}function We(e,t){Fe(e,"__uint32Fields").add(String(t))}function He(e,t){Fe(e,"__int16Fields").add(String(t))}function Ue(e,t){Fe(e,"__uint16Fields").add(String(t))}function Ge(e,t){Fe(e,"__int8Fields").add(String(t))}function qe(e,t){Fe(e,"__uint8Fields").add(String(t))}function je(e,t){Fe(e,"__uint8ClampedFields").add(String(t))}function Ve(e,t){Fe(e,"__serializeMapFields").add(String(t))}function Qe(e,t){Fe(e,"__serializeSetFields").add(String(t))}function Ye(e,t){Fe(e,"__serializeArrayFields").add(String(t))}function Je(e,t){Fe(e,"__deepCopyFields").add(String(t))}ze._logger=$("SoASerializer");class Ze{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.fieldTypes=new Map,this.serializeMapFields=new Set,this.serializeSetFields=new Set,this.serializeArrayFields=new Set,this.type=e,this.initializeFields(e)}initializeFields(e){const t=new e,n=e,s=n.__float64Fields||new Set,i=n.__float32Fields||new Set,r=n.__int32Fields||new Set,o=n.__uint32Fields||new Set,a=n.__int16Fields||new Set,c=n.__uint16Fields||new Set,h=n.__int8Fields||new Set,l=n.__uint8Fields||new Set,d=n.__uint8ClampedFields||new Set;this.serializeMapFields=n.__serializeMapFields||new Set,this.serializeSetFields=n.__serializeSetFields||new Set,this.serializeArrayFields=n.__serializeArrayFields||new Set;const u=new Map;for(const e of s)u.set(e,"float64");for(const e of i)u.set(e,"float32");for(const e of r)u.set(e,"int32");for(const e of o)u.set(e,"uint32");for(const e of a)u.set(e,"int16");for(const e of c)u.set(e,"uint16");for(const e of h)u.set(e,"int8");for(const e of l)u.set(e,"uint8");for(const e of d)u.set(e,"uint8clamped");const m=Object.keys(t).filter(e=>"id"!==e);for(const e of m){const n=t[e],s=typeof n;if("function"===s)continue;const i=u.get(e),r=i?"number":s;if(this.fieldTypes.set(e,r),i){const t=Re.getConstructor(i);this.fields.set(e,new t(this._capacity))}else"number"===s?this.fields.set(e,new Float32Array(this._capacity)):"boolean"===s?this.fields.set(e,new Uint8Array(this._capacity)):"string"===s?this.stringFields.set(e,new Array(this._capacity)):"object"===s&&null!==n&&(this.serializeMapFields.has(e)||this.serializeSetFields.has(e)||this.serializeArrayFields.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,r=i.__highPrecisionFields||new Set,o=i.__serializeMapFields||new Set,a=i.__serializeSetFields||new Set,c=i.__serializeArrayFields||new Set,h=i.__deepCopyFields||new Set,l=t;for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&"id"!==n){const t=l[n],i=typeof t;if("number"===i){const i=t;if(r.has(n)||!this.fields.has(n))s.set(n,i);else{this.fields.get(n)[e]=i}}else if("boolean"===i&&this.fields.has(n)){this.fields.get(n)[e]=t?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[e]=String(t)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[e]=ze.serialize(t,n,{isMap:o.has(n),isSet:a.has(n),isArray:c.has(n)})}else h.has(n)?s.set(n,ze.deepClone(t)):s.set(n,t)}s.size>0&&this.complexFields.set(n,s)}getComponent(e){const t=this.entityToIndex.get(e);return void 0===t?null:this.createProxyView(e,t)}createProxyView(e,t){const n=this;return new Proxy({},{get(s,i){const r=String(i),o=n.fields.get(r);if(o){return"boolean"===n.getFieldType(r)?1===o[t]:o[t]}const a=n.stringFields.get(r);if(a)return a[t];const c=n.serializedFields.get(r);if(c){const e=c[t];return e?ze.deserialize(e,r,{isMap:n.serializeMapFields.has(r),isSet:n.serializeSetFields.has(r),isArray:n.serializeArrayFields.has(r)}):void 0}const h=n.complexFields.get(e);return h?.has(r)?h.get(r):void 0},set(s,i,r){const o=String(i);if("entityId"===o)return!1;const a=n.fields.get(o);if(a){const e=n.getFieldType(o);return a[t]="boolean"===e?r?1:0:r,!0}const c=n.stringFields.get(o);if(c)return c[t]=String(r),!0;if(n.serializedFields.has(o)){return n.serializedFields.get(o)[t]=ze.serialize(r,o,{isMap:n.serializeMapFields.has(o),isSet:n.serializeSetFields.has(o),isArray:n.serializeArrayFields.has(o)}),!0}let h=n.complexFields.get(e);return h||(h=new Map,n.complexFields.set(e,h)),h.set(o,r),!0},has(t,s){const i=String(s);return n.fields.has(i)||n.stringFields.has(i)||n.serializedFields.has(i)||n.complexFields.get(e)?.has(i)||!1},ownKeys(){const t=[];for(const e of n.fields.keys())t.push(e);for(const e of n.stringFields.keys())t.push(e);for(const e of n.serializedFields.keys())t.push(e);const s=n.complexFields.get(e);if(s)for(const e of s.keys())t.push(e);return t},getOwnPropertyDescriptor(t,s){const i=String(s);if(n.fields.has(i)||n.stringFields.has(i)||n.serializedFields.has(i)||n.complexFields.get(e)?.has(i))return{enumerable:!0,configurable:!0,writable:"entityId"!==i}}})}getComponentSnapshot(e){const t=this.entityToIndex.get(e);if(void 0===t)return null;const n=new this.type,s=n;for(const[e,n]of this.fields.entries()){const i=n[t],r=this.getFieldType(e);s[e]="boolean"===r?1===i:i}for(const[e,n]of this.stringFields.entries())s[e]=n[t];for(const[e,n]of this.serializedFields.entries()){const i=n[t];i&&(s[e]=ze.deserialize(i,e,{isMap:this.serializeMapFields.has(e),isSet:this.serializeSetFields.has(e),isArray:this.serializeArrayFields.has(e)}))}const i=this.complexFields.get(e);if(i)for(const[e,t]of i.entries())s[e]=t;return n}getFieldType(e){return this.fieldTypes.get(e)||"unknown"}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()){const s=Re.createSameType(n,e);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()){const i=Re.getTypeName(s),r=Re.getBytesPerElement(i),o=s.length*r;e+=o,t.set(n,{size:this._size,capacity:s.length,type:i,memory:o})}return{size:this._size,capacity:this._capacity,totalSlots:this._capacity,usedSlots:this._size,freeSlots:this._capacity-this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:e,fieldStats:t}}performVectorizedOperation(e){const t=this.getActiveIndices();e(this.fields,t)}}class Xe{get lastWriteEpoch(){return this._lastWriteEpoch}constructor(){this.entityId=null,this._lastWriteEpoch=0,this.id=Xe._idGenerator++}markDirty(e){this._lastWriteEpoch=e}onAddedToEntity(){}onRemovedFromEntity(){}onDeserialized(){}}Xe._idGenerator=0,e([Le,t("design:type",Object)],Xe.prototype,"entityId",void 0);const Ke=Symbol("SerializableMetadata"),et=Symbol("SerializeField"),tt=Symbol("SerializeOptions");function nt(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");let n;if(Object.prototype.hasOwnProperty.call(t,Ke))n=t[Ke],n.options=e;else{const s=t[Ke];n={options:e,fields:s?new Map(s.fields):new Map,ignoredFields:s?new Set(s.ignoredFields):new Set},t[Ke]=n}return t}}function st(e){return function(t,n){const s=t.constructor;let i;if(Object.prototype.hasOwnProperty.call(s,Ke))i=s[Ke];else{const e=s[Ke];i={options:e?{...e.options}:{version:1},fields:e?new Map(e.fields):new Map,ignoredFields:e?new Set(e.ignoredFields):new Set},s[Ke]=i}i.fields.set(n,e||{})}}function it(){return function(e,t){st({serializer:e=>e instanceof Map?Array.from(e.entries()):null,deserializer:e=>Array.isArray(e)?new Map(e):new Map})(e,t)}}function rt(){return function(e,t){st({serializer:e=>e instanceof Set?Array.from(e):null,deserializer:e=>Array.isArray(e)?new Set(e):new Set})(e,t)}}function ot(){return function(e,t){const n=e.constructor;let s;if(Object.prototype.hasOwnProperty.call(n,Ke))s=n[Ke];else{const e=n[Ke];s={options:e?{...e.options}:{version:1},fields:e?new Map(e.fields):new Map,ignoredFields:e?new Set(e.ignoredFields):new Set},n[Ke]=s}s.ignoredFields.add(t)}}function at(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Ke]||null}function ct(e){return null!==at(e)}let ht=class extends Xe{constructor(){super(...arguments),this.parentId=null,this.childIds=[],this.depth=0,this.bActiveInHierarchy=!0,this.bCacheDirty=!0}};e([st(),t("design:type",Object)],ht.prototype,"parentId",void 0),e([st(),t("design:type",Array)],ht.prototype,"childIds",void 0),ht=e([X("Hierarchy",{editor:{hideInInspector:!0}}),nt({version:1,typeId:"Hierarchy"})],ht);class lt{constructor(){this.condition={all:[],any:[],none:[]}}static all(...e){return(new lt).all(...e)}static any(...e){return(new lt).any(...e)}static none(...e){return(new lt).none(...e)}static byTag(e){return(new lt).withTag(e)}static byName(e){return(new lt).withName(e)}static byComponent(e){return(new lt).withComponent(e)}static complex(){return new lt}static empty(){return new lt}static nothing(){const e=new lt;return e.condition.matchNothing=!0,e}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},...this.condition.matchNothing&&{matchNothing:!0}}}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&&!this.condition.matchNothing}isNothing(){return!0===this.condition.matchNothing}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,delete this.condition.matchNothing,this}clone(){const e=new lt;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),this.condition.matchNothing&&(e.condition.matchNothing=!0),e}toString(){if(this.condition.matchNothing)return"Matcher[nothing]";const e=[];return this.condition.all.length>0&&e.push(`all(${this.condition.all.map(e=>w(e)).join(", ")})`),this.condition.any.length>0&&e.push(`any(${this.condition.any.map(e=>w(e)).join(", ")})`),this.condition.none.length>0&&e.push(`none(${this.condition.none.map(e=>w(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(${w(this.condition.component)})`),`Matcher[${e.join(" & ")}]`}}class dt{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 ut{constructor(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e}addComponent(e,t){if(this.entityToIndex.has(e))throw new Error(`Entity ${e} already has component ${w(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 mt{constructor(){this.storages=new Map}isSoAStorage(e){return this.storages.get(e)instanceof Ze}getSoAStorage(e){const t=this.getStorage(e);return t instanceof Ze?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 Ze(e),mt._logger.info(`为 ${w(e)} 启用SoA优化(适用于大规模批量操作)`)):t=new ut(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,t=j){const n=R.clone(R.ZERO);for(const[s,i]of this.storages.entries())if(i.hasComponent(e)){const e=t.getBitMask(s);R.orInPlace(n,e)}return n}getAllStats(){const e=new Map;for(const[t,n]of this.storages.entries()){const s=w(t);e.set(s,n.getStats())}return e}clear(){for(const e of this.storages.values())e.clear();this.storages.clear()}}mt._logger=$("ComponentStorage");const pt=$("CommandBuffer");var ft,gt;!function(e){e.ADD_COMPONENT="add_component",e.REMOVE_COMPONENT="remove_component",e.DESTROY_ENTITY="destroy_entity",e.SET_ENTITY_ACTIVE="set_entity_active"}(ft||(ft={}));class yt{constructor(e,t=!1){this._pending=new Map,this._commands=[],this._scene=null,this._debug=!1,this._useDeduplication=!0,this._scene=e??null,this._debug=t}setScene(e){this._scene=e}get scene(){return this._scene}setDeduplication(e){this._useDeduplication=e}get pendingCount(){if(this._useDeduplication){let e=0;for(const t of this._pending.values())t.bDestroy&&e++,void 0!==t.active&&e++,t.adds&&(e+=t.adds.size),t.removes&&(e+=t.removes.size);return e}return this._commands.length}get hasPending(){return this._useDeduplication?this._pending.size>0:this._commands.length>0}getPending(e){let t=this._pending.get(e);return t||(t={},this._pending.set(e,t)),t}getTypeId(e){return"function"==typeof e?j.getBitIndex(e):j.getBitIndex(e.constructor)}addComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略添加组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);if(n.removes?.delete(s),n.adds||(n.adds=new Map),n.adds.set(s,t),this._debug){const n=w(t.constructor);pt.debug(`CommandBuffer: 延迟添加组件 ${n} 到实体 ${e.name}`)}}else this._commands.push({type:ft.ADD_COMPONENT,entity:e,component:t})}removeComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略移除组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);n.adds?.delete(s),n.removes||(n.removes=new Set),n.removes.add(s),this._debug&&pt.debug(`CommandBuffer: 延迟移除组件 ${t.name} 从实体 ${e.name}`)}else this._commands.push({type:ft.REMOVE_COMPONENT,entity:e,componentType:t})}destroyEntity(e){if(this._useDeduplication){const t=this.getPending(e);t.adds?.clear(),t.removes?.clear(),delete t.active,t.bDestroy=!0,this._debug&&pt.debug(`CommandBuffer: 延迟销毁实体 ${e.name}`)}else this._commands.push({type:ft.DESTROY_ENTITY,entity:e})}setEntityActive(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&pt.debug(`CommandBuffer: 忽略设置激活状态,实体 ${e.name} 已标记销毁`));n.active=t,this._debug&&pt.debug(`CommandBuffer: 延迟设置实体 ${e.name} 激活状态为 ${t}`)}else this._commands.push({type:ft.SET_ENTITY_ACTIVE,entity:e,value:t})}flush(){return this._useDeduplication?this.flushDeduplication():this.flushLegacy()}flushDeduplication(){if(0===this._pending.size)return 0;const e=this._pending.size;let t=0;this._debug&&pt.debug(`CommandBuffer: 开始执行 ${e} 个实体的延迟命令`);const n=this._pending;this._pending=new Map;for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.removes&&s.removes.size>0)for(const n of s.removes)try{const s=j.getTypeByBitIndex(n);s&&(e.removeComponentByType(s),t++)}catch(t){pt.error("CommandBuffer: 移除组件失败",{entity:e.name,typeId:n,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.adds&&s.adds.size>0)for(const n of s.adds.values())try{e.addComponent(n),t++}catch(t){const s=w(n.constructor);pt.error("CommandBuffer: 添加组件失败",{entity:e.name,component:s,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&void 0!==s.active)try{e.active=s.active,t++}catch(t){pt.error("CommandBuffer: 设置激活状态失败",{entity:e.name,error:t})}for(const[e,s]of n)if(s.bDestroy&&e.scene)try{e.destroy(),t++}catch(t){pt.error("CommandBuffer: 销毁实体失败",{entity:e.name,error:t})}return this._debug&&pt.debug(`CommandBuffer: 完成执行 ${t} 个延迟命令`),t}flushLegacy(){if(0===this._commands.length)return 0;const e=this._commands.length;this._debug&&pt.debug(`CommandBuffer: 开始执行 ${e} 个延迟命令`);const t=this._commands;this._commands=[];for(const e of t)this.executeCommand(e);return this._debug&&pt.debug(`CommandBuffer: 完成执行 ${e} 个延迟命令`),e}executeCommand(e){if(e.entity.scene)try{switch(e.type){case ft.ADD_COMPONENT:e.component&&e.entity.addComponent(e.component);break;case ft.REMOVE_COMPONENT:e.componentType&&e.entity.removeComponentByType(e.componentType);break;case ft.DESTROY_ENTITY:e.entity.destroy();break;case ft.SET_ENTITY_ACTIVE:void 0!==e.value&&(e.entity.active=e.value)}}catch(t){pt.error("CommandBuffer: 执行命令失败",{command:e,error:t})}else this._debug&&pt.debug(`CommandBuffer: 跳过命令,实体 ${e.entity.name} 已无效`)}clear(){if(this._debug){const e=this._useDeduplication?this._pending.size:this._commands.length;e>0&&pt.debug(`CommandBuffer: 清空 ${e} 个未执行的命令`)}this._pending.clear(),this._commands.length=0}dispose(){this.clear(),this._scene=null}}class _t{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 addOrder(){return this._addOrder}set addOrder(e){this._addOrder=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get systemName(){return this._systemName}constructor(e){this.commands=new yt,this._lastProcessEpoch=0,this._shouldProcessThisFrame=!1,this._updateOrder=0,this._addOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=se(this),this._initialized=!1,this._matcher=e||lt.empty(),this._eventListeners=[],this._scene=null,this._destroyed=!1,this._entityIdMap=null,this._entityIdMapVersion=-1,this.logger=$(this.getLoggerName()),this._entityCache=new dt;const t=Ae(this);this._schedulingMetadata=t?{...t}:{stage:"update",before:[],after:[],sets:[]}}get scene(){return this._scene}set scene(e){this._scene=e,this.commands.setScene(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())}stage(e){return this._schedulingMetadata.stage=e,this._scene?.markSystemsOrderDirty(),this}before(...e){return this._schedulingMetadata.before.push(...e),this._scene?.markSystemsOrderDirty(),this}after(...e){return this._schedulingMetadata.after.push(...e),this._scene?.markSystemsOrderDirty(),this}inSet(...e){return this._schedulingMetadata.sets.push(...e),this._scene?.markSystemsOrderDirty(),this}getStage(){return this._schedulingMetadata.stage}getBefore(){return this._schedulingMetadata.before}getAfter(){return this._schedulingMetadata.after}getSets(){return this._schedulingMetadata.sets}initialize(){if(!this._initialized){if(this._initialized=!0,this.scene){this._entityCache.invalidate();const e=this.queryEntities();for(const t of e)this.onAdded(t)}this.onInitialize()}}onInitialize(){}clearEntityCache(){this._entityCache.invalidate()}resetEntityTracking(){this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1}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 this._matcher.isNothing()?[]:(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._shouldProcessThisFrame=this._enabled&&this.onCheckProcessing(),!this._shouldProcessThisFrame)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._shouldProcessThisFrame)return;const e=this.getPerformanceMonitor(),t=e.startMonitoring(`${this._systemName}_Late`);let n=0;try{const e=this.queryEntities();this._entityCache.setFrame(e),n=e.length,this.lateProcess(e),this.onEnd()}finally{e.endMonitoring(`${this._systemName}_Late`,t,n),this._entityCache.clearFrame()}}flushCommands(){return this.commands.flush()}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}`}matchesEntity(e){if(!this._matcher)return!1;if(this._matcher.isNothing())return!1;if(this._matcher.isEmpty())return!0;const t=this._matcher.getCondition();for(const n of t.all)if(!e.hasComponent(n))return!1;if(t.any.length>0){let n=!1;for(const s of t.any)if(e.hasComponent(s)){n=!0;break}if(!n)return!1}for(const n of t.none)if(e.hasComponent(n))return!1;return(void 0===t.tag||e.tag===t.tag)&&((void 0===t.name||e.name===t.name)&&!(void 0!==t.component&&!e.hasComponent(t.component)))}isTracking(e){return this._entityCache.isTracked(e)}handleEntityComponentChanged(e){if(!this._matcher||!this._enabled)return;const t=this._entityCache.isTracked(e),n=this.matchesEntity(e);!t&&n?(this._entityCache.addTracked(e),this._entityCache.invalidate(),this.onAdded(e)):t&&!n&&(this._entityCache.removeTracked(e),this._entityCache.invalidate(),this.onRemoved(e))}updateEntityTracking(e){const t=new Set(e);let n=!1;for(const t of e)this._entityCache.isTracked(t)||(this._entityCache.addTracked(t),n=!0);for(const e of this._entityCache.getTracked())t.has(e)||(this._entityCache.removeTracked(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.commands.dispose(),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 se(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}get lastProcessEpoch(){return this._lastProcessEpoch}get currentEpoch(){return this._scene?.epochManager?.current??0}saveEpoch(){this._lastProcessEpoch=this.currentEpoch}forEachChanged(e,t,n,s){const i=s??this._lastProcessEpoch;for(let s=0;s<e.length;s++){const r=e[s];let o=!1;for(const e of t){const t=r.getComponent(e);if(t&&t.lastWriteEpoch>i){o=!0;break}}o&&n(r,s)}this._lastProcessEpoch=this.currentEpoch}filterChanged(e,t,n){const s=n??this._lastProcessEpoch,i=[];for(let n=0;n<e.length;n++){const r=e[n];for(const e of t){const t=r.getComponent(e);if(t&&t.lastWriteEpoch>s){i.push(r);break}}}return i}hasChanged(e,t,n){const s=n??this._lastProcessEpoch;for(const n of t){const t=e.getComponent(n);if(t&&t.lastWriteEpoch>s)return!0}return!1}}class St extends _t{constructor(){super(lt.empty().all(ht)),this.dirtyEntities=new Set}get updateOrder(){return-1e3}process(e){if(0!==this.dirtyEntities.size){for(const e of this.dirtyEntities)e.scene&&this.updateHierarchyCache(e);this.dirtyEntities.clear()}}setParent(e,t){let n=e.getComponent(ht);n||(n=new ht,e.addComponent(n));const s=n.parentId;if(s!==(t?.id??null)){if(t&&this.isAncestorOf(e,t))throw new Error("Cannot set parent: would create circular reference");if(null!==s){const t=this.scene?.findEntityById(s);if(t){const n=t.getComponent(ht);if(n){const t=n.childIds.indexOf(e.id);-1!==t&&n.childIds.splice(t,1)}}}if(t){let s=t.getComponent(ht);s||(s=new ht,t.addComponent(s)),n.parentId=t.id,s.childIds.push(e.id)}else n.parentId=null;this.markCacheDirty(e)}}insertChildAt(e,t,n){let s=t.getComponent(ht),i=e.getComponent(ht);if(s||(s=new ht,t.addComponent(s)),i||(i=new ht,e.addComponent(i)),this.isAncestorOf(t,e))throw new Error("Cannot set parent: would create circular reference");if(null!==s.parentId&&s.parentId!==e.id){const e=this.scene?.findEntityById(s.parentId);if(e){const n=e.getComponent(ht);if(n){const e=n.childIds.indexOf(t.id);-1!==e&&n.childIds.splice(e,1)}}}s.parentId=e.id;const r=i.childIds.indexOf(t.id);-1!==r&&i.childIds.splice(r,1),n<0||n>=i.childIds.length?i.childIds.push(t.id):i.childIds.splice(n,0,t.id),this.markCacheDirty(t)}removeChild(e,t){const n=e.getComponent(ht),s=t.getComponent(ht);if(!n||!s)return!1;if(s.parentId!==e.id)return!1;const i=n.childIds.indexOf(t.id);return-1!==i&&n.childIds.splice(i,1),s.parentId=null,this.markCacheDirty(t),!0}removeAllChildren(e){const t=e.getComponent(ht);if(!t)return;const n=[...t.childIds];for(const t of n){const n=this.scene?.findEntityById(t);n&&this.removeChild(e,n)}}getParent(e){const t=e.getComponent(ht);return t&&null!==t.parentId?this.scene?.findEntityById(t.parentId)??null:null}getChildren(e){const t=e.getComponent(ht);if(!t)return[];const n=[];for(const e of t.childIds){const t=this.scene?.findEntityById(e);t&&n.push(t)}return n}getChildCount(e){const t=e.getComponent(ht);return t?.childIds.length??0}hasChildren(e){return this.getChildCount(e)>0}isAncestorOf(e,t){let n=this.getParent(t),s=0;for(;n&&s<St.MAX_DEPTH;){if(n.id===e.id)return!0;n=this.getParent(n),s++}return!1}isDescendantOf(e,t){return this.isAncestorOf(t,e)}getRoot(e){let t=e,n=this.getParent(t),s=0;for(;n&&s<St.MAX_DEPTH;)t=n,n=this.getParent(t),s++;return t}getDepth(e){const t=e.getComponent(ht);if(!t)return 0;if(!t.bCacheDirty)return t.depth;let n=0,s=this.getParent(e);for(;s&&n<St.MAX_DEPTH;)n++,s=this.getParent(s);return t.depth=n,n}isActiveInHierarchy(e){if(!e.active)return!1;const t=e.getComponent(ht);if(!t)return e.active;if(!t.bCacheDirty)return t.bActiveInHierarchy;const n=this.getParent(e);return t.bActiveInHierarchy=n?e.active&&this.isActiveInHierarchy(n):e.active,t.bActiveInHierarchy}getRootEntities(){const e=[];for(const t of this.entities){const n=t.getComponent(ht);n&&null===n.parentId&&e.push(t)}return e}findChild(e,t,n=!1){const s=this.getChildren(e);for(const e of s)if(e.name===t)return e;if(n)for(const e of s){const n=this.findChild(e,t,!0);if(n)return n}return null}findChildrenByTag(e,t,n=!1){const s=[],i=this.getChildren(e);for(const e of i)0!==(e.tag&t)&&s.push(e),n&&s.push(...this.findChildrenByTag(e,t,!0));return s}forEachChild(e,t,n=!1){const s=this.getChildren(e);for(const e of s)t(e),n&&this.forEachChild(e,t,!0)}flattenHierarchy(e){const t=[],n=(s,i)=>{const r=this.hasChildren(s),o=e.has(s.id);if(t.push({entity:s,depth:i,bHasChildren:r,bIsExpanded:o}),r&&o)for(const e of this.getChildren(s))n(e,i+1)};for(const e of this.getRootEntities())n(e,0);return t}markCacheDirty(e){const t=e.getComponent(ht);if(t&&!t.bCacheDirty){t.bCacheDirty=!0,this.dirtyEntities.add(e);for(const e of t.childIds){const t=this.scene?.findEntityById(e);t&&this.markCacheDirty(t)}}}updateHierarchyCache(e){const t=e.getComponent(ht);t&&(t.depth=this.getDepth(e),t.bActiveInHierarchy=this.isActiveInHierarchy(e),t.bCacheDirty=!1)}onAdded(e){const t=e.getComponent(ht);t&&t.bCacheDirty&&this.dirtyEntities.add(e)}onRemoved(e){this.dirtyEntities.delete(e);const t=e.getComponent(ht);if(t){if(null!==t.parentId){const n=this.scene?.findEntityById(t.parentId);if(n){const t=n.getComponent(ht);if(t){const n=t.childIds.indexOf(e.id);-1!==n&&t.childIds.splice(n,1)}}}for(const e of t.childIds){const t=this.scene?.findEntityById(e);if(t){const e=t.getComponent(ht);e&&(e.parentId=null,this.markCacheDirty(t))}}}}dispose(){this.dirtyEntities.clear()}}St.MAX_DEPTH=32;class Ct{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;if(!t?.buffer)return[];const n=e.getSystem(St);return t.buffer.map(e=>{const t=e.getComponent(ht),s=n?.isActiveInHierarchy(e)??e.active,i=n?.getDepth(e)??0;return{id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:s,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),parentId:t?.parentId??null,childIds:t?.childIds??[],depth:i,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=t.getSystem(St),r=i?.getParent(s),o=r?.name??null,a=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t,i),c=this.extractComponentDetails(s.components),h=this.getSceneInfo(t);return{...a,scene:h.name,sceneName:h.name,sceneType:h.type,parentName:o,components:c||[],componentCount:s.components?.length||0,componentTypes:s.components?.map(e=>I(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,e),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=>I(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=>I(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,t){if(!e?.buffer)return[];const n=t?.getSystem(St),s=[];return e.buffer.forEach(e=>{const t=e.getComponent(ht);if(null==t?.parentId){const t=this.buildEntityHierarchyNode(e,n);s.push(t)}}),s.sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:e.id-t.id),s}buildEntityHierarchyNode(e,t){const n=e.getComponent(ht),s=t?.isActiveInHierarchy(e)??e.active,i=t?.getDepth(e)??0;let r={id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:s,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),parentId:n?.parentId??null,children:[],depth:i,tag:e.tag||0,updateOrder:e.updateOrder||0};if(t){const n=t.getChildren(e);n.length>0&&(r.children=n.map(e=>this.buildEntityHierarchyNode(e,t)))}if("function"==typeof e.getDebugInfo){const t=e.getDebugInfo();r={...r,...t}}return e.components&&e.components.length>0&&(r.componentDetails=this.extractComponentDetails(e.components)),r}buildEntityDetailsMap(e,t){if(!e?.buffer)return{};const n=t?.getSystem(St),s={},i=e.buffer;for(let e=0;e<i.length;e+=100){i.slice(e,e+100).forEach(e=>{const i=e.getDebugInfo?e.getDebugInfo():this.buildFallbackEntityInfo(e,t,n),r=e.getComponentCacheStats?e.getComponentCacheStats():null,o=this.extractComponentDetails(e.components),a=n?.getParent(e),c=a?.name??null;s[e.id]={...i,parentName:c,components:o,componentTypes:i.componentTypes||o.map(e=>e.typeName),cachePerformance:r?{hitRate:r.cacheStats.hitRate,size:r.cacheStats.size,maxSize:r.cacheStats.maxSize}:null}})}return s}buildFallbackEntityInfo(e,t,n){const s=this.getSceneInfo(t),i=e.getComponent(ht),r=n?.isActiveInHierarchy(e)??e.active,o=n?.getDepth(e)??0;return{name:e.name||`Entity_${e.id}`,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:r,destroyed:e.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:e.components.length,componentTypes:e.components.map(e=>I(e)),componentMask:e.componentMask?.toString()||"0",parentId:i?.parentId??null,childCount:i?.childIds?.length??0,childIds:i?.childIds??[],depth:o,tag:e.tag||0,updateOrder:e.updateOrder||0}}extractComponentDetails(e){return e.map(e=>{const t=I(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=I(e))}catch(t){n._error="属性提取失败",n._componentId=I(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];if(!r)return{};const 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 vt{collectSystemData(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};const n=t.systems||[];let s=new Map,i=new Map;if(e)try{s=e.getAllSystemStats(),i=e.getAllSystemData()}catch(e){}return{totalSystems:n.length,systemsInfo:n.map(e=>{const t=e.systemName||se(e),n=s.get(t),r=i.get(t);return{name:t,type:se(e),entityCount:e.entities?.length||0,executionTime:n?.averageTime||r?.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:r?.lastUpdateTime||0}})}}}class Et{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(e){const t=n.deltaTime,s=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,a=s>0?o/s*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:s,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 bt{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 Tt{constructor(){this._pools=new Map,this._usageTracker=new Map,this._autoCleanupInterval=6e4,this._lastCleanupTime=0}static getInstance(){return Tt._instance||(Tt._instance=new Tt),Tt._instance}registerPool(e,t,n,s,i){this._pools.set(e,new bt(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 wt{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=I(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=Tt.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(wt.componentSizeCache.has(e))return wt.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=>I(t)===e);if(n){s=this.calculateQuickObjectSize(n);break}}}catch(e){s=64}return wt.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=>I(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(){wt.componentSizeCache.clear()}}wt.componentSizeCache=new Map;class It{constructor(){this.sceneStartTime=Date.now()}collectSceneData(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneUptime:0};const t=(Date.now()-this.sceneStartTime)/1e3,n=e.getStats();return{currentSceneName:e.name||"Unnamed Scene",isInitialized:!0,sceneRunTime:t,sceneEntityCount:n.entityCount,sceneSystemCount:n.processorCount,sceneUptime:t}}setSceneStartTime(e){this.sceneStartTime=e}}class Mt{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)}}!function(e){e.ECS="ECS",e.Rendering="Rendering",e.Physics="Physics",e.Audio="Audio",e.Network="Network",e.Script="Script",e.Memory="Memory",e.Animation="Animation",e.AI="AI",e.Input="Input",e.Loading="Loading",e.Custom="Custom"}(gt||(gt={}));const At={enabled:!1,maxFrameHistory:300,maxSampleDepth:32,collectMemory:!0,memorySampleInterval:100,detectLongTasks:!0,longTaskThreshold:50,enabledCategories:new Set(Object.values(gt))};let kt=0;class Dt{constructor(e){this.currentFrame=null,this.frameHistory=[],this.frameNumber=0,this.activeSamples=new Map,this.sampleStack=[],this.counters=new Map,this.callGraph=new Map,this.gcCount=0,this.previousHeapSize=0,this.longTasks=[],this.performanceObserver=null,this._config={...At,...e},this._config.detectLongTasks&&this._setupLongTaskObserver()}static getInstance(e){return Dt._instance||(Dt._instance=new Dt(e)),Dt._instance}static resetInstance(){Dt._instance&&(Dt._instance.dispose(),Dt._instance=null)}static beginSample(e,t=gt.Custom){return Dt.getInstance().beginSample(e,t)}static endSample(e){e&&Dt.getInstance().endSample(e)}static measure(e,t,n=gt.Custom){return Dt.getInstance().measure(e,t,n)}static async measureAsync(e,t,n=gt.Custom){return Dt.getInstance().measureAsync(e,t,n)}static beginFrame(){Dt.getInstance().beginFrame()}static endFrame(){Dt.getInstance().endFrame()}static incrementCounter(e,t=1,n=gt.Custom){Dt.getInstance().incrementCounter(e,t,n)}static setGauge(e,t,n=gt.Custom){Dt.getInstance().setGauge(e,t,n)}static setEnabled(e){Dt.getInstance().setEnabled(e)}static isEnabled(){return Dt.getInstance()._config.enabled}static getCurrentFrame(){return Dt.getInstance().currentFrame}static getFrameHistory(){return Dt.getInstance().frameHistory}static getReport(e){return Dt.getInstance().generateReport(e)}static reset(){Dt.getInstance().reset()}beginSample(e,t=gt.Custom){if(!this._config.enabled||!this._config.enabledCategories.has(t))return null;const n=this.sampleStack.length>0?this.sampleStack[this.sampleStack.length-1]:void 0;if(n&&this.sampleStack.length>=this._config.maxSampleDepth)return null;const s={id:`sample_${++kt}_${Date.now()}`,name:e,category:t,startTime:performance.now(),depth:this.sampleStack.length,parentId:n?.id};return this.activeSamples.set(s.id,s),this.sampleStack.push(s),s}endSample(e){if(!this._config.enabled||!this.activeSamples.has(e.id))return;const t=performance.now(),n=t-e.startTime,s=e.parentId?this.activeSamples.get(e.parentId):void 0,i={id:e.id,name:e.name,category:e.category,startTime:e.startTime,endTime:t,duration:n,selfTime:n,parentId:e.parentId,parentName:s?.name,depth:e.depth,callCount:1};this.currentFrame&&this.currentFrame.samples.push(i),this._updateCallGraph(e.name,e.category,n,s),this.activeSamples.delete(e.id);const r=this.sampleStack.indexOf(e);-1!==r&&this.sampleStack.splice(r,1)}measure(e,t,n=gt.Custom){const s=this.beginSample(e,n);try{return t()}finally{s&&this.endSample(s)}}async measureAsync(e,t,n=gt.Custom){const s=this.beginSample(e,n);try{return await t()}finally{s&&this.endSample(s)}}beginFrame(){this._config.enabled&&(this.frameNumber++,this.currentFrame={frameNumber:this.frameNumber,startTime:performance.now(),endTime:0,duration:0,samples:[],sampleStats:[],counters:new Map(this.counters),memory:this._captureMemory(),categoryStats:new Map},this._resetFrameCounters())}endFrame(){if(this._config.enabled&&this.currentFrame){for(this.currentFrame.endTime=performance.now(),this.currentFrame.duration=this.currentFrame.endTime-this.currentFrame.startTime,this._calculateSampleStats(),this._calculateCategoryStats(),this.frameHistory.push(this.currentFrame);this.frameHistory.length>this._config.maxFrameHistory;)this.frameHistory.shift();this.sampleStack=[],this.activeSamples.clear()}}incrementCounter(e,t=1,n=gt.Custom){if(!this._config.enabled)return;let s=this.counters.get(e);s||(s={name:e,category:n,value:0,type:"counter",history:[]},this.counters.set(e,s)),s.value+=t,s.history.push({time:performance.now(),value:s.value}),s.history.length>100&&s.history.shift()}setGauge(e,t,n=gt.Custom){if(!this._config.enabled)return;let s=this.counters.get(e);s||(s={name:e,category:n,value:0,type:"gauge",history:[]},this.counters.set(e,s)),s.value=t,s.history.push({time:performance.now(),value:t}),s.history.length>100&&s.history.shift()}setEnabled(e){this._config.enabled=e,e&&this._config.detectLongTasks&&!this.performanceObserver&&this._setupLongTaskObserver()}reset(){this.frameHistory=[],this.currentFrame=null,this.frameNumber=0,this.activeSamples.clear(),this.sampleStack=[],this.counters.clear(),this.callGraph.clear(),this.gcCount=0,this.longTasks=[]}generateReport(e){const t=e?this.frameHistory.slice(-e):this.frameHistory;if(0===t.length)return this._createEmptyReport();const n=t.map(e=>e.duration),s=[...n].sort((e,t)=>e-t),i=this._aggregateSampleStats(t).sort((e,t)=>t.inclusiveTime-e.inclusiveTime).slice(0,20),r=this._aggregateCategoryStats(t),o=this._buildCallGraphFromFrames(t),a=t[0],c=t[t.length-1];return{startTime:a?.startTime??0,endTime:c?.endTime??0,totalFrames:t.length,averageFrameTime:n.reduce((e,t)=>e+t,0)/n.length,minFrameTime:Math.min(...n),maxFrameTime:Math.max(...n),p95FrameTime:s[Math.floor(.95*s.length)]||0,p99FrameTime:s[Math.floor(.99*s.length)]||0,hotspots:i,callGraph:o,categoryBreakdown:r,memoryTrend:t.map(e=>e.memory),longTasks:[...this.longTasks]}}_buildCallGraphFromFrames(e){const t=new Map;for(const n of e)for(const e of n.samples){let n=t.get(e.name);if(n||(n={category:e.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},t.set(e.name,n)),n.callCount++,n.totalTime+=e.duration,e.parentName){const s=n.callers.get(e.parentName)||{count:0,totalTime:0};s.count++,s.totalTime+=e.duration,n.callers.set(e.parentName,s);let i=t.get(e.parentName);i||(i={category:e.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},t.set(e.parentName,i));const r=i.callees.get(e.name)||{count:0,totalTime:0};r.count++,r.totalTime+=e.duration,i.callees.set(e.name,r)}}const n=new Map;for(const[e,s]of t){const t=new Map;for(const[e,n]of s.callers)t.set(e,{count:n.count,totalTime:n.count>0?n.totalTime/n.count:0});const i=new Map;for(const[e,t]of s.callees)i.set(e,{count:t.count,totalTime:t.count>0?t.totalTime/t.count:0});n.set(e,{name:e,category:s.category,callCount:s.callCount,totalTime:s.callCount>0?s.totalTime/s.callCount:0,callers:t,callees:i})}return n}getCallGraph(){return new Map(this.callGraph)}getFunctionCallInfo(e){const t=this.callGraph.get(e);return t?{callers:Array.from(t.callers.entries()).map(([e,t])=>({name:e,...t})),callees:Array.from(t.callees.entries()).map(([e,t])=>({name:e,...t}))}:null}dispose(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.reset()}_captureMemory(){const e=performance.now();let t=0,n=0,s=0;const i=performance;return i.memory&&(t=i.memory.usedJSHeapSize||0,n=i.memory.totalJSHeapSize||0,s=i.memory.jsHeapSizeLimit||0,this.previousHeapSize>0&&t<this.previousHeapSize-1048576&&this.gcCount++,this.previousHeapSize=t),{timestamp:e,usedHeapSize:t,totalHeapSize:n,heapSizeLimit:s,utilizationPercent:s>0?t/s*100:0,gcCount:this.gcCount}}_resetFrameCounters(){for(const e of this.counters.values())"counter"===e.type&&(e.value=0)}_calculateSampleStats(){if(!this.currentFrame)return;const e=new Map;for(const t of this.currentFrame.samples){let n=e.get(t.name);n||(n={name:t.name,category:t.category,inclusiveTime:0,exclusiveTime:0,callCount:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,percentOfFrame:0,percentOfParent:0,children:[],depth:t.depth},e.set(t.name,n)),n.inclusiveTime+=t.duration,n.callCount+=1,n.minTime=Math.min(n.minTime,t.duration),n.maxTime=Math.max(n.maxTime,t.duration)}for(const t of this.currentFrame.samples)if(t.parentId){const n=this.currentFrame.samples.find(e=>e.id===t.parentId);if(n){const t=e.get(n.name);if(t){t.exclusiveTime=t.inclusiveTime;for(const e of this.currentFrame.samples)e.parentId===n.id&&(t.exclusiveTime-=e.duration)}}}const t=this.currentFrame.duration||1;for(const n of e.values())n.averageTime=n.inclusiveTime/n.callCount,n.percentOfFrame=n.inclusiveTime/t*100,0===n.exclusiveTime&&(n.exclusiveTime=n.inclusiveTime);this.currentFrame.sampleStats=Array.from(e.values()).sort((e,t)=>t.inclusiveTime-e.inclusiveTime)}_calculateCategoryStats(){if(!this.currentFrame)return;const e=new Map;for(const t of this.currentFrame.samples)if(0===t.depth){let n=e.get(t.category);n||(n={totalTime:0,sampleCount:0},e.set(t.category,n)),n.totalTime+=t.duration,n.sampleCount+=1}const t=this.currentFrame.duration||1;for(const[n,s]of e)this.currentFrame.categoryStats.set(n,{...s,percentOfFrame:s.totalTime/t*100})}_updateCallGraph(e,t,n,s){let i=this.callGraph.get(e);if(i||(i={name:e,category:t,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(e,i)),i.callCount++,i.totalTime+=n,s){const t=i.callers.get(s.name)||{count:0,totalTime:0};t.count++,t.totalTime+=n,i.callers.set(s.name,t);let r=this.callGraph.get(s.name);r||(r={name:s.name,category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(s.name,r));const o=r.callees.get(e)||{count:0,totalTime:0};o.count++,o.totalTime+=n,r.callees.set(e,o)}}_aggregateSampleStats(e){const t=new Map;for(const n of e)for(const e of n.sampleStats){let n=t.get(e.name);n?(n.inclusiveTime+=e.inclusiveTime,n.exclusiveTime+=e.exclusiveTime,n.callCount+=e.callCount,n.minTime=Math.min(n.minTime,e.minTime),n.maxTime=Math.max(n.maxTime,e.maxTime)):(n={...e,minTime:Number.MAX_VALUE},t.set(e.name,n))}const n=e.reduce((e,t)=>e+t.duration,0);for(const e of t.values())e.averageTime=e.inclusiveTime/e.callCount,e.percentOfFrame=e.inclusiveTime/n*100;return Array.from(t.values())}_aggregateCategoryStats(e){const t=new Map;for(const n of e)for(const[e,s]of n.categoryStats){let n=t.get(e);n||(n={totalTime:0,frameCount:0},t.set(e,n)),n.totalTime+=s.totalTime,n.frameCount++}const n=e.reduce((e,t)=>e+t.duration,0),s=new Map;for(const[e,i]of t)s.set(e,{totalTime:i.totalTime,averageTime:i.frameCount>0?i.totalTime/i.frameCount:0,percentOfTotal:n>0?i.totalTime/n*100:0});return s}_setupLongTaskObserver(){if("undefined"!=typeof PerformanceObserver)try{this.performanceObserver=new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>this._config.longTaskThreshold&&(this.longTasks.push({startTime:t.startTime,duration:t.duration,attribution:t.attribution?.map(e=>e.name)||[]}),this.longTasks.length>100&&this.longTasks.shift())}),this.performanceObserver.observe({entryTypes:["longtask"]})}catch{}}_createEmptyReport(){return{startTime:0,endTime:0,totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,hotspots:[],callGraph:new Map,categoryBreakdown:new Map,memoryTrend:[],longTasks:[]}}}Dt._instance=null;class xt{constructor(){this.selectedFunction=null,this.peakMemory=0}setSelectedFunction(e){this.selectedFunction=e}collectAdvancedData(e){const t=Dt.getFrameHistory(),n=Dt.getCurrentFrame(),s=Dt.getReport(300),i=n?.memory||this.getDefaultMemory();return i.usedHeapSize>this.peakMemory&&(this.peakMemory=i.usedHeapSize),{currentFrame:this.buildCurrentFrameData(n),frameTimeHistory:this.buildFrameTimeHistory(t),categoryStats:this.buildCategoryStats(n,e),hotspots:this.buildHotspots(s),callGraph:this.buildCallGraph(s),longTasks:s.longTasks,memoryTrend:this.buildMemoryTrend(s.memoryTrend),summary:this.buildSummary(s,i)}}collectFromLegacyMonitor(e){if(!e)return this.createEmptyData();const t=e.getAllSystemStats?.()||new Map,s=e.getAllSystemData?.()||new Map,i=1e3*n.deltaTime,r=i>0?Math.round(1e3/i):0,o=this.buildCategoryStatsFromLegacy(t,s,i),a=this.buildHotspotsFromLegacy(t,s,i);return{currentFrame:{frameNumber:0,frameTime:i,fps:r,memory:this.getCurrentMemory()},frameTimeHistory:[],categoryStats:o,hotspots:a,callGraph:{currentFunction:this.selectedFunction,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:i,minFrameTime:i,maxFrameTime:i,p95FrameTime:i,p99FrameTime:i,currentMemoryMB:this.getCurrentMemory().usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:0,longTaskCount:0}}}buildCurrentFrameData(e){if(!e){const e=1e3*n.deltaTime;return{frameNumber:0,frameTime:e,fps:e>0?Math.round(1e3/e):0,memory:this.getCurrentMemory()}}return{frameNumber:e.frameNumber,frameTime:e.duration,fps:e.duration>0?Math.round(1e3/e.duration):0,memory:e.memory}}buildFrameTimeHistory(e){return e.map(e=>({frameNumber:e.frameNumber,time:e.startTime,duration:e.duration}))}buildCategoryStats(e,t){const s=[];if(e&&e.categoryStats.size>0){const t=e.duration||1;for(const[n,i]of e.categoryStats){const r=e.sampleStats.filter(e=>e.category===n).map(e=>({name:e.name,inclusiveTime:e.inclusiveTime,exclusiveTime:e.exclusiveTime,callCount:e.callCount,percentOfCategory:i.totalTime>0?e.inclusiveTime/i.totalTime*100:0,percentOfFrame:e.inclusiveTime/t*100})).sort((e,t)=>t.inclusiveTime-e.inclusiveTime);s.push({category:n,totalTime:i.totalTime,percentOfFrame:i.percentOfFrame,sampleCount:i.sampleCount,items:r})}}if(t&&0===s.length){const e=t.getAllSystemStats?.()||new Map,s=t.getAllSystemData?.()||new Map,i=1e3*n.deltaTime||1;return this.buildCategoryStatsFromLegacy(e,s,i)}return s.sort((e,t)=>t.totalTime-e.totalTime)}buildCategoryStatsFromLegacy(e,t,n){const s=[];let i=0;for(const[r,o]of e.entries()){const e=t.get(r),a=e?.executionTime||o?.averageTime||0;i+=a,s.push({name:r,inclusiveTime:a,exclusiveTime:a,callCount:1,percentOfCategory:0,percentOfFrame:n>0?a/n*100:0})}for(const e of s)e.percentOfCategory=i>0?e.inclusiveTime/i*100:0;return s.sort((e,t)=>t.inclusiveTime-e.inclusiveTime),0===s.length?[]:[{category:gt.ECS,totalTime:i,percentOfFrame:n>0?i/n*100:0,sampleCount:s.length,items:s}]}buildHotspots(e){const t=e.hotspots.reduce((e,t)=>e+t.inclusiveTime,0)||1,n=new Set,s=new Set;for(const[t,i]of e.callGraph)if(0===i.callers.size)n.add(t);else{let r=!1;for(const n of i.callers.keys())if(e.callGraph.has(n)){r=!0,s.add(t);break}r||n.add(t)}const i=(n,s,r)=>{if(r.has(n))return null;r.add(n);const o=e.hotspots.find(e=>e.name===n),a=e.callGraph.get(n);if(!o&&!a)return null;const c=o?.inclusiveTime||a?.totalTime||0,h=o?.exclusiveTime||c,l=o?.callCount||a?.callCount||1,d=[];if(a&&s<5){for(const[e]of a.callees){const t=i(e,s+1,r);t&&d.push(t)}d.sort((e,t)=>t.inclusiveTime-e.inclusiveTime)}return{name:n,category:o?.category||a?.category||gt.Custom,inclusiveTime:c,inclusiveTimePercent:c/t*100,exclusiveTime:h,exclusiveTimePercent:h/t*100,callCount:l,avgCallTime:l>0?c/l:0,depth:s,children:d.length>0?d:void 0}},r=[],o=new Set;for(const e of n){const t=i(e,0,o);t&&r.push(t)}return r.sort((e,t)=>t.inclusiveTime-e.inclusiveTime),r.slice(0,50)}buildHotspotsFromLegacy(e,t,n){const s=[];for(const[i,r]of e.entries()){const e=t.get(i),o=e?.executionTime||r?.averageTime||0;s.push({name:i,category:gt.ECS,inclusiveTime:o,inclusiveTimePercent:n>0?o/n*100:0,exclusiveTime:o,exclusiveTimePercent:n>0?o/n*100:0,callCount:r?.executionCount||1,avgCallTime:r?.averageTime||o,depth:0})}return s.sort((e,t)=>t.inclusiveTime-e.inclusiveTime).slice(0,50)}buildCallGraph(e){if(!this.selectedFunction)return{currentFunction:null,callers:[],callees:[]};const t=e.callGraph.get(this.selectedFunction);if(!t)return{currentFunction:this.selectedFunction,callers:[],callees:[]};let n=0;for(const e of t.callers.values())n+=e.count;const s=Array.from(t.callers.entries()).map(([e,t])=>({name:e,callCount:t.count,totalTime:t.totalTime,percentOfCurrent:n>0?t.count/n*100:0})).sort((e,t)=>t.callCount-e.callCount),i=Array.from(t.callees.entries()).map(([e,n])=>({name:e,callCount:n.count,totalTime:n.totalTime,percentOfCurrent:t.totalTime>0?n.totalTime/t.totalTime*100:0})).sort((e,t)=>t.totalTime-e.totalTime);return{currentFunction:this.selectedFunction,callers:s,callees:i}}buildMemoryTrend(e){return e.map(e=>({time:e.timestamp,usedMB:e.usedHeapSize/1048576,totalMB:e.totalHeapSize/1048576,gcCount:e.gcCount}))}buildSummary(e,t){return{totalFrames:e.totalFrames,averageFrameTime:e.averageFrameTime,minFrameTime:e.minFrameTime,maxFrameTime:e.maxFrameTime,p95FrameTime:e.p95FrameTime,p99FrameTime:e.p99FrameTime,currentMemoryMB:t.usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:t.gcCount,longTaskCount:e.longTasks.length}}getCurrentMemory(){const e=performance,t=e.memory?.usedJSHeapSize||0,n=e.memory?.totalJSHeapSize||0,s=e.memory?.jsHeapSizeLimit||0;return{timestamp:performance.now(),usedHeapSize:t,totalHeapSize:n,heapSizeLimit:s,utilizationPercent:s>0?t/s*100:0,gcCount:0}}getDefaultMemory(){return{timestamp:performance.now(),usedHeapSize:0,totalHeapSize:0,heapSizeLimit:0,utilizationPercent:0,gcCount:0}}createEmptyData(){return{currentFrame:{frameNumber:0,frameTime:0,fps:0,memory:this.getDefaultMemory()},frameTimeHistory:[],categoryStats:[],hotspots:[],callGraph:{currentFunction:null,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,currentMemoryMB:0,peakMemoryMB:0,gcCount:0,longTaskCount:0}}}}function Ot(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}(e)}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}()}function Pt(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}const Rt="00000000-0000-0000-0000-000000000000",zt=28,Nt=20,Ft=268435455,Bt=1048575,$t=1<<28,Lt=1<<20,Wt=0;function Ht(e,t){return(t&Bt)*$t+(e&Ft)}function Ut(e){return e&Ft}function Gt(e){return Math.floor(e/$t)&Bt}function qt(e){return 0!==e}function jt(e,t){return e===t}function Vt(e){return 0===e?"Entity(NULL)":`Entity(idx=${Ut(e)}, gen=${Gt(e)})`}var Qt,Yt;!function(e){e.ENTITY_CREATED="entity:created",e.ENTITY_DESTROYED="entity:destroyed",e.ENTITY_ENABLED="entity:enabled",e.ENTITY_DISABLED="entity:disabled",e.ENTITY_TAG_ADDED="entity:tag:added",e.ENTITY_TAG_REMOVED="entity:tag:removed",e.ENTITY_NAME_CHANGED="entity:name:changed",e.COMPONENT_ADDED="component:added",e.COMPONENT_REMOVED="component:removed",e.COMPONENT_MODIFIED="component:modified",e.COMPONENT_ENABLED="component:enabled",e.COMPONENT_DISABLED="component:disabled",e.SYSTEM_ADDED="system:added",e.SYSTEM_REMOVED="system:removed",e.SYSTEM_ENABLED="system:enabled",e.SYSTEM_DISABLED="system:disabled",e.SYSTEM_PROCESSING_START="system:processing:start",e.SYSTEM_PROCESSING_END="system:processing:end",e.SYSTEM_ERROR="system:error",e.SCENE_CREATED="scene:created",e.SCENE_DESTROYED="scene:destroyed",e.SCENE_ACTIVATED="scene:activated",e.SCENE_DEACTIVATED="scene:deactivated",e.SCENE_PAUSED="scene:paused",e.SCENE_RESUMED="scene:resumed",e.QUERY_EXECUTED="query:executed",e.QUERY_CACHE_HIT="query:cache:hit",e.QUERY_CACHE_MISS="query:cache:miss",e.QUERY_OPTIMIZED="query:optimized",e.PERFORMANCE_WARNING="performance:warning",e.PERFORMANCE_CRITICAL="performance:critical",e.MEMORY_USAGE_HIGH="memory:usage:high",e.FRAME_RATE_DROP="frame:rate:drop",e.INDEX_CREATED="index:created",e.INDEX_UPDATED="index:updated",e.INDEX_OPTIMIZED="index:optimized",e.ARCHETYPE_CREATED="archetype:created",e.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",e.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",e.DIRTY_MARK_ADDED="dirty:mark:added",e.DIRTY_BATCH_PROCESSED="dirty:batch:processed",e.ERROR_OCCURRED="error:occurred",e.WARNING_ISSUED="warning:issued",e.FRAMEWORK_INITIALIZED="framework:initialized",e.FRAMEWORK_SHUTDOWN="framework:shutdown",e.DEBUG_INFO="debug:info",e.DEBUG_STATS_UPDATED="debug:stats:updated"}(Qt||(Qt={})),function(e){e[e.LOWEST=0]="LOWEST",e[e.LOW=25]="LOW",e[e.NORMAL=50]="NORMAL",e[e.HIGH=75]="HIGH",e[e.HIGHEST=100]="HIGHEST",e[e.CRITICAL=200]="CRITICAL"}(Yt||(Yt={}));const Jt={ENTITY:{CREATED:Qt.ENTITY_CREATED,DESTROYED:Qt.ENTITY_DESTROYED,ENABLED:Qt.ENTITY_ENABLED,DISABLED:Qt.ENTITY_DISABLED,TAG_ADDED:Qt.ENTITY_TAG_ADDED,TAG_REMOVED:Qt.ENTITY_TAG_REMOVED,NAME_CHANGED:Qt.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:Qt.COMPONENT_ADDED,REMOVED:Qt.COMPONENT_REMOVED,MODIFIED:Qt.COMPONENT_MODIFIED,ENABLED:Qt.COMPONENT_ENABLED,DISABLED:Qt.COMPONENT_DISABLED},SYSTEM:{ADDED:Qt.SYSTEM_ADDED,REMOVED:Qt.SYSTEM_REMOVED,ENABLED:Qt.SYSTEM_ENABLED,DISABLED:Qt.SYSTEM_DISABLED,PROCESSING_START:Qt.SYSTEM_PROCESSING_START,PROCESSING_END:Qt.SYSTEM_PROCESSING_END,ERROR:Qt.SYSTEM_ERROR},PERFORMANCE:{WARNING:Qt.PERFORMANCE_WARNING,CRITICAL:Qt.PERFORMANCE_CRITICAL,MEMORY_HIGH:Qt.MEMORY_USAGE_HIGH,FRAME_DROP:Qt.FRAME_RATE_DROP}};class Zt{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)}}Zt.validTypes=new Set([...Object.values(Qt),...Object.values(Jt.ENTITY),...Object.values(Jt.COMPONENT),...Object.values(Jt.SYSTEM),...Object.values(Jt.PERFORMANCE)]);class Xt{constructor(e,t,n){this._handle=0,this.scene=null,this._isDestroyed=!1,this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=R.clone(R.ZERO),this._componentCache=null,this._lifecyclePolicy=0,this.name=e,this.id=t,this.persistentId=n??Ot()}get lifecyclePolicy(){return this._lifecyclePolicy}get isPersistent(){return 1===this._lifecyclePolicy}get handle(){return this._handle}setHandle(e){this._handle=e}setPersistent(){return this._lifecyclePolicy=1,this}setSceneLocal(){return this._lifecyclePolicy=0,this}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=this.scene.componentRegistry,s=n.getRegisteredCount();for(let i=0;i<s;i++)if(R.getBit(t,i)){const t=n.getTypeByBitIndex(i);if(t){const n=this.scene.componentStorageManager.getComponent(this.id,t);n&&e.push(n)}}this._componentCache=e}get active(){return this._active}set active(e){this._active!==e&&(this._active=e,this.onActiveChanged())}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,n=(this.scene?.componentRegistry??j).getBitMask(t);return R.orInPlace(this._componentMask,n),this._componentCache=null,e}notifyQuerySystems(e){this.scene?.querySystem&&(this.scene.querySystem.updateEntity(this),this.scene.clearSystemEntityCaches(),this.scene.notifyEntityComponentChanged?.(this,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 ${w(t)}`);return this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,this.scene.referenceTracker?.registerEntityScene(this.id,this.scene),this.scene.isEditorMode?this.scene.queueDeferredComponentCallback(()=>e.onAddedToEntity()):e.onAddedToEntity(),this.scene.eventSystem&&this.scene.eventSystem.emitSync(Qt.COMPONENT_ADDED,{timestamp:Date.now(),source:"Entity",entity:this,entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:w(t),component:e}),this.notifyQuerySystems(t),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){const t=this.scene?.componentRegistry??j;if(!t.isRegistered(e))return!1;const n=t.getBitMask(e);return R.hasAny(this._componentMask,n)}getOrCreateComponent(e,...t){let n=this.getComponent(e);return n||(n=this.createComponent(e,...t)),n}markDirty(...e){if(!this.scene)return;const t=this.scene.epochManager.current;for(const n of e)n.markDirty(t)}removeComponent(e){const t=e.constructor,n=this.scene?.componentRegistry??j;if(!n.isRegistered(t))return;const s=n.getBitIndex(t);R.clearBit(this._componentMask,s),this._componentCache=null,this.scene?.componentStorageManager?.removeComponent(this.id,t),this.scene?.referenceTracker?.clearComponentReferences(e),e.onRemovedFromEntity?.(),e.entityId=null,this.scene?.eventSystem&&this.scene.eventSystem.emitSync(Qt.COMPONENT_REMOVED,{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:w(t),component:e}),this.notifyQuerySystems(t)}removeComponentByType(e){const t=this.getComponent(e);return t?(this.removeComponent(t),t):null}removeAllComponents(){const e=[...this.components];R.clear(this._componentMask),this._componentCache=null;for(const t of e){const e=t.constructor;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){Xt._logger.warn(`添加组件失败 ${I(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}onActiveChanged(){if(this.scene?.eventSystem){const e=this._active?Qt.ENTITY_ENABLED:Qt.ENTITY_DISABLED;this.scene.eventSystem.emitSync(e,{entity:this,scene:this.scene})}}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.scene?.eventSystem&&this.scene.eventSystem.emitSync(Qt.ENTITY_DESTROYED,{entity:this,entityId:this.id,scene:this.scene}),this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id)),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this)))}compareTo(e){return n=e,(t=this).updateOrder-n.updateOrder||t.id-n.id;var t,n}toString(){return`Entity[${this.name}:${this.id}:${this.persistentId.slice(0,8)}]`}getDebugInfo(){return{name:this.name,id:this.id,persistentId:this.persistentId,enabled:this._enabled,active:this._active,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map(e=>I(e)),componentMask:R.toString(this._componentMask,2),cacheBuilt:null!==this._componentCache}}}Xt._logger=$("Entity");class Kt{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();for(const t of this._entitiesToAdd)e.push(t.id),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))}}}reorderEntity(e,t){const n=this._idToEntity.get(e);if(!n)return;const s=this.buffer.indexOf(n);if(-1===s||s===t)return;const i=Math.max(0,Math.min(t,this.buffer.length-1));this.buffer.splice(s,1),this.buffer.splice(i,0,n)}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 en{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>en.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${en.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:en.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>en.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<=en.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}}en.MAX_INDEX=65535,en.MAX_GENERATION=65535;class tn{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){tn._logger.error(`Error in processor ${se(e)}:`,t)}this._isDirty=!1,this._processors.length=0}update(){this.sortProcessors();for(const e of this._processors)try{e.update()}catch(t){tn._logger.error(`Error in processor ${se(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}}tn._logger=$("EntityProcessorList");class nn{constructor(e){if(e&&"object"==typeof e)this._value=R.clone(e);else if("number"==typeof e)this._value=R.fromNumber(e);else if("string"==typeof e){const t=parseInt(e,10);this._value=R.fromNumber(t)}else this._value=R.clone(R.ZERO)}set(e){if(e<0)throw new Error("Bit index cannot be negative");R.setBit(this._value,e)}clear(e){if(e<0)throw new Error("Bit index cannot be negative");R.clearBit(this._value,e)}get(e){return R.getBit(this._value,e)}containsAll(e){return R.hasAll(this._value,e._value)}intersects(e){return R.hasAny(this._value,e._value)}excludes(e){return R.hasNone(this._value,e._value)}clearAll(){R.clear(this._value)}isEmpty(){return R.isZero(this._value)}cardinality(){return R.popCount(this._value)}and(e){const t=new nn;return R.copy(this._value,t._value),R.andInPlace(t._value,e._value),t}or(e){const t=new nn;return R.copy(this._value,t._value),R.orInPlace(t._value,e._value),t}xor(e){const t=new nn;return R.copy(this._value,t._value),R.xorInPlace(t._value,e._value),t}not(e=64){e>64&&(e=64);const t=new nn;if(R.copy(this._value,t._value),e<=32){const n=(1<<e)-1;t._value.base[O.LOW]=~t._value.base[O.LOW]&n,t._value.base[O.HIGH]=0}else if(t._value.base[O.LOW]=~t._value.base[O.LOW],e<64){const n=(1<<e-32)-1;t._value.base[O.HIGH]=~t._value.base[O.HIGH]&n}else t._value.base[O.HIGH]=~t._value.base[O.HIGH];return t}copyFrom(e){R.copy(e._value,this._value)}clone(){return new nn(this._value)}getValue(){return this._value}setValue(e){if("object"==typeof e)R.copy(e,this._value);else if("number"==typeof e)this._value=R.fromNumber(e);else{const t=parseInt(e,10);this._value=R.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 R.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 nn(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 nn(n)}equals(e){return R.equals(this._value,e._value)}getHighestBitIndex(){if(R.isZero(this._value))return-1;if(0!==this._value.base[O.HIGH])for(let e=31;e>=0;e--)if(this._value.base[O.HIGH]&1<<e)return e+32;for(let e=31;e>=0;e--)if(this._value.base[O.LOW]&1<<e)return e;return-1}getLowestBitIndex(){if(R.isZero(this._value))return-1;for(let e=0;e<32;e++)if(this._value.base[O.LOW]&1<<e)return e;for(let e=0;e<32;e++)if(this._value.base[O.HIGH]&1<<e)return e+32;return-1}}class sn{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 rn extends Set{constructor(...e){super()}reset(){this.clear()}}class on{constructor(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new sn}addEntity(e){this._entities.has(e)&&this.removeEntity(e);const t=R.clone(R.ZERO),n=new Set;for(const s of e.components){const e=s.constructor;n.add(e);const i=j.getBitMask(e);R.orInPlace(t,i)}this._entities.add(e);const s=this._entities.getIndex(e);for(;this._componentMasks.length<=s;)this._componentMasks.push(R.clone(R.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=R.clone(R.ZERO);for(const n of e){if(!j.isRegistered(n))return new Set;const e=j.getBitMask(n);R.orInPlace(t,e)}const n=on._entitySetPool.obtain();return this._entities.forEach((e,s)=>{const i=this._componentMasks[s];R.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=R.clone(R.ZERO);for(const n of e)if(j.isRegistered(n)){const e=j.getBitMask(n);R.orInPlace(t,e)}if(R.equals(t,R.ZERO))return new Set;const n=on._entitySetPool.obtain();return this._entities.forEach((e,s)=>{const i=this._componentMasks[s];R.hasAny(i,t)&&n.add(e)}),n}hasComponent(e,t){const n=this._entities.getIndex(e);if(void 0===n)return!1;if(!j.isRegistered(t))return!1;const s=this._componentMasks[n],i=j.getBitMask(t);return R.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())on._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=on._entitySetPool.obtain(),this._componentToEntities.set(s,t)),t.add(e)):t&&(t.delete(e),0===t.size&&(this._componentToEntities.delete(s),on._entitySetPool.release(t)))}}}on._entitySetPool=S.getPool(rn,50,512);class an{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 cn{constructor(){this._archetypes=new an,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)R.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=R.clone(R.ZERO);for(const n of e){const e=j.getBitMask(n);R.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}}var hn;!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(hn||(hn={}));const ln=$("ReactiveQuery");var dn;!function(e){e.ADDED="added",e.REMOVED="removed",e.BATCH_UPDATE="batch_update"}(dn||(dn={}));class un{constructor(e,t={}){this._entities=[],this._entityIdSet=new Set,this._snapshot=null,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&&ln.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&&ln.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 null!==this._snapshot||(this._snapshot=[...this._entities]),this._snapshot}get count(){return this._entities.length}matches(e){const t=e.componentMask;switch(this._condition.type){case hn.ALL:return R.hasAll(t,this._condition.mask);case hn.ANY:return R.hasAny(t,this._condition.mask);case hn.NONE:return R.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._snapshot=null,this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:dn.ADDED,entity:e}),this._config.debug&&ln.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._snapshot=null,this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:dn.REMOVED,entity:e}),this._config.debug&&ln.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(),this._snapshot=null;for(const t of e)this.matches(t)&&(this._entities.push(t),this._entityIdSet.add(t.id));this._config.debug&&ln.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:dn.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&ln.debug(`ReactiveQuery ${this._id}: 批量更新 +${e.length} -${t.length}`)}notifyListeners(e){const t=[...this._listeners];for(const n of t)try{n(e)}catch(e){ln.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._snapshot=null,this._config.debug&&ln.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 mn{constructor(e,...t){this._lastVersion=-1,this._cachedEntities=[],this._querySystem=e,this._componentTypes=t}get componentTypes(){return this._componentTypes}get entities(){return this._refreshCache(),this._cachedEntities}get count(){return this.entities.length}_refreshCache(){const e=this._querySystem.version;if(this._lastVersion!==e){const t=this._querySystem.queryAll(...this._componentTypes);this._cachedEntities=t.entities,this._lastVersion=e}}forEach(e){const t=this.entities,n=this._componentTypes,s=n.length;for(let i=0,r=t.length;i<r;i++){const r=t[i],o=new Array(s);for(let e=0;e<s;e++){const t=r.getComponent(n[e]);t&&(o[e]=t)}e(r,...o)}}forEachChanged(e,t){const n=this.entities,s=this._componentTypes,i=s.length;for(let r=0,o=n.length;r<o;r++){const o=n[r],a=new Array(i);let c=!1;for(let t=0;t<i;t++){const n=o.getComponent(s[t]);n&&(a[t]=n,n.lastWriteEpoch>e&&(c=!0))}c&&t(o,...a)}}first(){const e=this.entities;if(0===e.length)return null;const t=e[0],n=[];for(const e of this._componentTypes){const s=t.getComponent(e);if(!s)return null;n.push(s)}return[t,...n]}toArray(){const e=[];return this.forEach((t,...n)=>{e.push([t,...n])}),e}map(e){const t=[];return this.forEach((n,...s)=>{t.push(e(n,...s))}),t}filter(e){const t=[];return this.forEach((n,...s)=>{e(n,...s)&&t.push(n)}),t}find(e){const t=this.entities,n=this._componentTypes,s=n.length;for(let i=0,r=t.length;i<r;i++){const r=t[i],o=new Array(s);for(let e=0;e<s;e++){const t=r.getComponent(n[e]);t&&(o[e]=t)}if(e(r,...o))return r}}any(){return this.count>0}empty(){return 0===this.count}}class pn{constructor(){this._logger=$("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 cn}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(hn.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(hn.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(hn.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}}queryChangedSince(e,...t){const n=performance.now();this._queryStats.totalQueries++,this._queryStats.dirtyChecks++;const s=this.queryAll(...t),i=[];for(const n of s.entities){let s=!1;for(const i of t){const t=n.getComponent(i);if(t&&t.lastWriteEpoch>e){s=!0;break}}s&&i.push(n)}return{entities:i,count:i.length,executionTime:performance.now()-n,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}:${w(t[0])}`}return`${e}:${t.map(e=>w(e)).sort().join(",")}`}clearCache(){this.clearQueryCache(),this.clearReactiveQueries()}compile(...e){return new mn(this,...e)}createReactiveQuery(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");const n=this.createComponentMask(e),s={type:hn.ALL,componentTypes:e,mask:n},i=new un(s,t),r=this.executeTraditionalQuery(hn.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=>w(e)).sort().join(","),n=this._componentMaskCache.get(t);if(n)return n;const s=R.clone(R.ZERO);for(const t of e){const e=j.getBitMask(t);R.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=>w(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 un({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 hn.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 hn.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 hn.NONE:{const e=this.createComponentMask(t);return this._entities.filter(t=>R.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 fn{constructor(e){this._logger=$("QueryBuilder"),this.conditions=[],this.querySystem=e}withAll(...e){return this.conditions.push({type:hn.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this}withAny(...e){return this.conditions.push({type:hn.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this}without(...e){return this.conditions.push({type:hn.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 hn.ALL:return this.querySystem.queryAll(...e.componentTypes);case hn.ANY:return this.querySystem.queryAny(...e.componentTypes);case hn.NONE:return this.querySystem.queryNone(...e.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-e,fromCache:!1}}createComponentMask(e){const t=R.clone(R.ZERO);for(const n of e)try{const e=j.getBitMask(n);R.orInPlace(t,e)}catch(e){this._logger.warn(`组件类型 ${w(n)} 未注册,跳过`)}return t}reset(){return this.conditions=[],this}}class gn{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){gn._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 gn._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){gn._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){gn._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}}}gn._logger=$("EventSystem");const yn=new class{constructor(){this._runtimeEnvironment="standalone"}get runtimeEnvironment(){return this._runtimeEnvironment}set runtimeEnvironment(e){this._runtimeEnvironment=e}get isServer(){return"server"===this._runtimeEnvironment}get isClient(){return"client"===this._runtimeEnvironment}};class _n{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 _n(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 Sn{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 Sn([...this._all,...e],this._any,this._none,this._tag,this._name)}withAny(...e){return new Sn(this._all,[...this._any,...e],this._none,this._tag,this._name)}withNone(...e){return new Sn(this._all,this._any,[...this._none,...e],this._tag,this._name)}withTag(e){return new Sn(this._all,this._any,this._none,e,this._name)}withName(e){return new Sn(this._all,this._any,this._none,this._tag,e)}buildMatcher(){let e=lt.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 Sn([...this._all],[...this._any],[...this._none],this._tag,this._name)}}function Cn(){return new Sn}function vn(e){return new Sn([e])}function En(...e){return new Sn(e)}const bn=new Map;function Tn(e,t){bn.set(e,t)}Tn("Date",{check:e=>e instanceof Date,serialize:e=>({__type:"Date",value:e.toISOString()}),deserialize:e=>new Date(e.value)}),Tn("Map",{check:e=>e instanceof Map,serialize:(e,t)=>({__type:"Map",value:[...e].map(([e,n])=>[t(e),t(n)])}),deserialize:e=>new Map(e.value)}),Tn("Set",{check:e=>e instanceof Set,serialize:(e,t)=>({__type:"Set",value:[...e].map(t)}),deserialize:e=>new Set(e.value)});const wn={serialize:function e(t,n=new WeakSet){if(null==t)return t;const s=typeof t;if("string"===s||"number"===s||"boolean"===s)return t;if("function"===s)return;const i=t;if(n.has(i))return;n.add(i);for(const[,s]of bn)if(s.check(t))return s.serialize(t,t=>e(t,n));if(Array.isArray(t))return t.map(t=>e(t,n));const r={};for(const s of Object.keys(t))r[s]=e(t[s],n);return r},deserialize:function e(t){if(null==t)return t;const n=typeof t;if("string"===n||"number"===n||"boolean"===n)return t;if(function(e){if(null===e||"object"!=typeof e)return!1;return"__type"in e}(t)){const e=bn.get(t.__type);return e?e.deserialize(t):t}if(Array.isArray(t))return t.map(e);const s={};for(const n of Object.keys(t))s[n]=e(t[n]);return s},register:Tn},In=$("ComponentSerializer");class Mn{static serialize(e){const t=at(e);if(!t)return null;const n=e.constructor,s=t.options.typeId||w(n),i={};for(const[n,s]of t.fields){if(t.ignoredFields.has(n))continue;const r="symbol"==typeof n?n.toString():n,o=e[n];let a;a=fe(e,r)?this.serializeEntityRef(o):s.serializer?s.serializer(o):wn.serialize(o),i[s.alias||r]=a}return{type:s,version:t.options.version,data:i}}static deserialize(e,t,n){const s=t.get(e.type);if(!s)return In.warn(`Component type not found: ${e.type} | 未找到组件类型: ${e.type}`),null;const i=at(s);if(!i)return In.warn(`Component ${e.type} is not serializable | 组件 ${e.type} 不可序列化`),null;const r=new s;for(const[t,s]of i.fields){const i="symbol"==typeof t?t.toString():t,o=s.alias||i,a=e.data[o];if(void 0===a)continue;if(this.isSerializedEntityRef(a)){if(n){const e=a.__entityRef;n.registerPendingRef(r,i,e.id,e.guid)}r[t]=null;continue}const c=s.deserializer?s.deserializer(a):wn.deserialize(a);r[t]=c}return r}static serializeComponents(e){return e.map(e=>this.serialize(e)).filter(e=>null!==e)}static deserializeComponents(e,t,n){return e.map(e=>this.deserialize(e,t,n)).filter(e=>null!==e)}static validateVersion(e,t){return e.version===t}static getSerializationInfo(e){const t=at(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||w(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}}static serializeEntityRef(e){return e?{__entityRef:{id:e.id,guid:e.persistentId}}:null}static isSerializedEntityRef(e){return"object"==typeof e&&null!==e&&"__entityRef"in e}}class An{static serialize(e,t=!0,n){const s=Mn.serializeComponents(Array.from(e.components)),i={id:e.id,guid:e.persistentId,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:s,children:[]},r=e.getComponent(ht);if(null!=r?.parentId&&(i.parentId=r.parentId),t&&r&&r.childIds.length>0){const t=n?.scene??e.scene;if(t)for(const e of r.childIds){const s=t.findEntityById(e);s&&i.children.push(this.serialize(s,!0,n))}}return i}static deserialize(e,t,n,s=!1,i,r,o,a){const c=s?e.id:n(),h=new Xt(e.name,c,e.guid);o?.set(h.id,h),a&&a.registerEntity(h,e.id,e.guid),i&&(h.scene=i),h.tag=e.tag,h.active=e.active,h.enabled=e.enabled,h.updateOrder=e.updateOrder;const l=Mn.deserializeComponents(e.components,t,a);for(const e of l)h.addComponent(e);const d=h.getComponent(ht);d&&(d.parentId=null,d.childIds=[]);for(const c of e.children){const e=this.deserialize(c,t,n,s,i,r,o,a);r?.setParent(e,h)}return h}static serializeEntities(e,t=!0,n){const s=[];for(const i of e){const e=i.getComponent(ht);null!=e?.parentId&&t||s.push(this.serialize(i,t,n))}return s}static deserializeEntities(e,t,n,s=!1,i,r,o){const a=[],c=new Map;for(const h of e){const e=this.deserialize(h,t,n,s,i,r,c,o);a.push(e)}return{rootEntities:a,allEntities:c}}static clone(e,t,n){const s=this.serialize(e,!0);return this.deserialize(s,t,n,!1)}}class kn{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 Dn{constructor(){this._idRemapping=new Map,this._guidLookup=new Map,this._pendingRefs=[],this._preserveIds=!1}setPreserveIds(e){this._preserveIds=e}get preserveIds(){return this._preserveIds}registerEntity(e,t,n){const s=n??e.persistentId;this._guidLookup.set(s,e),void 0!==t&&this._idRemapping.set(t,e)}getEntityById(e){return this._idRemapping.get(e)??null}getEntityByGuid(e){return this._guidLookup.get(e)??null}resolveEntityRef(e){if(!e)return null;if(e.guid){const t=this._guidLookup.get(e.guid);if(t)return t}if(void 0!==e.id){const t=this._idRemapping.get(e.id);if(t)return t}return null}registerPendingRef(e,t,n,s){this._pendingRefs.push({component:e,propertyKey:t,originalId:n,originalGuid:s})}resolveAllReferences(){let e=0;for(const t of this._pendingRefs){const n=this.resolveEntityRef({id:t.originalId,guid:t.originalGuid});n&&(t.component[t.propertyKey]=n,e++)}return e}getUnresolvedCount(){let e=0;for(const t of this._pendingRefs){this.resolveEntityRef({id:t.originalId,guid:t.originalGuid})||e++}return e}getPendingCount(){return this._pendingRefs.length}getRegisteredEntityCount(){return this._guidLookup.size}clear(){this._idRemapping.clear(),this._guidLookup.clear(),this._pendingRefs=[]}getDebugInfo(){return{registeredEntities:this._guidLookup.size,pendingRefs:this._pendingRefs.length,unresolvedRefs:this.getUnresolvedCount(),preserveIds:this._preserveIds}}}const xn=$("SceneSerializer");class On{static serialize(e,t){const n={systems:!1,format:"json",pretty:!0,includeMetadata:!0,...t},s=this.filterEntities(e,n),i=e.getSystem(St),r=An.serializeEntities(s,!0,i??void 0),o=this.buildComponentTypeRegistry(s),a=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:r,componentTypeRegistry:o};return a&&Object.keys(a).length>0&&(c.sceneData=a),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:r.length,componentTypeCount:o.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):kn.encode(c)}static deserialize(e,t,n){const s={strategy:"replace",preserveIds:!1,...n};let i;try{i="string"==typeof t?JSON.parse(t):kn.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=e.getSystem(St),a=new Dn;a.setPreserveIds(s.preserveIds||!1);const{rootEntities:c,allEntities:h}=An.deserializeEntities(i.entities,r,()=>e.identifierPool.checkOut(),s.preserveIds||!1,e,o,a);for(const t of c)e.addEntity(t,!0),this.addChildrenRecursively(t,e,o,h);e.querySystem.clearCache(),e.clearSystemEntityCaches();const l=a.resolveAllReferences(),d=a.getUnresolvedCount();d>0&&xn.warn(`${d} EntityRef(s) could not be resolved. Resolved: ${l}, Total pending: ${a.getPendingCount()} | ${d} 个实体引用无法解析`),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData);const u=[];for(const e of h.values())this.callOnDeserializedForEntity(e,u);u.length>0&&Promise.all(u).catch(e=>{xn.error("Error in onDeserialized | onDeserialized 执行错误:",e)})}static callOnDeserializedForEntity(e,t){for(const n of e.components)try{const e=n.onDeserialized();e instanceof Promise&&t.push(e)}catch(e){const t=w(n.constructor);xn.error(`Error calling onDeserialized on component ${t} | 调用组件 ${t} 的 onDeserialized 时出错:`,e)}}static addChildrenRecursively(e,t,n,s){const i=e.getComponent(ht);if(i&&0!==i.childIds.length)for(const e of i.childIds){const i=s?.get(e)??t.findEntityById(e);i&&(t.addEntity(i,!0),this.addChildrenRecursively(i,t,n,s))}}static serializeSceneData(e){const t={};for(const[n,s]of e)t[n]=wn.serialize(s);return t}static deserializeSceneData(e,t){t.clear();for(const[n,s]of Object.entries(e))t.set(n,wn.deserialize(s))}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=w(e.constructor),s=at(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 j.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 Pn;On.SERIALIZATION_VERSION=1,function(e){e.EntityAdded="entity_added",e.EntityRemoved="entity_removed",e.EntityUpdated="entity_updated",e.ComponentAdded="component_added",e.ComponentRemoved="component_removed",e.ComponentUpdated="component_updated",e.SceneDataUpdated="scene_data_updated"}(Pn||(Pn={}));const Rn={deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1,format:"json",pretty:!1};class zn{static createSnapshot(e,t){const n={...Rn,...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(n.entityFilter&&!n.entityFilter(t))continue;s.entityIds.add(t.id);const e=t.getComponent(ht),i=e?.parentId;if(s.entities.set(t.id,{name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,...null!=i&&{parentId:i}}),n.deepComponentComparison){const e=new Map;for(const n of t.components){const t=Mn.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={...Rn,...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(s.entityFilter&&!s.entityFilter(n))continue;r.add(n.id);const e=n.getComponent(ht),o=e?.parentId;if(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!==o)&&i.entityChanges.push({operation:Pn.EntityUpdated,entityId:n.id,entityData:{name:n.name,tag:n.tag,active:n.active,enabled:n.enabled,updateOrder:n.updateOrder,...null!=o&&{parentId:o}}}),s.deepComponentComparison&&this.detectComponentChanges(n,t,i.componentChanges)}else{i.entityChanges.push({operation:Pn.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,...null!=o&&{parentId:o},components:[],children:[]}});for(const e of n.components){const t=Mn.serialize(e);t&&i.componentChanges.push({operation:Pn.ComponentAdded,entityId:n.id,componentType:t.type,componentData:t})}}}for(const e of t.entityIds)r.has(e)||i.entityChanges.push({operation:Pn.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=Mn.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:Pn.ComponentUpdated,entityId:e.id,componentType:t,componentData:r}):n.push({operation:Pn.ComponentAdded,entityId:e.id,componentType:t,componentData:r})}if(s)for(const t of s.keys())i.has(t)||n.push({operation:Pn.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:Pn.SceneDataUpdated,key:i,value:r})}for(const e of t.sceneData.keys())s.has(e)||n.push({operation:Pn.SceneDataUpdated,key:e,value:void 0,deleted:!0})}static applyIncremental(e,t,n){for(const n of t.entityChanges)switch(n.operation){case Pn.EntityAdded:this.applyEntityAdded(e,n);break;case Pn.EntityRemoved:this.applyEntityRemoved(e,n);break;case Pn.EntityUpdated:this.applyEntityUpdated(e,n)}for(const s of t.componentChanges)switch(s.operation){case Pn.ComponentAdded:this.applyComponentAdded(e,s,n);break;case Pn.ComponentRemoved:this.applyComponentRemoved(e,s,n);break;case Pn.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 Xt(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)return;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);const s=e.getSystem(St);if(s){const i=n.getComponent(ht),r=i?.parentId;if(void 0!==t.entityData.parentId){const i=e.entities.findEntityById(t.entityData.parentId);i&&r!==t.entityData.parentId&&s.setParent(n,i)}else null!=r&&s.setParent(n,null)}}static applyComponentAdded(e,t,n){if(!t.componentData)return;const s=e.entities.findEntityById(t.entityId);if(!s)return;const i=Mn.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=Mn.deserialize(t.componentData,n);r&&s.addComponent(r)}static serializeIncremental(e,t){const n=t?.format??"json",s=t?.pretty??!1;return"binary"===n?kn.encode(e):s?JSON.stringify(e,null,2):JSON.stringify(e)}static deserializeIncremental(e){return"string"==typeof e?JSON.parse(e):kn.decode(e)}static getIncrementalStats(e){const t={added:0,removed:0,updated:0},n={added:0,removed:0,updated:0};for(const n of e.entityChanges)n.operation===Pn.EntityAdded?t.added++:n.operation===Pn.EntityRemoved?t.removed++:n.operation===Pn.EntityUpdated&&t.updated++;for(const t of e.componentChanges)t.operation===Pn.ComponentAdded?n.added++:t.operation===Pn.ComponentRemoved?n.removed++:t.operation===Pn.ComponentUpdated&&n.updated++;return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:t.added,removedEntities:t.removed,updatedEntities:t.updated,addedComponents:n.added,removedComponents:n.removed,updatedComponents:n.updated}}static resetVersion(){this.snapshotVersion=0}}zn.snapshotVersion=0;const Nn={enabled:!0,sampleInterval:10,minDuration:.1,trackAsync:!0,excludePatterns:[/^_/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/],maxBufferSize:1e4};class Fn{constructor(e){this.wrappedObjects=new WeakMap,this.samplingProfiler=null,this.registeredClasses=new Map,this._config={...Nn,...e}}static getInstance(e){return Fn._instance||(Fn._instance=new Fn(e)),Fn._instance}static resetInstance(){Fn._instance&&(Fn._instance.dispose(),Fn._instance=null)}static setEnabled(e){Fn.getInstance().setEnabled(e)}static registerClass(e,t=gt.Custom,n){return Fn.getInstance().registerClass(e,t,n)}static wrapInstance(e,t,n=gt.Custom){return Fn.getInstance().wrapInstance(e,t,n)}static wrapFunction(e,t,n=gt.Custom){return Fn.getInstance().wrapFunction(e,t,n)}static startSampling(){Fn.getInstance().startSampling()}static stopSampling(){return Fn.getInstance().stopSampling()}setEnabled(e){this._config.enabled=e,!e&&this.samplingProfiler&&this.samplingProfiler.stop()}registerClass(e,t=gt.Custom,n){const s=n||e.name;this.registeredClasses.set(s,{constructor:e,category:t});const i=this;return new Proxy(e,{construct(e,n,r){const o=Reflect.construct(e,n,r);return i._config.enabled&&i.wrapInstance(o,s,t),o}})}wrapInstance(e,t,n=gt.Custom){if(!this._config.enabled)return e;if(this.wrappedObjects.has(e))return e;const s=new Map;this.wrappedObjects.set(e,s);const i=this._getAllMethodNames(e);for(const r of i){if(this._shouldExcludeMethod(r))continue;const i=this._getPropertyDescriptor(e,r);if(!i||"function"!=typeof i.value)continue;const o=i.value,a=this._createWrappedMethod(o,t,r,n);s.set(r,{className:t,methodName:r,category:n,original:o});try{e[r]=a}catch{}}return e}wrapFunction(e,t,n=gt.Custom){if(!this._config.enabled)return e;const s=this,i=function(...i){const r=Dt.beginSample(t,n);try{const t=e.apply(this,i);return s._config.trackAsync&&t instanceof Promise?t.finally(()=>{Dt.endSample(r)}):(Dt.endSample(r),t)}catch(e){throw Dt.endSample(r),e}};return Object.defineProperty(i,"name",{value:e.name||t}),Object.defineProperty(i,"length",{value:e.length}),i}startSampling(){this.samplingProfiler||(this.samplingProfiler=new Bn(this._config)),this.samplingProfiler.start()}stopSampling(){return this.samplingProfiler?this.samplingProfiler.stop():[]}dispose(){this.samplingProfiler&&(this.samplingProfiler.stop(),this.samplingProfiler=null),this.registeredClasses.clear()}_createWrappedMethod(e,t,n,s){const i=this,r=`${t}.${n}`,o=this._config.minDuration;return function(...t){if(!i._config.enabled||!Dt.isEnabled())return e.apply(this,t);const n=performance.now(),a=Dt.beginSample(r,s);try{const s=e.apply(this,t);if(i._config.trackAsync&&s instanceof Promise)return s.then(e=>(performance.now()-n>=o&&Dt.endSample(a),e),e=>{throw Dt.endSample(a),e});return performance.now()-n>=o&&Dt.endSample(a),s}catch(e){throw Dt.endSample(a),e}}}_getAllMethodNames(e){const t=new Set;let n=e;for(;n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))"constructor"!==e&&t.add(e);n=Object.getPrototypeOf(n)}return Array.from(t)}_getPropertyDescriptor(e,t){let n=e;for(;n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}_shouldExcludeMethod(e){if("constructor"===e||e.startsWith("__"))return!0;for(const t of this._config.excludePatterns)if(t.test(e))return!0;return!1}}Fn._instance=null;class Bn{constructor(e){this.samples=[],this.intervalId=null,this.isRunning=!1,this.config=e}start(){if(this.isRunning)return;this.isRunning=!0,this.samples=[];const e=()=>{if(!this.isRunning)return;const t=this.captureStack();t.length>0&&(this.samples.push({timestamp:performance.now(),stack:t}),this.samples.length>this.config.maxBufferSize&&this.samples.shift()),this.config.sampleInterval,this.intervalId=setTimeout(e,this.config.sampleInterval)};e()}stop(){return this.isRunning=!1,null!==this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),[...this.samples]}captureStack(){try{const e=new Error,t=(e.stack||"").split("\n").slice(3),n=[];for(const e of t){const t=this.parseStackFrame(e);t&&!this.isInternalFrame(t)&&n.push(t)}return n}catch{return[]}}parseStackFrame(e){let t=(e=e.trim()).match(/at\s+(.+?)\s+\(/);if(t&&t[1])return t[1];if(t=e.match(/at\s+(.+)/),t&&t[1]){const e=t[1];if(!e.includes("("))return e}return t=e.match(/^(.+?)@/),t&&t[1]?t[1]:null}isInternalFrame(e){return["SamplingProfiler","AutoProfiler","ProfilerSDK","setTimeout","setInterval","requestAnimationFrame","<anonymous>","eval"].some(t=>e.includes(t))}}function $n(e,t=gt.Custom){return function(n,s,i){const r=i.value,o=e||`${n.constructor.name}.${String(s)}`;return i.value=function(...e){if(!Dt.isEnabled())return r.apply(this,e);const n=Dt.beginSample(o,t);try{const t=r.apply(this,e);return t instanceof Promise?t.finally(()=>{Dt.endSample(n)}):(Dt.endSample(n),t)}catch(e){throw Dt.endSample(n),e}},i}}function Ln(e=gt.Custom){return function(t){return Fn.registerClass(t,e)}}const Wn=$("ServiceContainer");var Hn;!function(e){e.Singleton="singleton",e.Transient="transient"}(Hn||(Hn={}));class Un{constructor(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}registerSingleton(e,t){this._services.has(e)?Wn.warn(`Service ${e.name} is already registered`):(this._services.set(e,{identifier:e,type:e,...t&&{factory:t},lifetime:Hn.Singleton}),Wn.debug(`Registered singleton service: ${e.name}`))}registerTransient(e,t){this._services.has(e)?Wn.warn(`Service ${e.name} is already registered`):(this._services.set(e,{identifier:e,type:e,...t&&{factory:t},lifetime:Hn.Transient}),Wn.debug(`Registered transient service: ${e.name}`))}registerInstance(e,t){if(this._services.has(e)){const t="symbol"==typeof e?e.description:e.name;return void Wn.warn(`Service ${t} is already registered`)}if(this._services.set(e,{identifier:e,instance:t,lifetime:Hn.Singleton}),"symbol"!=typeof e&&m(e)){const n=p(e),s=n?.priority??0;this._updatableServices.push({instance:t,priority:s}),this._updatableServices.sort((e,t)=>e.priority-t.priority),Wn.debug(`Service ${e.name} is updatable (priority: ${s}), added to update list`)}const n="symbol"==typeof e?e.description:e.name;Wn.debug(`Registered service instance: ${n}`)}resolve(e){const t=this._services.get(e),n="symbol"==typeof e?e.description:e.name;if(!t)throw new Error(`Service ${n} is not registered`);if(this._resolving.has(e)){const e=Array.from(this._resolving).map(e=>"symbol"==typeof e?e.description:e.name).join(" -> ");throw new Error(`Circular dependency detected: ${e} -> ${n}`)}if(t.lifetime===Hn.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{let e;if(t.factory)e=t.factory(this);else{if(!t.type)throw new Error(`Service ${n} has no factory or type to construct`);e=new t.type}if(t.lifetime===Hn.Singleton&&(t.instance=e,t.type&&m(t.type))){const s=p(t.type),i=s?.priority??0;this._updatableServices.push({instance:e,priority:i}),this._updatableServices.sort((e,t)=>e.priority-t.priority),Wn.debug(`Service ${n} is updatable (priority: ${i}), added to update list`)}return e}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()}this._services.delete(e);const n="symbol"==typeof e?e.description:e.name;return Wn.debug(`Unregistered service: ${n}`),!0}clear(){for(const[,e]of this._services)e.instance&&e.instance.dispose();this._services.clear(),this._updatableServices=[],Wn.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 Gn extends Error{constructor(e){super(`[SystemDependencyGraph] 检测到循环依赖 | Cycle dependency detected: ${e.join(" -> ")}`),this.name="CycleDependencyError",this.involvedNodes=e,Object.setPrototypeOf(this,new.target.prototype)}}const qn="set:";class jn{constructor(){this._nodes=new Map}addSystemNode(e){this.getOrCreateNode(e,!1)}addSetNode(e){const t=qn+e;this.getOrCreateNode(t,!0)}addEdge(e,t){if(e===t)return;const n=this.getOrCreateNode(e,e.startsWith(qn)),s=this.getOrCreateNode(t,t.startsWith(qn));n.outEdges.add(t),s.inEdges.add(e)}buildFromSystems(e){this.clear();for(const t of e){this.addSystemNode(t.name);for(const e of t.sets)this.addSetNode(e)}for(const t of e){for(const e of t.sets){const n=qn+e;this.addEdge(n,t.name)}for(const e of t.before){const n=this.resolveTargetId(e);this.addEdge(t.name,n)}for(const e of t.after){const n=this.resolveTargetId(e);this.addEdge(n,t.name)}}}topologicalSort(){const e=new Map;for(const[t,n]of this._nodes)e.set(t,n.inEdges.size);const t=[];for(const[n,s]of e)0===s&&t.push(n);const n=[];let s=0;for(;t.length>0;){const i=t.shift();s++;const r=this._nodes.get(i);if(r){r.bIsVirtual||n.push(i);for(const n of r.outEdges){const s=(e.get(n)??0)-1;e.set(n,s),0===s&&t.push(n)}}}if(s<this._nodes.size){const t=[];for(const[n,s]of e)s>0&&t.push(n);throw new Gn(t)}return n}clear(){this._nodes.clear()}get size(){return this._nodes.size}getOrCreateNode(e,t){let n=this._nodes.get(e);return n||(n={id:e,bIsVirtual:t,inEdges:new Set,outEdges:new Set},this._nodes.set(e,n)),n}resolveTargetId(e){return e.startsWith(qn),e}}const Vn=$("SystemScheduler"),Qn=["startup","preUpdate","update","postUpdate","cleanup"];class Yn{constructor(){this._sortedByStage=new Map,this._dirty=!0,this._graph=new jn,this._useDependencySort=!0}setUseDependencySort(e){this._useDependencySort!==e&&(this._useDependencySort=e,this._dirty=!0)}markDirty(){this._dirty=!0}getSortedSystems(e,t){if(this.ensureBuilt(e),t)return this._sortedByStage.get(t)??[];const n=[];for(const e of Qn){const t=this._sortedByStage.get(e);t&&n.push(...t)}return n}getAllSortedSystems(e){return this.getSortedSystems(e)}ensureBuilt(e){this._dirty&&(this._sortedByStage.clear(),this._useDependencySort&&this.hasDependencies(e)?this.buildWithDependencyGraph(e):this.buildWithUpdateOrder(e),this._dirty=!1)}hasDependencies(e){for(const t of e){const e=this.getSchedulingMetadata(t);if(e.before.length>0||e.after.length>0||e.sets.length>0)return!0;if("update"!==e.stage)return!0}return!1}buildWithUpdateOrder(e){const t=[...e].sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder});this._sortedByStage.set("update",t)}buildWithDependencyGraph(e){const t=new Map;for(const e of Qn)t.set(e,[]);for(const n of e){const e=this.getSchedulingMetadata(n).stage,s=t.get(e);s?s.push(n):t.get("update").push(n)}for(const[e,n]of t){if(0===n.length){this._sortedByStage.set(e,[]);continue}const t=this.sortSystemsInStage(n);this._sortedByStage.set(e,t)}}sortSystemsInStage(e){const t=new Map,n=[];for(const s of e){const e=s.systemName;t.set(e,s);const i=this.getSchedulingMetadata(s);n.push({name:e,before:i.before,after:i.after,sets:i.sets})}this._graph.buildFromSystems(n);try{const e=this._graph.topologicalSort(),n=[];for(const s of e){const e=t.get(s);e&&n.push(e)}return this.stableSortByUpdateOrder(n)}catch(t){if(t instanceof Gn)throw t;return Vn.warn("Topological sort failed, falling back to updateOrder | 拓扑排序失败,回退到 updateOrder 排序",t),this.fallbackSort(e)}}stableSortByUpdateOrder(e){return e}fallbackSort(e){return[...e].sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})}getSchedulingMetadata(e){return{stage:e.getStage(),before:[...e.getBefore()],after:[...e.getAfter()],sets:[...e.getSets()]}}}class Jn{constructor(e=1024){this._freeList=[],this._nextIndex=1,this._aliveCount=0,this._capacity=e,this._generations=new Uint32Array(e),this._alive=new Uint8Array(e),this._enabled=new Uint8Array(e),this._alive[0]=0,this._enabled[0]=0}get aliveCount(){return this._aliveCount}get capacity(){return this._capacity}create(){let e;this._freeList.length>0?e=this._freeList.pop():(e=this._nextIndex++,e>=this._capacity&&this.grow(e));const t=this._generations[e];return this._alive[e]=1,this._enabled[e]=1,this._aliveCount++,Ht(e,t)}destroy(e){const t=Ut(e),n=Gt(e);if(t>=this._capacity||0===t)return!1;if(this._generations[t]!==n)return!1;if(1!==this._alive[t])return!1;this._alive[t]=0,this._enabled[t]=0,this._aliveCount--;const s=(n+1)%Lt;return this._generations[t]=s,this._freeList.push(t),!0}isAlive(e){const t=Ut(e),n=Gt(e);return!(t>=this._capacity||0===t)&&(1===this._alive[t]&&this._generations[t]===n)}isEnabled(e){if(!this.isAlive(e))return!1;const t=Ut(e);return 1===this._enabled[t]}setEnabled(e,t){if(!this.isAlive(e))return!1;const n=Ut(e);return this._enabled[n]=t?1:0,!0}validate(e){return this.isAlive(e)}grow(e){let t=this._capacity;for(;t<=e;)t<<=1;if(t>$t&&(t=$t,e>=t))throw new Error("EntityHandleManager: 超过最大实体数量 268435456");const n=new Uint32Array(t),s=new Uint8Array(t),i=new Uint8Array(t);n.set(this._generations),s.set(this._alive),i.set(this._enabled),this._generations=n,this._alive=s,this._enabled=i,this._capacity=t}reset(){this._generations.fill(0),this._alive.fill(0),this._enabled.fill(0),this._freeList.length=0,this._nextIndex=1,this._aliveCount=0}forEach(e){for(let t=1;t<this._nextIndex;t++)if(1===this._alive[t]){e(Ht(t,this._generations[t]))}}getAllAlive(){const e=[];return this.forEach(t=>e.push(t)),e}}class Zn{constructor(){this._current=1}get current(){return this._current}increment(){this._current++,this._current>=Number.MAX_SAFE_INTEGER&&(this._current=1)}reset(){this._current=1}isChangedSince(e,t){return e>t}}class Xn{get runtimeEnvironment(){return this._runtimeEnvironmentOverride?this._runtimeEnvironmentOverride:yn.runtimeEnvironment}get isServer(){return"server"===this.runtimeEnvironment}get isClient(){return"client"===this.runtimeEnvironment}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);try{return this._systemScheduler.markDirty(),this._systemScheduler.getAllSortedSystems(t)}catch(e){return e instanceof Gn?this._logger.error("[Scene] 系统存在循环依赖,回退到 updateOrder 排序 | Cycle dependency detected, falling back to updateOrder sort",e.involvedNodes):this._logger.error("[Scene] 系统排序失败 | System sorting failed",e),this._sortSystemsByUpdateOrder(t)}}_filterEntitySystems(e){return e.filter(e=>e instanceof _t)}_sortSystemsByUpdateOrder(e){return e.sort((e,t)=>{const n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})}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._handleToEntity=new Map,this.epochManager=new Zn,this._performanceMonitor=null,this._didSceneBegin=!1,this.isEditorMode=!1,this._deferredComponentCallbacks=[],this._cachedSystems=null,this._systemsOrderDirty=!0,this._systemErrorCount=new Map,this._systemAddCounter=0,this._systemScheduler=new Yn,this._componentIdToSystems=new Map,this._globalNotifySystems=new Set,this.entities=new Kt(this),this.identifierPool=new en,this.componentStorageManager=new mt,this.componentRegistry=new q,!1!==e?.inheritGlobalRegistry&&this.componentRegistry.cloneFrom(j),this.querySystem=new pn,this.eventSystem=new gn,this.referenceTracker=new ae,this.handleManager=new Jn,this._services=new Un,this._logger=$("Scene"),this._maxErrorCount=e?.maxSystemErrorCount??10,e?.runtimeEnvironment&&(this._runtimeEnvironmentOverride=e.runtimeEnvironment),e?.name&&(this.name=e.name)}get performanceMonitor(){return this._performanceMonitor||(this._performanceMonitor=this._services.tryResolve(_)??new _),this._performanceMonitor}initialize(){}onStart(){}unload(){}queueDeferredComponentCallback(e){this._deferredComponentCallbacks.push(e)}begin(){if(this._didSceneBegin=!0,this._deferredComponentCallbacks.length>0){for(const e of this._deferredComponentCallbacks)try{e()}catch(e){this._logger.error("Error executing deferred component callback:",e)}this._deferredComponentCallbacks=[]}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,this._componentIdToSystems.clear(),this._globalNotifySystems.clear(),this._handleToEntity.clear(),this.handleManager.reset(),this.epochManager.reset()}update(){this.epochManager.increment(),Dt.beginFrame();const e=Dt.beginSample("Scene.update",gt.ECS);try{Tt.getInstance().update(),this.entities.updateLists();const e=this.systems;this._runSystemPhase(e,"update","Systems.update"),this._runSystemPhase(e,"lateUpdate","Systems.lateUpdate"),this.flushCommandBuffers(e)}finally{Dt.endSample(e),Dt.endFrame()}}_runSystemPhase(e,t,n){const s=Dt.beginSample(n,gt.ECS);try{for(const n of e){if(!this._shouldSystemRun(n))continue;const e="lateUpdate"===t?".late":"",s=Dt.beginSample(`${n.systemName}${e}`,gt.ECS);try{n[t]()}catch(e){this._handleSystemError(n,t,e)}finally{Dt.endSample(s)}}}finally{Dt.endSample(s)}}_shouldSystemRun(e){if(!e.enabled)return!1;if(!this.isEditorMode)return!0;const t=te(e);return!1!==t?.runInEditMode}flushCommandBuffers(e){const t=Dt.beginSample("Scene.flushCommandBuffers",gt.ECS);try{for(const t of e)try{t.flushCommands()}catch(e){this._logger.error(`Error flushing commands for system ${t.systemName}:`,e)}}finally{Dt.endSample(t)}}_handleSystemError(e,t,n){const s=(this._systemErrorCount.get(e)||0)+1;this._systemErrorCount.set(e,s);const i=e.systemName;this._logger.error(`Error in system ${i}.${t}() [${s}/${this._maxErrorCount}]:`,n),s>=this._maxErrorCount&&(e.enabled=!1,this._logger.error(`System ${i} has been disabled due to excessive errors (${s} errors)`))}createEntity(e){const t=new Xt(e,this.identifierPool.checkOut()),n=this.handleManager.create();return t.setHandle(n),this._handleToEntity.set(n,t),this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)}clearSystemEntityCaches(){for(const e of this.systems)e.clearEntityCache()}notifyEntityComponentChanged(e,t){const n=new Set;if(t&&this.componentRegistry.isRegistered(t)){const s=this.componentRegistry.getBitIndex(t),i=this._componentIdToSystems.get(s);if(i)for(const t of i)t.handleEntityComponentChanged(e),n.add(t)}for(const t of this._globalNotifySystems)n.has(t)||(t.handleEntityComponentChanged(e),n.add(t));if(!t)for(const t of this.systems)n.has(t)||t.handleEntityComponentChanged(e)}indexSystemByComponents(e){const t=e.matcher;if(!t)return;if(t.isNothing())return;const n=t.getCondition();if((n.none.length>0||void 0!==n.tag||void 0!==n.name)&&this._globalNotifySystems.add(e),t.isEmpty())this._globalNotifySystems.add(e);else{for(const t of n.all)this.addSystemToComponentIndex(t,e);for(const t of n.any)this.addSystemToComponentIndex(t,e);n.component&&this.addSystemToComponentIndex(n.component,e)}}addSystemToComponentIndex(e,t){const n=this.componentRegistry.getBitIndex(e);let s=this._componentIdToSystems.get(n);s||(s=new Set,this._componentIdToSystems.set(n,s)),s.add(t)}removeSystemFromIndex(e){this._globalNotifySystems.delete(e);for(const t of this._componentIdToSystems.values())t.delete(e)}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 Xt(`${t}_${s}`,this.identifierPool.checkOut());e.scene=this;const i=this.handleManager.create();e.setHandle(i),this._handleToEntity.set(i,e),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),qt(t.handle)&&(this._handleToEntity.delete(t.handle),this.handleManager.destroy(t.handle));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)}findEntityByHandle(e){return qt(e)&&this.handleManager.isAlive(e)?this._handleToEntity.get(e)??null:null}findEntitiesByTag(e){const t=[];for(const n of this.entities.buffer)n.tag===e&&t.push(n);return t}findPersistentEntities(){return this.entities.buffer.filter(e=>e.isPersistent)}extractPersistentEntities(){const e=this.findPersistentEntities();for(const t of e)this.entities.remove(t),this.querySystem.removeEntity(t),t.scene=null;return e}receiveMigratedEntities(e){for(const t of e){t.scene=this,this.entities.add(t),this.querySystem.addEntity(t);for(const e of t.components)this.componentStorageManager.addComponent(t.id,e),this.referenceTracker?.registerEntityScene(t.id,this)}e.length>0&&this.clearSystemEntityCaches()}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 Sn}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=h(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.addOrder=this._systemAddCounter++,t.setPerformanceMonitor(this.performanceMonitor);const s=ee(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(),this.indexSystemByComponents(t),u(t,this._services),Dt.isEnabled()&&Fn.wrapInstance(t,t.systemName,gt.ECS),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(),this.removeSystemFromIndex(e),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=>I(e))})),processors:e.map(e=>({name:se(e),updateOrder:e.updateOrder,entityCount:e.entities.length})),componentStats:this.componentStorageManager.getAllStats()}}serialize(e){return On.serialize(this,e)}deserialize(e,t){On.deserialize(this,e,t)}createIncrementalSnapshot(e){this._incrementalBaseSnapshot=zn.createSnapshot(this,e)}serializeIncremental(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return zn.computeIncremental(this,this._incrementalBaseSnapshot,e)}applyIncremental(e,t){const n="string"==typeof e||e instanceof Uint8Array?zn.deserializeIncremental(e):e,s=t||this.componentRegistry.getAllComponentNames();zn.applyIncremental(this,n,s)}updateIncrementalSnapshot(e){this.createIncrementalSnapshot(e)}clearIncrementalSnapshot(){this._incrementalBaseSnapshot=void 0}hasIncrementalSnapshot(){return void 0!==this._incrementalBaseSnapshot}}class Kn{constructor(e,t){this.scene=e,this.storageManager=t;const n=e.identifierPool.checkOut();this.entity=new Xt("",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(),n=this.scene.getSystem(St);return n?.setParent(t,this.entity),this}withChildren(...e){const t=this.scene.getSystem(St);for(const n of e){const e=n.build();t?.setParent(e,this.entity)}return this}withChildFactory(e){const t=e(this.entity).build(),n=this.scene.getSystem(St);return n?.setParent(t,this.entity),this}withChildIf(e,t){if(e){const e=t.build(),n=this.scene.getSystem(St);n?.setParent(e,this.entity)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const e=new Kn(this.scene,this.storageManager);return e.entity=this.entity,e}}class es{constructor(){this.scene=new Xn}named(e){return this.scene.name=e,this}withEntity(e){return this.scene.addEntity(e),this}withEntityBuilder(e){const t=e(new Kn(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 ts{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 ns{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 ns(this.entities.filter(e))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class ss{constructor(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}createEntity(){return new Kn(this.scene,this.scene.componentStorageManager)}createScene(){return new es}createComponent(e,...t){return new ts(e,...t)}query(){return new fn(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 ns(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 is(e,t,n){return new ss(e,t,n)}const rs=$("World"),os={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,cleanupThresholdMs:3e5};class as{constructor(e={}){this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config={...os,...e},this.name=this._config.name,this._createdAt=Date.now(),this._services=new Un}get services(){return this._services}get isActive(){return this._isActive}get sceneCount(){return this._scenes.size}get createdAt(){return this._createdAt}createScene(e,t){this.validateSceneName(e);const n=t??new Xn;if(this._config.debug){const e=new _;e.enable(),n.services.registerInstance(_,e)}return n.id=e,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),rs.info(`从World '${this.name}' 中移除Scene: ${e}`),!0)}removeAllScenes(){this._scenes.forEach((e,t)=>this.removeScene(t)),rs.info(`从World '${this.name}' 中移除所有Scene`)}getScene(e){return this._scenes.get(e)??null}getSceneIds(){return Array.from(this._scenes.keys())}getAllScenes(){return Array.from(this._scenes.values())}setSceneActive(e,t){const n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin?.(),rs.debug(`在World '${this.name}' 中激活Scene: ${e}`)):(this._activeScenes.delete(e),rs.debug(`在World '${this.name}' 中停用Scene: ${e}`)):rs.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?.(),rs.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?.(),rs.debug(`从World '${this.name}' 中移除全局System: ${e.name}`),!0)}getGlobalSystem(e){return this._globalSystems.find(t=>t instanceof e)??null}start(){this._isActive||(this._isActive=!0,this._globalSystems.forEach(e=>e.initialize?.()),rs.info(`启动World: ${this.name}`))}stop(){this._isActive&&(this._activeScenes.forEach(e=>this.setSceneActive(e,!1)),this._globalSystems.forEach(e=>e.reset?.()),this._isActive=!1,rs.info(`停止World: ${this.name}`))}destroy(){rs.info(`销毁World: ${this.name}`),this.stop(),this.removeAllScenes(),this._globalSystems.forEach(e=>e.destroy?.()??e.reset?.()),this._globalSystems.length=0,this._services.clear(),this._scenes.clear(),this._activeScenes.clear()}updateGlobalSystems(){this._isActive&&this._globalSystems.forEach(e=>e.update?.())}updateScenes(){this._isActive&&(this._activeScenes.forEach(e=>{this._scenes.get(e)?.update?.()}),this._config.autoCleanup&&this.cleanup())}getStatus(){const e=[];return this._scenes.forEach((t,n)=>{e.push({id:n,name:t.name||n,isActive:this._activeScenes.has(n)})}),{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:e}}getStats(){let e=0,t=this._globalSystems.length;return this._scenes.forEach(n=>{e+=n.entities?.count??0,t+=n.systems?.length??0}),{totalEntities:e,totalSystems:t,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}}}validateSceneName(e){if(!e?.trim())throw new Error("Scene name不能为空");if(this._scenes.has(e))throw new Error(`Scene name '${e}' 已存在于World '${this.name}' 中`);if(this._scenes.size>=this._config.maxScenes)throw new Error(`World '${this.name}' 已达到最大Scene数量限制: ${this._config.maxScenes}`)}isCleanupCandidate(e,t){const n=Date.now()-this._createdAt;return!this._activeScenes.has(e)&&null!=t.entities&&0===t.entities.count&&n>this._config.cleanupThresholdMs}cleanup(){const e=[];this._scenes.forEach((t,n)=>{this.isCleanupCandidate(n,t)&&e.push(n)}),e.forEach(e=>{this.removeScene(e),rs.debug(`自动清理空Scene: ${e} from World ${this.name}`)})}}class cs{constructor(e){this._nextScene=null,this._ecsAPI=null,this._logger=$("SceneManager"),this._performanceMonitor=null,this._pendingPersistentEntities=[],this._defaultWorld=new as({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}setSceneChangedCallback(e){this._onSceneChangedCallback=e}setScene(e){const t=this.currentScene;return t&&t instanceof Xn&&(this._pendingPersistentEntities=t.extractPersistentEntities(),this._pendingPersistentEntities.length>0&&this._logger.debug(`Extracted ${this._pendingPersistentEntities.length} persistent entities for migration`)),this._defaultWorld.removeAllScenes(),this._performanceMonitor&&e.services.registerInstance(_,this._performanceMonitor),this._defaultWorld.createScene(cs.DEFAULT_SCENE_ID,e),this._defaultWorld.setSceneActive(cs.DEFAULT_SCENE_ID,!0),this._pendingPersistentEntities.length>0&&e instanceof Xn&&(e.receiveMigratedEntities(this._pendingPersistentEntities),this._logger.debug(`Migrated ${this._pendingPersistentEntities.length} persistent entities to new scene`),this._pendingPersistentEntities=[]),e.querySystem&&e.eventSystem?this._ecsAPI=is(e,e.querySystem,e.eventSystem):this._ecsAPI=null,n.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(cs.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(cs.DEFAULT_SCENE_ID)}get hasPendingScene(){return null!==this._nextScene}dispose(){this.destroy()}}cs.DEFAULT_SCENE_ID="__main__";let hs=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(){}};hs=e([o(),t("design:paramtypes",[])],hs);let ls=class{constructor(){this.frameCounter=0,this.lastSendTime=0,this.sendInterval=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)}}onInitialize(){this.config=this.configService.getConfig(),this.entityCollector=new Ct,this.systemCollector=new vt,this.performanceCollector=new Et,this.componentCollector=new wt,this.sceneCollector=new It,this.advancedProfilerCollector=new xt,Dt.setEnabled(!0),this.webSocketManager=new Mt(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const e=this.config.debugFrameRate||30;this.sendInterval=1e3/e,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 Mt(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"get_advanced_profiler_data":this.handleGetAdvancedProfilerDataRequest(e);break;case"set_profiler_selected_function":this.handleSetProfilerSelectedFunction(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)})}}handleGetAdvancedProfilerDataRequest(e){try{const{requestId:t}=e,n=Dt.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):this.advancedProfilerCollector.collectFromLegacyMonitor(this.performanceMonitor);this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:t,data:n})}catch(t){this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}}handleSetProfilerSelectedFunction(e){try{const{functionName:t,requestId:n}=e;this.advancedProfilerCollector.setSelectedFunction(t||null),this.sendDebugData(),this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:n,success:!0})}catch(t){this.webSocketManager.send({type:"set_profiler_selected_function_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=I(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(I(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=se(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=Tt.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=S.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=this.getDebugData(),t=Dt.isEnabled(),n={type:"debug_data",data:e,advancedProfiler:t?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):null};this.webSocketManager.send(n)}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}};var ds;e([c(cs),t("design:type",cs)],ls.prototype,"sceneManager",void 0),e([c(_),t("design:type",_)],ls.prototype,"performanceMonitor",void 0),e([c(hs),t("design:type",hs)],ls.prototype,"configService",void 0),ls=e([o(),a()],ls),function(e){e.NotInstalled="not_installed",e.Installed="installed",e.Failed="failed"}(ds||(ds={}));const us=$("PluginManager");class ms{constructor(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}initialize(e,t){this._core=e,this._services=t,us.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 us.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:ds.NotInstalled,installedAt:Date.now()};this._metadata.set(e.name,t);try{us.info(`Installing plugin: ${e.name} v${e.version}`),await e.install(this._core,this._services),this._plugins.set(e.name,e),t.state=ds.Installed,us.info(`Plugin ${e.name} installed successfully`)}catch(n){throw t.state=ds.Failed,t.error=n instanceof Error?n.message:String(n),us.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{us.info(`Uninstalling plugin: ${e}`),await t.uninstall(),this._plugins.delete(e),this._metadata.delete(e),us.info(`Plugin ${e} uninstalled successfully`)}catch(t){throw us.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{us.info(`Disposing plugin: ${t.name}`),t.uninstall()}catch(e){us.error(`Error disposing plugin ${t.name}:`,e)}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,us.info("PluginManager disposed")}}function ps(e){const t=`@esengine/service:${e}`;return{id:Symbol.for(t),name:e}}class fs{constructor(){this._services=new Map}register(e,t){this._services.set(e.id,t)}get(e){return this._services.get(e.id)}require(e){const t=this._services.get(e.id);if(void 0===t)throw new Error(`Service not found: ${e.name}`);return t}has(e){return this._services.has(e.id)}unregister(e){return this._services.delete(e.id)}clear(){this._services.clear()}dispose(){this.clear()}}const gs=$("WorldManager"),ys={maxWorlds:50,autoCleanup:!0,cleanupFrameInterval:1800,debug:!1};class _s{constructor(e={}){this._worlds=new Map,this._isRunning=!0,this._framesSinceCleanup=0,this._config={...ys,...e},gs.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupFrameInterval:this._config.cleanupFrameInterval})}get worldCount(){return this._worlds.size}get activeWorldCount(){let e=0;return this._worlds.forEach(t=>{t.isActive&&e++}),e}get isRunning(){return this._isRunning}get config(){return{...this._config}}createWorld(e,t){this.validateWorldName(e);const n={...t,name:e,debug:t?.debug??this._config.debug},s=new as(n);return this._worlds.set(e,s),s}removeWorld(e){const t=this._worlds.get(e);return!!t&&(t.destroy(),this._worlds.delete(e),gs.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(),gs.debug(`激活World: ${e}`)):(n.stop(),gs.debug(`停用World: ${e}`)):gs.warn(`World '${e}' 不存在`)}isWorldActive(e){return this._worlds.get(e)?.isActive??!1}getActiveWorlds(){const e=[];return this._worlds.forEach(t=>{t.isActive&&e.push(t)}),e}findWorlds(e){const t=[];return this._worlds.forEach(n=>{e(n)&&t.push(n)}),t}findWorldByName(e){let t=null;return this._worlds.forEach(n=>{n.name===e&&(t=n)}),t}startAll(){this._isRunning=!0,this._worlds.forEach(e=>e.start()),gs.info("启动所有World")}stopAll(){this._isRunning=!1,this._worlds.forEach(e=>e.stop()),gs.info("停止所有World")}destroy(){gs.info("正在销毁WorldManager..."),this.stopAll();Array.from(this._worlds.keys()).forEach(e=>this.removeWorld(e)),this._worlds.clear(),this._isRunning=!1,gs.info("WorldManager已销毁")}dispose(){this.destroy()}updateAll(){this._isRunning&&(this._worlds.forEach(e=>{e.isActive&&(e.updateGlobalSystems(),e.updateScenes())}),this.processAutoCleanup())}getStats(){let e=0,t=0,n=0;const s=[];return this._worlds.forEach((i,r)=>{const o=i.getStats();e+=i.sceneCount,t+=o.totalEntities,n+=o.totalSystems,s.push({id:r,name:i.name,isActive:i.isActive,sceneCount:i.sceneCount,...o})}),{totalWorlds:this._worlds.size,activeWorlds:this.activeWorldCount,totalScenes:e,totalEntities:t,totalSystems:n,memoryUsage:0,isRunning:this._isRunning,config:{...this._config},worlds:s}}getDetailedStatus(){const e=[];return this._worlds.forEach((t,n)=>{e.push({id:n,isActive:t.isActive,status:t.getStatus()})}),{...this.getStats(),worlds:e}}cleanup(){const e=[];return this._worlds.forEach((t,n)=>{this.isCleanupCandidate(t)&&e.push(n)}),e.forEach(e=>this.removeWorld(e)),e.length>0&&gs.debug(`清理了 ${e.length} 个World`),e.length}validateWorldName(e){if(!e?.trim())throw new Error("World name不能为空");if(this._worlds.has(e))throw new Error(`World name '${e}' 已存在`);if(this._worlds.size>=this._config.maxWorlds)throw new Error(`已达到最大World数量限制: ${this._config.maxWorlds}`)}processAutoCleanup(){this._config.autoCleanup&&(this._framesSinceCleanup++,this._framesSinceCleanup>=this._config.cleanupFrameInterval&&(this.cleanup(),this._framesSinceCleanup=0,this._config.debug&&gs.debug(`执行定期清理World (间隔: ${this._config.cleanupFrameInterval} 帧)`)))}isCleanupCandidate(e){if(e.isActive)return!1;if(Date.now()-e.createdAt<=6e5)return!1;if(0===e.sceneCount)return!0;return!e.getAllScenes().some(e=>e.entities&&e.entities.count>0)}}class Ss{static get runtimeEnvironment(){return yn.runtimeEnvironment}static set runtimeEnvironment(e){yn.runtimeEnvironment=e}static get isServer(){return yn.isServer}static get isClient(){return yn.isClient}constructor(e={}){if(Ss._instance=this,this._config={debug:!0,...e},this._serviceContainer=new Un,e.runtimeEnvironment&&(Ss.runtimeEnvironment=e.runtimeEnvironment),this._timerManager=new g,this._serviceContainer.registerInstance(g,this._timerManager),this._performanceMonitor=new _,this._serviceContainer.registerInstance(_,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new C,this._serviceContainer.registerInstance(C,this._poolManager),this._sceneManager=new cs(this._performanceMonitor),this._serviceContainer.registerInstance(cs,this._sceneManager),this._sceneManager.setSceneChangedCallback(()=>this._debugManager?.onSceneChanged()),this._worldManager=new _s({debug:!!this._config.debug,...this._config.worldManagerConfig}),this._serviceContainer.registerInstance(_s,this._worldManager),this._pluginManager=new ms,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(ms,this._pluginManager),this._pluginServiceRegistry=new fs,this._serviceContainer.registerInstance(fs,this._pluginServiceRegistry),this.debug=this._config.debug??!0,this._config.debugConfig?.enabled){const e=new hs;e.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(hs,e),this._serviceContainer.registerSingleton(ls,e=>d(ls,e)),this._debugManager=this._serviceContainer.resolve(ls),this._debugManager.onInitialize()}this.initialize()}static get Instance(){return this._instance}static get services(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}static get pluginServices(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._pluginServiceRegistry}static get worldManager(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._worldManager}static create(e=!0){if(null==this._instance){const t="boolean"==typeof e?{debug:e}:e;this._instance=new Ss(t)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance}static setScene(e){if(!this._instance)throw Ss._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):Ss._logger.warn("Core实例未创建,请先调用Core.create()")}static update(e){this._instance?this._instance.updateInternal(e):Ss._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 hs;t.setConfig(e),this._instance._serviceContainer.registerInstance(hs,t),this._instance._serviceContainer.registerSingleton(ls,e=>d(ls,e)),this._instance._debugManager=this._instance._serviceContainer.resolve(ls),this._instance._debugManager.onInitialize()}this._instance._config.debugConfig=e}else Ss._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 get performanceMonitor(){return this._instance?._performanceMonitor||null}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(){Ss._logger.info("Core initialized",{debug:this.debug,debugEnabled:this._config.debugConfig?.enabled||!1})}updateInternal(e){if(Ss.paused)return;const t=this._performanceMonitor.startMonitoring("Core.update");n.update(e),this._performanceMonitor.updateFPS?.(n.deltaTime);const s=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",s,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?.stop(),this._instance._serviceContainer.clear(),Ss._logger.info("Core destroyed"),this._instance=null)}}Ss.paused=!1,Ss._instance=null,Ss._logger=$("Core");const Cs=ps("runtimeMode");class vs{constructor(e={}){this._callbacks=new Set,this._isEditor=e.isEditor??!1,this._isPlaying=e.isPlaying??!1,this._isPreview=e.isPreview??!1}get isEditor(){return this._isEditor}get isPlaying(){return this._isPlaying}get isPreview(){return this._isPreview}get isStandalone(){return!this._isEditor}onModeChanged(e){return this._callbacks.add(e),()=>{this._callbacks.delete(e)}}setEditorMode(e){this._isEditor!==e&&(this._isEditor=e,this._notifyChange())}setPlaying(e){this._isPlaying!==e&&(this._isPlaying=e,this._notifyChange())}setPreview(e){this._isPreview!==e&&(this._isPreview=e,this._notifyChange())}updateMode(e){let t=!1;void 0!==e.isEditor&&this._isEditor!==e.isEditor&&(this._isEditor=e.isEditor,t=!0),void 0!==e.isPlaying&&this._isPlaying!==e.isPlaying&&(this._isPlaying=e.isPlaying,t=!0),void 0!==e.isPreview&&this._isPreview!==e.isPreview&&(this._isPreview=e.isPreview,t=!0),t&&this._notifyChange()}_notifyChange(){for(const e of this._callbacks)try{e(this)}catch(e){vs._logger.error("Callback error:",e)}}dispose(){this._callbacks.clear()}}function Es(){return new vs({isEditor:!0,isPlaying:!1,isPreview:!1})}function bs(){return new vs({isEditor:!1,isPlaying:!0,isPreview:!1})}vs._logger=$("RuntimeModeService");const Ts=$("DebugPlugin");let ws=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(_s),Ts.info("ECS Debug Plugin installed"),this.autoStart&&this.start()}async uninstall(){this.stop(),this.worldManager=null,Ts.info("ECS Debug Plugin uninstalled")}dispose(){this.stop(),this.worldManager=null}start(){this.updateTimer?Ts.warn("Debug monitoring already started"):(Ts.info("Starting debug monitoring"),this.updateTimer=setInterval(()=>{this.logStats()},this.updateInterval))}stop(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,Ts.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.sceneName||n.name===e.sceneName)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();Ts.info("=== ECS Debug Stats ==="),Ts.info(`Total Entities: ${e.totalEntities}`),Ts.info(`Total Systems: ${e.totalSystems}`),Ts.info(`Scenes: ${e.scenes.length}`);for(const t of e.scenes){Ts.info(`\n[Scene: ${t.name}]`),Ts.info(` Entities: ${t.entityCount}`),Ts.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`:"";Ts.info(` - ${e.name} (${e.enabled?"enabled":"disabled"}) | Entities: ${e.entityCount}${t}`)}}Ts.info("========================\n")}exportJSON(){const e=this.getStats();return JSON.stringify(e,null,2)}};ws=e([o(),t("design:paramtypes",[Object])],ws);class Is{constructor(e,t){this.func=e,this.context=t}}class Ms{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 Is(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}}class As{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(){}}class ks extends _t{constructor(e){super(e)}process(e){this.processSystem()}}class Ds extends _t{constructor(e){super(e)}process(e){}}class xs extends _t{constructor(e,t){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}onCheckProcessing(){return this.acc+=n.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class Os{constructor(){this._adapter=null,this._logger=$("PlatformManager")}static getInstance(){return Os._instance||(Os._instance=new Os),Os._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()}}const Ps="Worker pool has been destroyed";class Rs{constructor(e,t){this.workerStates=new Map,this.pendingTasks=new Map,this.taskQueue=[],this.taskCounter=0,this._isDestroyed=!1,this.workers=e,this.initializeWorkers(t)}get isDestroyed(){return this._isDestroyed}get workerCount(){return this.workers.length}get isReady(){if(this._isDestroyed)return!1;for(const e of this.workerStates.values())if(0===e)return!1;return this.workers.length>0}get hasPendingTasks(){return this.taskQueue.length>0||this.pendingTasks.size>0}executeSharedBuffer(e){return this.createTask("shared-"+ ++this.taskCounter,{...e,type:"shared"},()=>{})}execute(e){return this.createTask("task-"+ ++this.taskCounter,e,e=>e)}getStatus(){const e={idle:0,busy:0,initializing:0};for(const t of this.workerStates.values())1===t?e.idle++:2===t?e.busy++:0===t&&e.initializing++;return{total:this.workers.length,...e,queuedTasks:this.taskQueue.length}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const e=new Error(Ps);for(const t of this.pendingTasks.values())t.reject(e);for(const t of this.taskQueue)t.reject(e);for(const e of this.workers)e.terminate();this.workers.length=0,this.taskQueue.length=0,this.pendingTasks.clear(),this.workerStates.clear()}initializeWorkers(e){for(let t=0;t<this.workers.length;t++){const n=this.workers[t];n&&(this.workerStates.set(t,e?0:1),n.onMessage(e=>this.handleMessage(t,e.data)),n.onError(e=>this.handleError(t,e)),e&&n.postMessage({type:"init",sharedBuffer:e}))}}createTask(e,t,n){return new Promise((s,i)=>{this._isDestroyed?i(new Error(Ps)):this.enqueueTask({id:e,data:t,resolve:e=>s(n(e)),reject:i})})}enqueueTask(e){this.taskQueue.push(e),this.dispatchTasks()}dispatchTasks(){for(;this.taskQueue.length>0;){const e=this.findIdleWorker();if(-1===e)break;const t=this.taskQueue.shift();this.assignTask(e,t)}}findIdleWorker(){for(let e=0;e<this.workers.length;e++)if(1===this.workerStates.get(e))return e;return-1}assignTask(e,t){const n=this.workers[e];n&&(this.workerStates.set(e,2),this.pendingTasks.set(e,t),n.postMessage({id:t.id,...t.data}))}handleMessage(e,t){if("init"===t.type)return this.workerStates.set(e,1),void this.dispatchTasks();t.error?this.completeTask(e,new Error(t.error)):this.completeTask(e,void 0,t.result)}handleError(e,t){this.completeTask(e,new Error(t.message))}completeTask(e,t,n){const s=this.pendingTasks.get(e);s&&(this.pendingTasks.delete(e),this.workerStates.set(e,1),t?s.reject(t):s.resolve(n),this.dispatchTasks())}}class zs extends _t{constructor(e,t={}){super(e),this.sharedBuffer=null,this.sharedFloatArray=null,this.workerPool=null,this.isProcessing=!1,this.hasLoggedSyncMode=!1,this.platformAdapter=Os.getInstance().getAdapter(),this.config=this.resolveConfig(t),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()}resolveConfig(e){const t=this.getMaxSystemWorkerCount(),n=e.workerCount??t,s=Math.min(n,t);return n>t&&this.logger.warn(`请求 ${n} 个 Worker,但系统最多支持 ${t} 个。实际使用 ${s} 个 Worker。`),{enableWorker:e.enableWorker??!0,workerCount:s,useSharedArrayBuffer:e.useSharedArrayBuffer??this.isSharedArrayBufferSupported(),entityDataSize:e.entityDataSize??this.getDefaultEntityDataSize(),maxEntities:e.maxEntities??1e4,systemConfig:e.systemConfig,...void 0!==e.entitiesPerWorker&&{entitiesPerWorker:e.entitiesPerWorker},...void 0!==e.workerScriptPath&&{workerScriptPath:e.workerScriptPath}}}isWorkerSupported(){return this.platformAdapter.isWorkerSupported()}isSharedArrayBufferSupported(){return this.platformAdapter.isSharedArrayBufferSupported()}getMaxSystemWorkerCount(){return this.platformAdapter.getPlatformConfig().maxWorkerCount}initializeWorkerSystem(){this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool()}initializeSharedArrayBuffer(){try{if(!this.isSharedArrayBufferSupported())return void this.fallbackToSingleWorker("平台不支持 SharedArrayBuffer");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} bytes)`))}catch(e){this.fallbackToSingleWorker("SharedArrayBuffer 初始化失败"),this.logger.warn(`${this.systemName}:`,e)}}fallbackToSingleWorker(e){this.logger.warn(`${this.systemName}: ${e},降级到单 Worker 模式`),this.config.useSharedArrayBuffer=!1,this.config.workerCount=1,this.sharedBuffer=null,this.sharedFloatArray=null}initializeWorkerPool(){try{const e=this.resolveWorkerScript();if(!e)return void(this.config.enableWorker=!1);const t=this.createWorkers(e);this.workerPool=new Rs(t,this.sharedBuffer)}catch(e){this.logger.error(`${this.systemName}: Worker 池初始化失败`,e),this.config.enableWorker=!1}}resolveWorkerScript(){const e=this.platformAdapter.getPlatformConfig();if(this.config.workerScriptPath)return this.logger.info(`${this.systemName}: 使用外部 Worker 文件: ${this.config.workerScriptPath}`),this.config.workerScriptPath;if(e.limitations?.noEval)return this.logger.error(`${this.systemName}: 当前平台不支持动态 Worker 脚本,请配置 workerScriptPath 指定预编译的 Worker 文件`),null;const t=this.createWorkerScript();return(e.workerScriptPrefix||"")+t}createWorkers(e){const t=[];for(let n=0;n<this.config.workerCount;n++){const s=this.platformAdapter.createWorker(e,{name:`${this.systemName}-Worker-${n}`});t.push(s)}return t}createWorkerScript(){const e=this.extractFunctionBody(this.workerProcess.toString()),t=this.getSharedProcessFunctionBody();return`\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = ${this.config.entityDataSize};\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n try {\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n if (type === 'shared') {\n if (!sharedFloatArray) {\n self.postMessage({ id, error: 'SharedArrayBuffer not initialized' });\n return;\n }\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null });\n return;\n }\n\n if (entities) {\n function workerProcess(entities, deltaTime, systemConfig) {\n ${e}\n }\n\n const result = workerProcess(entities, deltaTime, systemConfig);\n\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 function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n ${t}\n }\n `}extractFunctionBody(e){const t=e.match(/\{([\s\S]*)\}/);if(!t||void 0===t[1])throw new Error("无法解析 workerProcess 方法");return t[1]}getSharedProcessFunctionBody(){const e=this.getSharedArrayBufferProcessFunction?.();if(!e)return"";return`\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n ${this.extractFunctionBody(e.toString())}\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n `}process(e){if(this.isProcessing)return;this.isProcessing=!0;const t=this.getCurrentProcessingMode();try{switch(t){case"shared-buffer":this.processWithSharedArrayBuffer(e).finally(()=>{this.isProcessing=!1});break;case"worker":this.processWithWorker(e).finally(()=>{this.isProcessing=!1});break;default:this.processSynchronously(e),this.isProcessing=!1}}catch(e){throw this.isProcessing=!1,this.logger.error(`${this.systemName}: 处理失败`,e),e}}getCurrentProcessingMode(){return this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray?"shared-buffer":"worker":(this.hasLoggedSyncMode||(this.logger.info(`${this.systemName}: Worker 不可用,使用同步处理`),this.hasLoggedSyncMode=!0),"sync")}async processWithSharedArrayBuffer(e){if(!this.sharedFloatArray||!this.workerPool)return;this.writeEntitiesToBuffer(e);const t=this.createBatchTasks(e.length,!0);await Promise.all(t),this.readResultsFromBuffer(e)}async processWithWorker(e){if(!this.workerPool)return;const t=e.map(e=>this.extractEntityData(e)),s=this.createDataBatches(t),i=n.deltaTime,r=await Promise.all(s.map(e=>this.workerPool.execute({entities:e,deltaTime:i,systemConfig:this.config.systemConfig})));this.applyBatchResults(e,r)}processSynchronously(e){const t=e.map(e=>this.extractEntityData(e)),s=n.deltaTime,i=this.workerProcess(t,s,this.config.systemConfig);i&&"function"==typeof i.then?i.then(t=>{this.applyResults(e,t)}):this.applyResults(e,i)}createDataBatches(e){return this.splitIntoBatches(e.length,(t,n)=>e.slice(t,n))}createBatchTasks(e,t){return this.splitIntoBatches(e,(e,s)=>t?this.workerPool.executeSharedBuffer({startIndex:e,endIndex:s,deltaTime:n.deltaTime,systemConfig:this.config.systemConfig}):Promise.resolve())}splitIntoBatches(e,t){const n=[],{workerCount:s,entitiesPerWorker:i}=this.config;if(i)for(let s=0;s<e;s+=i){const r=Math.min(s+i,e);n.push(t(s,r))}else{const i=Math.ceil(e/s);for(let r=0;r<s;r++){const s=r*i,o=Math.min(s+i,e);s<e&&n.push(t(s,o))}}return n}applyBatchResults(e,t){let n=0;for(const s of t)for(const t of s)n<e.length&&t&&this.applyResult(e[n],t),n++}applyResults(e,t){for(let n=0;n<e.length&&n<t.length;n++)this.applyResult(e[n],t[n])}writeEntitiesToBuffer(e){if(!this.sharedFloatArray)return;const t=Math.min(e.length,this.config.maxEntities);for(let n=0;n<t;n++){const t=this.extractEntityData(e[n]),s=n*this.config.entityDataSize;this.writeEntityToBuffer(t,s)}}readResultsFromBuffer(e){if(!this.sharedFloatArray)return;const t=Math.min(e.length,this.config.maxEntities);for(let n=0;n<t;n++){const t=n*this.config.entityDataSize,s=this.readEntityFromBuffer(t);s&&this.applyResult(e[n],s)}}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?this.reinitializeSystem():t.workerCount!==this.config.workerCount?this.reinitializeWorkerPool():!this.config.enableWorker&&this.workerPool?this.destroyWorkerPool():this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()}reinitializeSystem(){this.destroyWorkerPool(),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()}reinitializeWorkerPool(){this.destroyWorkerPool(),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()}destroyWorkerPool(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)}getWorkerInfo(){return{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:this.getCurrentProcessingMode()}}onDestroy(){super.onDestroy(),this.destroyWorkerPool()}getLoggerName(){return se(this)}}let Ns=class extends Xe{constructor(e="",t="",n=!1){super(),this.sourcePrefabGuid="",this.sourcePrefabPath="",this.isRoot=!1,this.rootInstanceEntityId=null,this.modifiedProperties=[],this.instantiatedAt=0,this.originalValues={},this.sourcePrefabGuid=e,this.sourcePrefabPath=t,this.isRoot=n,this.instantiatedAt=Date.now()}markPropertyModified(e,t){const n=`${e}.${t}`;this.modifiedProperties.includes(n)||this.modifiedProperties.push(n)}isPropertyModified(e,t){const n=`${e}.${t}`;return this.modifiedProperties.includes(n)}clearPropertyModified(e,t){const n=`${e}.${t}`,s=this.modifiedProperties.indexOf(n);-1!==s&&this.modifiedProperties.splice(s,1)}clearAllModifications(){this.modifiedProperties=[],this.originalValues={}}storeOriginalValue(e,t,n){const s=`${e}.${t}`;s in this.originalValues||(this.originalValues[s]=this.deepClone(n))}getOriginalValue(e){return this.originalValues[e]}hasOriginalValue(e,t){return`${e}.${t}`in this.originalValues}deepClone(e){if(null==e)return e;if("object"==typeof e)try{return JSON.parse(JSON.stringify(e))}catch{return e}return e}};e([st(),t("design:type",String)],Ns.prototype,"sourcePrefabGuid",void 0),e([st(),t("design:type",String)],Ns.prototype,"sourcePrefabPath",void 0),e([st(),t("design:type",Boolean)],Ns.prototype,"isRoot",void 0),e([st(),t("design:type",Object)],Ns.prototype,"rootInstanceEntityId",void 0),e([st(),t("design:type",Array)],Ns.prototype,"modifiedProperties",void 0),e([st(),t("design:type",Number)],Ns.prototype,"instantiatedAt",void 0),e([st(),t("design:type",Object)],Ns.prototype,"originalValues",void 0),Ns=e([X("PrefabInstance",{editor:{hideInInspector:!0}}),nt({version:1,typeId:"PrefabInstance"}),t("design:paramtypes",[String,String,Boolean])],Ns);class Fs{constructor(e=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new gn,this.isDebugMode=e}emit(e,t,n=!1){this.validateEventType(e);const s=n?this.enhanceEventData(e,t):t;this.isDebugMode&&Fs._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&&Fs._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||Yt.NORMAL,async:n.async||!1};return n.thisArg&&(s.thisArg=n.thisArg),this.isDebugMode&&Fs._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&&Fs._logger.info(`移除监听器: ${t} 事件: ${e}`),this.eventSystem.off(e,t)}offAll(e){this.isDebugMode&&Fs._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&&Fs._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(Qt.ENTITY_CREATED,e)}emitEntityDestroyed(e){this.emit(Qt.ENTITY_DESTROYED,e)}emitComponentAdded(e){this.emit(Qt.COMPONENT_ADDED,e)}emitComponentRemoved(e){this.emit(Qt.COMPONENT_REMOVED,e)}emitSystemAdded(e){this.emit(Qt.SYSTEM_ADDED,e)}emitSystemRemoved(e){this.emit(Qt.SYSTEM_REMOVED,e)}emitSceneChanged(e){this.emit(Qt.SCENE_ACTIVATED,e)}emitPerformanceWarning(e){this.emit(Qt.PERFORMANCE_WARNING,e)}onEntityCreated(e,t){return this.on(Qt.ENTITY_CREATED,e,t)}onComponentAdded(e,t){return this.on(Qt.COMPONENT_ADDED,e,t)}onSystemError(e,t){return this.on(Qt.SYSTEM_ERROR,e,t)}onPerformanceWarning(e,t){return this.on(Qt.PERFORMANCE_WARNING,e,t)}validateEventType(e){this.isDebugMode&&(Zt.isValid(e)||(Fs._logger.warn(`未知事件类型: ${e}`),Zt.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}}}Fs._logger=$("EventBus");class Bs{static getInstance(e=!1){return this._instance||(this._instance=new Fs(e)),this._instance}static reset(e=!1){return this._instance&&this._instance.clear(),this._instance=new Fs(e),this._instance}}const $s=$("VersionMigration");class Ls{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 $s.warn(`No migration path found for component ${e.type} | 未找到组件 ${e.type} 的迁移路径`),e;const i={...e};let r=n;for(;r<t;){const t=s.get(r);if(!t){$s.warn(`Missing migration from version ${r} to ${r+1} for ${e.type} | 缺少组件 ${e.type} 从版本 ${r} 到 ${r+1} 的迁移`);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){$s.warn(`Missing scene migration from version ${i} to ${i+1} | 缺少场景从版本 ${i} 到 ${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}}Ls.componentMigrations=new Map,Ls.sceneMigrations=new Map;class Ws{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?Ls.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):Ls.registerSceneMigration(this.fromVersion,this.toVersion,e)}}const Hs=1;class Us{static createPrefab(e,t,n){const s=t.includeChildren??!0,i=An.serialize(e,s,n),r=this.toPrefabEntity(i,!0),{componentTypes:o,componentTypeRegistry:a}=this.collectComponentTypes(r),c=Date.now(),h={name:t.name,createdAt:c,modifiedAt:c,componentTypes:o,referencedAssets:[]};return t.description&&(h.description=t.description),t.tags&&(h.tags=t.tags),{version:1,metadata:h,root:r,componentTypeRegistry:a}}static instantiate(e,t,n,s={}){const{parentId:i,name:r,preserveIds:o=!1,trackInstance:a=!0}=s,c=t.getSystem(St)??null;let h=1;const{rootEntities:l,allEntities:d}=An.deserializeEntities([e.root],n,()=>{for(;t.findEntityById(h);)h++;return h++},o,t,c),u=l[0];if(!u)throw new Error("Failed to instantiate prefab: no root entity created");r&&(u.name=r);for(const e of d.values())t.entities.add(e);if(void 0!==i&&c){const e=t.findEntityById(i);e&&c.setParent(u,e)}if(a){const t=e.metadata.guid||"";this.addPrefabInstanceComponents(u,d,t,"",c)}return u}static toPrefabEntity(e,t){return{...e,isPrefabRoot:t,children:e.children.map(e=>this.toPrefabEntity(e,!1))}}static collectComponentTypes(e){const t=new Map,n=e=>{for(const n of e.components)t.has(n.type)||t.set(n.type,n.version);for(const t of e.children)n(t)};n(e);return{componentTypes:Array.from(t.keys()),componentTypeRegistry:Array.from(t.entries()).map(([e,t])=>({typeName:e,version:t}))}}static addPrefabInstanceComponents(e,t,n,s,i){const r=e.id,o=new Ns(n,s,!0);o.rootInstanceEntityId=r,e.addComponent(o);for(const e of t.values()){if(e.id===r)continue;const t=new Ns(n,s,!1);t.rootInstanceEntityId=r,e.addComponent(t)}}static isPrefabInstance(e){return e.hasComponent(Ns)}static getSourcePrefabGuid(e){const t=e.getComponent(Ns);return t?.sourcePrefabGuid||null}static getPrefabInstanceRoot(e){const t=e.getComponent(Ns);if(!t||!t.rootInstanceEntityId)return null;const n=e.scene;return n&&n.findEntityById(t.rootInstanceEntityId)||null}static serialize(e,t=!0){return JSON.stringify(e,null,t?2:void 0)}static deserialize(e){const t=JSON.parse(e);if(!t.version||!t.metadata||!t.root)throw new Error("Invalid prefab data format");return t}static validate(e){const t=[];return"number"!=typeof e.version&&t.push("Invalid or missing version"),e.metadata?(e.metadata.name||t.push("Missing metadata.name"),Array.isArray(e.metadata.componentTypes)||t.push("Invalid metadata.componentTypes")):t.push("Missing metadata"),e.root?this.validateEntity(e.root,t,"root"):t.push("Missing root entity"),Array.isArray(e.componentTypeRegistry)||t.push("Invalid componentTypeRegistry"),t.length>0?{valid:!1,errors:t}:{valid:!0}}static validateEntity(e,t,n){"number"!=typeof e.id&&t.push(`${n}: Invalid or missing id`),"string"!=typeof e.name&&t.push(`${n}: Invalid or missing name`),Array.isArray(e.components)||t.push(`${n}: Invalid or missing components`),Array.isArray(e.children)?e.children.forEach((e,s)=>{this.validateEntity(e,t,`${n}.children[${s}]`)}):t.push(`${n}: Invalid or missing children`)}}const Gs={NONE:0,FOLDER:4096,HIDDEN:8192,LOCKED:16384,EDITOR_ONLY:32768,PREFAB_INSTANCE:256,PREFAB_ROOT:512};function qs(e,t){return 0!==(e&t)}function js(e,t){return e|t}function Vs(e,t){return e&~t}function Qs(e){return qs(e,Gs.FOLDER)}function Ys(e){return qs(e,Gs.HIDDEN)}function Js(e){return qs(e,Gs.LOCKED)}class Zs{constructor(){this._dirtyFields=new Set,this._hasChanges=!1,this._lastSyncTime=0}setDirty(e){this._dirtyFields.add(e),this._hasChanges=!0}hasChanges(){return this._hasChanges}isDirty(e){return this._dirtyFields.has(e)}getDirtyFields(){return Array.from(this._dirtyFields)}getDirtyCount(){return this._dirtyFields.size}clear(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=Date.now()}clearField(e){this._dirtyFields.delete(e),0===this._dirtyFields.size&&(this._hasChanges=!1)}get lastSyncTime(){return this._lastSyncTime}markAllDirty(e){for(let t=0;t<e;t++)this._dirtyFields.add(t);this._hasChanges=e>0}reset(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=0}}function Xs(e){return function(t,n){const s=function(e){const t=e.constructor;if(Object.prototype.hasOwnProperty.call(t,Y))return t[Y];const n=t[Y],s={typeId:w(t),fields:n?[...n.fields]:[],fieldIndexMap:n?new Map(n.fieldIndexMap):new Map};return t[Y]=s,s}(t),i=s.fields.length,r={index:i,name:n,type:e};s.fields.push(r),s.fieldIndexMap.set(n,i);const o=`_sync_${n}`;Object.defineProperty(t,n,{get(){return this[o]},set(e){if(this[o]!==e){this[o]=e;const t=this[J];t&&t.setDirty(i)}},enumerable:!0,configurable:!0})}}function Ks(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Y]||null}function ei(e){const t=Ks(e);return null!==t&&t.fields.length>0}function ti(e){return e&&e[J]||null}function ni(e){const t=Ks(e);if(!t)throw new Error("Component does not have sync metadata. Use @sync decorator on fields.");let n=e[J];return n||(n=new Zs,e[J]=n),n.markAllDirty(t.fields.length),n}function si(e){const t=ti(e);t&&t.clear()}function ii(e){const t=ti(e);return!!t&&t.hasChanges()}const ri=Symbol("NetworkEntityMetadata");function oi(e,t){return function(n){const s={prefabType:e,autoSpawn:t?.autoSpawn??!0,autoDespawn:t?.autoDespawn??!0};return n[ri]=s,n}}function ai(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[ri]||null}function ci(e){return null!==ai(e)}function hi(e){if(e<0)throw new Error("Varint only supports non-negative integers");return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}function li(e,t,n){if(e<0)throw new Error("Varint only supports non-negative integers");for(;e>=128;)t[n++]=127&e|128,e>>>=7;return t[n++]=e,n}function di(e,t){let n,s=0,i=0;do{if(t>=e.length)throw new Error("Varint decode: buffer overflow");n=e[t++],s|=(127&n)<<i,i+=7}while(n>=128);return[s,t]}function ui(e){return e<<1^e>>31}function mi(e){return e>>>1^-(1&e)}function pi(e,t,n){return li(ui(e),t,n)}function fi(e,t){const[n,s]=di(e,t);return[mi(n),s]}const gi="undefined"!=typeof TextEncoder?new TextEncoder:null;class yi{constructor(e=256){this._offset=0,this._buffer=new Uint8Array(e),this._view=new DataView(this._buffer.buffer)}get offset(){return this._offset}toUint8Array(){return this._buffer.slice(0,this._offset)}reset(){this._offset=0}ensureCapacity(e){const t=this._offset+e;if(t>this._buffer.length){const e=Math.max(2*this._buffer.length,t),n=new Uint8Array(e);n.set(this._buffer),this._buffer=n,this._view=new DataView(this._buffer.buffer)}}writeUint8(e){this.ensureCapacity(1),this._buffer[this._offset++]=e}writeInt8(e){this.ensureCapacity(1),this._view.setInt8(this._offset++,e)}writeBoolean(e){this.writeUint8(e?1:0)}writeUint16(e){this.ensureCapacity(2),this._view.setUint16(this._offset,e,!0),this._offset+=2}writeInt16(e){this.ensureCapacity(2),this._view.setInt16(this._offset,e,!0),this._offset+=2}writeUint32(e){this.ensureCapacity(4),this._view.setUint32(this._offset,e,!0),this._offset+=4}writeInt32(e){this.ensureCapacity(4),this._view.setInt32(this._offset,e,!0),this._offset+=4}writeFloat32(e){this.ensureCapacity(4),this._view.setFloat32(this._offset,e,!0),this._offset+=4}writeFloat64(e){this.ensureCapacity(8),this._view.setFloat64(this._offset,e,!0),this._offset+=8}writeVarint(e){this.ensureCapacity(hi(e)),this._offset=li(e,this._buffer,this._offset)}writeString(e){if(gi){const t=gi.encode(e);this.writeVarint(t.length),this.ensureCapacity(t.length),this._buffer.set(t,this._offset),this._offset+=t.length}else{const t=this.stringToUtf8Bytes(e);this.writeVarint(t.length),this.ensureCapacity(t.length),this._buffer.set(t,this._offset),this._offset+=t.length}}writeBytes(e){this.ensureCapacity(e.length),this._buffer.set(e,this._offset),this._offset+=e.length}stringToUtf8Bytes(e){const t=[];for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s>=55296&&s<=56319&&n+1<e.length){const t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),n++)}s<128?t.push(s):s<2048?(t.push(192|s>>6),t.push(128|63&s)):s<65536?(t.push(224|s>>12),t.push(128|s>>6&63),t.push(128|63&s)):(t.push(240|s>>18),t.push(128|s>>12&63),t.push(128|s>>6&63),t.push(128|63&s))}return new Uint8Array(t)}}const _i="undefined"!=typeof TextDecoder?new TextDecoder:null;class Si{constructor(e){this._offset=0,this._buffer=e,this._view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get offset(){return this._offset}set offset(e){this._offset=e}get remaining(){return this._buffer.length-this._offset}hasMore(){return this._offset<this._buffer.length}readUint8(){return this.checkBounds(1),this._buffer[this._offset++]}readInt8(){return this.checkBounds(1),this._view.getInt8(this._offset++)}readBoolean(){return 0!==this.readUint8()}readUint16(){this.checkBounds(2);const e=this._view.getUint16(this._offset,!0);return this._offset+=2,e}readInt16(){this.checkBounds(2);const e=this._view.getInt16(this._offset,!0);return this._offset+=2,e}readUint32(){this.checkBounds(4);const e=this._view.getUint32(this._offset,!0);return this._offset+=4,e}readInt32(){this.checkBounds(4);const e=this._view.getInt32(this._offset,!0);return this._offset+=4,e}readFloat32(){this.checkBounds(4);const e=this._view.getFloat32(this._offset,!0);return this._offset+=4,e}readFloat64(){this.checkBounds(8);const e=this._view.getFloat64(this._offset,!0);return this._offset+=8,e}readVarint(){const[e,t]=di(this._buffer,this._offset);return this._offset=t,e}readString(){const e=this.readVarint();this.checkBounds(e);const t=this._buffer.subarray(this._offset,this._offset+e);return this._offset+=e,_i?_i.decode(t):this.utf8BytesToString(t)}readBytes(e){this.checkBounds(e);const t=this._buffer.slice(this._offset,this._offset+e);return this._offset+=e,t}peekUint8(){return this.checkBounds(1),this._buffer[this._offset]}skip(e){this.checkBounds(e),this._offset+=e}checkBounds(e){if(this._offset+e>this._buffer.length)throw new Error(`BinaryReader: buffer overflow (offset=${this._offset}, size=${e}, bufferLength=${this._buffer.length})`)}utf8BytesToString(e){let t="",n=0;for(;n<e.length;){let s;const i=e[n++];if(i<128)s=i;else if(i<224){s=(31&i)<<6|63&e[n++]}else if(i<240){s=(15&i)<<12|(63&e[n++])<<6|63&e[n++]}else{s=(7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++],s>65535&&(s-=65536,t+=String.fromCharCode(55296+(s>>10)),s=56320+(1023&s))}t+=String.fromCharCode(s)}return t}}function Ci(e,t,n){switch(n){case"boolean":e.writeBoolean(t);break;case"int8":e.writeInt8(t);break;case"uint8":e.writeUint8(t);break;case"int16":e.writeInt16(t);break;case"uint16":e.writeUint16(t);break;case"int32":e.writeInt32(t);break;case"uint32":e.writeUint32(t);break;case"float32":e.writeFloat32(t);break;case"float64":e.writeFloat64(t);break;case"string":e.writeString(t??"")}}function vi(e,t,n){const s=t.fields;n.writeVarint(s.length);for(const t of s){n.writeUint8(t.index);Ci(n,e[t.name],t.type)}}function Ei(e,t,n,s){if(!n.hasChanges())return!1;const i=n.getDirtyFields();s.writeVarint(i.length);for(const n of i){const i=t.fields[n];if(i){s.writeUint8(i.index);Ci(s,e[i.name],i.type)}}return i.length>0}function bi(e,t,n=!1){t.writeUint32(e.id);const s=e.components,i=[];for(const e of s){const t=e.constructor[Y];if(t&&t.fields.length>0){const s=e[J];if(n&&s&&!s.hasChanges())continue;i.push({component:e,metadata:t,tracker:s})}}t.writeVarint(i.length);for(const{component:e,metadata:s,tracker:r}of i)t.writeString(s.typeId),n&&r?Ei(e,s,r,t):vi(e,s,t);return i.length}function Ti(e,t=V.FULL){const n=new yi(1024);n.writeUint8(t),n.writeVarint(e.length);const s=t===V.DELTA;for(const t of e)bi(t,n,s);return n.toUint8Array()}function wi(e,t){const n=new yi(256);n.writeUint8(V.SPAWN),n.writeUint32(e.id),n.writeString(t||"");const s=e.components,i=[];for(const e of s){const t=e.constructor[Y];t&&t.fields.length>0&&i.push({component:e,metadata:t})}n.writeVarint(i.length);for(const{component:e,metadata:t}of i)n.writeString(t.typeId),vi(e,t,n);return n.toUint8Array()}function Ii(e){const t=new yi(8);return t.writeUint8(V.DESPAWN),t.writeUint32(e),t.toUint8Array()}function Mi(e){const t=new yi(8+4*e.length);t.writeUint8(V.DESPAWN),t.writeVarint(e.length);for(const n of e)t.writeUint32(n);return t.toUint8Array()}function Ai(e,t){switch(t){case"boolean":return e.readBoolean();case"int8":return e.readInt8();case"uint8":return e.readUint8();case"int16":return e.readInt16();case"uint16":return e.readUint16();case"int32":return e.readInt32();case"uint32":return e.readUint32();case"float32":return e.readFloat32();case"float64":return e.readFloat64();case"string":return e.readString()}}function ki(e,t,n){const s=n.readVarint();for(let i=0;i<s;i++){const s=n.readUint8(),i=t.fields[s];if(i){const t=Ai(n,i.type);e[`_sync_${i.name}`]=t}else console.warn(`Unknown sync field index: ${s}`)}}function Di(e,t,n){const s=t.readUint32(),i=t.readVarint(),r=[];let o=n?.get(s),a=!1;o||(o=e.findEntityById(s)),o||(o=e.createEntity(`entity_${s}`),a=!0,n?.set(s,o));for(let e=0;e<i;e++){const e=t.readString();r.push(e);const n=j.getComponentType(e);if(!n){console.warn(`Unknown component type: ${e}`);const n=t.readVarint();for(let s=0;s<n;s++){t.readUint8(),console.error(`Cannot skip unknown component type: ${e}`);break}continue}const s=n[Y];if(!s){console.warn(`Component ${e} has no sync metadata`);continue}let i=o.getComponent(n);i||(i=o.addComponent(new n)),ki(i,s,t)}return{entityId:s,isNew:a,componentTypes:r}}function xi(e,t,n){const s=new Si(t),i=s.readUint8(),r=s.readVarint(),o=[],a=n||new Map;for(let t=0;t<r;t++){const t=Di(e,s,a);o.push(t)}return{operation:i,entities:o}}function Oi(e,t,n){const s=new Si(t);if(s.readUint8()!==V.SPAWN)return null;const i=s.readUint32(),r=s.readString(),o=s.readVarint(),a=[],c=e.createEntity(`entity_${i}`);n?.set(i,c);for(let e=0;e<o;e++){const e=s.readString();a.push(e);const t=j.getComponentType(e);if(!t){console.warn(`Unknown component type: ${e}`);const t=s.readVarint();for(let e=0;e<t;e++)s.readUint8();continue}const n=t[Y];if(!n)continue;ki(c.addComponent(new t),n,s)}return{entity:c,prefabType:r,componentTypes:a}}function Pi(e){const t=new Si(e);if(t.readUint8()!==V.DESPAWN)return null;const n=[];if(4===t.remaining)n.push(t.readUint32());else{const e=t.readVarint();for(let s=0;s<e;s++)n.push(t.readUint32())}return{entityIds:n}}function Ri(e,t,n){const s=Pi(t);if(!s)return[];for(const t of s.entityIds){const s=n?.get(t)||e.findEntityById(t);s&&(s.destroy(),n?.delete(t))}return s.entityIds}function zi(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}function Ni(e,t){const n=e.getComponent(t);return null!==n?n:void 0}function Fi(e,...t){return t.map(t=>e.getComponent(t))}function Bi(e,...t){return t.every(t=>e.hasComponent(t))}function $i(e,...t){return t.some(t=>e.hasComponent(t))}function Li(e,t,n){return e.addComponent(t),n(t),e}function Wi(e,t,n){let s=e.getComponent(t);return s||(s=n(),e.addComponent(s)),s}function Hi(e,t,n){const s=e.getComponent(t);return!!s&&(Object.assign(s,n),!0)}class Ui{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){const t=this._entity.scene?.getSystem(St);return t?.setParent(e,this._entity),this}build(){return this._entity}get entity(){return this._entity}}function Gi(e){return new Ui(e)}class qi{static getType(e){return e.constructor}}class ji{static toNumber(e){return null==e?0:Number(e)}}function Vi(e){return"function"==typeof e&&e.prototype instanceof Xe}function Qi(e){return e.every(Vi)}function Yi(){return globalThis}function Ji(){return performance}class Zi{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(){const e=this.miniGameGlobals.wx;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}static isByteDanceMiniGame(){const e=this.miniGameGlobals.tt;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}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(){const e=this.miniGameGlobals.my;return!!e&&!(!e.getSystemInfo||!e.createCanvas)}static isBaiduMiniGame(){const e=this.miniGameGlobals.swan;return!!e&&!(!e.getSystemInfo||!e.createCanvas)}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location}static isTauriEnvironment(){return"undefined"!=typeof window&&("__TAURI__"in window||"__TAURI_INTERNALS__"in window)}static isEditorEnvironment(){return"undefined"!=typeof window&&(!!this.isTauriEnvironment()||"__ESENGINE_EDITOR__"in window)}static getDetailedInfo(){const e={},t=this.miniGameGlobals;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!==t.wx,tt:void 0!==t.tt,my:void 0!==t.my,swan:void 0!==t.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}}function Xi(e){return Os.getInstance().registerAdapter(e)}function Ki(){return Os.getInstance().getAdapter()}function er(){return Os.getInstance().getBasicWorkerConfig()}function tr(){return Os.getInstance().getFullPlatformConfig()}function nr(e){return Os.getInstance().supportsFeature(e)}function sr(){return Os.getInstance().hasAdapter()}Zi.miniGameGlobals=Yi();export{xt as AdvancedProfilerCollector,Ie as After,Fn as AutoProfiler,we as Before,Si as BinaryReader,kn as BinarySerializer,yi as BinaryWriter,R as BitMask64Utils,nn as Bits,J as CHANGE_TRACKER,E as COMPONENT_DEPENDENCIES,b as COMPONENT_EDITOR_OPTIONS,v as COMPONENT_TYPE_NAME,Pn as ChangeOperation,Zs as ChangeTracker,xe as ClientOnly,z as Colors,yt as CommandBuffer,ft as CommandType,mn as CompiledQuery,Xe as Component,wt as ComponentDataCollector,Tt as ComponentPoolManager,q as ComponentRegistry,Mn as ComponentSerializer,on as ComponentSparseSet,ut as ComponentStorage,N as ConsoleLogger,Ss as Core,Gn as CycleDependencyError,At as DEFAULT_PROFILER_CONFIG,Qn as DEFAULT_STAGE_ORDER,hs as DebugConfigService,ls as DebugManager,ws as DebugPlugin,Je as DeepCopy,X as ECSComponent,Qt as ECSEventType,ss as ECSFluentAPI,K as ECSSystem,Rt as EMPTY_GUID,he as ENTITY_REF_METADATA,Jt as EVENT_TYPES,Ms as Emitter,Ne as EnableSoA,Xt as Entity,Ct as EntityDataCollector,Jn as EntityHandleManager,Kt as EntityList,tn as EntityProcessorList,ue as EntityRef,An as EntitySerializer,_t as EntitySystem,Gs as EntityTags,Zn as EpochManager,Fs as EventBus,Yt as EventPriority,Zt as EventTypeValidator,$e as Float32,Be as Float64,Is as FuncPack,Nt as GEN_BITS,Bt as GEN_MASK,j as GlobalComponentRegistry,Bs as GlobalEventBus,As as GlobalManager,ht as HierarchyComponent,St as HierarchySystem,zt as INDEX_BITS,Ft as INDEX_MASK,en as IdentifierPool,ot as IgnoreSerialization,Me as InSet,zn as IncrementalSerializer,c as InjectProperty,o as Injectable,He as Int16,Le as Int32,Ge as Int8,xs as IntervalSystem,P as LogLevel,B as Logger,F as LoggerManager,$t as MAX_ENTITIES,Lt as MAX_GENERATION,lt as Matcher,Ws as MigrationBuilder,ri as NETWORK_ENTITY_METADATA,Wt as NULL_HANDLE,oi as NetworkEntity,Oe as NotClient,Pe as NotServer,ji as NumberExtension,Hs as PREFAB_FORMAT_VERSION,_e as PROPERTY_METADATA,Ds as PassiveSystem,Et as PerformanceDataCollector,_ as PerformanceMonitor,y as PerformanceWarningType,Zi as PlatformDetector,Os as PlatformManager,Rs as PlatformWorkerPool,ms as PluginManager,fs as PluginServiceRegistry,ds as PluginState,S as Pool,C as PoolManager,Ns as PrefabInstanceComponent,Us as PrefabSerializer,ks as ProcessingSystem,$n as Profile,gt as ProfileCategory,Ln as ProfileClass,Dt as ProfilerSDK,Se as Property,pn as QuerySystem,un as ReactiveQuery,dn as ReactiveQueryChangeType,ae as ReferenceTracker,yn as RuntimeConfig,vs as RuntimeModeService,Cs as RuntimeModeToken,Ee as SCHEDULING_METADATA,Ke as SERIALIZABLE_METADATA,et as SERIALIZE_FIELD,tt as SERIALIZE_OPTIONS,Y as SYNC_METADATA,Z as SYSTEM_TYPE_NAME,Xn as Scene,It as SceneDataCollector,cs as SceneManager,On as SceneSerializer,nt as Serializable,Dn as SerializationContext,st as Serialize,Ye as SerializeArray,it as SerializeAsMap,rt as SerializeAsSet,Ve as SerializeMap,Qe as SerializeSet,De as ServerOnly,Un as ServiceContainer,Hn as ServiceLifetime,Ze as SoAStorage,sn as SparseSet,Te as Stage,V as SyncOperation,vt as SystemDataCollector,jn as SystemDependencyGraph,Yn as SystemScheduler,Q as TYPE_SIZES,n as Time,s as Timer,g as TimerManager,gn as TypeSafeEventSystem,qi as TypeUtils,Ui as TypedEntityBuilder,Sn as TypedQueryBuilder,_n as TypedQueryResult,Ue as Uint16,We as Uint32,qe as Uint8,je as Uint8Clamped,a as Updatable,wn as ValueSerializer,Ls as VersionMigrationManager,Mt as WebSocketManager,zs as WorkerEntitySystem,as as World,_s as WorldManager,Li as addAndConfigure,js as addEntityTag,Gi as buildEntity,si as clearChanges,is as createECSAPI,Es as createEditorModeService,d as createInstance,$ as createLogger,Cn as createQuery,ps as createServiceToken,bs as createStandaloneModeService,ki as decodeComponent,Pi as decodeDespawn,Di as decodeEntity,fi as decodeSignedVarint,xi as decodeSnapshot,Oi as decodeSpawn,di as decodeVarint,Ei as encodeComponentDelta,vi as encodeComponentFull,Ii as encodeDespawn,Mi as encodeDespawnBatch,bi as encodeEntity,pi as encodeSignedVarint,Ti as encodeSnapshot,wi as encodeSpawn,li as encodeVarint,Gt as genOf,Ot as generateGUID,er as getBasicWorkerConfig,ti as getChangeTracker,M as getComponentDependencies,A as getComponentEditorOptions,k as getComponentInstanceEditorOptions,I as getComponentInstanceTypeName,w as getComponentTypeName,Fi as getComponents,Ki as getCurrentAdapter,me as getEntityRefMetadata,ge as getEntityRefProperties,tr as getFullPlatformConfig,Yi as getGlobalWithMiniGame,ai as getNetworkEntityMetadata,Wi as getOrAddComponent,Ji as getPerformanceWithMemory,l as getPropertyInjectMetadata,Ce as getPropertyMetadata,oe as getSceneByEntityId,Ae as getSchedulingMetadata,at as getSerializationMetadata,Ks as getSyncMetadata,te as getSystemInstanceMetadata,se as getSystemInstanceTypeName,ee as getSystemMetadata,ne as getSystemTypeName,p as getUpdatableMetadata,jt as handleEquals,Vt as handleToString,sr as hasAdapter,$i as hasAnyComponent,ii as hasChanges,Bi as hasComponents,T as hasECSComponentDecorator,pe as hasEntityRef,qs as hasEntityTag,ve as hasPropertyMetadata,ke as hasSchedulingMetadata,ei as hasSyncFields,Ut as indexOf,ni as initChangeTracker,u as injectProperties,Qi as isComponentArray,D as isComponentHiddenInInspector,x as isComponentInstanceHiddenInInspector,Vi as isComponentType,fe as isEntityRefProperty,Qs as isFolder,Ys as isHidden,Js as isLocked,ci as isNetworkEntity,ct as isSerializable,m as isUpdatable,Pt as isValidGUID,qt as isValidHandle,Ht as makeHandle,Ri as processDespawn,vn as queryFor,En as queryForAll,f as registerInjectable,Xi as registerPlatformAdapter,Vs as removeEntityTag,zi as requireComponent,W as resetLoggerColors,H as setGlobalLogLevel,L as setLoggerColors,U as setLoggerFactory,nr as supportsFeature,Xs as sync,Ni as tryGetComponent,Hi as updateComponent,hi as varintSize,mi as zigzagDecode,ui as zigzagEncode};
2
2
  //# sourceMappingURL=index.mjs.map