@esengine/ecs-framework
Version:
用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架
1 lines • 299 kB
JavaScript
"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){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;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,t){const n=new e;return d(n,t),n}function d(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 u(e){const t=r.get(e);return t?.updatable??!1}function p(e){return r.get(e)}var m;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,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=[]}},exports.TimerManager=e([a()],exports.TimerManager),exports.PerformanceWarningType=void 0,(m=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",m.HIGH_MEMORY_USAGE="high_memory_usage",m.HIGH_CPU_USAGE="high_cpu_usage",m.FREQUENT_GC="frequent_gc",m.LOW_FPS="low_fps",m.HIGH_ENTITY_COUNT="high_entity_count";class f{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 g{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 g(()=>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}}g._pools=new Map;class y{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 g(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 _=Symbol("ComponentTypeName"),S=Symbol("ComponentDependencies"),C=Symbol("ComponentEditorOptions");function E(e){return void 0!==e[_]}function v(e){const t=e[_];return t||(e.name||"UnknownComponent")}function b(e){return v(e.constructor)}function T(e){return e[C]}function w(e){const t=T(e);return t?.hideInInspector??!1}var x,I;!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(x||(x={}));class M{static create(e){if(e<0)throw new Error(`Bit index ${e} out of range [0, ∞)`);const t={base:[0,0]};return M.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[x.LOW]&n[x.LOW])||0!==(s[x.HIGH]&n[x.HIGH]);return!o&&i&&r?r.some((e,t)=>{const n=i[t];return n&&(0!==(e[x.LOW]&n[x.LOW])||0!==(e[x.HIGH]&n[x.HIGH]))}):o}static hasAll(e,t){const n=e.base,s=t.base,i=e.segments,r=t.segments,o=(n[x.LOW]&s[x.LOW])===s[x.LOW]&&(n[x.HIGH]&s[x.HIGH])===s[x.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[x.LOW]&n[x.LOW])!==n[x.LOW]||(t[x.HIGH]&n[x.HIGH])!==n[x.HIGH])return!1}for(let e=a;e<r.length;e++){const t=r[e];if(0!==t[x.LOW]||0!==t[x.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[x.LOW]&s[x.LOW])&&0===(n[x.HIGH]&s[x.HIGH]);return i&&o&&r?i.every((e,t)=>{const n=r[t];return!n||0===(e[x.LOW]&n[x.LOW])&&0===(e[x.HIGH]&n[x.HIGH])}):o}static isZero(e){const t=0===e.base[x.LOW]&&0===e.base[x.HIGH];return e.segments&&t?e.segments.every(e=>0===e[x.LOW]&&0===e[x.HIGH]):t}static equals(e,t){const n=e.base[x.LOW]===t.base[x.LOW]&&e.base[x.HIGH]===t.base[x.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[x.LOW]||0!==t[x.HIGH])return!1}else if(!t&&n){if(0!==n[x.LOW]||0!==n[x.HIGH])return!1}else if(t&&n&&(t[x.LOW]!==n[x.LOW]||t[x.HIGH]!==n[x.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=M.getSegmentByBitIndex(e,t),s=63&t;s<32?n[x.LOW]|=1<<s:n[x.HIGH]|=1<<s-32}static getBit(e,t){if(t<0)return!1;const n=M.getSegmentByBitIndex(e,t,!1);if(!n)return!1;const s=63&t;return s<32?!!(n[x.LOW]&1<<s):!!(n[x.HIGH]&1<<s-32)}static clearBit(e,t){if(t<0)throw new Error(`Bit index ${t} out of range [0, 63]`);const n=M.getSegmentByBitIndex(e,t,!1);if(!n)return;const s=63&t;s<32?n[x.LOW]&=~(1<<s):n[x.HIGH]&=~(1<<s-32)}static orInPlace(e,t){e.base[x.LOW]|=t.base[x.LOW],e.base[x.HIGH]|=t.base[x.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[x.LOW]|=i[x.LOW],s[x.HIGH]|=i[x.HIGH]}}}static andInPlace(e,t){e.base[x.LOW]&=t.base[x.LOW],e.base[x.HIGH]&=t.base[x.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[x.LOW]&=i[x.LOW],s[x.HIGH]&=i[x.HIGH]}}}static xorInPlace(e,t){e.base[x.LOW]^=t.base[x.LOW],e.base[x.HIGH]^=t.base[x.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[x.LOW]^=i[x.LOW],t[x.HIGH]^=i[x.HIGH]}}static clear(e){if(e.base[x.LOW]=0,e.base[x.HIGH]=0,e.segments)for(let t=0;t<e.segments.length;t++){const n=e.segments[t];n[x.LOW]=0,n[x.HIGH]=0}}static copy(e,t){if(M.clear(t),t.base[x.LOW]=e.base[x.LOW],t.base[x.HIGH]=e.base[x.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[x.LOW]=n[x.LOW],t[x.HIGH]=n[x.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[x.HIGH],c=o[x.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[x.LOW],r=s[x.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}}}M.ZERO={base:[0,0]},exports.LogLevel=void 0,(I=exports.LogLevel||(exports.LogLevel={}))[I.Debug=0]="Debug",I[I.Info=1]="Info",I[I.Warn=2]="Warn",I[I.Error=3]="Error",I[I.Fatal=4]="Fatal",I[I.None=5]="None";const A={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 D{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:A.BRIGHT_BLACK,info:A.GREEN,warn:A.YELLOW,error:A.RED,fatal:A.BRIGHT_RED,reset:A.RESET},...this._config.colors}}}class k{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 D({level:this._defaultLevel})}static getInstance(){return k._instance||(k._instance=new k),k._instance}getLogger(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new D({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 D&&this._defaultLogger.setLevel(e);for(const t of this._loggers.values())t instanceof D&&t.setLevel(e)}createChildLogger(e,t){const n=`${e}.${t}`;return this.getLogger(n)}setGlobalColors(e){this._defaultLogger instanceof D&&this._defaultLogger.setColors(e);for(const t of this._loggers.values())t instanceof D&&t.setColors(e)}resetColors(){this._defaultLogger instanceof D&&this._defaultLogger.setColors({});for(const e of this._loggers.values())e instanceof D&&e.setColors({})}setLoggerFactory(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()}}const P=k.getInstance().getLogger();function O(e){return k.getInstance().getLogger(e)}const R=O("ComponentRegistry");class N{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=v(e);if(E(e)||this._warnedComponents.has(e)||(this._warnedComponents.add(e),R.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),R.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=v(e);throw new Error(`Component type ${t} is not registered`)}return M.create(t)}getBitIndex(e){const t=this._componentTypes.get(e);if(void 0===t){const t=v(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=M.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=M.clone(M.ZERO);for(const t of e){const e=this.getComponentId(t);if(void 0!==e){const t=M.create(e);M.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(),R.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=v(e);this._componentNameToType.set(t,e),this._componentNameToId.set(t,n)}this._nextBitIndex=e.getRegisteredCount(),this._hotReloadEnabled=e.isHotReloadEnabled()}}const z=new N;var F;exports.SyncOperation=void 0,(F=exports.SyncOperation||(exports.SyncOperation={}))[F.FULL=0]="FULL",F[F.DELTA=1]="DELTA",F[F.SPAWN=2]="SPAWN",F[F.DESPAWN=3]="DESPAWN";const B=Symbol("SyncMetadata"),$=Symbol("ChangeTracker"),L=Symbol("SystemTypeName");function H(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");const s=n;s[_]=e,t?.requires&&(s[S]=t.requires),t?.editor&&(s[C]=t.editor);const i=n[B];return i&&(i.typeId=e),z.register(n),n}}function W(e){return e.__systemMetadata__}function U(e){return W(e.constructor)}function G(e){const t=e[L];return t||(e.name||"UnknownSystem")}function q(e){return G(e.constructor)}const j="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}},V=new Map;function Q(e){const t=V.get(e);return t?.deref()||null}class Y{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 j(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){V.set(e,new j(t))}unregisterEntityScene(e){V.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 J=O("EntityRefDecorator"),Z=Symbol("EntityRefMetadata"),X=Symbol("EntityRefValues");function K(e){let t=e[X];return t||(t=new Map,e[X]=t),t}function ee(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[Z]||null}function te(e,t){const n=ee(e);return!!n&&n.properties.has(t)}const ne=new WeakMap,se=Symbol.for("@esengine/property:metadata");const ie=Symbol("schedulingMetadata");function re(e){const t=e;return t[ie]||(t[ie]={stage:"update",before:[],after:[],sets:[]}),t[ie]}function oe(e){let t=Object.getPrototypeOf(e);for(;t;){const e=t[ie];if(e)return e;t=Object.getPrototypeOf(t)}}class ae{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}}ae.TYPE_CONSTRUCTORS={float32:Float32Array,float64:Float64Array,int32:Int32Array,uint32:Uint32Array,int16:Int16Array,uint16:Uint16Array,int8:Int8Array,uint8:Uint8Array,uint8clamped:Uint8ClampedArray},ae.TYPE_BYTES={float32:4,float64:8,int32:4,uint32:4,int16:2,uint16:2,int8:1,uint8:1,uint8clamped:1};class ce{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 he(e,t){const n=e.constructor;let s=n[t];return s||(s=new Set,n[t]=s),s}function le(e,t){he(e,"__int32Fields").add(String(t))}ce._logger=O("SoASerializer");class de{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 p=Object.keys(t).filter(e=>"id"!==e);for(const e of p){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=ae.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]=ce.serialize(t,n,{isMap:o.has(n),isSet:a.has(n),isArray:c.has(n)})}else h.has(n)?s.set(n,ce.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?ce.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]=ce.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]=ce.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=ae.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=ae.getTypeName(s),r=ae.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 ue{get lastWriteEpoch(){return this._lastWriteEpoch}constructor(){this.entityId=null,this._lastWriteEpoch=0,this.id=ue._idGenerator++}markDirty(e){this._lastWriteEpoch=e}onAddedToEntity(){}onRemovedFromEntity(){}onDeserialized(){}}ue._idGenerator=0,e([le,t("design:type",Object)],ue.prototype,"entityId",void 0);const pe=Symbol("SerializableMetadata"),me=Symbol("SerializeField"),fe=Symbol("SerializeOptions");function ge(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");let n;if(Object.prototype.hasOwnProperty.call(t,pe))n=t[pe],n.options=e;else{const s=t[pe];n={options:e,fields:s?new Map(s.fields):new Map,ignoredFields:s?new Set(s.ignoredFields):new Set},t[pe]=n}return t}}function ye(e){return function(t,n){const s=t.constructor;let i;if(Object.prototype.hasOwnProperty.call(s,pe))i=s[pe];else{const e=s[pe];i={options:e?{...e.options}:{version:1},fields:e?new Map(e.fields):new Map,ignoredFields:e?new Set(e.ignoredFields):new Set},s[pe]=i}i.fields.set(n,e||{})}}function _e(e){if(!e)return null;return("function"==typeof e?e:e.constructor)[pe]||null}exports.HierarchyComponent=class extends ue{constructor(){super(...arguments),this.parentId=null,this.childIds=[],this.depth=0,this.bActiveInHierarchy=!0,this.bCacheDirty=!0}},e([ye(),t("design:type",Object)],exports.HierarchyComponent.prototype,"parentId",void 0),e([ye(),t("design:type",Array)],exports.HierarchyComponent.prototype,"childIds",void 0),exports.HierarchyComponent=e([H("Hierarchy",{editor:{hideInInspector:!0}}),ge({version:1,typeId:"Hierarchy"})],exports.HierarchyComponent);class Se{constructor(){this.condition={all:[],any:[],none:[]}}static all(...e){return(new Se).all(...e)}static any(...e){return(new Se).any(...e)}static none(...e){return(new Se).none(...e)}static byTag(e){return(new Se).withTag(e)}static byName(e){return(new Se).withName(e)}static byComponent(e){return(new Se).withComponent(e)}static complex(){return new Se}static empty(){return new Se}static nothing(){const e=new Se;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 Se;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=>v(e)).join(", ")})`),this.condition.any.length>0&&e.push(`any(${this.condition.any.map(e=>v(e)).join(", ")})`),this.condition.none.length>0&&e.push(`none(${this.condition.none.map(e=>v(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(${v(this.condition.component)})`),`Matcher[${e.join(" & ")}]`}}class Ce{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 Ee{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 ${v(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 ve{constructor(){this.storages=new Map}isSoAStorage(e){return this.storages.get(e)instanceof de}getSoAStorage(e){const t=this.getStorage(e);return t instanceof de?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 de(e),ve._logger.info(`为 ${v(e)} 启用SoA优化(适用于大规模批量操作)`)):t=new Ee(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=z){const n=M.clone(M.ZERO);for(const[s,i]of this.storages.entries())if(i.hasComponent(e)){const e=t.getBitMask(s);M.orInPlace(n,e)}return n}getAllStats(){const e=new Map;for(const[t,n]of this.storages.entries()){const s=v(t);e.set(s,n.getStats())}return e}clear(){for(const e of this.storages.values())e.clear();this.storages.clear()}}ve._logger=O("ComponentStorage");const be=O("CommandBuffer");var Te,we;exports.CommandType=void 0,(Te=exports.CommandType||(exports.CommandType={})).ADD_COMPONENT="add_component",Te.REMOVE_COMPONENT="remove_component",Te.DESTROY_ENTITY="destroy_entity",Te.SET_ENTITY_ACTIVE="set_entity_active";class xe{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?z.getBitIndex(e):z.getBitIndex(e.constructor)}addComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&be.debug(`CommandBuffer: 忽略添加组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);if(n.removes?.delete(s),n.adds||(n.adds=new Map),n.adds.set(s,t),this._debug){const n=v(t.constructor);be.debug(`CommandBuffer: 延迟添加组件 ${n} 到实体 ${e.name}`)}}else this._commands.push({type:exports.CommandType.ADD_COMPONENT,entity:e,component:t})}removeComponent(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&be.debug(`CommandBuffer: 忽略移除组件,实体 ${e.name} 已标记销毁`));const s=this.getTypeId(t);n.adds?.delete(s),n.removes||(n.removes=new Set),n.removes.add(s),this._debug&&be.debug(`CommandBuffer: 延迟移除组件 ${t.name} 从实体 ${e.name}`)}else this._commands.push({type:exports.CommandType.REMOVE_COMPONENT,entity:e,componentType:t})}destroyEntity(e){if(this._useDeduplication){const t=this.getPending(e);t.adds?.clear(),t.removes?.clear(),delete t.active,t.bDestroy=!0,this._debug&&be.debug(`CommandBuffer: 延迟销毁实体 ${e.name}`)}else this._commands.push({type:exports.CommandType.DESTROY_ENTITY,entity:e})}setEntityActive(e,t){if(this._useDeduplication){const n=this.getPending(e);if(n.bDestroy)return void(this._debug&&be.debug(`CommandBuffer: 忽略设置激活状态,实体 ${e.name} 已标记销毁`));n.active=t,this._debug&&be.debug(`CommandBuffer: 延迟设置实体 ${e.name} 激活状态为 ${t}`)}else this._commands.push({type:exports.CommandType.SET_ENTITY_ACTIVE,entity:e,value:t})}flush(){return this._useDeduplication?this.flushDeduplication():this.flushLegacy()}flushDeduplication(){if(0===this._pending.size)return 0;const e=this._pending.size;let t=0;this._debug&&be.debug(`CommandBuffer: 开始执行 ${e} 个实体的延迟命令`);const n=this._pending;this._pending=new Map;for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.removes&&s.removes.size>0)for(const n of s.removes)try{const s=z.getTypeByBitIndex(n);s&&(e.removeComponentByType(s),t++)}catch(t){be.error("CommandBuffer: 移除组件失败",{entity:e.name,typeId:n,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&s.adds&&s.adds.size>0)for(const n of s.adds.values())try{e.addComponent(n),t++}catch(t){const s=v(n.constructor);be.error("CommandBuffer: 添加组件失败",{entity:e.name,component:s,error:t})}for(const[e,s]of n)if(!s.bDestroy&&e.scene&&void 0!==s.active)try{e.active=s.active,t++}catch(t){be.error("CommandBuffer: 设置激活状态失败",{entity:e.name,error:t})}for(const[e,s]of n)if(s.bDestroy&&e.scene)try{e.destroy(),t++}catch(t){be.error("CommandBuffer: 销毁实体失败",{entity:e.name,error:t})}return this._debug&&be.debug(`CommandBuffer: 完成执行 ${t} 个延迟命令`),t}flushLegacy(){if(0===this._commands.length)return 0;const e=this._commands.length;this._debug&&be.debug(`CommandBuffer: 开始执行 ${e} 个延迟命令`);const t=this._commands;this._commands=[];for(const e of t)this.executeCommand(e);return this._debug&&be.debug(`CommandBuffer: 完成执行 ${e} 个延迟命令`),e}executeCommand(e){if(e.entity.scene)try{switch(e.type){case exports.CommandType.ADD_COMPONENT:e.component&&e.entity.addComponent(e.component);break;case exports.CommandType.REMOVE_COMPONENT:e.componentType&&e.entity.removeComponentByType(e.componentType);break;case exports.CommandType.DESTROY_ENTITY:e.entity.destroy();break;case exports.CommandType.SET_ENTITY_ACTIVE:void 0!==e.value&&(e.entity.active=e.value)}}catch(t){be.error("CommandBuffer: 执行命令失败",{command:e,error:t})}else this._debug&&be.debug(`CommandBuffer: 跳过命令,实体 ${e.entity.name} 已无效`)}clear(){if(this._debug){const e=this._useDeduplication?this._pending.size:this._commands.length;e>0&&be.debug(`CommandBuffer: 清空 ${e} 个未执行的命令`)}this._pending.clear(),this._commands.length=0}dispose(){this.clear(),this._scene=null}}class Ie{get entities(){const e=this._entityCache.getFrame();return null!==e?e:(this._entityCache.hasPersistent()||this._entityCache.setPersistent(this.queryEntities()),this._entityCache.getPersistent())}get updateOrder(){return this._updateOrder}set updateOrder(e){this.setUpdateOrder(e)}get addOrd