UNPKG

@esengine/ecs-framework

Version:

用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架

1 lines 218 kB
"use strict";function e(e,t,n,s){var i,r=arguments.length,o=r<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(r<3?i(o):r>3?i(t,n,o):i(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}function t(e,t){return function(n,s){t(n,s,e)}}function n(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;class s{static update(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++}static sceneChanged(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0}static checkEvery(e,t){return this.totalTime-t>=e}}s.deltaTime=0,s.unscaledDeltaTime=0,s.totalTime=0,s.unscaledTotalTime=0,s.timeScale=1,s.frameCount=0;class i{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}get isDone(){return this._isDone}get elapsedTime(){return this._elapsedTime}reset(){this._elapsedTime=0}stop(){this._isDone=!0}tick(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=s.deltaTime,this._isDone}initialize(e,t,n,s){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}const r=new WeakMap,o=new WeakMap,a=new WeakMap;function c(){return function(e){const t=r.get(e);r.set(e,{injectable:!0,dependencies:[],...t?.properties&&{properties:t.properties}})}}function h(e=0){return function(t){const n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error(`@Updatable() decorator requires class ${t.name} to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.`);a.set(t,{updatable:!0,priority:e})}}function l(e){return function(t,n,s){let i=o.get(t);i||(i=new Map,o.set(t,i)),i.set(s,e)}}function u(e){const t=r.get(e);return t?.injectable??!1}function d(e,t){const n=(s=e,o.get(s)||new Map);var s;const i=[],r=e.length;for(let s=0;s<r;s++){const r=n.get(s);if(r){if("string"==typeof r||"symbol"==typeof r)throw new Error(`String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for ${e.name} parameter ${s}`);i.push(t.resolve(r))}else i.push(void 0)}return new e(...i)}function p(e,t){const n=e.constructor,s=(i=n,r.get(i));var i;if(s?.properties&&0!==s.properties.size)for(const[n,i]of s.properties){const s=t.resolve(i);null!==s&&(e[n]=s)}}function m(e){const t=a.get(e);return t?.updatable??!1}function g(e){return a.get(e)}var y;exports.TimerManager=class{constructor(){this._timers=[]}update(){for(let e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))}schedule(e,t,n,s){const r=new i;return r.initialize(e,t,n,s),this._timers.push(r),r}dispose(){for(const e of this._timers)e.unload();this._timers=[]}},exports.TimerManager=e([h()],exports.TimerManager),exports.PerformanceWarningType=void 0,(y=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",y.HIGH_MEMORY_USAGE="high_memory_usage",y.HIGH_CPU_USAGE="high_cpu_usage",y.FREQUENT_GC="frequent_gc",y.LOW_FPS="low_fps",y.HIGH_ENTITY_COUNT="high_entity_count";class f{constructor(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(e){return this._isEnabled?performance.now():0}endMonitoring(e,t,n=0){if(!this._isEnabled||0===t)return;const s=performance.now(),i=s-t,r={name:e,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(e,r),this.updateStats(e,i)}updateStats(e,t){let n=this._systemStats.get(e);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(e,n)),n.totalTime+=t,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,t),n.maxTime=Math.max(n.maxTime,t),n.recentTimes.push(t),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(e){if(0===e.recentTimes.length)return;const t=e.recentTimes.reduce(((e,t)=>e+t),0)/e.recentTimes.length,n=e.recentTimes.reduce(((e,n)=>e+Math.pow(n-t,2)),0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);const s=[...e.recentTimes].sort(((e,t)=>e-t)),i=s.length;e.percentile95=s[Math.floor(.95*i)]||0,e.percentile99=s[Math.floor(.99*i)]||0}getSystemData(e){return this._systemData.get(e)}getSystemStats(e){return this._systemStats.get(e)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const e=[];e.push("=== ECS Performance Report ==="),e.push("");const t=Array.from(this._systemStats.entries()).sort(((e,t)=>t[1].averageTime-e[1].averageTime));for(const[n,s]of t){const t=this._systemData.get(n);e.push(`System: ${n}`),e.push(` Current: ${t?.executionTime.toFixed(2)}ms (${t?.entityCount} entities)`),e.push(` Average: ${s.averageTime.toFixed(2)}ms`),e.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),e.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),t?.averageTimePerEntity&&t.averageTimePerEntity>0&&e.push(` Per Entity: ${t.averageTimePerEntity.toFixed(4)}ms`),e.push("")}const n=Array.from(this._systemData.values()).reduce(((e,t)=>e+t.executionTime),0);return e.push(`Total Frame Time: ${n.toFixed(2)}ms`),e.push(`Systems Count: ${this._systemData.size}`),e.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(e){this._systemData.delete(e),this._systemStats.delete(e)}getPerformanceWarnings(e=16.67){const t=[];for(const[n,s]of this._systemData.entries())s.executionTime>e&&t.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${e}ms)`);return t}setMaxRecentSamples(e){this._maxRecentSamples=e;for(const t of this._systemStats.values())for(;t.recentTimes.length>e;)t.recentTimes.shift()}dispose(){this._systemData.clear(),this._systemStats.clear(),this._isEnabled=!1}}class _{constructor(e,t=100,n=1024){this._objects=[],this._createFn=e,this._maxSize=t,this._objectSize=n,this._stats={size:0,maxSize:t,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(e,t=100,n=1024){let s=this._pools.get(e);return s||(s=new _((()=>new e),t,n),this._pools.set(e,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const e of this._objects)e.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(e){const t=e??Math.floor(this._objects.length/2);for(;this._objects.length>t;){const e=this._objects.pop();e&&(e.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(e){const t=Math.min(e,this._maxSize-this._objects.length);for(let e=0;e<t;e++){const e=this._createFn();e.reset(),this._objects.push(e),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)}getAvailableCount(){return this._objects.length}isEmpty(){return 0===this._objects.length}isFull(){return this._objects.length>=this._maxSize}static getAllPoolTypes(){return Array.from(this._pools.keys())}static getAllPoolStats(){const e={};for(const[t,n]of this._pools){e[t.name||t.toString()]=n.getStats()}return e}static compactAllPools(){for(const e of this._pools.values())e.compact()}static clearAllPools(){for(const e of this._pools.values())e.clear();this._pools.clear()}static getGlobalStatsString(){const e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(const[n,s]of Object.entries(e))t.push(`${n}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Total Created: ${s.totalCreated}`),t.push(` Total Obtained: ${s.totalObtained}`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");return t.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}_._pools=new Map;class S{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}registerPool(e,t){this.pools.set(e,t)}getPool(e){return this.pools.get(e)||null}update(){const e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)}createPool(e,t,n=100,s=1024){let i=this.pools.get(e);return i||(i=new _(t,n,s),this.pools.set(e,i)),i}removePool(e){const t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const e of this.pools.values())e.compact()}clearAllPools(){for(const e of this.pools.values())e.clear()}getAllStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,n.getStats());return e}getGlobalStats(){let e=0,t=0,n=0,s=0,i=0,r=0;for(const o of this.pools.values()){const a=o.getStats();e+=a.size,t+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,r+=a.estimatedMemoryUsage}return{size:e,maxSize:t,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:r}}getStatsString(){const e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");const t=this.getGlobalStats();e.push(`Total Pools: ${this.pools.size}`),e.push(`Global Hit Rate: ${(100*t.hitRate).toFixed(1)}%`),e.push(`Global Memory Usage: ${(t.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");for(const[t,n]of this.pools){const s=n.getStats();e.push(`${t}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("")}return e.join("\n")}setAutoCompactInterval(e){this.autoCompactInterval=e}prewarmAllPools(){for(const e of this.pools.values()){const t=e.getStats(),n=Math.floor(.2*t.maxSize);e.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}dispose(){this.reset()}}const C=Symbol("ComponentTypeName"),v=Symbol("SystemTypeName");function E(e){return e.__systemMetadata__}function b(e){const t=e[C];return t||(e.name||"UnknownComponent")}function T(e){const t=e[v];return t||(e.name||"UnknownSystem")}function w(e){return b(e.constructor)}function A(e){return T(e.constructor)}const M="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||class{constructor(e){this._target=e}deref(){return this._target}},I=new Map;function x(e){const t=I.get(e);return t?.deref()||null}class D{constructor(){this._references=new Map}registerReference(e,t,n){const s=e.id;let i=this._references.get(s);i||(i=new Set,this._references.set(s,i));this._findRecord(i,t,n)||i.add({component:new M(t),propertyKey:n})}unregisterReference(e,t,n){const s=e.id,i=this._references.get(s);if(!i)return;const r=this._findRecord(i,t,n);r&&(i.delete(r),0===i.size&&this._references.delete(s))}clearReferencesTo(e){const t=this._references.get(e);if(!t)return;const n=[];for(const e of t){e.component.deref()&&n.push(e)}for(const e of n){const t=e.component.deref();t&&(t[e.propertyKey]=null)}this._references.delete(e)}clearComponentReferences(e){for(const[t,n]of this._references.entries()){const s=[];for(const t of n){const n=t.component.deref();n&&n!==e||s.push(t)}for(const e of s)n.delete(e);0===n.size&&this._references.delete(t)}}getReferencesTo(e){const t=this._references.get(e);if(!t)return[];const n=[];for(const e of t){e.component.deref()&&n.push(e)}return n}cleanup(){const e=[];for(const[t,n]of this._references.entries()){const s=[];for(const e of n)e.component.deref()||s.push(e);for(const e of s)n.delete(e);0===n.size&&e.push(t)}for(const t of e)this._references.delete(t)}registerEntityScene(e,t){I.set(e,new M(t))}unregisterEntityScene(e){I.delete(e)}getDebugInfo(){const e={};for(const[t,n]of this._references.entries()){const s=[];for(const e of n){const t=e.component.deref();t&&s.push({componentId:t.id,propertyKey:e.propertyKey})}s.length>0&&(e[`entity_${t}`]=s)}return e}_findRecord(e,t,n){for(const s of e){if(s.component.deref()===t&&s.propertyKey===n)return s}}}var k;exports.LogLevel=void 0,(k=exports.LogLevel||(exports.LogLevel={}))[k.Debug=0]="Debug",k[k.Info=1]="Info",k[k.Warn=2]="Warn",k[k.Error=3]="Error",k[k.Fatal=4]="Fatal",k[k.None=5]="None";const R={BLACK:"",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 O{constructor(e={}){this._config={level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...e}}debug(e,...t){this.log(exports.LogLevel.Debug,e,...t)}info(e,...t){this.log(exports.LogLevel.Info,e,...t)}warn(e,...t){this.log(exports.LogLevel.Warn,e,...t)}error(e,...t){this.log(exports.LogLevel.Error,e,...t)}fatal(e,...t){this.log(exports.LogLevel.Fatal,e,...t)}setLevel(e){this._config.level=e}setColors(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors={...this._config.colors,...e}}setPrefix(e){this._config.prefix=e}log(e,t,...n){if(e<this._config.level)return;let s=t;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${exports.LogLevel[e].toUpperCase()}] ${s}`,this._config.output?this._config.output(e,s):this.outputToConsole(e,s,...n)}outputToConsole(e,t,...n){const s=this._config.enableColors?this.getColors():null;switch(e){case exports.LogLevel.Debug:s?console.debug(`${s.debug}${t}${s.reset}`,...n):console.debug(t,...n);break;case exports.LogLevel.Info:s?console.info(`${s.info}${t}${s.reset}`,...n):console.info(t,...n);break;case exports.LogLevel.Warn:s?console.warn(`${s.warn}${t}${s.reset}`,...n):console.warn(t,...n);break;case exports.LogLevel.Error:s?console.error(`${s.error}${t}${s.reset}`,...n):console.error(t,...n);break;case exports.LogLevel.Fatal:s?console.error(`${s.fatal}${t}${s.reset}`,...n):console.error(t,...n)}}getColors(){return{...{debug:R.BRIGHT_BLACK,info:R.GREEN,warn:R.YELLOW,error:R.RED,fatal:R.BRIGHT_RED,reset:R.RESET},...this._config.colors}}}class z{constructor(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info}get defaultLogger(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}createDefaultLogger(){return this._loggerFactory?this._loggerFactory():new O({level:this._defaultLevel})}static getInstance(){return z._instance||(z._instance=new z),z._instance}getLogger(e){if(!e)return this.defaultLogger;if(!this._loggers.has(e)){const t=this._loggerFactory?this._loggerFactory(e):new O({prefix:e,level:this._defaultLevel});this._loggers.set(e,t)}return this._loggers.get(e)}setLogger(e,t){this._loggers.set(e,t)}setGlobalLevel(e){this._defaultLevel=e,this._defaultLogger instanceof O&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof O&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof O&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof O&&t.setColors(e)}resetColors(){this._defaultLogger instanceof O&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof O&&e.setColors({})}setLoggerFactory(e){(this._defaultLogger||this._loggers.size>0)&&console.warn("[LoggerManager] setLoggerFactory 应该在导入 ECS 模块之前调用。已创建的 logger 引用不会被更新。"),this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()}}const P=z.getInstance().getLogger();function N(e){return z.getInstance().getLogger(e)}const L=N("EntityRefDecorator"),B=Symbol("EntityRefMetadata"),$=Symbol("EntityRefValues");function W(e){let t=e[$];return t||(t=new Map,e[$]=t),t}function F(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[B]||null}class H{collectEntityData(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeData(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(e){if(!e)return[];const t=e.entities;return t?.buffer?t.buffer.map((e=>({id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),parentId:e.parent?.id||null,childIds:e.children?.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}))):[]}getEntityDetails(e,t){try{if(!t)return null;const n=t.entities;if(!n?.buffer)return null;const s=n.buffer.find((t=>t.id===e));if(!s)return null;const i=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t),r=this.extractComponentDetails(s.components),o=this.getSceneInfo(t);return{...i,scene:o.name,sceneName:o.name,sceneType:o.type,parentName:s.parent?.name||null,components:r||[],componentCount:s.components?.length||0,componentTypes:s.components?.map((e=>w(e)))||[]}}catch(e){return{error:`获取实体详情失败: ${e instanceof Error?e.message:String(e)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(e){let t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{const s=Object.getPrototypeOf(e)?.constructor?.name;s&&"Object"!==s&&(t=s,n=s)}}catch(e){t="场景名获取失败"}return{name:t,type:n}}collectEntityDataWithMemory(e){if(!e)return this.getEmptyEntityDebugData();const t=e.entities;if(!t)return this.getEmptyEntityDebugData();let n;try{n=t.getStats?t.getStats():this.calculateFallbackEntityStats(t)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeDataWithMemory(e);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:this.buildEntityHierarchyTree(t),entityDetailsMap:this.buildEntityDetailsMap(t,e)}}collectArchetypeData(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionFast(t),topEntities:this.getTopEntitiesByComponentsFast(t)}}getArchetypeDistributionFast(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>w(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);i?i.count++:t.set(s,{count:1,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:0}))).sort(((e,t)=>t.count-e.count)).slice(0,20)}getTopEntitiesByComponentsFast(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}collectArchetypeDataWithMemory(e){if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);const t={entities:e.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionWithMemory(t),topEntities:this.getTopEntitiesByComponentsWithMemory(t)}}extractArchetypeStatistics(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;n.push({signature:t,count:i,memory:0}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:0})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}extractArchetypeStatisticsWithMemory(e){const t=e.getAllArchetypes(),n=[],s=[];return t.forEach((e=>{const t=e.componentTypes?.map((e=>e.name)).join(",")||"Unknown",i=e.entities?.length||0;let r=0;if(e.entities&&e.entities.length>0){const t=Math.min(5,e.entities.length);let n=0;for(let s=0;s<t;s++)n+=this.estimateEntityMemoryUsage(e.entities[s]);r=n/t*i}n.push({signature:t,count:i,memory:r}),e.entities&&e.entities.forEach((e=>{s.push({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)})}))})),n.sort(((e,t)=>t.count-e.count)),s.sort(((e,t)=>t.componentCount-e.componentCount)),{distribution:n,topEntities:s}}getArchetypeDistributionWithMemory(e){const t=new Map;return e&&e.entities&&e.entities.forEach((e=>{const n=e.components?.map((e=>w(e)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=t.get(s);let r=this.estimateEntityMemoryUsage(e);(isNaN(r)||r<0)&&(r=0),i?(i.count++,i.memory+=r):t.set(s,{count:1,memory:r,componentTypes:n})})),Array.from(t.entries()).map((([e,t])=>({signature:e,count:t.count,memory:isNaN(t.memory)?0:t.memory}))).sort(((e,t)=>t.count-e.count))}getTopEntitiesByComponentsWithMemory(e){return e&&e.entities?e.entities.map((e=>({id:e.id.toString(),name:e.name||`Entity_${e.id}`,componentCount:e.components?.length||0,memory:this.estimateEntityMemoryUsage(e)}))).sort(((e,t)=>t.componentCount-e.componentCount)):[]}getEmptyEntityDebugData(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}calculateFallbackEntityStats(e){const t=e.buffer||[],n=t.filter((e=>e.enabled&&!e.isDestroyed));return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce(((e,t)=>e+(t.components?.length||0)),0)/n.length:0}}estimateEntityMemoryUsage(e){try{let t=0;const n=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(n)&&n>0&&(t+=n),e.components&&Array.isArray(e.components)&&e.components.forEach((e=>{const n=this.calculateObjectSize(e,["entity"]);!isNaN(n)&&n>0&&(t+=n)})),isNaN(t)||t<0?0:t}catch(e){return 0}}calculateObjectSize(e,t=[]){if(!e||"object"!=typeof e)return 0;const n=new WeakSet,s=(e,i=0)=>{if(!e||"object"!=typeof e||i>=2)return 0;if(n.has(e))return 0;n.add(e);let r=32;try{const n=Object.keys(e),o=Math.min(n.length,20);for(let a=0;a<o;a++){const o=n[a];if(!o||t.includes(o)||"constructor"===o||"__proto__"===o||o.startsWith("_cc_")||o.startsWith("__"))continue;const c=e[o];r+=2*o.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:Array.isArray(c)?r+=40+Math.min(8*c.length,160):"object"==typeof c&&null!==c&&(r+=s(c,i+1))}}catch(e){return 64}return r};try{const t=s(e);return Math.max(t,32)}catch(e){return 64}}buildEntityHierarchyTree(e){if(!e?.buffer)return[];const t=[];return e.buffer.forEach((e=>{if(!e.parent){const n=this.buildEntityHierarchyNode(e);t.push(n)}})),t.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:e.id-t.id)),t}buildEntityHierarchyNode(e){let t={id:e.id,name:e.name||`Entity_${e.id}`,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),parentId:e.parent?.id||null,children:[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0};if(e.children&&e.children.length>0&&(t.children=e.children.map((e=>this.buildEntityHierarchyNode(e)))),"function"==typeof e.getDebugInfo){const n=e.getDebugInfo();t={...t,...n}}return e.components&&e.components.length>0&&(t.componentDetails=this.extractComponentDetails(e.components)),t}buildEntityDetailsMap(e,t){if(!e?.buffer)return{};const n={},s=e.buffer;for(let e=0;e<s.length;e+=100){s.slice(e,e+100).forEach((e=>{const s=e.getDebugInfo?e.getDebugInfo():this.buildFallbackEntityInfo(e,t),i=e.getComponentCacheStats?e.getComponentCacheStats():null,r=this.extractComponentDetails(e.components);n[e.id]={...s,parentName:e.parent?.name||null,components:r,componentTypes:s.componentTypes||r.map((e=>e.typeName)),cachePerformance:i?{hitRate:i.cacheStats.hitRate,size:i.cacheStats.size,maxSize:i.cacheStats.maxSize}:null}}))}return n}buildFallbackEntityInfo(e,t){const n=this.getSceneInfo(t);return{name:e.name||`Entity_${e.id}`,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:!1!==e.activeInHierarchy,destroyed:e.isDestroyed||!1,scene:n.name,sceneName:n.name,sceneType:n.type,componentCount:e.components.length,componentTypes:e.components.map((e=>w(e))),componentMask:e.componentMask?.toString()||"0",parentId:e.parent?.id||null,childCount:e.children?.length||0,childIds:e.children.map((e=>e.id))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}}extractComponentDetails(e){return e.map((e=>{const t=w(e),n={};try{Object.keys(e).forEach((t=>{if(!t.startsWith("_")&&"entity"!==t&&"constructor"!==t){const s=e[t];null!=s&&(n[t]=this.formatPropertyValue(s))}})),0===Object.keys(n).length&&(n._info="该组件没有公开属性",n._componentId=w(e))}catch(t){n._error="属性提取失败",n._componentId=w(e)}return{typeName:t,properties:n}}))}getComponentProperties(e,t,n){try{if(!n)return{};const s=n.entities;if(!s?.buffer)return{};const i=s.buffer.find((t=>t.id===e));if(!i||t>=i.components.length)return{};const r=i.components[t],o={};return Object.keys(r).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e){const t=r[e];null!=t&&(o[e]=this.formatPropertyValue(t))}})),o}catch(e){return{_error:"属性提取失败"}}}formatPropertyValue(e,t=0){return null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?`[长字符串: ${e.length}字符] ${e.substring(0,100)}...`:e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)}formatObjectFirstLevel(e){try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){const t=e.slice(0,3).map((e=>this.formatPropertyValue(e,1)));return{_isLazyArray:!0,_arrayLength:e.length,_sample:t,_summary:`数组[${e.length}个元素]`}}return e.map((e=>this.formatPropertyValue(e,1)))}const t=Object.keys(e);if(0===t.length)return{};const n={};let s=0;const i=15;for(const r of t){if(s>=i){n._hasMoreProperties=!0,n._totalProperties=t.length,n._hiddenCount=t.length-s;break}if(!r.startsWith("_")&&!r.startsWith("$")&&"function"!=typeof e[r])try{const t=e[r];null!=t&&(n[r]=this.formatPropertyValue(t,1),s++)}catch(e){n[r]=`[访问失败: ${e instanceof Error?e.message:String(e)}]`,s++}}return n}catch(e){return`[对象解析失败: ${e instanceof Error?e.message:String(e)}]`}}createLazyLoadPlaceholder(e){try{const t=e.constructor?.name||"Object";return{_isLazyObject:!0,_typeName:t,_summary:this.getObjectSummary(e,t),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:`无法分析的对象: ${e instanceof Error?e.message:String(e)}`,_objectId:Math.random().toString(36).substr(2,9)}}}getObjectSummary(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){const n=void 0!==e.z?e.z:"";return`${t}(${e.x}, ${e.y}${n?", "+n:""})`}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){const n=void 0!==e.a?e.a:1;return`${t}(${e.r}, ${e.g}, ${e.b}, ${n})`}if(t.toLowerCase().includes("node")){return`${t}: ${e.name||e._name||"未命名"}`}if(t.toLowerCase().includes("component")){const n=e.node?.name||e.node?._name||"";return`${t}${n?` on ${n}`:""}`}const n=Object.keys(e);return 0===n.length?`${t} (空对象)`:`${t} (${n.length}个属性)`}catch(e){return`${t} (无法分析)`}}generateObjectId(e){try{return void 0!==e.id?`obj_${e.id}`:void 0!==e._id?`obj_${e._id}`:void 0!==e.uuid?`obj_${e.uuid}`:void 0!==e._uuid?`obj_${e._uuid}`:`obj_${Math.random().toString(36).substr(2,9)}`}catch{return`obj_${Math.random().toString(36).substr(2,9)}`}}expandLazyObject(e,t,n,s){try{if(!s)return null;const i=s.entities;if(!i?.buffer)return null;const r=i.buffer.find((t=>t.id===e));if(!r)return null;if(t>=r.components.length)return null;const o=r.components[t],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:`展开失败: ${e instanceof Error?e.message:String(e)}`}}}getObjectByPath(e,t){if(!t)return e;const n=t.split(".");let s=e;for(const e of n){if(null==s)return null;if(e.includes("[")&&e.includes("]")){const t=e.substring(0,e.indexOf("[")),n=parseInt(e.substring(e.indexOf("[")+1,e.indexOf("]")));if(t&&(s=s[t]),!(Array.isArray(s)&&n>=0&&n<s.length))return null;s=s[n]}else s=s[e]}return s}}class U{collectSystemData(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};const n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};const s=n.processors||[];let i=new Map,r=new Map;if(e)try{i=e.getAllSystemStats(),r=e.getAllSystemData()}catch(e){}return{totalSystems:s.length,systemsInfo:s.map((e=>{const t=e.systemName||A(e),n=i.get(t),s=r.get(t);return{name:t,type:A(e),entityCount:e.entities?.length||0,executionTime:n?.averageTime||s?.executionTime||0,minExecutionTime:n?.minTime===Number.MAX_VALUE?0:n?.minTime||0,maxExecutionTime:n?.maxTime||0,executionTimeHistory:n?.recentTimes||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:s?.lastUpdateTime||0}}))}}}class q{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(e){const t=s.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,a=n>0?o/n*100:0;let c=0;performance.memory&&(c=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const h=this.frameTimeHistory.filter((e=>e>=0));return{frameTime:o,engineFrameTime:n,ecsPercentage:a,memoryUsage:c,fps:i,averageFrameTime:h.length>0?h.reduce(((e,t)=>e+t),0)/h.length:o,minFrameTime:h.length>0?Math.min(...h):o,maxFrameTime:h.length>0?Math.max(...h):o,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{let t=0;const n=[],s=e.getAllSystemStats();if(0===s.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[e,i]of s.entries()){const s=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;t+=s,n.push({systemName:e,executionTime:s,percentage:0})}return n.forEach((e=>{e.percentage=t>0?e.executionTime/t*100:0})),n.sort(((e,t)=>t.executionTime-e.executionTime)),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(e){if(!e)return[];try{const t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map((([e,t])=>{const s=n.get(e);return{systemName:e,averageTime:t.averageTime||0,maxTime:t.maxTime||0,minTime:t.minTime===Number.MAX_VALUE?0:t.minTime||0,samples:t.executionCount||0,percentage:0,entityCount:s?.entityCount||0,lastExecutionTime:s?.executionTime||0}}))}catch(e){return[]}}getMemoryDetails(){const e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){const t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0){this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++}this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e}updateGCCount(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}}}class G{constructor(e,t,n=1e3,s=10){this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,t&&(this.resetFn=t),this.maxSize=n,this.minSize=Math.max(1,s)}acquire(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())}release(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))}prewarm(e){const t=Math.min(e,this.maxSize);for(let e=this.pool.length;e<t;e++){const e=this.createFn();this.resetFn&&this.resetFn(e),this.pool.push(e),this.stats.totalCreated++}}shrink(){for(;this.pool.length>this.minSize;)this.pool.pop()}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}getStats(){const e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}}}class j{constructor(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}static getInstance(){return j.instance||(j.instance=new j),j.instance}registerPool(e,t,n,s,i){this.pools.set(e,new G(t,n,s,i)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})}acquireComponent(e){const t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null}releaseComponent(e,t){const n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)}trackUsage(e,t){let n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()}update(){const e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(const[t,n]of this.usageTracker.entries()){if(e-n.lastAccessTime>12e4){const e=this.pools.get(t);e&&e.shrink()}}this.lastCleanupTime=e}}getHotComponents(e=100){return Array.from(this.usageTracker.entries()).filter((([t,n])=>n.createCount>e)).map((([e])=>e))}prewarmAll(e=100){for(const t of this.pools.values())t.prewarm(e)}clearAll(){for(const e of this.pools.values())e.clear()}reset(){this.pools.clear(),this.usageTracker.clear()}getGlobalStats(){const e=[];for(const[t,n]of this.pools.entries())e.push({componentName:t,poolStats:n.getStats(),usage:this.usageTracker.get(t)});return e}getPoolStats(){const e=new Map;for(const[t,n]of this.pools)e.set(t,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return e}getPoolUtilization(){const e=new Map;for(const[t,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),r=i-s,o=i>0?r/i*100:0;e.set(t,{used:r,total:i,utilization:o})}return e}getComponentUtilization(e){const t=this.pools.get(e);if(!t)return 0;const n=t.getAvailableCount(),s=t.getMaxSize();return s>0?(s-n)/s*100:0}}class Q{collectComponentData(e){if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};const t=e.entities;if(!t?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const n=new Map;let s=0;t.buffer.forEach((e=>{e.components&&e.components.forEach((e=>{const t=w(e),i=n.get(t)||{count:0,entities:0};i.count++,s++,n.set(t,i)}))}));const i=new Map,r=new Map;try{const e=j.getInstance(),t=e.getPoolStats(),n=e.getPoolUtilization();for(const[e,n]of t.entries())r.set(e,n.maxSize);for(const[e,t]of n.entries())i.set(e,t.utilization)}catch(e){}return{componentTypes:n.size,componentInstances:s,componentStats:Array.from(n.entries()).map((([n,s])=>{const o=r.get(n)||0,a=i.get(n)||0,c=this.getEstimatedComponentSize(n,e);return{typeName:n,instanceCount:s.count,memoryPerInstance:c,totalMemory:s.count*c,poolSize:o,poolUtilization:a,averagePerEntity:s.count/t.buffer.length}}))}}getEstimatedComponentSize(e,t){if(Q.componentSizeCache.has(e))return Q.componentSizeCache.get(e);if(!t)return 64;const n=t.entities;if(!n?.buffer)return 64;let s=64;try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>w(t)===e));if(n){s=this.calculateQuickObjectSize(n);break}}}catch(e){s=64}return Q.componentSizeCache.set(e,s),s}calculateQuickObjectSize(e){if(!e||"object"!=typeof e)return 8;let t=32;const n=new WeakSet,s=(e,t=0)=>{if(!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);let i=0;try{const n=Object.keys(e);for(let r=0;r<Math.min(n.length,20);r++){const o=n[r];if(!o||"entity"===o||"_entity"===o||"constructor"===o)continue;const a=e[o];i+=2*o.length,"string"==typeof a?i+=Math.min(2*a.length,200):"number"==typeof a?i+=8:"boolean"==typeof a?i+=4:"object"==typeof a&&null!==a&&(i+=s(a,t+1))}}catch(e){return 32}return i};return t+=s(e),Math.max(t,32)}calculateDetailedComponentMemory(e,t){if(!t)return this.getEstimatedComponentSize(e,t);const n=t.entities;if(!n?.buffer)return this.getEstimatedComponentSize(e,t);try{for(const t of n.buffer)if(t.components){const n=t.components.find((t=>w(t)===e));if(n)return this.estimateObjectSize(n)}}catch(e){}return this.getEstimatedComponentSize(e,t)}estimateObjectSize(e,t=new WeakSet,n=0){if(null==e||n>10)return 0;if(t.has(e))return 0;let s=0;switch(typeof e){case"boolean":s=4;break;case"number":default:s=8;break;case"string":s=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){s=40+8*e.length;const i=Math.min(e.length,50);for(let r=0;r<i;r++)s+=this.estimateObjectSize(e[r],t,n+1)}else{s=32;try{const i=Object.getOwnPropertyNames(e),r=Math.min(i.length,30);for(let o=0;o<r;o++){const r=i[o];if(r&&("constructor"!==r&&"__proto__"!==r&&"entity"!==r&&"_entity"!==r&&!r.startsWith("_cc_")&&!r.startsWith("__")))try{s+=16+2*r.length;const i=e[r];null!=i&&(s+=this.estimateObjectSize(i,t,n+1))}catch(e){continue}}}catch(e){s=128}}}return 8*Math.ceil(s/8)}static clearCache(){Q.componentSizeCache.clear()}}Q.componentSizeCache=new Map;class V{constructor(){this.sceneStartTime=Date.now()}collectSceneData(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};const t=(Date.now()-this.sceneStartTime)/1e3,n=e.entities,s=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:t,sceneEntityCount:n?.buffer?.length||0,sceneSystemCount:s?.processors?.length||0,sceneMemory:0,sceneUptime:t}}setSceneStartTime(e){this.sceneStartTime=e}}class Y{constructor(e,t=!0){this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.url=e,this.autoReconnect=t}setMessageHandler(e){this.messageHandler=e}connect(){return new Promise(((e,t)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=t=>{this.handleOpen(t),e()},this.ws.onclose=e=>{this.handleClose(e)},this.ws.onerror=e=>{this.handleError(e),t(e)},this.ws.onmessage=e=>{this.handleMessage(e)}}catch(e){this.handleConnectionFailure(e),t(e)}}))}disconnect(){this.ws&&(this.autoReconnect=!1,this.ws.close(),delete this.ws),this.isConnected=!1}send(e){if(this.isConnected&&this.ws)try{const t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}}getConnectionStatus(){return this.isConnected}setMaxReconnectAttempts(e){this.maxReconnectAttempts=e}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((()=>{this.connect().catch((e=>{this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}))}),e)}handleMessage(e){try{const t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}}handleOpen(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)}handleClose(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}handleError(e){this.onError&&this.onError(e)}handleConnectionFailure(e){this.onError&&this.onError(e)}}var J,Z;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(J||(J={}));class X{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0]};return X.setBit(t,e),t}static fromNumber(e){return{base:[e>>>0,0]}}static hasAny(e,t){const n=t.base,s=e.base,i=t.segments,r=e.segments,o=0!==(s[J.LOW]&n[J.LOW])||0!==(s[J.HIGH]&n[J.HIGH]);return!o&&i&&r?r.some(((e,t)=>{const n=i[t];return n&&(0!==(e[J.LOW]&n[J.LOW])||0!==(e[J.HIGH]&n[J.HIGH]))})):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[J.LOW]&s[J.LOW])===s[J.LOW]&&(n[J.HIGH]&s[J.HIGH])===s[J.HIGH];if(!o||!r)return o;const a=i?.length??0;if(i)for(let e=0;e<Math.min(a,r.length);e++){const t=i[e],n=r[e];if((t[J.LOW]&n[J.LOW])!==n[J.LOW]||(t[J.HIGH]&n[J.HIGH])!==n[J.HIGH])return!1}for(let e=a;e<r.length;e++){const t=r[e];if(0!==t[J.LOW]||0!==t[J.HIGH])return!1}return!0}static hasNone(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=0===(n[J.LOW]&s[J.LOW])&&0===(n[J.HIGH]&s[J.HIGH]);return i&&o&&r?i.every(((e,t)=>{const n=r[t];return!n||0===(e[J.LOW]&n[J.LOW])&&0===(e[J.HIGH]&n[J.HIGH])})):o}static isZero(e){const t=0===e.base[J.LOW]&&0===e.base[J.HIGH];return e.segments&&t?e.segments.every((e=>0===e[J.LOW]&&0===e[J.HIGH])):t}static equals(e,t){const n=e.base[J.LOW]===t.base[J.LOW]&&e.base[J.HIGH]===t.base[J.HIGH];if(!n||!e.segments&&!t.segments)return n;const s=e.segments??[],i=t.segments??[];for(let e=0;e<Math.max(s.length,i.length);e++){const t=s[e],n=i[e];if(t&&!n){if(0!==t[J.LOW]||0!==t[J.HIGH])return!1}else if(!t&&n){if(0!==n[J.LOW]||0!==n[J.HIGH])return!1}else if(t&&n&&(t[J.LOW]!==n[J.LOW]||t[J.HIGH]!==n[J.HIGH]))return!1}return!0}static setBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t),s=63&t;s<32?n[J.LOW]|=1<<s:n[J.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[J.LOW]&1<<s):!!(n[J.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=X.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[J.LOW]&=~(1<<s):n[J.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[J.LOW]|=t.base[J.LOW],e.base[J.HIGH]|=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++){const s=t[e],i=n[e];s[J.LOW]|=i[J.LOW],s[J.HIGH]|=i[J.HIGH]}}}static andInPlace(e,t){e.base[J.LOW]&=t.base[J.LOW],e.base[J.HIGH]&=t.base[J.HIGH];const n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);const t=e.segments;for(;t.length<n.length;)t.push([0,0]);for(let e=0;e<n.length;e++){const s=t[e],i=n[e];s[J.LOW]&=i[J.LOW],s[J.HIGH]&=i[J.HIGH]}}}static xorInPlace(e,t){e.base[J.LOW]^=t.base[J.LOW],e.base[J.HIGH]^=t.base[J.HIGH];const n=t.segments;if(!n||0==n.length)return;e.segments||(e.segments=[]);const s=e.segments;for(;s.length<n.length;)s.push([0,0]);for(let e=0;e<n.length;e++){const t=s[e],i=n[e];t[J.LOW]^=i[J.LOW],t[J.HIGH]^=i[J.HIGH]}}static clear(e){if(e.base[J.LOW]=0,e.base[J.HIGH]=0,e.segments)for(let t=0;t<e.segments.length;t++){const n=e.segments[t];n[J.LOW]=0,n[J.HIGH]=0}}static copy(e,t){if(X.clear(t),t.base[J.LOW]=e.base[J.LOW],t.base[J.HIGH]=e.base[J.HIGH],!e.segments||0==e.segments.length)return;if(!t.segments)return void(t.segments=e.segments.map((e=>[...e])));const n=e.segments.length-t.segments.length;for(let e=0;e<n;e++)t.segments.push([0,0]);const s=t.segments,i=e.segments;for(let e=0;e<i.length;e++){const t=s[e],n=i[e];t[J.LOW]=n[J.LOW],t[J.HIGH]=n[J.HIGH]}}static clone(e){return{base:e.base.slice(),...e.segments&&{segments:e.segments.map((e=>[...e]))}}}static toString(e,t=2,n=!1){2!=t&&16!=t&&(t=2);const s=e.segments?.length??0;let i="";if(n){let e=0;e=2===t?66:19;for(let t=0;t<=s;t++){i+=(0===t?"0 (Base):":`${t} (${64*t}):`).toString().padEnd(e)}i+="\n"}for(let r=-1;r<s;r++){let s="";const o=-1==r?e.base:e.segments[r],a=o[J.HIGH],c=o[J.LOW];if(2==t){s=a.toString(2).padStart(32,"0")+"_"+c.toString(2).padStart(32,"0")}else{let e=a?a.toString(16).toUpperCase():"";n&&(e=e.padStart(8,"0"));let t=c.toString(16).toUpperCase();e&&(t=t.padStart(8,"0")),s="0x"+e+t}i+=-1===r?s:" "+s}return i}static popCount(e){let t=0;for(let n=-1;n<(e.segments?.length??0);n++){const s=-1==n?e.base:e.segments[n];let i=s[J.LOW],r=s[J.HIGH];for(;i;)i&=i-1,t++;for(;r;)r&=r-1,t++}return t}static getSegmentByBitIndex(e,t,n=!0){if(t<=63)return e.base;{let s=e.segments;if(!s){if(!n)return null;s=e.segments=[]}const i=(t>>6)-1;if(s.length<=i){if(!n)return null;const e=i-s.length+1;for(let t=0;t<e;t++)s.push([0,0])}return s[i]??null}}}X.ZERO={base:[0,0]};class K{static inferOptimalType(e,t={}){const n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";const{minValue:s,maxValue:i,precision:r,signed:o}=t;if(!0===r)return Math.abs(e)>34028235e31||void 0!==s&&Math.abs(s)>34028235e31||void 0!==i&&Math.abs(i)>34028235e31?"float64":"float32";if(!1===r||Number.isInteger(e)){const t=void 0!==s?s:e,n=void 0!==i?i:e;return!1!==o&&(t<0||e<0)?t>=-128&&n<=127?"int8":t>=-32768&&n<=32767?"int16":t>=-2147483648&&n<=2147483647?"int32":"float64":n<=255?"uint8":n<=65535?"uint16":n<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"}static getTypedArrayConstructor(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}}}class ee{constructor(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}initializeFields(e){const t=new e,n=e.__highPrecisionFields||new Set,s=e.__float64Fields||new Set,i=e.__float32Fields||new Set,r=e.__int32Fields||new Set,o=e.__uint32Fields||new Set,a=e.__int16Fields||new Set,c=e.__uint16Fields||new Set,h=e.__int8Fields||new Set,l=e.__uint8Fields||new Set,u=e.__uint8ClampedFields||new Set,d=e.__autoTypedFields||new Map,p=e.__serializeMapFields||new Set,m=e.__serializeSetFields||new Set,g=e.__serializeArrayFields||new Set;for(const e in t)if(t.hasOwnProperty(e)&&"id"!==e){const y=t[e],f=typeof y;if("number"===f)if(n.has(e));else if(d.has(e)){const t=d.get(e),n=K.inferOptimalType(y,t),s=K.getTypedArrayConstructor(n);this.fields.set(e,new s(this._capacity)),ee._logger.info(`字段 ${e} 自动推断为 ${n} 类型,值: ${y}, 选项:`,t)}else s.has(e)?this.fields.set(e,new Float64Array(this._capacity)):r.has(e)?this.fields.set(e,new Int32Array(this._capacity)):o.has(e)?this.fields.set(e,new Uint32Array(this._capacity)):a.has(e)?this.fields.set(e,new Int16Array(this._capacity)):c.has(e)?this.fields.set(e,new Uint16Array(this._capacity)):h.has(e)?this.fields.set(e,new Int8Array(this._capacity)):l.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):u.has(e)?this.fields.set(e,new Uint8ClampedArray(this._capacity)):(i.has(e),this.fields.set(e,new Float32Array(this._capacity)));else"boolean"===f?l.has(e)||!i.has(e)&&!s.has(e)?this.fields.set(e,new Uint8Array(this._capacity)):this.fields.set(e,new Float32Array(this._capacity)):"string"===f?this.stringFields.set(e,new Array(this._capacity)):"object"===f&&null!==y&&(p.has(e)||m.has(e)||g.has(e))&&this.serializedFields.set(e,new Array(this._capacity))}}addComponent(e,t){if(this.entityToIndex.has(e)){const n=this.entityToIndex.get(e);return void this.updateComponentAtIndex(n,t)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(e,n),this.in