@esengine/ecs-framework
Version:
用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架
1 lines • 293 kB
JavaScript
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:"[30m",RED:"[31m",GREEN:"[32m",YELLOW:"[33m",BLUE:"[34m",MAGENTA:"[35m",CYAN:"[36m",WHITE:"[37m",BRIGHT_BLACK:"[90m",BRIGHT_RED:"[91m",BRIGHT_GREEN:"[92m",BRIGHT_YELLOW:"[93m",BRIGHT_BLUE:"[94m",BRIGHT_MAGENTA:"[95m",BRIGHT_CYAN:"[96m",BRIGHT_WHITE:"[97m",RESET:"[0m",BOLD:"[1m",UNDERLINE:"[4m"};class 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