@esengine/ecs-framework 2.4.4 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
1
  !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ECS={})}(this,function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function n(e,t,n,i,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(i,r)}function i(e){return function(){var t=this,i=arguments;return new Promise(function(r,o){var s=e.apply(t,i);function a(e){n(s,r,o,a,c,"next",e)}function c(e){n(s,r,o,a,c,"throw",e)}a(void 0)})}}function r(e,t,n){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return n&&p(r,n.prototype),r}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,m(i.key),i)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function a(e,n){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,n){if(e){if("string"==typeof e)return t(e,n);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,n):void 0}}(e))||n){i&&(e=i);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},c.apply(null,arguments)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function l(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(h=function(){return!!e})()}function d(){
2
2
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
- var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function o(n,i,r,o){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,i,r){var o,a,c,u=0,l=r||[],h=!1,d={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,a=0,c=e,d.n=n,s}};function f(n,i){for(a=n,c=i,t=0;!h&&u&&!r&&t<l.length;t++){var r,o=l[t],f=d.p,p=o[2];n>3?(r=p===i)&&(c=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=f&&((r=n<2&&f<o[1])?(a=0,d.v=i,d.n=o[1]):f<p&&(r=n<3||o[0]>i||i>p)&&(o[4]=n,o[5]=i,d.n=p,a=0))}if(r||n>1)return s;throw h=!0,i}return function(r,l,p){if(u>1)throw TypeError("Generator is already running");for(h&&1===l&&f(l,p),a=l,c=p;(t=a<2?e:c)||!h;){o||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(u=2,o){if(a||(r="next"),t=o[r]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,a<2&&(a=0)}else 1===a&&(t=o.return)&&t.call(o),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=e}else if((t=(h=d.n<0)?c:n.call(i,d))!==s)break}catch(t){o=e,a=1,c=t}finally{u=1}}return{value:t,done:h}}}(n,r,o),!0),u}var s={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var l=[][i]?t(t([][i]())):(f(t={},i,function(){return this}),t),h=u.prototype=a.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,r,"GeneratorFunction")),e.prototype=Object.create(h),e}return c.prototype=u,f(h,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,r,"GeneratorFunction"),f(h),f(h,r,"Generator"),f(h,i,function(){return this}),f(h,"toString",function(){return"[object Generator]"}),(d=function(){return{w:o,m:p}})()}function f(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}f=function(e,t,n,i){function o(t,n){f(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},f(e,t,n,i)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function m(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function v(e){var t="function"==typeof Map?new Map:void 0;return v=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,u(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),p(n,e)},v(e)}function g(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;var _=function(){function e(){}return e.update=function(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},e.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},e.checkEvery=function(e,t){return this.totalTime-t>=e},e}();_.deltaTime=0,_.unscaledDeltaTime=0,_.totalTime=0,_.unscaledTotalTime=0,_.timeScale=1,_.frameCount=0;var S,C=function(){function e(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var t=e.prototype;return t.getContext=function(){return this.context},t.reset=function(){this._elapsedTime=0},t.stop=function(){this._isDone=!0},t.tick=function(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=_.deltaTime,this._isDone},t.initialize=function(e,t,n,i){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=i.bind(n)},t.unload=function(){this.context=null,this._onTime=null},s(e,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),E=new WeakMap,b=new WeakMap;function T(){return function(e){var t=E.get(e);E.set(e,c({injectable:!0,dependencies:[]},(null==t?void 0:t.properties)&&{properties:t.properties}))}}function w(e){return void 0===e&&(e=0),function(t){var 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.");b.set(t,{updatable:!0,priority:e})}}function I(e){return function(t,n){var i=E.get(t.constructor);i||(i={injectable:!0,dependencies:[]},E.set(t.constructor,i)),i.properties||(i.properties=new Map),i.properties.set(n,e)}}function M(e){var t,n=E.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function A(e,t){var n=new e;return k(n,t),n}function k(e,t){var n,i=e.constructor,r=(n=i,E.get(n));if(null!=r&&r.properties&&0!==r.properties.size)for(var o,s=a(r.properties);!(o=s()).done;){var c=o.value,u=c[0],l=c[1],h=t.resolve(l);null!==h&&(e[u]=h)}}function D(e){var t,n=b.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function P(e){return b.get(e)}e.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,i){var r=new C;return r.initialize(e,t,n,i),this._timers.push(r),r},t.dispose=function(){for(var e,t=a(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),e.TimerManager=g([w()],e.TimerManager),e.PerformanceWarningType=void 0,(S=e.PerformanceWarningType||(e.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",S.HIGH_MEMORY_USAGE="high_memory_usage",S.HIGH_CPU_USAGE="high_cpu_usage",S.FREQUENT_GC="frequent_gc",S.LOW_FPS="low_fps",S.HIGH_ENTITY_COUNT="high_entity_count";var O=function(){function e(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}var t=e.prototype;return t.updateFPS=function(e){},t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.startMonitoring=function(e){return this._isEnabled?performance.now():0},t.endMonitoring=function(e,t,n){if(void 0===n&&(n=0),this._isEnabled&&0!==t){var i=performance.now(),r=i-t,o={name:e,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(e,o),this.updateStats(e,r)}},t.updateStats=function(e,t){var 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)},t.calculateAdvancedStats=function(e){if(0!==e.recentTimes.length){var t=e.recentTimes.reduce(function(e,t){return e+t},0)/e.recentTimes.length,n=e.recentTimes.reduce(function(e,n){return e+Math.pow(n-t,2)},0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);var i=[].concat(e.recentTimes).sort(function(e,t){return e-t}),r=i.length;e.percentile95=i[Math.floor(.95*r)]||0,e.percentile99=i[Math.floor(.99*r)]||0}},t.getSystemData=function(e){return this._systemData.get(e)},t.getSystemStats=function(e){return this._systemStats.get(e)},t.getAllSystemData=function(){return new Map(this._systemData)},t.getAllSystemStats=function(){return new Map(this._systemStats)},t.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var e=[];e.push("=== ECS Performance Report ==="),e.push("");for(var t,n=a(Array.from(this._systemStats.entries()).sort(function(e,t){return t[1].averageTime-e[1].averageTime}));!(t=n()).done;){var i=t.value,r=i[0],o=i[1],s=this._systemData.get(r);e.push("System: "+r),e.push(" Current: "+(null==s?void 0:s.executionTime.toFixed(2))+"ms ("+(null==s?void 0:s.entityCount)+" entities)"),e.push(" Average: "+o.averageTime.toFixed(2)+"ms"),e.push(" Min/Max: "+o.minTime.toFixed(2)+"ms / "+o.maxTime.toFixed(2)+"ms"),e.push(" Total: "+o.totalTime.toFixed(2)+"ms ("+o.executionCount+" calls)"),null!=s&&s.averageTimePerEntity&&s.averageTimePerEntity>0&&e.push(" Per Entity: "+s.averageTimePerEntity.toFixed(4)+"ms"),e.push("")}var c=Array.from(this._systemData.values()).reduce(function(e,t){return e+t.executionTime},0);return e.push("Total Frame Time: "+c.toFixed(2)+"ms"),e.push("Systems Count: "+this._systemData.size),e.join("\n")},t.reset=function(){this._systemData.clear(),this._systemStats.clear()},t.resetSystem=function(e){this._systemData.delete(e),this._systemStats.delete(e)},t.getPerformanceWarnings=function(e){void 0===e&&(e=16.67);for(var t,n=[],i=a(this._systemData.entries());!(t=i()).done;){var r=t.value,o=r[0],s=r[1];s.executionTime>e&&n.push(o+": "+s.executionTime.toFixed(2)+"ms (>"+e+"ms)")}return n},t.setMaxRecentSamples=function(e){this._maxRecentSamples=e;for(var t,n=a(this._systemStats.values());!(t=n()).done;)for(var i=t.value;i.recentTimes.length>e;)i.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._isEnabled=!1},s(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),x=function(){function e(e,t,n){void 0===t&&(t=100),void 0===n&&(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}}e.getPool=function(t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(t);return r||(r=new e(function(){return new t},n,i),this._pools.set(t,r)),r};var t=e.prototype;return t.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},t.release=function(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))},t.getStats=function(){return c({},this._stats)},t.clear=function(){for(var e,t=a(this._objects);!(e=t()).done;){e.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},t.compact=function(e){for(var t=null!=e?e:Math.floor(this._objects.length/2);this._objects.length>t;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},t.prewarm=function(e){for(var t=Math.min(e,this._maxSize-this._objects.length),n=0;n<t;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},t.setMaxSize=function(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)},t.getAvailableCount=function(){return this._objects.length},t.isEmpty=function(){return 0===this._objects.length},t.isFull=function(){return this._objects.length>=this._maxSize},e.getAllPoolTypes=function(){return Array.from(this._pools.keys())},e.getAllPoolStats=function(){for(var e,t={},n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t[r.name||r.toString()]=o.getStats()}return t},e.compactAllPools=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.compact()}},e.clearAllPools=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.clear()}this._pools.clear()},e.getGlobalStatsString=function(){var e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],o=r[0],s=r[1];t.push(o+":"),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")},t._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}},t._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},e}();x._pools=new Map;var R,z=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(e);return r||(r=new x(t,n,i),this.pools.set(e,r)),r},t.removePool=function(e){var t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)},t.getPoolNames=function(){return Array.from(this.pools.keys())},t.getPoolCount=function(){return this.pools.size},t.compactAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){e.value.compact()}},t.clearAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){e.value.clear()}},t.getAllStats=function(){for(var e,t=new Map,n=a(this.pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,o.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,i=0,r=0,o=0,s=0,c=a(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,o+=u.totalReleased,s+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:o,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:s}},t.getStatsString=function(){var e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");var 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(var n,i=a(this.pools);!(n=i()).done;){var r=n.value,o=r[0],s=r[1].getStats();e.push(o+":"),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")},t.setAutoCompactInterval=function(e){this.autoCompactInterval=e},t.prewarmAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){var n=e.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}(),N=Symbol("ComponentTypeName"),F=Symbol("ComponentDependencies"),B=Symbol("ComponentEditorOptions");function L(e){return void 0!==e[N]}function H(e){var t=e[N];return t||(e.name||"UnknownComponent")}function W(e){return H(e.constructor)}function G(e){return e[B]}function j(e){var t,n=G(e);return null!==(t=null==n?void 0:n.hideInInspector)&&void 0!==t&&t}!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(R||(R={}));var U,q=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0]};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0]}},e.hasAny=function(e,t){var n=t.base,i=e.base,r=t.segments,o=e.segments,s=0!==(i[R.LOW]&n[R.LOW])||0!==(i[R.HIGH]&n[R.HIGH]);return!s&&r&&o?o.some(function(e,t){var n=r[t];return n&&(0!==(e[R.LOW]&n[R.LOW])||0!==(e[R.HIGH]&n[R.HIGH]))}):s},e.hasAll=function(e,t){var n,i=e.base,r=t.base,o=e.segments,s=t.segments,a=(i[R.LOW]&r[R.LOW])===r[R.LOW]&&(i[R.HIGH]&r[R.HIGH])===r[R.HIGH];if(!a||!s)return a;var c=null!==(n=null==o?void 0:o.length)&&void 0!==n?n:0;if(o)for(var u=0;u<Math.min(c,s.length);u++){var l=o[u],h=s[u];if((l[R.LOW]&h[R.LOW])!==h[R.LOW]||(l[R.HIGH]&h[R.HIGH])!==h[R.HIGH])return!1}for(var d=c;d<s.length;d++){var f=s[d];if(0!==f[R.LOW]||0!==f[R.HIGH])return!1}return!0},e.hasNone=function(e,t){var n=e.base,i=t.base,r=e.segments,o=t.segments,s=0===(n[R.LOW]&i[R.LOW])&&0===(n[R.HIGH]&i[R.HIGH]);return r&&s&&o?r.every(function(e,t){var n=o[t];return!n||0===(e[R.LOW]&n[R.LOW])&&0===(e[R.HIGH]&n[R.HIGH])}):s},e.isZero=function(e){var t=0===e.base[R.LOW]&&0===e.base[R.HIGH];return e.segments&&t?e.segments.every(function(e){return 0===e[R.LOW]&&0===e[R.HIGH]}):t},e.equals=function(e,t){var n,i,r=e.base[R.LOW]===t.base[R.LOW]&&e.base[R.HIGH]===t.base[R.HIGH];if(!r||!e.segments&&!t.segments)return r;for(var o=null!==(n=e.segments)&&void 0!==n?n:[],s=null!==(i=t.segments)&&void 0!==i?i:[],a=0;a<Math.max(o.length,s.length);a++){var c=o[a],u=s[a];if(c&&!u){if(0!==c[R.LOW]||0!==c[R.HIGH])return!1}else if(!c&&u){if(0!==u[R.LOW]||0!==u[R.HIGH])return!1}else if(c&&u&&(c[R.LOW]!==u[R.LOW]||c[R.HIGH]!==u[R.HIGH]))return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n),r=63&n;r<32?i[R.LOW]|=1<<r:i[R.HIGH]|=1<<r-32},e.getBit=function(t,n){if(n<0)return!1;var i=e.getSegmentByBitIndex(t,n,!1);if(!i)return!1;var r=63&n;return r<32?!!(i[R.LOW]&1<<r):!!(i[R.HIGH]&1<<r-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n,!1);if(i){var r=63&n;r<32?i[R.LOW]&=~(1<<r):i[R.HIGH]&=~(1<<r-32)}},e.orInPlace=function(e,t){e.base[R.LOW]|=t.base[R.LOW],e.base[R.HIGH]|=t.base[R.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]|=s[R.LOW],o[R.HIGH]|=s[R.HIGH]}}},e.andInPlace=function(e,t){e.base[R.LOW]&=t.base[R.LOW],e.base[R.HIGH]&=t.base[R.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]&=s[R.LOW],o[R.HIGH]&=s[R.HIGH]}}},e.xorInPlace=function(e,t){e.base[R.LOW]^=t.base[R.LOW],e.base[R.HIGH]^=t.base[R.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]^=s[R.LOW],o[R.HIGH]^=s[R.HIGH]}}},e.clear=function(e){if(e.base[R.LOW]=0,e.base[R.HIGH]=0,e.segments)for(var t=0;t<e.segments.length;t++){var n=e.segments[t];n[R.LOW]=0,n[R.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[R.LOW]=t.base[R.LOW],n.base[R.HIGH]=t.base[R.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var i=t.segments.length-n.segments.length,r=0;r<i;r++)n.segments.push([0,0]);for(var o=n.segments,s=t.segments,a=0;a<s.length;a++){var c=o[a],u=s[a];c[R.LOW]=u[R.LOW],c[R.HIGH]=u[R.HIGH]}}else n.segments=t.segments.map(function(e){return[].concat(e)})},e.clone=function(e){return c({base:e.base.slice()},e.segments&&{segments:e.segments.map(function(e){return[].concat(e)})})},e.toString=function(e,t,n){var i,r;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var o=null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0,s="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=o;c++){s+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}s+="\n"}for(var u=-1;u<o;u++){var l="",h=-1==u?e.base:e.segments[u],d=h[R.HIGH],f=h[R.LOW];if(2==t){l=d.toString(2).padStart(32,"0")+"_"+f.toString(2).padStart(32,"0")}else{var p=d?d.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var m=f.toString(16).toUpperCase();p&&(m=m.padStart(8,"0")),l="0x"+p+m}s+=-1===u?l:" "+l}return s},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0);n++){for(var i,r,o=-1==n?e.base:e.segments[n],s=o[R.LOW],a=o[R.HIGH];s;)s&=s-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var i,r=e.segments;if(!r){if(!n)return null;r=e.segments=[]}var o=(t>>6)-1;if(r.length<=o){if(!n)return null;for(var s=o-r.length+1,a=0;a<s;a++)r.push([0,0])}return null!==(i=r[o])&&void 0!==i?i:null},e}();q.ZERO={base:[0,0]},e.LogLevel=void 0,(U=e.LogLevel||(e.LogLevel={}))[U.Debug=0]="Debug",U[U.Info=1]="Info",U[U.Warn=2]="Warn",U[U.Error=3]="Error",U[U.Fatal=4]="Fatal",U[U.None=5]="None";var Q={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""},V=function(){function t(t){void 0===t&&(t={}),this._config=c({level:e.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},t)}var n=t.prototype;return n.debug=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Debug,t].concat(i))},n.info=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Info,t].concat(i))},n.warn=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Warn,t].concat(i))},n.error=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Error,t].concat(i))},n.fatal=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Fatal,t].concat(i))},n.setLevel=function(e){this._config.level=e},n.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=c({},this._config.colors,e)},n.setPrefix=function(e){this._config.prefix=e},n.log=function(t,n){if(!(t<this._config.level)){var i=n;if(this._config.enableTimestamp)i="["+(new Date).toISOString()+"] "+i;if(this._config.prefix&&(i="["+this._config.prefix+"] "+i),i="["+e.LogLevel[t].toUpperCase()+"] "+i,this._config.output)this._config.output(t,i);else{for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];this.outputToConsole.apply(this,[t,i].concat(o))}}},n.outputToConsole=function(t,n){for(var i=this._config.enableColors?this.getColors():null,r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];switch(t){case e.LogLevel.Debug:var a,c;if(i)(a=console).debug.apply(a,[""+i.debug+n+i.reset].concat(o));else(c=console).debug.apply(c,[n].concat(o));break;case e.LogLevel.Info:var u,l;if(i)(u=console).info.apply(u,[""+i.info+n+i.reset].concat(o));else(l=console).info.apply(l,[n].concat(o));break;case e.LogLevel.Warn:var h,d;if(i)(h=console).warn.apply(h,[""+i.warn+n+i.reset].concat(o));else(d=console).warn.apply(d,[n].concat(o));break;case e.LogLevel.Error:var f,p;if(i)(f=console).error.apply(f,[""+i.error+n+i.reset].concat(o));else(p=console).error.apply(p,[n].concat(o));break;case e.LogLevel.Fatal:var m,v;if(i)(m=console).error.apply(m,[""+i.fatal+n+i.reset].concat(o));else(v=console).error.apply(v,[n].concat(o))}},n.getColors=function(){return c({},{debug:Q.BRIGHT_BLACK,info:Q.GREEN,warn:Q.YELLOW,error:Q.RED,fatal:Q.BRIGHT_RED,reset:Q.RESET},this._config.colors)},t}(),Y=function(){function t(){this._loggers=new Map,this._defaultLevel=e.LogLevel.Info}var n=t.prototype;return n.createDefaultLogger=function(){return this._loggerFactory?this._loggerFactory():new V({level:this._defaultLevel})},t.getInstance=function(){return t._instance||(t._instance=new t),t._instance},n.getLogger=function(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new V({prefix:e,level:this._defaultLevel})),this._loggers.get(e)):this.defaultLogger},n.setLogger=function(e,t){this._loggers.set(e,t)},n.setGlobalLevel=function(e){this._defaultLevel=e,this._defaultLogger instanceof V&&this._defaultLogger.setLevel(e);for(var t,n=a(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof V&&i.setLevel(e)}},n.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},n.setGlobalColors=function(e){this._defaultLogger instanceof V&&this._defaultLogger.setColors(e);for(var t,n=a(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof V&&i.setColors(e)}},n.resetColors=function(){this._defaultLogger instanceof V&&this._defaultLogger.setColors({});for(var e,t=a(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof V&&n.setColors({})}},n.setLoggerFactory=function(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()},s(t,[{key:"defaultLogger",get:function(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}}])}(),J=Y.getInstance().getLogger();function Z(e){return Y.getInstance().getLogger(e)}var X=Z("ComponentRegistry"),K=function(){function e(){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}var t=e.prototype;return t.register=function(e){var t=H(e);if(L(e)||this._warnedComponents.has(e)||(this._warnedComponents.add(e),X.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)){var n=this._componentNameToType.get(t);if(n!==e){var i=this._componentTypes.get(n);return this._componentTypes.delete(n),this._componentTypes.set(e,i),this._bitIndexToType.set(i,e),this._componentNameToType.set(t,e),X.debug('Hot reload: replaced component "'+t+'"'),i}}var r=this._nextBitIndex++;return this._componentTypes.set(e,r),this._bitIndexToType.set(r,e),this._componentNameToType.set(t,e),this._componentNameToId.set(t,r),r},t.getBitMask=function(e){var t=this._componentTypes.get(e);if(void 0===t){var n=H(e);throw new Error("Component type "+n+" is not registered")}return q.create(t)},t.getBitIndex=function(e){var t=this._componentTypes.get(e);if(void 0===t){var n=H(e);throw new Error("Component type "+n+" is not registered")}return t},t.isRegistered=function(e){return this._componentTypes.has(e)},t.getTypeByBitIndex=function(e){return this._bitIndexToType.get(e)||null},t.getRegisteredCount=function(){return this._nextBitIndex},t.getComponentType=function(e){return this._componentNameToType.get(e)||null},t.getAllRegisteredTypes=function(){return new Map(this._componentTypes)},t.getAllComponentNames=function(){return new Map(this._componentNameToType)},t.getComponentId=function(e){return this._componentNameToId.get(e)},t.registerComponentByName=function(e){if(this._componentNameToId.has(e))return this._componentNameToId.get(e);var t=this._nextBitIndex++;return this._componentNameToId.set(e,t),t},t.createSingleComponentMask=function(e){var t="single:"+e;if(this._maskCache.has(t))return this._maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var i=q.create(n);return this._maskCache.set(t,i),i},t.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this._maskCache.has(t))return this._maskCache.get(t);for(var n,i=q.clone(q.ZERO),r=a(e);!(n=r()).done;){var o=n.value,s=this.getComponentId(o);if(void 0!==s){var c=q.create(s);q.orInPlace(i,c)}}return this._maskCache.set(t,i),i},t.clearMaskCache=function(){this._maskCache.clear()},t.enableHotReload=function(){this._hotReloadEnabled=!0},t.disableHotReload=function(){this._hotReloadEnabled=!1},t.isHotReloadEnabled=function(){return this._hotReloadEnabled},t.unregister=function(e){var t=this._componentNameToType.get(e);if(t){var 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(),X.debug("Component unregistered: "+e)}},t.getRegisteredComponents=function(){for(var e,t=[],n=a(this._componentNameToType);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=this._componentTypes.get(o);void 0!==s&&t.push({name:r,type:o,bitIndex:s})}return t},t.reset=function(){this._componentTypes.clear(),this._bitIndexToType.clear(),this._componentNameToType.clear(),this._componentNameToId.clear(),this._maskCache.clear(),this._warnedComponents.clear(),this._nextBitIndex=0,this._hotReloadEnabled=!1},t.cloneFrom=function(e){for(var t,n=a(e.getAllRegisteredTypes());!(t=n()).done;){var i=t.value,r=i[0],o=i[1];this._componentTypes.set(r,o),this._bitIndexToType.set(o,r);var s=H(r);this._componentNameToType.set(s,r),this._componentNameToId.set(s,o)}this._nextBitIndex=e.getRegisteredCount(),this._hotReloadEnabled=e.isHotReloadEnabled()},e}(),$=new K,ee=Symbol("SystemTypeName");function te(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");var i=n;return i[N]=e,null!=t&&t.requires&&(i[F]=t.requires),null!=t&&t.editor&&(i[B]=t.editor),$.register(n),n}}function ne(e){return e.__systemMetadata__}function ie(e){return ne(e.constructor)}function re(e){var t=e[ee];return t||(e.name||"UnknownSystem")}function oe(e){return re(e.constructor)}var se=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),ae="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||se,ce=new Map;function ue(e){var t=ce.get(e);return(null==t?void 0:t.deref())||null}var le=function(){function e(){this._references=new Map}var t=e.prototype;return t.registerReference=function(e,t,n){var i=e.id,r=this._references.get(i);r||(r=new Set,this._references.set(i,r)),this._findRecord(r,t,n)||r.add({component:new ae(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var i=e.id,r=this._references.get(i);if(r){var o=this._findRecord(r,t,n);o&&(r.delete(o),0===r.size&&this._references.delete(i))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;o.component.deref()&&i.push(o)}for(var s=0,c=i;s<c.length;s++){var u=c[s],l=u.component.deref();l&&(l[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=a(this._references.entries());!(t=n()).done;){for(var i,r=t.value,o=r[0],s=r[1],c=[],u=a(s);!(i=u()).done;){var l=i.value,h=l.component.deref();h&&h!==e||c.push(l)}for(var d=0,f=c;d<f.length;d++){var p=f[d];s.delete(p)}0===s.size&&this._references.delete(o)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;o.component.deref()&&i.push(o)}return i},t.cleanup=function(){for(var e,t=[],n=a(this._references.entries());!(e=n()).done;){for(var i,r=e.value,o=r[0],s=r[1],c=[],u=a(s);!(i=u()).done;){var l=i.value;l.component.deref()||c.push(l)}for(var h=0,d=c;h<d.length;h++){var f=d[h];s.delete(f)}0===s.size&&t.push(o)}for(var p=0,m=t;p<m.length;p++){var v=m[p];this._references.delete(v)}},t.registerEntityScene=function(e,t){ce.set(e,new ae(t))},t.unregisterEntityScene=function(e){ce.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=a(this._references.entries());!(e=n()).done;){for(var i,r=e.value,o=r[0],s=[],c=a(r[1]);!(i=c()).done;){var u=i.value,l=u.component.deref();l&&s.push({componentId:l.id,propertyKey:u.propertyKey})}s.length>0&&(t["entity_"+o]=s)}return t},t._findRecord=function(e,t,n){for(var i,r=a(e);!(i=r()).done;){var o=i.value;if(o.component.deref()===t&&o.propertyKey===n)return o}},e}(),he=Z("EntityRefDecorator"),de=Symbol("EntityRefMetadata"),fe=Symbol("EntityRefValues");function pe(e){var t=e[fe];return t||(t=new Map,e[fe]=t),t}function me(e){return e&&("function"==typeof e?e:e.constructor)[de]||null}function ve(e,t){var n=me(e);return!!n&&n.properties.has(t)}var ge=new WeakMap,ye=Symbol.for("@esengine/property:metadata");var _e=Symbol("schedulingMetadata");function Se(e){var t=e;return t[_e]||(t[_e]={stage:"update",before:[],after:[],sets:[]}),t[_e]}function Ce(e){for(var t=Object.getPrototypeOf(e);t;){var n=t[_e];if(n)return n;t=Object.getPrototypeOf(t)}}var Ee=function(){function e(){}return e.getConstructor=function(e){return this.TYPE_CONSTRUCTORS[e]||Float32Array},e.getBytesPerElement=function(e){return this.TYPE_BYTES[e]||4},e.getTypeName=function(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"},e.createSameType=function(e,t){var n=this.getTypeName(e);return new(this.getConstructor(n))(t)},e.extractFieldMetadata=function(e){var t=new e,n=new Map,i=e,r=new Map,o=function(e,t){if(e)for(var n,i=a(e);!(n=i()).done;){var o=n.value;r.set(o,t)}};o(i.__float64Fields,"float64"),o(i.__float32Fields,"float32"),o(i.__int32Fields,"int32"),o(i.__uint32Fields,"uint32"),o(i.__int16Fields,"int16"),o(i.__uint16Fields,"uint16"),o(i.__int8Fields,"int8"),o(i.__uint8Fields,"uint8"),o(i.__uint8ClampedFields,"uint8clamped");for(var s,c=Object.keys(t).filter(function(e){return"id"!==e}),u=a(c);!(s=u()).done;){var l,h,d,f,p=s.value,m=typeof t[p];if("function"!==m){var v={name:p,type:m},g=r.get(p);g?v.arrayType=g:"number"===m?v.arrayType="float32":"boolean"===m&&(v.arrayType="uint8"),null!==(l=i.__serializeMapFields)&&void 0!==l&&l.has(p)&&(v.isSerializedMap=!0),null!==(h=i.__serializeSetFields)&&void 0!==h&&h.has(p)&&(v.isSerializedSet=!0),null!==(d=i.__serializeArrayFields)&&void 0!==d&&d.has(p)&&(v.isSerializedArray=!0),null!==(f=i.__deepCopyFields)&&void 0!==f&&f.has(p)&&(v.isDeepCopy=!0),n.set(p,v)}}return n},e}();Ee.TYPE_CONSTRUCTORS={float32:Float32Array,float64:Float64Array,int32:Int32Array,uint32:Uint32Array,int16:Int16Array,uint16:Uint16Array,int8:Int8Array,uint8:Uint8Array,uint8clamped:Uint8ClampedArray},Ee.TYPE_BYTES={float32:4,float64:8,int32:4,uint32:4,int16:2,uint16:2,int8:1,uint8:1,uint8clamped:1};var be=function(){function e(){}return e.serialize=function(e,t,n){void 0===n&&(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),"{}"}},e.deserialize=function(e,t,n){void 0===n&&(n={});try{var i=JSON.parse(e);return n.isMap?new Map(i):n.isSet?new Set(i):i}catch(e){return this._logger.warn("SoA反序列化字段 "+t+" 失败:",e),null}},e.deepClone=function(e){var t=this;if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(function(e){return t.deepClone(e)});if(e instanceof Map){for(var n,i=new Map,r=a(e.entries());!(n=r()).done;){var o=n.value,s=o[0],c=o[1];i.set(s,this.deepClone(c))}return i}if(e instanceof Set){for(var u,l=new Set,h=a(e.values());!(u=h()).done;){var d=u.value;l.add(this.deepClone(d))}return l}var f={};for(var p in e)Object.prototype.hasOwnProperty.call(e,p)&&(f[p]=this.deepClone(e[p]));return f},e}();function Te(e,t){var n=e.constructor,i=n[t];return i||(i=new Set,n[t]=i),i}function we(e,t){Te(e,"__int32Fields").add(String(t))}be._logger=Z("SoASerializer");var Ie=function(){function e(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)}var t=e.prototype;return t.initializeFields=function(e){var t=new e,n=e,i=n.__float64Fields||new Set,r=n.__float32Fields||new Set,o=n.__int32Fields||new Set,s=n.__uint32Fields||new Set,c=n.__int16Fields||new Set,u=n.__uint16Fields||new Set,l=n.__int8Fields||new Set,h=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;for(var f,p=new Map,m=a(i);!(f=m()).done;){var v=f.value;p.set(v,"float64")}for(var g,y=a(r);!(g=y()).done;){var _=g.value;p.set(_,"float32")}for(var S,C=a(o);!(S=C()).done;){var E=S.value;p.set(E,"int32")}for(var b,T=a(s);!(b=T()).done;){var w=b.value;p.set(w,"uint32")}for(var I,M=a(c);!(I=M()).done;){var A=I.value;p.set(A,"int16")}for(var k,D=a(u);!(k=D()).done;){var P=k.value;p.set(P,"uint16")}for(var O,x=a(l);!(O=x()).done;){var R=O.value;p.set(R,"int8")}for(var z,N=a(h);!(z=N()).done;){var F=z.value;p.set(F,"uint8")}for(var B,L=a(d);!(B=L()).done;){var H=B.value;p.set(H,"uint8clamped")}for(var W,G=Object.keys(t).filter(function(e){return"id"!==e}),j=a(G);!(W=j()).done;){var U=W.value,q=t[U],Q=typeof q;if("function"!==Q){var V=p.get(U),Y=V?"number":Q;if(this.fieldTypes.set(U,Y),V){var J=Ee.getConstructor(V);this.fields.set(U,new J(this._capacity))}else"number"===Q?this.fields.set(U,new Float32Array(this._capacity)):"boolean"===Q?this.fields.set(U,new Uint8Array(this._capacity)):"string"===Q?this.stringFields.set(U,new Array(this._capacity)):"object"===Q&&null!==q&&(this.serializeMapFields.has(U)||this.serializeSetFields.has(U)||this.serializeArrayFields.has(U))&&this.serializedFields.set(U,new Array(this._capacity))}}},t.addComponent=function(e,t){if(this.entityToIndex.has(e)){var n=this.entityToIndex.get(e);this.updateComponentAtIndex(n,t)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,i),this.indexToEntity[i]=e,this.updateComponentAtIndex(i,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],i=new Map,r=this.type,o=r.__highPrecisionFields||new Set,s=r.__serializeMapFields||new Set,a=r.__serializeSetFields||new Set,c=r.__serializeArrayFields||new Set,u=r.__deepCopyFields||new Set,l=t;for(var h in t)if(Object.prototype.hasOwnProperty.call(t,h)&&"id"!==h){var d=l[h],f=typeof d;if("number"===f){var p=d;if(o.has(h)||!this.fields.has(h))i.set(h,p);else this.fields.get(h)[e]=p}else if("boolean"===f&&this.fields.has(h)){this.fields.get(h)[e]=d?1:0}else if(this.stringFields.has(h)){this.stringFields.get(h)[e]=String(d)}else if(this.serializedFields.has(h)){this.serializedFields.get(h)[e]=be.serialize(d,h,{isMap:s.has(h),isSet:a.has(h),isArray:c.has(h)})}else u.has(h)?i.set(h,be.deepClone(d)):i.set(h,d)}i.size>0&&this.complexFields.set(n,i)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0===t?null:this.createProxyView(e,t)},t.createProxyView=function(e,t){var n=this;return new Proxy({},{get:function(i,r){var o=String(r),s=n.fields.get(o);if(s)return"boolean"===n.getFieldType(o)?1===s[t]:s[t];var a=n.stringFields.get(o);if(a)return a[t];var c=n.serializedFields.get(o);if(c){var u=c[t];return u?be.deserialize(u,o,{isMap:n.serializeMapFields.has(o),isSet:n.serializeSetFields.has(o),isArray:n.serializeArrayFields.has(o)}):void 0}var l=n.complexFields.get(e);return null!=l&&l.has(o)?l.get(o):void 0},set:function(i,r,o){var s=String(r);if("entityId"===s)return!1;var a=n.fields.get(s);if(a){var c=n.getFieldType(s);return a[t]="boolean"===c?o?1:0:o,!0}var u=n.stringFields.get(s);if(u)return u[t]=String(o),!0;if(n.serializedFields.has(s))return n.serializedFields.get(s)[t]=be.serialize(o,s,{isMap:n.serializeMapFields.has(s),isSet:n.serializeSetFields.has(s),isArray:n.serializeArrayFields.has(s)}),!0;var l=n.complexFields.get(e);return l||(l=new Map,n.complexFields.set(e,l)),l.set(s,o),!0},has:function(t,i){var r,o=String(i);return n.fields.has(o)||n.stringFields.has(o)||n.serializedFields.has(o)||(null===(r=n.complexFields.get(e))||void 0===r?void 0:r.has(o))||!1},ownKeys:function(){for(var t,i=[],r=a(n.fields.keys());!(t=r()).done;){var o=t.value;i.push(o)}for(var s,c=a(n.stringFields.keys());!(s=c()).done;){var u=s.value;i.push(u)}for(var l,h=a(n.serializedFields.keys());!(l=h()).done;){var d=l.value;i.push(d)}var f=n.complexFields.get(e);if(f)for(var p,m=a(f.keys());!(p=m()).done;){var v=p.value;i.push(v)}return i},getOwnPropertyDescriptor:function(t,i){var r,o=String(i);if(n.fields.has(o)||n.stringFields.has(o)||n.serializedFields.has(o)||null!==(r=n.complexFields.get(e))&&void 0!==r&&r.has(o))return{enumerable:!0,configurable:!0,writable:"entityId"!==o}}})},t.getComponentSnapshot=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,i=new this.type,r=i,o=a(this.fields.entries());!(n=o()).done;){var s=n.value,c=s[0],u=s[1][t],l=this.getFieldType(c);r[c]="boolean"===l?1===u:u}for(var h,d=a(this.stringFields.entries());!(h=d()).done;){var f=h.value,p=f[0],m=f[1];r[p]=m[t]}for(var v,g=a(this.serializedFields.entries());!(v=g()).done;){var y=v.value,_=y[0],S=y[1][t];S&&(r[_]=be.deserialize(S,_,{isMap:this.serializeMapFields.has(_),isSet:this.serializeSetFields.has(_),isArray:this.serializeArrayFields.has(_)}))}var C=this.complexFields.get(e);if(C)for(var E,b=a(C.entries());!(E=b()).done;){var T=E.value,w=T[0],I=T[1];r[w]=I}return i},t.getFieldType=function(e){return this.fieldTypes.get(e)||"unknown"},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(e){for(var t,n=a(this.fields.entries());!(t=n()).done;){var i=t.value,r=i[0],o=i[1],s=Ee.createSameType(o,e);s.set(o),this.fields.set(r,s)}for(var c,u=a(this.stringFields.entries());!(c=u()).done;){for(var l=c.value,h=l[0],d=l[1],f=new Array(e),p=0;p<d.length;p++)f[p]=d[p];this.stringFields.set(h,f)}for(var m,v=a(this.serializedFields.entries());!(m=v()).done;){for(var g=m.value,y=g[0],_=g[1],S=new Array(e),C=0;C<_.length;C++)S[C]=_[C];this.serializedFields.set(y,S)}this._capacity=e},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=a(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,i=a(this.stringFields.values());!(n=i()).done;)for(var r=n.value,o=0;o<r.length;o++)r[o]=void 0;for(var s,c=a(this.serializedFields.values());!(s=c()).done;)for(var u=s.value,l=0;l<u.length;l++)u[l]=void 0},t.compact=function(){if(0!==this.freeIndices.length){for(var e=Array.from(this.entityToIndex.entries()).sort(function(e,t){return e[1]-t[1]}),t=new Map,n=[],i=0;i<e.length;i++){var r=e[i];if(r){var o=r[0],s=r[1];if(t.set(o,i),n[i]=o,i!==s){for(var c,u=a(this.fields.entries());!(c=u()).done;){var l=c.value[1],h=l[s];void 0!==h&&(l[i]=h)}for(var d,f=a(this.stringFields.entries());!(d=f()).done;){var p=d.value[1],m=p[s];void 0!==m&&(p[i]=m)}for(var v,g=a(this.serializedFields.entries());!(v=g()).done;){var y=v.value[1],_=y[s];void 0!==_&&(y[i]=_)}}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,i=a(this.fields.entries());!(e=i()).done;){var r=e.value,o=r[0],s=r[1],c=Ee.getTypeName(s),u=Ee.getBytesPerElement(c),l=s.length*u;t+=l,n.set(o,{size:this._size,capacity:s.length,type:c,memory:l})}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:t,fieldStats:n}},t.performVectorizedOperation=function(e){var t=this.getActiveIndices();e(this.fields,t)},e}(),Me=function(){function e(){this.entityId=null,this._lastWriteEpoch=0,this.id=e._idGenerator++}var t=e.prototype;return t.markDirty=function(e){this._lastWriteEpoch=e},t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},t.onDeserialized=function(){},s(e,[{key:"lastWriteEpoch",get:function(){return this._lastWriteEpoch}}])}();Me._idGenerator=0,g([we,y("design:type",Object)],Me.prototype,"entityId",void 0);var Ae=Symbol("SerializableMetadata"),ke=Symbol("SerializeField"),De=Symbol("SerializeOptions");function Pe(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n;if(Object.prototype.hasOwnProperty.call(t,Ae))(n=t[Ae]).options=e;else{var i=t[Ae];n={options:e,fields:i?new Map(i.fields):new Map,ignoredFields:i?new Set(i.ignoredFields):new Set},t[Ae]=n}return t}}function Oe(e){return function(t,n){var i,r=t.constructor;if(Object.prototype.hasOwnProperty.call(r,Ae))i=r[Ae];else{var o=r[Ae];i={options:o?c({},o.options):{version:1},fields:o?new Map(o.fields):new Map,ignoredFields:o?new Set(o.ignoredFields):new Set},r[Ae]=i}i.fields.set(n,e||{})}}function xe(e){return e&&("function"==typeof e?e:e.constructor)[Ae]||null}e.HierarchyComponent=function(e){function t(){var t;return(t=e.apply(this,arguments)||this).parentId=null,t.childIds=[],t.depth=0,t.bActiveInHierarchy=!0,t.bCacheDirty=!0,t}return l(t,e),t}(Me),g([Oe(),y("design:type",Object)],e.HierarchyComponent.prototype,"parentId",void 0),g([Oe(),y("design:type",Array)],e.HierarchyComponent.prototype,"childIds",void 0),e.HierarchyComponent=g([te("Hierarchy",{editor:{hideInInspector:!0}}),Pe({version:1,typeId:"Hierarchy"})],e.HierarchyComponent);var Re=function(){function e(){this.condition={all:[],any:[],none:[]}}e.all=function(){var t=new e;return t.all.apply(t,arguments)},e.any=function(){var t=new e;return t.any.apply(t,arguments)},e.none=function(){var t=new e;return t.none.apply(t,arguments)},e.byTag=function(t){return(new e).withTag(t)},e.byName=function(t){return(new e).withName(t)},e.byComponent=function(t){return(new e).withComponent(t)},e.complex=function(){return new e},e.empty=function(){return new e},e.nothing=function(){var t=new e;return t.condition.matchNothing=!0,t};var t=e.prototype;return t.all=function(){var e;return(e=this.condition.all).push.apply(e,arguments),this},t.any=function(){var e;return(e=this.condition.any).push.apply(e,arguments),this},t.none=function(){var e;return(e=this.condition.none).push.apply(e,arguments),this},t.exclude=function(){return this.none.apply(this,arguments)},t.one=function(){return this.any.apply(this,arguments)},t.withTag=function(e){return this.condition.tag=e,this},t.withName=function(e){return this.condition.name=e,this},t.withComponent=function(e){return this.condition.component=e,this},t.withoutTag=function(){return delete this.condition.tag,this},t.withoutName=function(){return delete this.condition.name,this},t.withoutComponent=function(){return delete this.condition.component,this},t.getCondition=function(){return c({all:[].concat(this.condition.all),any:[].concat(this.condition.any),none:[].concat(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})},t.isEmpty=function(){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},t.isNothing=function(){return!0===this.condition.matchNothing},t.reset=function(){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},t.clone=function(){var t,n,i,r=new e;return(t=r.condition.all).push.apply(t,this.condition.all),(n=r.condition.any).push.apply(n,this.condition.any),(i=r.condition.none).push.apply(i,this.condition.none),void 0!==this.condition.tag&&(r.condition.tag=this.condition.tag),void 0!==this.condition.name&&(r.condition.name=this.condition.name),void 0!==this.condition.component&&(r.condition.component=this.condition.component),this.condition.matchNothing&&(r.condition.matchNothing=!0),r},t.toString=function(){if(this.condition.matchNothing)return"Matcher[nothing]";var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map(function(e){return H(e)}).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map(function(e){return H(e)}).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map(function(e){return H(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("+H(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),ze=function(){function e(){this._frameCache=null,this._persistentCache=null,this._trackedEntities=new Set}var t=e.prototype;return t.getFrame=function(){return this._frameCache},t.setFrame=function(e){this._frameCache=e},t.getPersistent=function(){return this._persistentCache},t.setPersistent=function(e){this._persistentCache=e},t.getTracked=function(){return this._trackedEntities},t.addTracked=function(e){this._trackedEntities.add(e)},t.removeTracked=function(e){this._trackedEntities.delete(e)},t.isTracked=function(e){return this._trackedEntities.has(e)},t.invalidate=function(){this._persistentCache=null},t.clearFrame=function(){this._frameCache=null},t.clearAll=function(){this._frameCache=null,this._persistentCache=null,this._trackedEntities.clear()},t.hasPersistent=function(){return null!==this._persistentCache},t.hasFrame=function(){return null!==this._frameCache},t.getStats=function(){var e,t,n,i;return{hasFrame:null!==this._frameCache,hasPersistent:null!==this._persistentCache,trackedCount:this._trackedEntities.size,frameEntityCount:null!==(e=null===(t=this._frameCache)||void 0===t?void 0:t.length)&&void 0!==e?e:0,persistentEntityCount:null!==(n=null===(i=this._persistentCache)||void 0===i?void 0:i.length)&&void 0!==n?n:0}},e}(),Ne=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e}var t=e.prototype;return t.addComponent=function(e,t){if(this.entityToIndex.has(e))throw new Error("Entity "+e+" already has component "+H(this.componentType));var n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.dense[t],i=this.dense.length-1;if(t!==i){var r=this.dense[i],o=this.entityIds[i];this.dense[t]=r,this.entityIds[t]=o,this.entityToIndex.set(o,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n},t.forEach=function(e){for(var t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)},t.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},t.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},t.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(e,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),Fe=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof Ie},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof Ie?t:null},t.getFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getFieldArray(t):null},t.getTypedFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null},t.getActiveIndices=function(e){var t=this.getSoAStorage(e);return t?t.getActiveIndices():[]},t.getEntityIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0},t.getEntityIdByIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0},t.getStorage=function(t){var n=this.storages.get(t);n||(t.__enableSoA?(n=new Ie(t),e._logger.info("为 "+H(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new Ne(t),this.storages.set(t,n));return n},t.addComponent=function(e,t){var n=t.constructor;this.getStorage(n).addComponent(e,t)},t.getComponent=function(e,t){var n=this.storages.get(t);return n?n.getComponent(e):null},t.hasComponent=function(e,t){var n=this.storages.get(t);return!!n&&n.hasComponent(e)},t.removeComponent=function(e,t){var n=this.storages.get(t);return n?n.removeComponent(e):null},t.removeAllComponents=function(e){for(var t,n=a(this.storages.values());!(t=n()).done;){t.value.removeComponent(e)}},t.getComponentMask=function(e,t){void 0===t&&(t=$);for(var n,i=q.clone(q.ZERO),r=a(this.storages.entries());!(n=r()).done;){var o=n.value,s=o[0];if(o[1].hasComponent(e)){var c=t.getBitMask(s);q.orInPlace(i,c)}}return i},t.getAllStats=function(){for(var e,t=new Map,n=a(this.storages.entries());!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=H(r);t.set(s,o.getStats())}return t},t.clear=function(){for(var e,t=a(this.storages.values());!(e=t()).done;){e.value.clear()}this.storages.clear()},e}();Fe._logger=Z("ComponentStorage");var Be,Le=Z("CommandBuffer");e.CommandType=void 0,(Be=e.CommandType||(e.CommandType={})).ADD_COMPONENT="add_component",Be.REMOVE_COMPONENT="remove_component",Be.DESTROY_ENTITY="destroy_entity",Be.SET_ENTITY_ACTIVE="set_entity_active";var He=function(){function t(e,t){void 0===t&&(t=!1),this._pending=new Map,this._commands=[],this._scene=null,this._debug=!1,this._useDeduplication=!0,this._scene=null!=e?e:null,this._debug=t}var n=t.prototype;return n.setScene=function(e){this._scene=e},n.setDeduplication=function(e){this._useDeduplication=e},n.getPending=function(e){var t=this._pending.get(e);return t||(t={},this._pending.set(e,t)),t},n.getTypeId=function(e){return"function"==typeof e?$.getBitIndex(e):$.getBitIndex(e.constructor)},n.addComponent=function(t,n){if(this._useDeduplication){var i,r=this.getPending(t);if(r.bDestroy)return void(this._debug&&Le.debug("CommandBuffer: 忽略添加组件,实体 "+t.name+" 已标记销毁"));var o=this.getTypeId(n);if(null===(i=r.removes)||void 0===i||i.delete(o),r.adds||(r.adds=new Map),r.adds.set(o,n),this._debug){var s=H(n.constructor);Le.debug("CommandBuffer: 延迟添加组件 "+s+" 到实体 "+t.name)}}else this._commands.push({type:e.CommandType.ADD_COMPONENT,entity:t,component:n})},n.removeComponent=function(t,n){if(this._useDeduplication){var i,r=this.getPending(t);if(r.bDestroy)return void(this._debug&&Le.debug("CommandBuffer: 忽略移除组件,实体 "+t.name+" 已标记销毁"));var o=this.getTypeId(n);null===(i=r.adds)||void 0===i||i.delete(o),r.removes||(r.removes=new Set),r.removes.add(o),this._debug&&Le.debug("CommandBuffer: 延迟移除组件 "+n.name+" 从实体 "+t.name)}else this._commands.push({type:e.CommandType.REMOVE_COMPONENT,entity:t,componentType:n})},n.destroyEntity=function(t){if(this._useDeduplication){var n,i,r=this.getPending(t);null===(n=r.adds)||void 0===n||n.clear(),null===(i=r.removes)||void 0===i||i.clear(),delete r.active,r.bDestroy=!0,this._debug&&Le.debug("CommandBuffer: 延迟销毁实体 "+t.name)}else this._commands.push({type:e.CommandType.DESTROY_ENTITY,entity:t})},n.setEntityActive=function(t,n){if(this._useDeduplication){var i=this.getPending(t);if(i.bDestroy)return void(this._debug&&Le.debug("CommandBuffer: 忽略设置激活状态,实体 "+t.name+" 已标记销毁"));i.active=n,this._debug&&Le.debug("CommandBuffer: 延迟设置实体 "+t.name+" 激活状态为 "+n)}else this._commands.push({type:e.CommandType.SET_ENTITY_ACTIVE,entity:t,value:n})},n.flush=function(){return this._useDeduplication?this.flushDeduplication():this.flushLegacy()},n.flushDeduplication=function(){if(0===this._pending.size)return 0;var e=this._pending.size,t=0;this._debug&&Le.debug("CommandBuffer: 开始执行 "+e+" 个实体的延迟命令");var n=this._pending;this._pending=new Map;for(var i,r=a(n);!(i=r()).done;){var o=i.value,s=o[0],c=o[1];if(!c.bDestroy&&s.scene&&(c.removes&&c.removes.size>0))for(var u,l=a(c.removes);!(u=l()).done;){var h=u.value;try{var d=$.getTypeByBitIndex(h);d&&(s.removeComponentByType(d),t++)}catch(e){Le.error("CommandBuffer: 移除组件失败",{entity:s.name,typeId:h,error:e})}}}for(var f,p=a(n);!(f=p()).done;){var m=f.value,v=m[0],g=m[1];if(!g.bDestroy&&v.scene&&(g.adds&&g.adds.size>0))for(var y,_=a(g.adds.values());!(y=_()).done;){var S=y.value;try{v.addComponent(S),t++}catch(e){var C=H(S.constructor);Le.error("CommandBuffer: 添加组件失败",{entity:v.name,component:C,error:e})}}}for(var E,b=a(n);!(E=b()).done;){var T=E.value,w=T[0],I=T[1];if(!I.bDestroy&&w.scene&&void 0!==I.active)try{w.active=I.active,t++}catch(e){Le.error("CommandBuffer: 设置激活状态失败",{entity:w.name,error:e})}}for(var M,A=a(n);!(M=A()).done;){var k=M.value,D=k[0];if(k[1].bDestroy&&D.scene)try{D.destroy(),t++}catch(e){Le.error("CommandBuffer: 销毁实体失败",{entity:D.name,error:e})}}return this._debug&&Le.debug("CommandBuffer: 完成执行 "+t+" 个延迟命令"),t},n.flushLegacy=function(){if(0===this._commands.length)return 0;var e=this._commands.length;this._debug&&Le.debug("CommandBuffer: 开始执行 "+e+" 个延迟命令");var t=this._commands;this._commands=[];for(var n,i=a(t);!(n=i()).done;){var r=n.value;this.executeCommand(r)}return this._debug&&Le.debug("CommandBuffer: 完成执行 "+e+" 个延迟命令"),e},n.executeCommand=function(t){if(t.entity.scene)try{switch(t.type){case e.CommandType.ADD_COMPONENT:t.component&&t.entity.addComponent(t.component);break;case e.CommandType.REMOVE_COMPONENT:t.componentType&&t.entity.removeComponentByType(t.componentType);break;case e.CommandType.DESTROY_ENTITY:t.entity.destroy();break;case e.CommandType.SET_ENTITY_ACTIVE:void 0!==t.value&&(t.entity.active=t.value)}}catch(e){Le.error("CommandBuffer: 执行命令失败",{command:t,error:e})}else this._debug&&Le.debug("CommandBuffer: 跳过命令,实体 "+t.entity.name+" 已无效")},n.clear=function(){if(this._debug){var e=this._useDeduplication?this._pending.size:this._commands.length;e>0&&Le.debug("CommandBuffer: 清空 "+e+" 个未执行的命令")}this._pending.clear(),this._commands.length=0},n.dispose=function(){this.clear(),this._scene=null},s(t,[{key:"scene",get:function(){return this._scene}},{key:"pendingCount",get:function(){if(this._useDeduplication){for(var e,t=0,n=a(this._pending.values());!(e=n()).done;){var i=e.value;i.bDestroy&&t++,void 0!==i.active&&t++,i.adds&&(t+=i.adds.size),i.removes&&(t+=i.removes.size)}return t}return this._commands.length}},{key:"hasPending",get:function(){return this._useDeduplication?this._pending.size>0:this._commands.length>0}}])}(),We=function(){function e(e){this.commands=new He,this._lastProcessEpoch=0,this._shouldProcessThisFrame=!1,this._updateOrder=0,this._addOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=oe(this),this._initialized=!1,this._matcher=e||Re.empty(),this._eventListeners=[],this._scene=null,this._destroyed=!1,this._entityIdMap=null,this._entityIdMapVersion=-1,this.logger=Z(this.getLoggerName()),this._entityCache=new ze;var t=Ce(this);this._schedulingMetadata=t?c({},t):{stage:"update",before:[],after:[],sets:[]}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){var t;this._updateOrder!==e&&(this._updateOrder=e,null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty())},t.stage=function(e){var t;return this._schedulingMetadata.stage=e,null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.before=function(){var e,t;return(e=this._schedulingMetadata.before).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.after=function(){var e,t;return(e=this._schedulingMetadata.after).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.inSet=function(){var e,t;return(e=this._schedulingMetadata.sets).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.getStage=function(){return this._schedulingMetadata.stage},t.getBefore=function(){return this._schedulingMetadata.before},t.getAfter=function(){return this._schedulingMetadata.after},t.getSets=function(){return this._schedulingMetadata.sets},t.initialize=function(){if(!this._initialized){if(this._initialized=!0,this.scene){this._entityCache.invalidate();for(var e,t=a(this.queryEntities());!(e=t()).done;){var n=e.value;this.onAdded(n)}}this.onInitialize()}},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.resetEntityTracking=function(){this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1},t.reset=function(){this._destroyed||(this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this.destroy())},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return this._matcher.isNothing()?[]:(i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(i),i)},t.isSingleCondition=function(e){var t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)},t.executeSingleConditionQuery=function(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll.apply(t,e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny.apply(t,e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone.apply(t,e.none).entities:[]},t.executeComplexQueryWithIdSets=function(e,t){var n=null;if(void 0!==e.tag){var i=t.queryByTag(e.tag);n=this.extractEntityIds(i.entities)}if(void 0!==e.name){var r=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==e.component){var o=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,o):o}if(e.all.length>0){var s=this.extractEntityIds(t.queryAll.apply(t,e.all).entities);n=n?this.intersectIdSets(n,s):s}if(e.any.length>0){var a=this.extractEntityIds(t.queryAny.apply(t,e.any).entities);n=n?this.intersectIdSets(n,a):a}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));var c=t.queryAny.apply(t,e.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]},t.extractEntityIds=function(e){for(var t=e.length,n=new Set,i=0;i<t;i=i+1|0)n.add(0|e[i].id);return n},t.intersectIdSets=function(e,t){var n,i;e.size<=t.size?(n=e,i=t):(n=t,i=e);for(var r,o=new Set,s=a(n);!(r=s()).done;){var c=r.value;i.has(c)&&o.add(c)}return o},t.differenceIdSets=function(e,t){for(var n,i=new Set,r=a(e);!(n=r()).done;){var o=n.value;t.has(o)||i.add(o)}return i},t.getEntityIdMap=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n||null===(n=n.querySystem)||void 0===n?void 0:n.version)&&void 0!==t?t:0;return null!==this._entityIdMap&&this._entityIdMapVersion===i?this._entityIdMap:this.rebuildEntityIdMap(e,i)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var i=e.length,r=0;r<i;r=r+1|0){var o=e[r];n.set(0|o.id,o)}return this._entityIdMap=n,this._entityIdMapVersion=t,n},t.idSetToEntityArray=function(e,t){for(var n,i=this.getEntityIdMap(t),r=e.size,o=new Array(r),s=0,c=a(e);!(n=c()).done;){var u=n.value,l=i.get(u);void 0!==l&&(o[s]=l,s=s+1|0)}return s<r&&(o.length=s),o},t.executeComplexQuery=function(e,t){return this.executeComplexQueryWithIdSets(e,t)},t.update=function(){if(this._shouldProcessThisFrame=this._enabled&&this.onCheckProcessing(),this._shouldProcessThisFrame){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin();var i=this.queryEntities();this._entityCache.setFrame(i),n=i.length,this.process(i)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._shouldProcessThisFrame){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var i=this.queryEntities();this._entityCache.setFrame(i),n=i.length,this.lateProcess(i),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.flushCommands=function(){return this.commands.flush()},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.matchesEntity=function(e){if(!this._matcher)return!1;if(this._matcher.isNothing())return!1;if(this._matcher.isEmpty())return!0;for(var t,n=this._matcher.getCondition(),i=a(n.all);!(t=i()).done;){var r=t.value;if(!e.hasComponent(r))return!1}if(n.any.length>0){for(var o,s=!1,c=a(n.any);!(o=c()).done;){var u=o.value;if(e.hasComponent(u)){s=!0;break}}if(!s)return!1}for(var l,h=a(n.none);!(l=h()).done;){var d=l.value;if(e.hasComponent(d))return!1}return(void 0===n.tag||e.tag===n.tag)&&((void 0===n.name||e.name===n.name)&&!(void 0!==n.component&&!e.hasComponent(n.component)))},t.isTracking=function(e){return this._entityCache.isTracked(e)},t.handleEntityComponentChanged=function(e){if(this._matcher&&this._enabled){var t=this._entityCache.isTracked(e),n=this.matchesEntity(e);!t&&n?(this._entityCache.addTracked(e),this._entityCache.invalidate(),this.onAdded(e)):t&&!n&&(this._entityCache.removeTracked(e),this._entityCache.invalidate(),this.onRemoved(e))}},t.updateEntityTracking=function(e){for(var t,n=new Set(e),i=!1,r=a(e);!(t=r()).done;){var o=t.value;this._entityCache.isTracked(o)||(this._entityCache.addTracked(o),i=!0)}for(var s,c=a(this._entityCache.getTracked());!(s=c()).done;){var u=s.value;n.has(u)||(this._entityCache.removeTracked(u),i=!0)}i&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this._destroyed||(this.cleanupManualEventListeners(),this.onDestroy(),this._entityCache.clearAll(),this._entityIdMap=null,this.commands.dispose(),this._initialized=!1,this._scene=null,this._destroyed=!0,this.logger.debug("System "+this._systemName+" disposed"))},t.addEventListener=function(e,t,n){var i;if(null===(i=this.scene)||void 0===i||!i.eventSystem)return this.logger.warn(this.systemName+": 无法添加事件监听器,scene.eventSystem 不可用"),null;var r=this.scene.eventSystem.on(e,t,n);return r&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,listenerRef:r}),r},t.removeEventListener=function(e,t){var n=this._eventListeners.findIndex(function(n){return n.eventType===e&&n.listenerRef===t});if(n>=0){var i=this._eventListeners[n];if(!i)return;i.eventSystem.off(e,i.listenerRef),this._eventListeners.splice(n,1)}},t.cleanupManualEventListeners=function(){for(var e,t=a(this._eventListeners);!(e=t()).done;){var n=e.value;try{n.eventSystem.off(n.eventType,n.listenerRef)}catch(e){this.logger.warn(this.systemName+': 移除事件监听器失败 "'+n.eventType+'"',e)}}this._eventListeners.length=0},t.destroy=function(){this._destroyed||(this.cleanupManualEventListeners(),this._destroyed=!0,this.onDestroy())},t.getLoggerName=function(){return oe(this)},t.onDestroy=function(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.map(function(n){return t.requireComponent(e,n)})},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},t.saveEpoch=function(){this._lastProcessEpoch=this.currentEpoch},t.forEachChanged=function(e,t,n,i){for(var r=null!=i?i:this._lastProcessEpoch,o=0;o<e.length;o++){for(var s,c=e[o],u=!1,l=a(t);!(s=l()).done;){var h=s.value,d=c.getComponent(h);if(d&&d.lastWriteEpoch>r){u=!0;break}}u&&n(c,o)}this._lastProcessEpoch=this.currentEpoch},t.filterChanged=function(e,t,n){for(var i=null!=n?n:this._lastProcessEpoch,r=[],o=0;o<e.length;o++)for(var s,c=e[o],u=a(t);!(s=u()).done;){var l=s.value,h=c.getComponent(l);if(h&&h.lastWriteEpoch>i){r.push(c);break}}return r},t.hasChanged=function(e,t,n){for(var i,r=null!=n?n:this._lastProcessEpoch,o=a(t);!(i=o()).done;){var s=i.value,c=e.getComponent(s);if(c&&c.lastWriteEpoch>r)return!0}return!1},s(e,[{key:"entities",get:function(){var e=this._entityCache.getFrame();return null!==e?e:(this._entityCache.hasPersistent()||this._entityCache.setPersistent(this.queryEntities()),this._entityCache.getPersistent())}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this.setUpdateOrder(e)}},{key:"addOrder",get:function(){return this._addOrder},set:function(e){this._addOrder=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(e){this._scene=e,this.commands.setScene(e)}},{key:"matcher",get:function(){return this._matcher}},{key:"lastProcessEpoch",get:function(){return this._lastProcessEpoch}},{key:"currentEpoch",get:function(){var e,t;return null!==(e=null===(t=this._scene)||void 0===t||null===(t=t.epochManager)||void 0===t?void 0:t.current)&&void 0!==e?e:0}}])}(),Ge=function(t){function n(){var n;return(n=t.call(this,Re.empty().all(e.HierarchyComponent))||this).dirtyEntities=new Set,n}l(n,t);var i=n.prototype;return i.process=function(e){if(0!==this.dirtyEntities.size){for(var t,n=a(this.dirtyEntities);!(t=n()).done;){var i=t.value;i.scene&&this.updateHierarchyCache(i)}this.dirtyEntities.clear()}},i.setParent=function(t,n){var i,r=t.getComponent(e.HierarchyComponent);r||(r=new e.HierarchyComponent,t.addComponent(r));var o=r.parentId;if(o!==(null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null)){if(n&&this.isAncestorOf(t,n))throw new Error("Cannot set parent: would create circular reference");if(null!==o){var s,a=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(o);if(a){var c=a.getComponent(e.HierarchyComponent);if(c){var u=c.childIds.indexOf(t.id);-1!==u&&c.childIds.splice(u,1)}}}if(n){var l=n.getComponent(e.HierarchyComponent);l||(l=new e.HierarchyComponent,n.addComponent(l)),r.parentId=n.id,l.childIds.push(t.id)}else r.parentId=null;this.markCacheDirty(t)}},i.insertChildAt=function(t,n,i){var r=n.getComponent(e.HierarchyComponent),o=t.getComponent(e.HierarchyComponent);if(r||(r=new e.HierarchyComponent,n.addComponent(r)),o||(o=new e.HierarchyComponent,t.addComponent(o)),this.isAncestorOf(n,t))throw new Error("Cannot set parent: would create circular reference");if(null!==r.parentId&&r.parentId!==t.id){var s,a=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(r.parentId);if(a){var c=a.getComponent(e.HierarchyComponent);if(c){var u=c.childIds.indexOf(n.id);-1!==u&&c.childIds.splice(u,1)}}}r.parentId=t.id;var l=o.childIds.indexOf(n.id);-1!==l&&o.childIds.splice(l,1),i<0||i>=o.childIds.length?o.childIds.push(n.id):o.childIds.splice(i,0,n.id),this.markCacheDirty(n)},i.removeChild=function(t,n){var i=t.getComponent(e.HierarchyComponent),r=n.getComponent(e.HierarchyComponent);if(!i||!r)return!1;if(r.parentId!==t.id)return!1;var o=i.childIds.indexOf(n.id);return-1!==o&&i.childIds.splice(o,1),r.parentId=null,this.markCacheDirty(n),!0},i.removeAllChildren=function(t){var n=t.getComponent(e.HierarchyComponent);if(n)for(var i,r=a([].concat(n.childIds));!(i=r()).done;){var o,s=i.value,c=null===(o=this.scene)||void 0===o?void 0:o.findEntityById(s);c&&this.removeChild(t,c)}},i.getParent=function(t){var n,i,r=t.getComponent(e.HierarchyComponent);return r&&null!==r.parentId&&null!==(n=null===(i=this.scene)||void 0===i?void 0:i.findEntityById(r.parentId))&&void 0!==n?n:null},i.getChildren=function(t){var n=t.getComponent(e.HierarchyComponent);if(!n)return[];for(var i,r=[],o=a(n.childIds);!(i=o()).done;){var s,c=i.value,u=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(c);u&&r.push(u)}return r},i.getChildCount=function(t){var n,i=t.getComponent(e.HierarchyComponent);return null!==(n=null==i?void 0:i.childIds.length)&&void 0!==n?n:0},i.hasChildren=function(e){return this.getChildCount(e)>0},i.isAncestorOf=function(e,t){for(var i=this.getParent(t),r=0;i&&r<n.MAX_DEPTH;){if(i.id===e.id)return!0;i=this.getParent(i),r++}return!1},i.isDescendantOf=function(e,t){return this.isAncestorOf(t,e)},i.getRoot=function(e){for(var t=e,i=this.getParent(t),r=0;i&&r<n.MAX_DEPTH;)t=i,i=this.getParent(t),r++;return t},i.getDepth=function(t){var i=t.getComponent(e.HierarchyComponent);if(!i)return 0;if(!i.bCacheDirty)return i.depth;for(var r=0,o=this.getParent(t);o&&r<n.MAX_DEPTH;)r++,o=this.getParent(o);return i.depth=r,r},i.isActiveInHierarchy=function(t){if(!t.active)return!1;var n=t.getComponent(e.HierarchyComponent);if(!n)return t.active;if(!n.bCacheDirty)return n.bActiveInHierarchy;var i=this.getParent(t);return n.bActiveInHierarchy=i?t.active&&this.isActiveInHierarchy(i):t.active,n.bActiveInHierarchy},i.getRootEntities=function(){for(var t,n=[],i=a(this.entities);!(t=i()).done;){var r=t.value,o=r.getComponent(e.HierarchyComponent);o&&null===o.parentId&&n.push(r)}return n},i.findChild=function(e,t,n){void 0===n&&(n=!1);for(var i,r=this.getChildren(e),o=a(r);!(i=o()).done;){var s=i.value;if(s.name===t)return s}if(n)for(var c,u=a(r);!(c=u()).done;){var l=c.value,h=this.findChild(l,t,!0);if(h)return h}return null},i.findChildrenByTag=function(e,t,n){void 0===n&&(n=!1);for(var i,r=[],o=a(this.getChildren(e));!(i=o()).done;){var s=i.value;0!==(s.tag&t)&&r.push(s),n&&r.push.apply(r,this.findChildrenByTag(s,t,!0))}return r},i.forEachChild=function(e,t,n){void 0===n&&(n=!1);for(var i,r=a(this.getChildren(e));!(i=r()).done;){var o=i.value;t(o),n&&this.forEachChild(o,t,!0)}},i.flattenHierarchy=function(e){for(var t,n=this,i=[],r=function(t,o){var s=n.hasChildren(t),c=e.has(t.id);if(i.push({entity:t,depth:o,bHasChildren:s,bIsExpanded:c}),s&&c)for(var u,l=a(n.getChildren(t));!(u=l()).done;){var h=u.value;r(h,o+1)}},o=a(this.getRootEntities());!(t=o()).done;){var s=t.value;r(s,0)}return i},i.markCacheDirty=function(t){var n=t.getComponent(e.HierarchyComponent);if(n&&!n.bCacheDirty){n.bCacheDirty=!0,this.dirtyEntities.add(t);for(var i,r=a(n.childIds);!(i=r()).done;){var o,s=i.value,c=null===(o=this.scene)||void 0===o?void 0:o.findEntityById(s);c&&this.markCacheDirty(c)}}},i.updateHierarchyCache=function(t){var n=t.getComponent(e.HierarchyComponent);n&&(n.depth=this.getDepth(t),n.bActiveInHierarchy=this.isActiveInHierarchy(t),n.bCacheDirty=!1)},i.onAdded=function(t){var n=t.getComponent(e.HierarchyComponent);n&&n.bCacheDirty&&this.dirtyEntities.add(t)},i.onRemoved=function(t){this.dirtyEntities.delete(t);var n=t.getComponent(e.HierarchyComponent);if(n){if(null!==n.parentId){var i,r=null===(i=this.scene)||void 0===i?void 0:i.findEntityById(n.parentId);if(r){var o=r.getComponent(e.HierarchyComponent);if(o){var s=o.childIds.indexOf(t.id);-1!==s&&o.childIds.splice(s,1)}}}for(var c,u=a(n.childIds);!(c=u()).done;){var l,h=c.value,d=null===(l=this.scene)||void 0===l?void 0:l.findEntityById(h);if(d){var f=d.getComponent(e.HierarchyComponent);f&&(f.parentId=null,this.markCacheDirty(d))}}}},i.dispose=function(){this.dirtyEntities.clear()},s(n,[{key:"updateOrder",get:function(){return-1e3}}])}(We);Ge.MAX_DEPTH=32;var je=function(){function t(){}var n=t.prototype;return n.collectEntityData=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},n.getRawEntityList=function(t){if(!t)return[];var n=t.entities;if(null==n||!n.buffer)return[];var i=t.getSystem(Ge);return n.buffer.map(function(t){var n,r,o,s,a=t.getComponent(e.HierarchyComponent),c=null!==(n=null==i?void 0:i.isActiveInHierarchy(t))&&void 0!==n?n:t.active,u=null!==(r=null==i?void 0:i.getDepth(t))&&void 0!==r?r:0;return{id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:c,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),parentId:null!==(o=null==a?void 0:a.parentId)&&void 0!==o?o:null,childIds:null!==(s=null==a?void 0:a.childIds)&&void 0!==s?s:[],depth:u,tag:t.tag||0,updateOrder:t.updateOrder||0}})},n.getEntityDetails=function(e,t){try{var n,i,r;if(!t)return null;var o=t.entities;if(null==o||!o.buffer)return null;var s=o.buffer.find(function(t){return t.id===e});if(!s)return null;var a=t.getSystem(Ge),u=null==a?void 0:a.getParent(s),l=null!==(n=null==u?void 0:u.name)&&void 0!==n?n:null,h=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t,a),d=this.extractComponentDetails(s.components),f=this.getSceneInfo(t);return c({},h,{scene:f.name,sceneName:f.name,sceneType:f.type,parentName:l,components:d||[],componentCount:(null===(i=s.components)||void 0===i?void 0:i.length)||0,componentTypes:(null===(r=s.components)||void 0===r?void 0:r.map(function(e){return W(e)}))||[]})}catch(e){return{error:"获取实体详情失败: "+(e instanceof Error?e.message:String(e)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},n.getSceneInfo=function(e){var t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(e))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(t=r,n=r)}}catch(e){t="场景名获取失败"}return{name:t,type:n}},n.collectEntityDataWithMemory=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n,e),entityDetailsMap:this.buildEntityDetailsMap(n,e)}},n.collectArchetypeData=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},n.getArchetypeDistributionFast=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach(function(e){var n,i=(null===(n=e.components)||void 0===n?void 0:n.map(function(e){return W(e)}))||[],r=i.length>0?i.sort().join(", "):"无组件",o=t.get(r);o?o.count++:t.set(r,{count:1,componentTypes:i})}),Array.from(t.entries()).map(function(e){return{signature:e[0],count:e[1].count,memory:0}}).sort(function(e,t){return t.count-e.count}).slice(0,20)},n.getTopEntitiesByComponentsFast=function(e){return e&&e.entities?e.entities.map(function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}}).sort(function(e,t){return t.componentCount-e.componentCount}):[]},n.collectArchetypeDataWithMemory=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},n.extractArchetypeStatistics=function(e){var t=e.getAllArchetypes(),n=[],i=[];return t.forEach(function(e){var t,r,o=(null===(t=e.componentTypes)||void 0===t?void 0:t.map(function(e){return e.name}).join(","))||"Unknown",s=(null===(r=e.entities)||void 0===r?void 0:r.length)||0;n.push({signature:o,count:s,memory:0}),e.entities&&e.entities.forEach(function(e){var t;i.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0})})}),n.sort(function(e,t){return t.count-e.count}),i.sort(function(e,t){return t.componentCount-e.componentCount}),{distribution:n,topEntities:i}},n.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),i=[],r=[];return n.forEach(function(e){var n,o,s=(null===(n=e.componentTypes)||void 0===n?void 0:n.map(function(e){return e.name}).join(","))||"Unknown",a=(null===(o=e.entities)||void 0===o?void 0:o.length)||0,c=0;if(e.entities&&e.entities.length>0){for(var u=Math.min(5,e.entities.length),l=0,h=0;h<u;h++)l+=t.estimateEntityMemoryUsage(e.entities[h]);c=l/u*a}i.push({signature:s,count:a,memory:c}),e.entities&&e.entities.forEach(function(e){var n;r.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)})})}),i.sort(function(e,t){return t.count-e.count}),r.sort(function(e,t){return t.componentCount-e.componentCount}),{distribution:i,topEntities:r}},n.getArchetypeDistributionWithMemory=function(e){var t=this,n=new Map;return e&&e.entities&&e.entities.forEach(function(e){var i,r=(null===(i=e.components)||void 0===i?void 0:i.map(function(e){return W(e)}))||[],o=r.length>0?r.sort().join(", "):"无组件",s=n.get(o),a=t.estimateEntityMemoryUsage(e);(isNaN(a)||a<0)&&(a=0),s?(s.count++,s.memory+=a):n.set(o,{count:1,memory:a,componentTypes:r})}),Array.from(n.entries()).map(function(e){var t=e[0],n=e[1];return{signature:t,count:n.count,memory:isNaN(n.memory)?0:n.memory}}).sort(function(e,t){return t.count-e.count})},n.getTopEntitiesByComponentsWithMemory=function(e){var t=this;return e&&e.entities?e.entities.map(function(e){var n;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)}}).sort(function(e,t){return t.componentCount-e.componentCount}):[]},n.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},n.calculateFallbackEntityStats=function(e){var t=e.buffer||[],n=t.filter(function(e){return e.enabled&&!e.isDestroyed});return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce(function(e,t){var n;return e+((null===(n=t.components)||void 0===n?void 0:n.length)||0)},0)/n.length:0}},n.estimateEntityMemoryUsage=function(e){var t=this;try{var n=0,i=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),e.components&&Array.isArray(e.components)&&e.components.forEach(function(e){var i=t.calculateObjectSize(e,["entity"]);!isNaN(i)&&i>0&&(n+=i)}),isNaN(n)||n<0?0:n}catch(e){return 0}},n.calculateObjectSize=function(e,t){if(void 0===t&&(t=[]),!e||"object"!=typeof e)return 0;var n=new WeakSet,i=function(e,r){if(void 0===r&&(r=0),!e||"object"!=typeof e||r>=2)return 0;if(n.has(e))return 0;n.add(e);var o=32;try{for(var s=Object.keys(e),a=Math.min(s.length,20),c=0;c<a;c++){var u=s[c];if(u&&!t.includes(u)&&"constructor"!==u&&"__proto__"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__")){var l=e[u];o+=2*u.length,"string"==typeof l?o+=Math.min(2*l.length,200):"number"==typeof l?o+=8:"boolean"==typeof l?o+=4:Array.isArray(l)?o+=40+Math.min(8*l.length,160):"object"==typeof l&&null!==l&&(o+=i(l,r+1))}}}catch(e){return 64}return o};try{var r=i(e);return Math.max(r,32)}catch(e){return 64}},n.buildEntityHierarchyTree=function(t,n){var i=this;if(null==t||!t.buffer)return[];var r=null==n?void 0:n.getSystem(Ge),o=[];return t.buffer.forEach(function(t){var n=t.getComponent(e.HierarchyComponent);if(null===(null==n?void 0:n.parentId)||void 0===(null==n?void 0:n.parentId)){var s=i.buildEntityHierarchyNode(t,r);o.push(s)}}),o.sort(function(e,t){return e.name<t.name?-1:e.name>t.name?1:e.id-t.id}),o},n.buildEntityHierarchyNode=function(t,n){var i,r,o,s=this,a=t.getComponent(e.HierarchyComponent),u=null!==(i=null==n?void 0:n.isActiveInHierarchy(t))&&void 0!==i?i:t.active,l=null!==(r=null==n?void 0:n.getDepth(t))&&void 0!==r?r:0,h={id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:u,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),parentId:null!==(o=null==a?void 0:a.parentId)&&void 0!==o?o:null,children:[],depth:l,tag:t.tag||0,updateOrder:t.updateOrder||0};if(n){var d=n.getChildren(t);d.length>0&&(h.children=d.map(function(e){return s.buildEntityHierarchyNode(e,n)}))}"function"==typeof t.getDebugInfo&&(h=c({},h,t.getDebugInfo()));return t.components&&t.components.length>0&&(h.componentDetails=this.extractComponentDetails(t.components)),h},n.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var i=null==t?void 0:t.getSystem(Ge),r={},o=e.buffer,s=0;s<o.length;s+=100){o.slice(s,s+100).forEach(function(e){var o,s=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t,i),a=e.getComponentCacheStats?e.getComponentCacheStats():null,u=n.extractComponentDetails(e.components),l=null==i?void 0:i.getParent(e),h=null!==(o=null==l?void 0:l.name)&&void 0!==o?o:null;r[e.id]=c({},s,{parentName:h,components:u,componentTypes:s.componentTypes||u.map(function(e){return e.typeName}),cachePerformance:a?{hitRate:a.cacheStats.hitRate,size:a.cacheStats.size,maxSize:a.cacheStats.maxSize}:null})})}return r},n.buildFallbackEntityInfo=function(t,n,i){var r,o,s,a,c,u,l,h=this.getSceneInfo(n),d=t.getComponent(e.HierarchyComponent),f=null!==(r=null==i?void 0:i.isActiveInHierarchy(t))&&void 0!==r?r:t.active,p=null!==(o=null==i?void 0:i.getDepth(t))&&void 0!==o?o:0;return{name:t.name||"Entity_"+t.id,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:f,destroyed:t.isDestroyed||!1,scene:h.name,sceneName:h.name,sceneType:h.type,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),componentMask:(null===(s=t.componentMask)||void 0===s?void 0:s.toString())||"0",parentId:null!==(a=null==d?void 0:d.parentId)&&void 0!==a?a:null,childCount:null!==(c=null==d||null===(u=d.childIds)||void 0===u?void 0:u.length)&&void 0!==c?c:0,childIds:null!==(l=null==d?void 0:d.childIds)&&void 0!==l?l:[],depth:p,tag:t.tag||0,updateOrder:t.updateOrder||0}},n.extractComponentDetails=function(e){var t=this;return e.map(function(e){var n=W(e),i={};try{Object.keys(e).forEach(function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(i[n]=t.formatPropertyValue(r))}}),0===Object.keys(i).length&&(i._info="该组件没有公开属性",i._componentId=W(e))}catch(t){i._error="属性提取失败",i._componentId=W(e)}return{typeName:n,properties:i}})},n.getComponentProperties=function(e,t,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var o=r.buffer.find(function(t){return t.id===e});if(!o||t>=o.components.length)return{};var s=o.components[t];if(!s)return{};var a={};return Object.keys(s).forEach(function(e){if(!e.startsWith("_")&&"entity"!==e){var t=s[e];null!=t&&(a[e]=i.formatPropertyValue(t))}}),a}catch(e){return{_error:"属性提取失败"}}},n.formatPropertyValue=function(e,t){return void 0===t&&(t=0),null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?"[长字符串: "+e.length+"字符] "+e.substring(0,100)+"...":e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)},n.formatObjectFirstLevel=function(e){var t=this;try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){var n=e.slice(0,3).map(function(e){return t.formatPropertyValue(e,1)});return{_isLazyArray:!0,_arrayLength:e.length,_sample:n,_summary:"数组["+e.length+"个元素]"}}return e.map(function(e){return t.formatPropertyValue(e,1)})}var i=Object.keys(e);if(0===i.length)return{};for(var r={},o=0,s=0,a=i;s<a.length;s++){var c=a[s];if(o>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-o;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),o++)}catch(e){r[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",o++}}return r}catch(e){return"[对象解析失败: "+(e instanceof Error?e.message:String(e))+"]"}},n.createLazyLoadPlaceholder=function(e){try{var t,n=(null===(t=e.constructor)||void 0===t?void 0:t.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(e,n),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(e instanceof Error?e.message:String(e)),_objectId:Math.random().toString(36).substr(2,9)}}},n.getObjectSummary=function(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){var n=void 0!==e.z?e.z:"";return t+"("+e.x+", "+e.y+(n?", "+n:"")+")"}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){var i=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+i+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var r,o,s=(null===(r=e.node)||void 0===r?void 0:r.name)||(null===(o=e.node)||void 0===o?void 0:o._name)||"";return t+(s?" on "+s:"")}var a=Object.keys(e);return 0===a.length?t+" (空对象)":t+" ("+a.length+"个属性)"}catch(e){return t+" (无法分析)"}},n.generateObjectId=function(e){try{return void 0!==e.id?"obj_"+e.id:void 0!==e._id?"obj_"+e._id:void 0!==e.uuid?"obj_"+e.uuid:void 0!==e._uuid?"obj_"+e._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(e){return"obj_"+Math.random().toString(36).substr(2,9)}},n.expandLazyObject=function(e,t,n,i){try{if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var o=r.buffer.find(function(t){return t.id===e});if(!o)return null;if(t>=o.components.length)return null;var s=o.components[t],a=this.getObjectByPath(s,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:"展开失败: "+(e instanceof Error?e.message:String(e))}}},n.getObjectByPath=function(e,t){if(!t)return e;for(var n,i=e,r=a(t.split("."));!(n=r()).done;){var o=n.value;if(null==i)return null;if(o.includes("[")&&o.includes("]")){var s=o.substring(0,o.indexOf("[")),c=parseInt(o.substring(o.indexOf("[")+1,o.indexOf("]")));if(s&&(i=i[s]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[o]}return i},t}(),Ue=function(){function e(){}return e.prototype.collectSystemData=function(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};var n=t.systems||[],i=new Map,r=new Map;if(e)try{i=e.getAllSystemStats(),r=e.getAllSystemData()}catch(e){}return{totalSystems:n.length,systemsInfo:n.map(function(e){var t,n=e.systemName||oe(e),o=i.get(n),s=r.get(n);return{name:n,type:oe(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==o?void 0:o.averageTime)||(null==s?void 0:s.executionTime)||0,minExecutionTime:(null==o?void 0:o.minTime)===Number.MAX_VALUE?0:(null==o?void 0:o.minTime)||0,maxExecutionTime:(null==o?void 0:o.maxTime)||0,executionTimeHistory:(null==o?void 0:o.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==s?void 0:s.lastUpdateTime)||0}})}},e}(),qe=function(){function e(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}var t=e.prototype;return t.collectPerformanceData=function(e){var t=_.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,s=n>0?o/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter(function(e){return e>=0});return{frameTime:o,engineFrameTime:n,ecsPercentage:s,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce(function(e,t){return e+t},0)/c.length:o,minFrameTime:c.length>0?Math.min.apply(Math,c):o,maxFrameTime:c.length>0?Math.max.apply(Math,c):o,frameTimeHistory:[].concat(this.frameTimeHistory),systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},t.getECSPerformanceData=function(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var t=0,n=[],i=e.getAllSystemStats();if(0===i.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var r,o=a(i.entries());!(r=o()).done;){var s=r.value,c=s[0],u=s[1],l=u.recentTimes&&u.recentTimes.length>0?u.recentTimes[u.recentTimes.length-1]:u.averageTime||0;t+=l,n.push({systemName:c,executionTime:l,percentage:0})}return n.forEach(function(e){e.percentage=t>0?e.executionTime/t*100:0}),n.sort(function(e,t){return t.executionTime-e.executionTime}),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}},t.getSystemPerformance=function(e){if(!e)return[];try{var t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map(function(e){var t=e[0],i=e[1],r=n.get(t);return{systemName:t,averageTime:i.averageTime||0,maxTime:i.maxTime||0,minTime:i.minTime===Number.MAX_VALUE?0:i.minTime||0,samples:i.executionCount||0,percentage:0,entityCount:(null==r?void 0:r.entityCount)||0,lastExecutionTime:(null==r?void 0:r.executionTime)||0}})}catch(e){return[]}},t.getMemoryDetails=function(){var e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e},t.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}},e}(),Qe=function(){function e(e,t,n,i){void 0===n&&(n=1e3),void 0===i&&(i=10),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,t&&(this.resetFn=t),this.maxSize=n,this.minSize=Math.max(1,i)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var i=this.createFn();this.resetFn&&this.resetFn(i),this.pool.push(i),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),Ve=function(){function e(){this._pools=new Map,this._usageTracker=new Map,this._autoCleanupInterval=6e4,this._lastCleanupTime=0}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.registerPool=function(e,t,n,i,r){this._pools.set(e,new Qe(t,n,i,r)),this._usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this._pools.get(e);return this._trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this._pools.get(e);this._trackUsage(e,"release"),n&&n.release(t)},t._trackUsage=function(e,t){var n=this._usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this._usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this._lastCleanupTime<this._autoCleanupInterval)){for(var t,n=a(this._usageTracker.entries());!(t=n()).done;){var i=t.value,r=i[0];if(e-i[1].lastAccessTime>12e4){var o=this._pools.get(r);o&&o.shrink()}}this._lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this._usageTracker.entries()).filter(function(t){return t[0],t[1].createCount>e}).map(function(e){return e[0]})},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=a(this._pools.values());!(t=n()).done;){t.value.prewarm(e)}},t.clearAll=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.clear()}},t.reset=function(){this._pools.clear(),this._usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=a(this._pools.entries());!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.push({componentName:r,poolStats:o.getStats(),usage:this._usageTracker.get(r)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,{available:o.getAvailableCount(),maxSize:o.getMaxSize()})}return t},t.getPoolUtilization=function(){for(var e,t=new Map,n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=o.getAvailableCount(),c=o.getMaxSize(),u=c-s,l=c>0?u/c*100:0;t.set(r,{used:u,total:c,utilization:l})}return t},t.getComponentUtilization=function(e){var t=this._pools.get(e);if(!t)return 0;var n=t.getAvailableCount(),i=t.getMaxSize();return i>0?(i-n)/i*100:0},e}(),Ye=function(){function e(){}var t=e.prototype;return t.collectComponentData=function(e){var t=this;if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=e.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach(function(e){e.components&&e.components.forEach(function(e){var t=W(e),n=i.get(t)||{count:0,entities:0};n.count++,r++,i.set(t,n)})});var o=new Map,s=new Map;try{for(var c,u=Ve.getInstance(),l=u.getPoolStats(),h=u.getPoolUtilization(),d=a(l.entries());!(c=d()).done;){var f=c.value,p=f[0],m=f[1];s.set(p,m.maxSize)}for(var v,g=a(h.entries());!(v=g()).done;){var y=v.value,_=y[0],S=y[1];o.set(_,S.utilization)}}catch(e){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map(function(i){var r=i[0],a=i[1],c=s.get(r)||0,u=o.get(r)||0,l=t.getEstimatedComponentSize(r,e);return{typeName:r,instanceCount:a.count,memoryPerInstance:l,totalMemory:a.count*l,poolSize:c,poolUtilization:u,averagePerEntity:a.count/n.buffer.length}})}},t.getEstimatedComponentSize=function(t,n){if(e.componentSizeCache.has(t))return e.componentSizeCache.get(t);if(!n)return 64;var i=n.entities;if(null==i||!i.buffer)return 64;var r=64;try{for(var o,s=a(i.buffer);!(o=s()).done;){var c=o.value;if(c.components){var u=c.components.find(function(e){return W(e)===t});if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(e){r=64}return e.componentSizeCache.set(t,r),r},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,i=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var r=0;try{for(var o=Object.keys(e),s=0;s<Math.min(o.length,20);s++){var a=o[s];if(a&&"entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=e[a];r+=2*a.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:"object"==typeof c&&null!==c&&(r+=i(c,t+1))}}}catch(e){return 32}return r};return t+=i(e),Math.max(t,32)},t.calculateDetailedComponentMemory=function(e,t){if(!t)return this.getEstimatedComponentSize(e,t);var n=t.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(e,t);try{for(var i,r=a(n.buffer);!(i=r()).done;){var o=i.value;if(o.components){var s=o.components.find(function(t){return W(t)===e});if(s)return this.estimateObjectSize(s)}}}catch(e){}return this.getEstimatedComponentSize(e,t)},t.estimateObjectSize=function(e,t,n){if(void 0===t&&(t=new WeakSet),void 0===n&&(n=0),null==e||n>10)return 0;if(t.has(e))return 0;var i=0;switch(typeof e){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){i=40+8*e.length;for(var r=Math.min(e.length,50),o=0;o<r;o++)i+=this.estimateObjectSize(e[o],t,n+1)}else{i=32;try{for(var s=Object.getOwnPropertyNames(e),a=Math.min(s.length,30),c=0;c<a;c++){var u=s[c];if(u&&("constructor"!==u&&"__proto__"!==u&&"entity"!==u&&"_entity"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__")))try{i+=16+2*u.length;var l=e[u];null!=l&&(i+=this.estimateObjectSize(l,t,n+1))}catch(e){continue}}}catch(e){i=128}}}return 8*Math.ceil(i/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();Ye.componentSizeCache=new Map;var Je,Ze=function(){function e(){this.sceneStartTime=Date.now()}var t=e.prototype;return t.collectSceneData=function(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneUptime:0};var t=(Date.now()-this.sceneStartTime)/1e3,n=e.getStats();return{currentSceneName:e.name||"Unnamed Scene",isInitialized:!0,sceneRunTime:t,sceneEntityCount:n.entityCount,sceneSystemCount:n.processorCount,sceneUptime:t}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),Xe=function(){function e(e,t){void 0===t&&(t=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.url=e,this.autoReconnect=t}var t=e.prototype;return t.setMessageHandler=function(e){this.messageHandler=e},t.connect=function(){var e=this;return new Promise(function(t,n){try{e.ws=new WebSocket(e.url),e.ws.onopen=function(n){e.handleOpen(n),t()},e.ws.onclose=function(t){e.handleClose(t)},e.ws.onerror=function(t){e.handleError(t),n(t)},e.ws.onmessage=function(t){e.handleMessage(t)}}catch(t){e.handleConnectionFailure(t),n(t)}})},t.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),delete this.ws),this.isConnected=!1},t.send=function(e){if(this.isConnected&&this.ws)try{var t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}},t.getConnectionStatus=function(){return this.isConnected},t.setMaxReconnectAttempts=function(e){this.maxReconnectAttempts=e},t.scheduleReconnect=function(){var e=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(function(){e.connect().catch(function(t){e.reconnectAttempts<e.maxReconnectAttempts&&e.scheduleReconnect()})},t)},t.handleMessage=function(e){try{var t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}},t.handleOpen=function(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)},t.handleClose=function(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},t.handleError=function(e){this.onError&&this.onError(e)},t.handleConnectionFailure=function(e){this.onError&&this.onError(e)},e}();e.ProfileCategory=void 0,(Je=e.ProfileCategory||(e.ProfileCategory={})).ECS="ECS",Je.Rendering="Rendering",Je.Physics="Physics",Je.Audio="Audio",Je.Network="Network",Je.Script="Script",Je.Memory="Memory",Je.Animation="Animation",Je.AI="AI",Je.Input="Input",Je.Loading="Loading",Je.Custom="Custom";var Ke={enabled:!1,maxFrameHistory:300,maxSampleDepth:32,collectMemory:!0,memorySampleInterval:100,detectLongTasks:!0,longTaskThreshold:50,enabledCategories:new Set(Object.values(e.ProfileCategory))},$e=0;var et=function(){function t(e){this.currentFrame=null,this.frameHistory=[],this.frameNumber=0,this.activeSamples=new Map,this.sampleStack=[],this.counters=new Map,this.callGraph=new Map,this.gcCount=0,this.previousHeapSize=0,this.longTasks=[],this.performanceObserver=null,this._config=c({},Ke,e),this._config.detectLongTasks&&this._setupLongTaskObserver()}t.getInstance=function(e){return t._instance||(t._instance=new t(e)),t._instance},t.resetInstance=function(){t._instance&&(t._instance.dispose(),t._instance=null)},t.beginSample=function(n,i){return void 0===i&&(i=e.ProfileCategory.Custom),t.getInstance().beginSample(n,i)},t.endSample=function(e){e&&t.getInstance().endSample(e)},t.measure=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().measure(n,i,r)},t.measureAsync=function(){var n=i(d().m(function n(i,r,o){return d().w(function(n){for(;;)if(0===n.n)return void 0===o&&(o=e.ProfileCategory.Custom),n.a(2,t.getInstance().measureAsync(i,r,o))},n)}));return function(e,t,i){return n.apply(this,arguments)}}(),t.beginFrame=function(){t.getInstance().beginFrame()},t.endFrame=function(){t.getInstance().endFrame()},t.incrementCounter=function(n,i,r){void 0===i&&(i=1),void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().incrementCounter(n,i,r)},t.setGauge=function(n,i,r){void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().setGauge(n,i,r)},t.setEnabled=function(e){t.getInstance().setEnabled(e)},t.isEnabled=function(){return t.getInstance()._config.enabled},t.getCurrentFrame=function(){return t.getInstance().currentFrame},t.getFrameHistory=function(){return t.getInstance().frameHistory},t.getReport=function(e){return t.getInstance().generateReport(e)},t.reset=function(){t.getInstance().reset()};var n=t.prototype;return n.beginSample=function(t,n){if(void 0===n&&(n=e.ProfileCategory.Custom),!this._config.enabled||!this._config.enabledCategories.has(n))return null;var i=this.sampleStack.length>0?this.sampleStack[this.sampleStack.length-1]:void 0;if(i&&this.sampleStack.length>=this._config.maxSampleDepth)return null;var r={id:"sample_"+ ++$e+"_"+Date.now(),name:t,category:n,startTime:performance.now(),depth:this.sampleStack.length,parentId:null==i?void 0:i.id};return this.activeSamples.set(r.id,r),this.sampleStack.push(r),r},n.endSample=function(e){if(this._config.enabled&&this.activeSamples.has(e.id)){var t=performance.now(),n=t-e.startTime,i=e.parentId?this.activeSamples.get(e.parentId):void 0,r={id:e.id,name:e.name,category:e.category,startTime:e.startTime,endTime:t,duration:n,selfTime:n,parentId:e.parentId,parentName:null==i?void 0:i.name,depth:e.depth,callCount:1};this.currentFrame&&this.currentFrame.samples.push(r),this._updateCallGraph(e.name,e.category,n,i),this.activeSamples.delete(e.id);var o=this.sampleStack.indexOf(e);-1!==o&&this.sampleStack.splice(o,1)}},n.measure=function(t,n,i){void 0===i&&(i=e.ProfileCategory.Custom);var r=this.beginSample(t,i);try{return n()}finally{r&&this.endSample(r)}},n.measureAsync=function(){var t=i(d().m(function t(n,i,r){var o;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:return void 0===r&&(r=e.ProfileCategory.Custom),o=this.beginSample(n,r),t.p=1,t.n=2,i();case 2:return t.a(2,t.v);case 3:return t.p=3,o&&this.endSample(o),t.f(3);case 4:return t.a(2)}},t,this,[[1,,3,4]])}));return function(e,n,i){return t.apply(this,arguments)}}(),n.beginFrame=function(){this._config.enabled&&(this.frameNumber++,this.currentFrame={frameNumber:this.frameNumber,startTime:performance.now(),endTime:0,duration:0,samples:[],sampleStats:[],counters:new Map(this.counters),memory:this._captureMemory(),categoryStats:new Map},this._resetFrameCounters())},n.endFrame=function(){if(this._config.enabled&&this.currentFrame){for(this.currentFrame.endTime=performance.now(),this.currentFrame.duration=this.currentFrame.endTime-this.currentFrame.startTime,this._calculateSampleStats(),this._calculateCategoryStats(),this.frameHistory.push(this.currentFrame);this.frameHistory.length>this._config.maxFrameHistory;)this.frameHistory.shift();this.sampleStack=[],this.activeSamples.clear()}},n.incrementCounter=function(t,n,i){if(void 0===n&&(n=1),void 0===i&&(i=e.ProfileCategory.Custom),this._config.enabled){var r=this.counters.get(t);r||(r={name:t,category:i,value:0,type:"counter",history:[]},this.counters.set(t,r)),r.value+=n,r.history.push({time:performance.now(),value:r.value}),r.history.length>100&&r.history.shift()}},n.setGauge=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),this._config.enabled){var r=this.counters.get(t);r||(r={name:t,category:i,value:0,type:"gauge",history:[]},this.counters.set(t,r)),r.value=n,r.history.push({time:performance.now(),value:n}),r.history.length>100&&r.history.shift()}},n.setEnabled=function(e){this._config.enabled=e,e&&this._config.detectLongTasks&&!this.performanceObserver&&this._setupLongTaskObserver()},n.reset=function(){this.frameHistory=[],this.currentFrame=null,this.frameNumber=0,this.activeSamples.clear(),this.sampleStack=[],this.counters.clear(),this.callGraph.clear(),this.gcCount=0,this.longTasks=[]},n.generateReport=function(e){var t,n,i=e?this.frameHistory.slice(-e):this.frameHistory;if(0===i.length)return this._createEmptyReport();var r=i.map(function(e){return e.duration}),o=[].concat(r).sort(function(e,t){return e-t}),s=this._aggregateSampleStats(i).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}).slice(0,20),a=this._aggregateCategoryStats(i),c=this._buildCallGraphFromFrames(i),u=i[0],l=i[i.length-1];return{startTime:null!==(t=null==u?void 0:u.startTime)&&void 0!==t?t:0,endTime:null!==(n=null==l?void 0:l.endTime)&&void 0!==n?n:0,totalFrames:i.length,averageFrameTime:r.reduce(function(e,t){return e+t},0)/r.length,minFrameTime:Math.min.apply(Math,r),maxFrameTime:Math.max.apply(Math,r),p95FrameTime:o[Math.floor(.95*o.length)]||0,p99FrameTime:o[Math.floor(.99*o.length)]||0,hotspots:s,callGraph:c,categoryBreakdown:a,memoryTrend:i.map(function(e){return e.memory}),longTasks:[].concat(this.longTasks)}},n._buildCallGraphFromFrames=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.samples);!(r=o()).done;){var s=r.value,c=n.get(s.name);if(c||(c={category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},n.set(s.name,c)),c.callCount++,c.totalTime+=s.duration,s.parentName){var u=c.callers.get(s.parentName)||{count:0,totalTime:0};u.count++,u.totalTime+=s.duration,c.callers.set(s.parentName,u);var l=n.get(s.parentName);l||(l={category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},n.set(s.parentName,l));var h=l.callees.get(s.name)||{count:0,totalTime:0};h.count++,h.totalTime+=s.duration,l.callees.set(s.name,h)}}for(var d,f=new Map,p=a(n);!(d=p()).done;){for(var m,v=d.value,g=v[0],y=v[1],_=new Map,S=a(y.callers);!(m=S()).done;){var C=m.value,E=C[0],b=C[1];_.set(E,{count:b.count,totalTime:b.count>0?b.totalTime/b.count:0})}for(var T,w=new Map,I=a(y.callees);!(T=I()).done;){var M=T.value,A=M[0],k=M[1];w.set(A,{count:k.count,totalTime:k.count>0?k.totalTime/k.count:0})}f.set(g,{name:g,category:y.category,callCount:y.callCount,totalTime:y.callCount>0?y.totalTime/y.callCount:0,callers:_,callees:w})}return f},n.getCallGraph=function(){return new Map(this.callGraph)},n.getFunctionCallInfo=function(e){var t=this.callGraph.get(e);return t?{callers:Array.from(t.callers.entries()).map(function(e){return c({name:e[0]},e[1])}),callees:Array.from(t.callees.entries()).map(function(e){return c({name:e[0]},e[1])})}:null},n.dispose=function(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.reset()},n._captureMemory=function(){var e=performance.now(),t=0,n=0,i=0,r=performance;return r.memory&&(t=r.memory.usedJSHeapSize||0,n=r.memory.totalJSHeapSize||0,i=r.memory.jsHeapSizeLimit||0,this.previousHeapSize>0&&t<this.previousHeapSize-1048576&&this.gcCount++,this.previousHeapSize=t),{timestamp:e,usedHeapSize:t,totalHeapSize:n,heapSizeLimit:i,utilizationPercent:i>0?t/i*100:0,gcCount:this.gcCount}},n._resetFrameCounters=function(){for(var e,t=a(this.counters.values());!(e=t()).done;){var n=e.value;"counter"===n.type&&(n.value=0)}},n._calculateSampleStats=function(){var e=this;if(this.currentFrame){for(var t,n=new Map,i=a(this.currentFrame.samples);!(t=i()).done;){var r=t.value,o=n.get(r.name);o||(o={name:r.name,category:r.category,inclusiveTime:0,exclusiveTime:0,callCount:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,percentOfFrame:0,percentOfParent:0,children:[],depth:r.depth},n.set(r.name,o)),o.inclusiveTime+=r.duration,o.callCount+=1,o.minTime=Math.min(o.minTime,r.duration),o.maxTime=Math.max(o.maxTime,r.duration)}for(var s,c=function(){var t=s.value;if(t.parentId){var i=e.currentFrame.samples.find(function(e){return e.id===t.parentId});if(i){var r=n.get(i.name);if(r){r.exclusiveTime=r.inclusiveTime;for(var o,c=a(e.currentFrame.samples);!(o=c()).done;){var u=o.value;u.parentId===i.id&&(r.exclusiveTime-=u.duration)}}}}},u=a(this.currentFrame.samples);!(s=u()).done;)c();for(var l,h=this.currentFrame.duration||1,d=a(n.values());!(l=d()).done;){var f=l.value;f.averageTime=f.inclusiveTime/f.callCount,f.percentOfFrame=f.inclusiveTime/h*100,0===f.exclusiveTime&&(f.exclusiveTime=f.inclusiveTime)}this.currentFrame.sampleStats=Array.from(n.values()).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime})}},n._calculateCategoryStats=function(){if(this.currentFrame){for(var e,t=new Map,n=a(this.currentFrame.samples);!(e=n()).done;){var i=e.value;if(0===i.depth){var r=t.get(i.category);r||(r={totalTime:0,sampleCount:0},t.set(i.category,r)),r.totalTime+=i.duration,r.sampleCount+=1}}for(var o,s=this.currentFrame.duration||1,u=a(t);!(o=u()).done;){var l=o.value,h=l[0],d=l[1];this.currentFrame.categoryStats.set(h,c({},d,{percentOfFrame:d.totalTime/s*100}))}}},n._updateCallGraph=function(e,t,n,i){var r=this.callGraph.get(e);if(r||(r={name:e,category:t,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(e,r)),r.callCount++,r.totalTime+=n,i){var o=r.callers.get(i.name)||{count:0,totalTime:0};o.count++,o.totalTime+=n,r.callers.set(i.name,o);var s=this.callGraph.get(i.name);s||(s={name:i.name,category:i.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(i.name,s));var a=s.callees.get(e)||{count:0,totalTime:0};a.count++,a.totalTime+=n,s.callees.set(e,a)}},n._aggregateSampleStats=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.sampleStats);!(r=o()).done;){var s=r.value,u=n.get(s.name);u?(u.inclusiveTime+=s.inclusiveTime,u.exclusiveTime+=s.exclusiveTime,u.callCount+=s.callCount,u.minTime=Math.min(u.minTime,s.minTime),u.maxTime=Math.max(u.maxTime,s.maxTime)):(u=c({},s,{minTime:Number.MAX_VALUE}),n.set(s.name,u))}for(var l,h=e.reduce(function(e,t){return e+t.duration},0),d=a(n.values());!(l=d()).done;){var f=l.value;f.averageTime=f.inclusiveTime/f.callCount,f.percentOfFrame=f.inclusiveTime/h*100}return Array.from(n.values())},n._aggregateCategoryStats=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.categoryStats);!(r=o()).done;){var s=r.value,c=s[0],u=s[1],l=n.get(c);l||(l={totalTime:0,frameCount:0},n.set(c,l)),l.totalTime+=u.totalTime,l.frameCount++}for(var h,d=e.reduce(function(e,t){return e+t.duration},0),f=new Map,p=a(n);!(h=p()).done;){var m=h.value,v=m[0],g=m[1];f.set(v,{totalTime:g.totalTime,averageTime:g.frameCount>0?g.totalTime/g.frameCount:0,percentOfTotal:d>0?g.totalTime/d*100:0})}return f},n._setupLongTaskObserver=function(){var e=this;if("undefined"!=typeof PerformanceObserver)try{this.performanceObserver=new PerformanceObserver(function(t){for(var n,i=a(t.getEntries());!(n=i()).done;){var r,o=n.value;if(o.duration>e._config.longTaskThreshold)e.longTasks.push({startTime:o.startTime,duration:o.duration,attribution:(null===(r=o.attribution)||void 0===r?void 0:r.map(function(e){return e.name}))||[]}),e.longTasks.length>100&&e.longTasks.shift()}}),this.performanceObserver.observe({entryTypes:["longtask"]})}catch(e){}},n._createEmptyReport=function(){return{startTime:0,endTime:0,totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,hotspots:[],callGraph:new Map,categoryBreakdown:new Map,memoryTrend:[],longTasks:[]}},t}();et._instance=null;var tt=function(){function t(){this.selectedFunction=null,this.peakMemory=0}var n=t.prototype;return n.setSelectedFunction=function(e){this.selectedFunction=e},n.collectAdvancedData=function(e){var t=et.getFrameHistory(),n=et.getCurrentFrame(),i=et.getReport(300),r=(null==n?void 0:n.memory)||this.getDefaultMemory();return r.usedHeapSize>this.peakMemory&&(this.peakMemory=r.usedHeapSize),{currentFrame:this.buildCurrentFrameData(n),frameTimeHistory:this.buildFrameTimeHistory(t),categoryStats:this.buildCategoryStats(n,e),hotspots:this.buildHotspots(i),callGraph:this.buildCallGraph(i),longTasks:i.longTasks,memoryTrend:this.buildMemoryTrend(i.memoryTrend),summary:this.buildSummary(i,r)}},n.collectFromLegacyMonitor=function(e){var t,n;if(!e)return this.createEmptyData();var i=(null===(t=e.getAllSystemStats)||void 0===t?void 0:t.call(e))||new Map,r=(null===(n=e.getAllSystemData)||void 0===n?void 0:n.call(e))||new Map,o=1e3*_.deltaTime,s=o>0?Math.round(1e3/o):0,a=this.buildCategoryStatsFromLegacy(i,r,o),c=this.buildHotspotsFromLegacy(i,r,o);return{currentFrame:{frameNumber:0,frameTime:o,fps:s,memory:this.getCurrentMemory()},frameTimeHistory:[],categoryStats:a,hotspots:c,callGraph:{currentFunction:this.selectedFunction,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:o,minFrameTime:o,maxFrameTime:o,p95FrameTime:o,p99FrameTime:o,currentMemoryMB:this.getCurrentMemory().usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:0,longTaskCount:0}}},n.buildCurrentFrameData=function(e){if(!e){var t=1e3*_.deltaTime;return{frameNumber:0,frameTime:t,fps:t>0?Math.round(1e3/t):0,memory:this.getCurrentMemory()}}return{frameNumber:e.frameNumber,frameTime:e.duration,fps:e.duration>0?Math.round(1e3/e.duration):0,memory:e.memory}},n.buildFrameTimeHistory=function(e){return e.map(function(e){return{frameNumber:e.frameNumber,time:e.startTime,duration:e.duration}})},n.buildCategoryStats=function(e,t){var n=[];if(e&&e.categoryStats.size>0)for(var i,r=e.duration||1,o=function(){var t=i.value,o=t[0],s=t[1],a=e.sampleStats.filter(function(e){return e.category===o}).map(function(e){return{name:e.name,inclusiveTime:e.inclusiveTime,exclusiveTime:e.exclusiveTime,callCount:e.callCount,percentOfCategory:s.totalTime>0?e.inclusiveTime/s.totalTime*100:0,percentOfFrame:e.inclusiveTime/r*100}}).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime});n.push({category:o,totalTime:s.totalTime,percentOfFrame:s.percentOfFrame,sampleCount:s.sampleCount,items:a})},s=a(e.categoryStats);!(i=s()).done;)o();if(t&&0===n.length){var c,u,l=(null===(c=t.getAllSystemStats)||void 0===c?void 0:c.call(t))||new Map,h=(null===(u=t.getAllSystemData)||void 0===u?void 0:u.call(t))||new Map,d=1e3*_.deltaTime||1;return this.buildCategoryStatsFromLegacy(l,h,d)}return n.sort(function(e,t){return t.totalTime-e.totalTime})},n.buildCategoryStatsFromLegacy=function(t,n,i){for(var r,o=[],s=0,c=a(t.entries());!(r=c()).done;){var u=r.value,l=u[0],h=u[1],d=n.get(l),f=(null==d?void 0:d.executionTime)||(null==h?void 0:h.averageTime)||0;s+=f,o.push({name:l,inclusiveTime:f,exclusiveTime:f,callCount:1,percentOfCategory:0,percentOfFrame:i>0?f/i*100:0})}for(var p=0,m=o;p<m.length;p++){var v=m[p];v.percentOfCategory=s>0?v.inclusiveTime/s*100:0}return o.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}),0===o.length?[]:[{category:e.ProfileCategory.ECS,totalTime:s,percentOfFrame:i>0?s/i*100:0,sampleCount:o.length,items:o}]},n.buildHotspots=function(t){for(var n,i=t.hotspots.reduce(function(e,t){return e+t.inclusiveTime},0)||1,r=new Set,o=new Set,s=a(t.callGraph);!(n=s()).done;){var c=n.value,u=c[0],l=c[1];if(0===l.callers.size)r.add(u);else{for(var h,d=!1,f=a(l.callers.keys());!(h=f()).done;){var p=h.value;if(t.callGraph.has(p)){d=!0,o.add(u);break}}d||r.add(u)}}for(var m,v=function(n,r,o){if(o.has(n))return null;o.add(n);var s=t.hotspots.find(function(e){return e.name===n}),c=t.callGraph.get(n);if(!s&&!c)return null;var u=(null==s?void 0:s.inclusiveTime)||(null==c?void 0:c.totalTime)||0,l=(null==s?void 0:s.exclusiveTime)||u,h=(null==s?void 0:s.callCount)||(null==c?void 0:c.callCount)||1,d=[];if(c&&r<5){for(var f,p=a(c.callees);!(f=p()).done;){var m=f.value[0],g=v(m,r+1,o);g&&d.push(g)}d.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime})}return{name:n,category:(null==s?void 0:s.category)||(null==c?void 0:c.category)||e.ProfileCategory.Custom,inclusiveTime:u,inclusiveTimePercent:u/i*100,exclusiveTime:l,exclusiveTimePercent:l/i*100,callCount:h,avgCallTime:h>0?u/h:0,depth:r,children:d.length>0?d:void 0}},g=[],y=new Set,_=a(r);!(m=_()).done;){var S=m.value,C=v(S,0,y);C&&g.push(C)}return g.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}),g.slice(0,50)},n.buildHotspotsFromLegacy=function(t,n,i){for(var r,o=[],s=a(t.entries());!(r=s()).done;){var c=r.value,u=c[0],l=c[1],h=n.get(u),d=(null==h?void 0:h.executionTime)||(null==l?void 0:l.averageTime)||0;o.push({name:u,category:e.ProfileCategory.ECS,inclusiveTime:d,inclusiveTimePercent:i>0?d/i*100:0,exclusiveTime:d,exclusiveTimePercent:i>0?d/i*100:0,callCount:(null==l?void 0:l.executionCount)||1,avgCallTime:(null==l?void 0:l.averageTime)||d,depth:0})}return o.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}).slice(0,50)},n.buildCallGraph=function(e){if(!this.selectedFunction)return{currentFunction:null,callers:[],callees:[]};var t=e.callGraph.get(this.selectedFunction);if(!t)return{currentFunction:this.selectedFunction,callers:[],callees:[]};for(var n,i=0,r=a(t.callers.values());!(n=r()).done;){var o=n.value;i+=o.count}var s=Array.from(t.callers.entries()).map(function(e){var t=e[0],n=e[1];return{name:t,callCount:n.count,totalTime:n.totalTime,percentOfCurrent:i>0?n.count/i*100:0}}).sort(function(e,t){return t.callCount-e.callCount}),c=Array.from(t.callees.entries()).map(function(e){var n=e[0],i=e[1];return{name:n,callCount:i.count,totalTime:i.totalTime,percentOfCurrent:t.totalTime>0?i.totalTime/t.totalTime*100:0}}).sort(function(e,t){return t.totalTime-e.totalTime});return{currentFunction:this.selectedFunction,callers:s,callees:c}},n.buildMemoryTrend=function(e){return e.map(function(e){return{time:e.timestamp,usedMB:e.usedHeapSize/1048576,totalMB:e.totalHeapSize/1048576,gcCount:e.gcCount}})},n.buildSummary=function(e,t){return{totalFrames:e.totalFrames,averageFrameTime:e.averageFrameTime,minFrameTime:e.minFrameTime,maxFrameTime:e.maxFrameTime,p95FrameTime:e.p95FrameTime,p99FrameTime:e.p99FrameTime,currentMemoryMB:t.usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:t.gcCount,longTaskCount:e.longTasks.length}},n.getCurrentMemory=function(){var e,t,n,i=performance,r=(null===(e=i.memory)||void 0===e?void 0:e.usedJSHeapSize)||0,o=(null===(t=i.memory)||void 0===t?void 0:t.totalJSHeapSize)||0,s=(null===(n=i.memory)||void 0===n?void 0:n.jsHeapSizeLimit)||0;return{timestamp:performance.now(),usedHeapSize:r,totalHeapSize:o,heapSizeLimit:s,utilizationPercent:s>0?r/s*100:0,gcCount:0}},n.getDefaultMemory=function(){return{timestamp:performance.now(),usedHeapSize:0,totalHeapSize:0,heapSizeLimit:0,utilizationPercent:0,gcCount:0}},n.createEmptyData=function(){return{currentFrame:{frameNumber:0,frameTime:0,fps:0,memory:this.getDefaultMemory()},frameTimeHistory:[],categoryStats:[],hotspots:[],callGraph:{currentFunction:null,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,currentMemoryMB:0,peakMemoryMB:0,gcCount:0,longTaskCount:0}}},t}();function nt(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){var t=Array.from(e,function(e){return e.toString(16).padStart(2,"0")}).join("");return t.slice(0,8)+"-"+t.slice(8,12)+"-"+t.slice(12,16)+"-"+t.slice(16,20)+"-"+t.slice(20)}(e)}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}()}var it=268435455,rt=1048575,ot=1<<28,st=1<<20;function at(e,t){return(t&rt)*ot+(e&it)}function ct(e){return e&it}function ut(e){return Math.floor(e/ot)&rt}function lt(e){return 0!==e}var ht=function(){function e(e,t,n){this._handle=0,this.scene=null,this._isDestroyed=!1,this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=q.clone(q.ZERO),this._componentCache=null,this._lifecyclePolicy=0,this.name=e,this.id=t,this.persistentId=null!=n?n:nt()}var t=e.prototype;return t.setHandle=function(e){this._handle=e},t.setPersistent=function(){return this._lifecyclePolicy=1,this},t.setSceneLocal=function(){return this._lifecyclePolicy=0,this},t.setDestroyedState=function(e){this._isDestroyed=e},t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,i=this.scene.componentRegistry,r=i.getRegisteredCount(),o=0;o<r;o++)if(q.getBit(n,o)){var s=i.getTypeByBitIndex(o);if(s){var a=this.scene.componentStorageManager.getComponent(this.id,s);a&&t.push(a)}}this._componentCache=t}else this._componentCache=t},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];var o=r(e,n);return this.addComponent(o)},t.addComponentInternal=function(e){var t,n,i=e.constructor,r=(null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:$).getBitMask(i);return q.orInPlace(this._componentMask,r),this._componentCache=null,e},t.notifyQuerySystems=function(e){var t,n,i;null!==(t=this.scene)&&void 0!==t&&t.querySystem&&(this.scene.querySystem.updateEntity(this),this.scene.clearSystemEntityCaches(),null===(n=(i=this.scene).notifyEntityComponentChanged)||void 0===n||n.call(i,this,e))},t.addComponent=function(e){var t,n,i=e.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+H(i));(this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,null===(t=this.scene.referenceTracker)||void 0===t||t.registerEntityScene(this.id,this.scene),this.scene.isEditorMode?this.scene.queueDeferredComponentCallback(function(){return e.onAddedToEntity()}):e.onAddedToEntity(),this.scene.eventSystem)&&this.scene.eventSystem.emitSync("component:added",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:H(i),component:e});return this.notifyQuerySystems(i),e},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:$;if(!i.isRegistered(e))return!1;var r=i.getBitMask(e);return q.hasAny(this._componentMask,r)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];t=this.createComponent.apply(this,[e].concat(i))}return t},t.markDirty=function(){if(this.scene){for(var e=this.scene.epochManager.current,t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0,o=n;r<o.length;r++){o[r].markDirty(e)}}},t.removeComponent=function(e){var t,n,i,r,o,s,a=e.constructor,c=null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:$;if(c.isRegistered(a)){var u,l=c.getBitIndex(a);if(q.clearBit(this._componentMask,l),this._componentCache=null,null===(i=this.scene)||void 0===i||null===(i=i.componentStorageManager)||void 0===i||i.removeComponent(this.id,a),null===(r=this.scene)||void 0===r||null===(r=r.referenceTracker)||void 0===r||r.clearComponentReferences(e),null===(o=e.onRemovedFromEntity)||void 0===o||o.call(e),e.entityId=null,null!==(s=this.scene)&&void 0!==s&&s.eventSystem)this.scene.eventSystem.emitSync("component:removed",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(u=this.tag)||void 0===u?void 0:u.toString(),componentType:H(a),component:e});this.notifyQuerySystems(a)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var e=[].concat(this.components);q.clear(this._componentMask),this._componentCache=null;for(var t,n=a(e);!(t=n()).done;){var i,r=t.value,o=r.constructor;null===(i=this.scene)||void 0===i||null===(i=i.componentStorageManager)||void 0===i||i.removeComponent(this.id,o),r.onRemovedFromEntity()}this.notifyQuerySystems()},t.addComponents=function(t){for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;try{i.push(this.addComponent(o))}catch(t){e._logger.warn("添加组件失败 "+W(o)+":",t)}}return i},t.removeComponentsByTypes=function(e){for(var t,n=[],i=a(e);!(t=i()).done;){var r=t.value;n.push(this.removeComponentByType(r))}return n},t.getComponents=function(e){for(var t,n=[],i=a(this.components);!(t=i()).done;){var r=t.value;r instanceof e&&n.push(r)}return n},t.getComponentByType=function(e){for(var t,n=a(this.components);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.onActiveChanged=function(){for(var e,t=a(this.components);!(e=t()).done;){var n=e.value;"onActiveChanged"in n&&"function"==typeof n.onActiveChanged&&n.onActiveChanged()}this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active})},t.destroy=function(){this._isDestroyed||(this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id)),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this)))},t.compareTo=function(e){return n=e,(t=this).updateOrder-n.updateOrder||t.id-n.id;var t,n},t.toString=function(){return"Entity["+this.name+":"+this.id+":"+this.persistentId.slice(0,8)+"]"},t.getDebugInfo=function(){return{name:this.name,id:this.id,persistentId:this.persistentId,enabled:this._enabled,active:this._active,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map(function(e){return W(e)}),componentMask:q.toString(this._componentMask,2),cacheBuilt:null!==this._componentCache}},s(e,[{key:"lifecyclePolicy",get:function(){return this._lifecyclePolicy}},{key:"isPersistent",get:function(){return 1===this._lifecyclePolicy}},{key:"handle",get:function(){return this._handle}},{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();ht._logger=Z("Entity");var dt=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();for(var n,i=a(this._entitiesToAdd);!(n=i()).done;){var r=n.value;e.push(r.id),r.destroy()}if(this._scene&&this._scene.identifierPool)for(var o,s=a(e);!(o=s()).done;){var c=o.value;this._scene.identifierPool.checkIn(c)}this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0},t.updateLists=function(){if(this._entitiesToAdd.length>0){for(var e,t=a(this._entitiesToAdd);!(e=t()).done;){var n=e.value;this.addImmediate(n)}this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(var i,r=a(this._entitiesToRemove);!(i=r()).done;){var o=i.value;this.removeImmediate(o)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],i=a(this.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],i=a(this.buffer);!(t=i()).done;){var r=t.value;r.hasComponent(e)&&n.push(r)}return n},t.forEach=function(e){for(var t,n=a(this.buffer);!(t=n()).done;){e(t.value)}},t.forEachWhere=function(e,t){for(var n,i=a(this.buffer);!(n=i()).done;){var r=n.value;e(r)&&t(r)}},t.updateNameIndex=function(e,t){if(e.name)if(t){var n=this._nameToEntities.get(e.name);n||(n=[],this._nameToEntities.set(e.name,n)),n.push(e)}else{var i=this._nameToEntities.get(e.name);if(i){var r=i.indexOf(e);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(e.name))}}},t.reorderEntity=function(e,t){var n=this._idToEntity.get(e);if(n){var i=this.buffer.indexOf(n);if(-1!==i&&i!==t){var r=Math.max(0,Math.min(t,this.buffer.length-1));this.buffer.splice(i,1),this.buffer.splice(r,0,n)}}},t.getStats=function(){for(var e,t=0,n=a(this.buffer);!(e=n()).done;){var i=e.value;i.enabled&&!i.isDestroyed&&t++}return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(e,[{key:"count",get:function(){return this.buffer.length}}])}(),ft=function(){function e(e,t){void 0===e&&(e=100),void 0===t&&(t=1024),this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}var t=e.prototype;return t.checkOut=function(){var t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>e.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+e.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}var n=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,n)},t.checkIn=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return!!this._isValidId(t,n)&&(!this._pendingRecycle.some(function(e){return e.index===t&&e.generation===n})&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},t.isValid=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)},t.getStats=function(){for(var t,n=0,i=0,r=a(this._generations);!(t=r()).done;){var o=t.value,s=o[0],c=o[1];s<this._nextAvailableIndex&&(n+=c,i++)}var u=i>0?n/i:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:e.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},t.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},t._processDelayedRecycle=function(t){if(void 0===t&&(t=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],o=[],s=a(this._pendingRecycle);!(n=s()).done;){var c=n.value;t||i-c.timestamp>=this._recycleDelay?r.push(c):o.push(c)}for(var u=0,l=r;u<l.length;u++){var h=l[u];if(this._isValidId(h.index,h.generation)){var d=h.generation+1;d>e.MAX_GENERATION&&(d=1),this._generations.set(h.index,d),this._freeIndices.push(h.index)}}this._pendingRecycle=o}},t._preAllocateGenerations=function(t,n){for(var i=0;i<n;i++){var r=t+i;r<=e.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},t._ensureGenerationCapacity=function(e){if(!this._generations.has(e)){var t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}},t._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},t._packId=function(e,t){return t<<16|e},t._unpackIndex=function(e){return 65535&e},t._unpackGeneration=function(e){return e>>>16&65535},t._isValidId=function(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;var n=this._generations.get(e);return void 0!==n&&n===t},e}();ft.MAX_INDEX=65535,ft.MAX_GENERATION=65535;var pt=function(){function e(){this._processors=[],this._isDirty=!1}var t=e.prototype;return t.setDirty=function(){this._isDirty=!0},t.add=function(e){this._processors.push(e),this.setDirty()},t.remove=function(e){var t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)},t.getProcessor=function(e){for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;try{i.reset()}catch(t){e._logger.error("Error in processor "+oe(i)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;try{i.update()}catch(t){e._logger.error("Error in processor "+oe(i)+":",t)}}},t.lateUpdate=function(){for(var e,t=a(this._processors);!(e=t()).done;){e.value.lateUpdate()}},t.sortProcessors=function(){this._isDirty&&(this._processors.sort(function(e,t){return e.updateOrder-t.updateOrder}),this._isDirty=!1)},s(e,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();pt._logger=Z("EntityProcessorList");var mt=function(){function e(e){if(e&&"object"==typeof e)this._value=q.clone(e);else if("number"==typeof e)this._value=q.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=q.fromNumber(t)}else this._value=q.clone(q.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");q.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");q.clearBit(this._value,e)},t.get=function(e){return q.getBit(this._value,e)},t.containsAll=function(e){return q.hasAll(this._value,e._value)},t.intersects=function(e){return q.hasAny(this._value,e._value)},t.excludes=function(e){return q.hasNone(this._value,e._value)},t.clearAll=function(){q.clear(this._value)},t.isEmpty=function(){return q.isZero(this._value)},t.cardinality=function(){return q.popCount(this._value)},t.and=function(t){var n=new e;return q.copy(this._value,n._value),q.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return q.copy(this._value,n._value),q.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return q.copy(this._value,n._value),q.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(q.copy(this._value,n._value),t<=32){var i=(1<<t)-1;n._value.base[R.LOW]=~n._value.base[R.LOW]&i,n._value.base[R.HIGH]=0}else if(n._value.base[R.LOW]=~n._value.base[R.LOW],t<64){var r=(1<<t-32)-1;n._value.base[R.HIGH]=~n._value.base[R.HIGH]&r}else n._value.base[R.HIGH]=~n._value.base[R.HIGH];return n},t.copyFrom=function(e){q.copy(e._value,this._value)},t.clone=function(){return new e(this._value)},t.getValue=function(){return this._value},t.setValue=function(e){if("object"==typeof e)q.copy(e,this._value);else if("number"==typeof e)this._value=q.fromNumber(e);else{var t=parseInt(e,10);this._value=q.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return q.toString(this._value,16)},e.fromBinaryString=function(t){var n,i=t.replace(/\s/g,"");if(i.length<=32){n={base:[parseInt(i,2)>>>0,0]}}else{var r=i.substring(i.length-32),o=i.substring(0,i.length-32);n={base:[parseInt(r,2)>>>0,parseInt(o,2)>>>0]}}return new e(n)},e.fromHexString=function(t){var n,i=t.replace(/^0x/i,"");if(i.length<=8){n={base:[parseInt(i,16)>>>0,0]}}else{var r=i.substring(i.length-8),o=i.substring(0,i.length-8);n={base:[parseInt(r,16)>>>0,parseInt(o,16)>>>0]}}return new e(n)},t.equals=function(e){return q.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(q.isZero(this._value))return-1;if(0!==this._value.base[R.HIGH])for(var e=31;e>=0;e--)if(this._value.base[R.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[R.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(q.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[R.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[R.HIGH]&1<<t)return t+32;return-1},e}(),vt=function(){function e(){this._dense=[],this._sparse=new Map}var t=e.prototype;return t.add=function(e){if(this._sparse.has(e))return!1;var t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0},t.remove=function(e){var t=this._sparse.get(e);if(void 0===t)return!1;var n=this._dense.length-1;if(t!==n){var i=this._dense[n];this._dense[t]=i,this._sparse.set(i,t)}return this._dense.pop(),this._sparse.delete(e),!0},t.has=function(e){return this._sparse.has(e)},t.getIndex=function(e){return this._sparse.get(e)},t.getByIndex=function(e){return this._dense[e]},t.forEach=function(e){for(var t=0;t<this._dense.length;t++)e(this._dense[t],t)},t.map=function(e){for(var t=[],n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t},t.filter=function(e){for(var t=[],n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t},t.find=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]},t.some=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1},t.every=function(e){for(var t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0},t.getDenseArray=function(){return[].concat(this._dense)},t.getDenseArrayUnsafe=function(){return this._dense},t.clear=function(){this._dense.length=0,this._sparse.clear()},t.toArray=function(){return[].concat(this._dense)},t.toSet=function(){return new Set(this._dense)},t.getMemoryStats=function(){var e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}},t.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var e=0;e<this._dense.length;e++){var t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(var n,i=a(this._sparse);!(n=i()).done;){var r=n.value,o=r[0],s=r[1];if(s>=this._dense.length||this._dense[s]!==o)return!1}return!0},s(e,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),gt=function(e){function t(){return e.call(this)||this}return l(t,e),t.prototype.reset=function(){this.clear()},t}(v(Set)),yt=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new vt}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=q.clone(q.ZERO),i=new Set,r=a(e.components);!(t=r()).done;){var o=t.value.constructor;i.add(o);var s=$.getBitMask(o);q.orInPlace(n,s)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(q.clone(q.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,i,!0)},t.removeEntity=function(e){var t=this._entities.getIndex(e);if(void 0!==t){var n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);var i=this._componentMasks.length-1;t!==i&&(this._componentMasks[t]=this._componentMasks[i]),this._componentMasks.pop()}},t.queryByComponent=function(e){var t=this._componentToEntities.get(e);return t?new Set(t):new Set},t.queryMultipleAnd=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=q.clone(q.ZERO),o=a(t);!(i=o()).done;){var s=i.value;if(!$.isRegistered(s))return new Set;var c=$.getBitMask(s);q.orInPlace(r,c)}var u=e._entitySetPool.obtain();return this._entities.forEach(function(e,t){var i=n._componentMasks[t];q.hasAll(i,r)&&u.add(e)}),u},t.queryMultipleOr=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=q.clone(q.ZERO),o=a(t);!(i=o()).done;){var s=i.value;if($.isRegistered(s)){var c=$.getBitMask(s);q.orInPlace(r,c)}}if(q.equals(r,q.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach(function(e,t){var i=n._componentMasks[t];q.hasAny(i,r)&&u.add(e)}),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!$.isRegistered(t))return!1;var i=this._componentMasks[n],r=$.getBitMask(t);return q.hasAny(i,r)},t.getEntityMask=function(e){var t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]},t.getAllEntities=function(){return this._entities.toArray()},t.forEach=function(e){var t=this;this._entities.forEach(function(n,i){e(n,t._componentMasks[i],i)})},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=a(this._componentToEntities.values());!(t=n()).done;){var i=t.value;e._entitySetPool.release(i)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=a(this._componentToEntities.values());!(e=r()).done;){i+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:t.totalMemory+n+i}},t.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var e,t=new Set,n=a(this._componentToEntities.values());!(e=n()).done;)for(var i,r=a(e.value);!(i=r()).done;){var o=i.value;t.add(o)}for(var s,c=a(t);!(s=c()).done;){var u=s.value;if(!this._entities.has(u))return!1}return!0},t.getEntityComponentTypes=function(e){for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value;n.add(r.constructor)}return n},t.updateComponentMappings=function(t,n,i){for(var r,o=a(n);!(r=o()).done;){var s=r.value,c=this._componentToEntities.get(s);i?(c||(c=e._entitySetPool.obtain(),this._componentToEntities.set(s,c)),c.add(t)):c&&(c.delete(t),0===c.size&&(this._componentToEntities.delete(s),e._entitySetPool.release(c)))}},s(e,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();yt._entitySetPool=x.getPool(gt,50,512);var _t,St=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,i=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(i(e.base[0]>>>0),i(e.base[1]>>>0),e.segments)for(var r,o=a(e.segments);!(r=o()).done;){var s=r.value;i(s[0]>>>0),i(s[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),i=n[0],r=n[1],o=this.buckets.get(i);o||(o=[],this.buckets.set(i,o));for(var s=0;s<o.length;s++)if(o[s][0]===r)return o[s][1]=t,this;return o.push([r,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(r)for(var o=0;o<r.length;o++)if(r[o][0]===i)return r[o][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(!r)return!1;for(var o=0;o<r.length;o++)if(r[o][0]===i)return r.splice(o,1),this._size--,0===r.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=d().m(function e(){var t,n,i,r,o,s,c,u;return d().w(function(e){for(;;)switch(e.n){case 0:t=a(this.buckets);case 1:if((n=t()).done){e.n=5;break}(i=n.value)[0],r=i[1],o=a(r);case 2:if((s=o()).done){e.n=4;break}return(c=s.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}},e,this)}),t.values=d().m(function e(){var t,n,i,r,o,s,c;return d().w(function(e){for(;;)switch(e.n){case 0:t=a(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}i=n.value,r=a(i);case 2:if((o=r()).done){e.n=4;break}return(s=o.value)[0],c=s[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}},e,this)}),s(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),Ct=function(){function e(){this._archetypes=new St,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),i=this._archetypes.get(n);i||(i=this.createArchetype(t)),i.entities.add(e),this._entityToArchetype.set(e,i)},t.removeEntity=function(e){var t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))},t.updateEntity=function(e){var t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);var n=this.getEntityComponentTypes(e),i=this.generateArchetypeId(n);if(!t||t.id!==i){t&&t.entities.delete(e);var r=this._archetypes.get(i);r||(r=this.createArchetype(n)),r.entities.add(e),this._entityToArchetype.set(e,r)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],i=0;if("AND"===t){if(0===e.length){for(var r,o=a(this._allArchetypes);!(r=o()).done;){var s=r.value;n.push(s),i+=s.entities.size}return{archetypes:n,totalEntities:i}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,l=a(c);!(u=l()).done;){var h=u.value;n.push(h),i+=h.entities.size}return{archetypes:n,totalEntities:i}}for(var d,f,p=1/0,m=a(e);!(f=m()).done;){var v=f.value,g=this._componentToArchetypes.get(v);if(!g||0===g.size)return{archetypes:[],totalEntities:0};g.size<p&&(p=g.size,d=g)}var y=this.generateArchetypeId(e);if(d)for(var _,S=a(d);!(_=S()).done;){var C=_.value;q.hasAll(C.id,y)&&(n.push(C),i+=C.entities.size)}}else{for(var E,b=new Set,T=a(e);!(E=T()).done;){var w=E.value,I=this._componentToArchetypes.get(w);if(I)for(var M,A=a(I);!(M=A()).done;){var k=M.value;b.add(k)}}for(var D,P=a(b);!(D=P()).done;){var O=D.value;n.push(O),i+=O.entities.size}}return{archetypes:n,totalEntities:i}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,i=[],r=a(t);!(n=r()).done;)for(var o,s=a(n.value.entities);!(o=s()).done;){var c=o.value;i.push(c)}return i},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=a(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map(function(e){return e.constructor}),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){for(var t,n=q.clone(q.ZERO),i=a(e);!(t=i()).done;){var r=t.value,o=$.getBitMask(r);q.orInPlace(n,o)}return n},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var i,r=a(e);!(i=r()).done;){var o=i.value,s=this._componentToArchetypes.get(o);s||(s=new Set,this._componentToArchetypes.set(o,s)),s.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(_t||(_t={}));var Et,bt=Z("ReactiveQuery");e.ReactiveQueryChangeType=void 0,(Et=e.ReactiveQueryChangeType||(e.ReactiveQueryChangeType={})).ADDED="added",Et.REMOVED="removed",Et.BATCH_UPDATE="batch_update";var Tt=function(){function t(e,t){var n,i,r;void 0===t&&(t={}),this._entities=[],this._entityIdSet=new Set,this._snapshot=null,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:null===(n=t.enableBatchMode)||void 0===n||n,batchDelay:null!==(i=t.batchDelay)&&void 0!==i?i:16,debug:null!==(r=t.debug)&&void 0!==r&&r},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&bt.debug("创建ReactiveQuery: "+this._id)}var n=t.prototype;return n.generateQueryId=function(){return this._condition.type+":"+this._condition.componentTypes.map(function(e){return e.name}).sort().join(",")},n.subscribe=function(e){var t=this;if(!this._active)throw new Error("Cannot subscribe to disposed ReactiveQuery "+this._id);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&bt.debug("订阅ReactiveQuery: "+this._id+", 监听器数量: "+this._listeners.length),function(){var n=t._listeners.indexOf(e);-1!==n&&t._listeners.splice(n,1)}},n.unsubscribeAll=function(){this._listeners.length=0},n.getEntities=function(){return null!==this._snapshot||(this._snapshot=[].concat(this._entities)),this._snapshot},n.matches=function(e){var t=e.componentMask;switch(this._condition.type){case _t.ALL:return q.hasAll(t,this._condition.mask);case _t.ANY:return q.hasAny(t,this._condition.mask);case _t.NONE:return q.hasNone(t,this._condition.mask);default:return!1}},n.notifyEntityAdded=function(t){this._active&&this.matches(t)&&(this._entityIdSet.has(t.id)||(this._entities.push(t),this._entityIdSet.add(t.id),this._snapshot=null,this._config.enableBatchMode?this.addToBatch("added",t):this.notifyListeners({type:e.ReactiveQueryChangeType.ADDED,entity:t}),this._config.debug&&bt.debug("ReactiveQuery "+this._id+": 实体添加 "+t.name+"("+t.id+")")))},n.notifyEntityRemoved=function(t){if(this._active&&this._entityIdSet.has(t.id)){var n=this._entities.indexOf(t);-1!==n&&this._entities.splice(n,1),this._entityIdSet.delete(t.id),this._snapshot=null,this._config.enableBatchMode?this.addToBatch("removed",t):this.notifyListeners({type:e.ReactiveQueryChangeType.REMOVED,entity:t}),this._config.debug&&bt.debug("ReactiveQuery "+this._id+": 实体移除 "+t.name+"("+t.id+")")}},n.notifyEntityChanged=function(e){if(this._active){var t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}},n.initializeWith=function(e){this._entities.length=0,this._entityIdSet.clear(),this._snapshot=null;for(var t,n=a(e);!(t=n()).done;){var i=t.value;this.matches(i)&&(this._entities.push(i),this._entityIdSet.add(i.id))}this._config.debug&&bt.debug("ReactiveQuery "+this._id+": 初始化 "+this._entities.length+" 个实体")},n.addToBatch=function(e,t){var n=this;"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout(function(){n.flushBatchChanges()},this._config.batchDelay))},n.flushBatchChanges=function(){if(0!==this._batchChanges.added.length||0!==this._batchChanges.removed.length){var t=[].concat(this._batchChanges.added),n=[].concat(this._batchChanges.removed);this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:e.ReactiveQueryChangeType.BATCH_UPDATE,added:t,removed:n,entities:this._entities}),this._config.debug&&bt.debug("ReactiveQuery "+this._id+": 批量更新 +"+t.length+" -"+n.length)}else this._batchChanges.timer=null},n.notifyListeners=function(e){for(var t,n=a([].concat(this._listeners));!(t=n()).done;){var i=t.value;try{i(e)}catch(e){bt.error("ReactiveQuery "+this._id+": 监听器执行出错",e)}}},n.pause=function(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0},n.resume=function(){this._active=!0},n.dispose=function(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._snapshot=null,this._config.debug&&bt.debug("ReactiveQuery "+this._id+": 已销毁")},s(t,[{key:"count",get:function(){return this._entities.length}},{key:"condition",get:function(){return this._condition}},{key:"id",get:function(){return this._id}},{key:"active",get:function(){return this._active}},{key:"listenerCount",get:function(){return this._listeners.length}}])}(),wt=function(){function e(e){this._lastVersion=-1,this._cachedEntities=[],this._querySystem=e;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this._componentTypes=n}var t=e.prototype;return t._refreshCache=function(){var e=this._querySystem.version;if(this._lastVersion!==e){var t,n=(t=this._querySystem).queryAll.apply(t,this._componentTypes);this._cachedEntities=n.entities,this._lastVersion=e}},t.forEach=function(e){for(var t=this.entities,n=this._componentTypes,i=n.length,r=0,o=t.length;r<o;r++){for(var s=t[r],a=new Array(i),c=0;c<i;c++){var u=s.getComponent(n[c]);u&&(a[c]=u)}e.apply(void 0,[s].concat(a))}},t.forEachChanged=function(e,t){for(var n=this.entities,i=this._componentTypes,r=i.length,o=0,s=n.length;o<s;o++){for(var a=n[o],c=new Array(r),u=!1,l=0;l<r;l++){var h=a.getComponent(i[l]);h&&(c[l]=h,h.lastWriteEpoch>e&&(u=!0))}u&&t.apply(void 0,[a].concat(c))}},t.first=function(){var e=this.entities;if(0===e.length)return null;for(var t,n=e[0],i=[],r=a(this._componentTypes);!(t=r()).done;){var o=t.value,s=n.getComponent(o);if(!s)return null;i.push(s)}return[n].concat(i)},t.toArray=function(){var e=[];return this.forEach(function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];e.push([t].concat(i))}),e},t.map=function(e){var t=[];return this.forEach(function(n){for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];t.push(e.apply(void 0,[n].concat(r)))}),t},t.filter=function(e){var t=[];return this.forEach(function(n){for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];e.apply(void 0,[n].concat(r))&&t.push(n)}),t},t.find=function(e){for(var t=this.entities,n=this._componentTypes,i=n.length,r=0,o=t.length;r<o;r++){for(var s=t[r],a=new Array(i),c=0;c<i;c++){var u=s.getComponent(n[c]);u&&(a[c]=u)}if(e.apply(void 0,[s].concat(a)))return s}},t.any=function(){return this.count>0},t.empty=function(){return 0===this.count},s(e,[{key:"componentTypes",get:function(){return this._componentTypes}},{key:"entities",get:function(){return this._refreshCache(),this._cachedEntities}},{key:"count",get:function(){return this.entities.length}}])}(),It=function(){function e(){this._logger=Z("QuerySystem"),this._entities=[],this._version=0,this._queryCache=new Map,this._cacheMaxSize=1e3,this._cacheTimeout=5e3,this._componentMaskCache=new Map,this._queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this._entityIndex={byTag:new Map,byName:new Map},this._archetypeSystem=new Ct}var t=e.prototype;return t.setEntities=function(e){this._entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this._entities.includes(e)||(this._entities.push(e),this.addEntityToIndexes(e),this._archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)},t.addEntities=function(e){if(0!==e.length){for(var t,n=new Set(this._entities.map(function(e){return e.id})),i=0,r=a(e);!(t=r()).done;){var o=t.value;n.has(o.id)||(this._entities.push(o),this.addEntityToIndexes(o),this._archetypeSystem.addEntity(o),n.add(o.id),i++)}i>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=a(e);!(t=n()).done;){var i=t.value;this._entities.push(i)}for(var r,o=a(e);!(r=o()).done;){var s=r.value;this.addEntityToIndexes(s),this._archetypeSystem.addEntity(s)}this.clearQueryCache()}},t.removeEntity=function(e){var t=this._entities.indexOf(e);if(-1!==t){for(var n,i=[],r=a(e.components);!(n=r()).done;){var o=n.value;i.push(o.constructor)}this._entities.splice(t,1),this.removeEntityFromIndexes(e),this._archetypeSystem.removeEntity(e),i.length>0?this.notifyReactiveQueriesEntityRemoved(e,i):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}},t.updateEntity=function(e){this._entities.includes(e)?(this.removeEntityFromIndexes(e),this._archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this._entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this._entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this._entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this._entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this._entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this._entityIndex.byTag.delete(e.tag))}if(e.name){var n=this._entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this._entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this._entityIndex.byTag.clear(),this._entityIndex.byName.clear(),this._archetypeSystem.clear();for(var e,t=a(this._entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this._archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(_t.ALL,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryAny=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(_t.ANY,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryNone=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(_t.NONE,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryByTag=function(e){var t=performance.now();this._queryStats.totalQueries++;var n="tag:"+e,i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=Array.from(this._entityIndex.byTag.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this._queryStats.totalQueries++;var n="name:"+e,i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=Array.from(this._entityIndex.byName.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryChangedSince=function(e){var t=performance.now();this._queryStats.totalQueries++,this._queryStats.dirtyChecks++;for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var o,s=[],c=a(this.queryAll.apply(this,i).entities);!(o=c()).done;){for(var u,l=o.value,h=!1,d=a(i);!(u=d()).done;){var f=u.value,p=l.getComponent(f);if(p&&p.lastWriteEpoch>e){h=!0;break}}h&&s.push(l)}return{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this._queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=this._archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.getFromCache=function(e){var t=this._queryCache.get(e);return t?Date.now()-t.timestamp>this._cacheTimeout||t.version!==this._version?(this._queryCache.delete(e),null):(t.hitCount++,t.entities):null},t.addToCache=function(e,t){this._queryCache.size>=this._cacheMaxSize&&this.cleanupCache(),this._queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})},t.cleanupCache=function(){for(var e,t=Date.now(),n=a(this._queryCache.entries());!(e=n()).done;){var i=e.value,r=i[0];t-i[1].timestamp>this._cacheTimeout&&this._queryCache.delete(r)}if(this._queryCache.size>=this._cacheMaxSize){for(var o,s=1/0,c="",u=1/0,l=a(this._queryCache.entries());!(o=l()).done;){var h=o.value,d=h[0],f=h[1];(f.hitCount<s||f.hitCount===s&&f.timestamp<u)&&(s=f.hitCount,c=d,u=f.timestamp)}c&&this._queryCache.delete(c)}},t.clearQueryCache=function(){this._queryCache.clear(),this._componentMaskCache.clear()},t.clearReactiveQueries=function(){for(var e,t=a(this._reactiveQueries.values());!(e=t()).done;){e.value.dispose()}this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+H(t[0]):e+":"+t.map(function(e){return H(e)}).sort().join(",")},t.clearCache=function(){this.clearQueryCache(),this.clearReactiveQueries()},t.compile=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r(wt,[this].concat(t))},t.createReactiveQuery=function(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");var n=this.createComponentMask(e),i={type:_t.ALL,componentTypes:e,mask:n},r=new Tt(i,t),o=this.executeTraditionalQuery(_t.ALL,e);r.initializeWith(o);var s=this.generateCacheKey("all",e);this._reactiveQueries.set(s,r);for(var c,u=a(e);!(c=u()).done;){var l=c.value,h=this._reactiveQueriesByComponent.get(l);h||(h=new Set,this._reactiveQueriesByComponent.set(l,h)),h.add(r)}return r},t.destroyReactiveQuery=function(e){if(e){var t=e.id;this._reactiveQueries.delete(t);for(var n,i=a(e.condition.componentTypes);!(n=i()).done;){var r=n.value,o=this._reactiveQueriesByComponent.get(r);o&&(o.delete(e),0===o.size&&this._reactiveQueriesByComponent.delete(r))}e.dispose()}},t.createComponentMask=function(e){var t=e.map(function(e){return H(e)}).sort().join(","),n=this._componentMaskCache.get(t);if(n)return n;for(var i,r=q.clone(q.ZERO),o=a(e);!(i=o()).done;){var s=i.value,c=$.getBitMask(s);q.orInPlace(r,c)}return this._componentMaskCache.set(t,r),r},t.getAllEntities=function(){return this._entities},t.getStats=function(){return{entityCount:this._entities.length,indexStats:{componentIndexSize:this._archetypeSystem.getAllArchetypes().length,tagIndexSize:this._entityIndex.byTag.size,nameIndexSize:this._entityIndex.byName.size},queryStats:c({},this._queryStats,{cacheHitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this._archetypeSystem.getAllArchetypes().map(function(e){return{id:e.id,componentTypes:e.componentTypes.map(function(e){return H(e)}),entityCount:e.entities.size}})},cacheStats:{size:this._reactiveQueries.size,hitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},t.getEntityArchetype=function(e){return this._archetypeSystem.getEntityArchetype(e)},t.getOrCreateReactiveQuery=function(e,t){var n=this.generateCacheKey(e,t),i=this._reactiveQueries.get(n);if(!i){var r=this.createComponentMask(t);i=new Tt({type:e,componentTypes:t,mask:r},{enableBatchMode:!1,debug:!1});var o=this.executeTraditionalQuery(e,t);i.initializeWith(o),this._reactiveQueries.set(n,i);for(var s,c=a(t);!(s=c()).done;){var u=s.value,l=this._reactiveQueriesByComponent.get(u);l||(l=new Set,this._reactiveQueriesByComponent.set(u,l)),l.add(i)}this._logger.debug("创建内部响应式查询缓存: "+n)}return i},t.executeTraditionalQuery=function(e,t){switch(e){case _t.ALL:for(var n,i=[],r=a(this._archetypeSystem.queryArchetypes(t,"AND").archetypes);!(n=r()).done;)for(var o,s=a(n.value.entities);!(o=s()).done;){var c=o.value;i.push(c)}return i;case _t.ANY:for(var u,l=[],h=a(this._archetypeSystem.queryArchetypes(t,"OR").archetypes);!(u=h()).done;)for(var d,f=a(u.value.entities);!(d=f()).done;){var p=d.value;l.push(p)}return l;case _t.NONE:var m=this.createComponentMask(t);return this._entities.filter(function(e){return q.hasNone(e.componentMask,m)});default:return[]}},t.notifyReactiveQueriesEntityAdded=function(e){if(0!==this._reactiveQueries.size)for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value.constructor,o=this._reactiveQueriesByComponent.get(r);if(o)for(var s,c=a(o);!(s=c()).done;){var u=s.value;n.has(u)||(u.notifyEntityAdded(e),n.add(u))}}},t.notifyReactiveQueriesEntityRemoved=function(e,t){if(0!==this._reactiveQueries.size)for(var n,i=new Set,r=a(t);!(n=r()).done;){var o=n.value,s=this._reactiveQueriesByComponent.get(o);if(s)for(var c,u=a(s);!(c=u()).done;){var l=c.value;i.has(l)||(l.notifyEntityRemoved(e),i.add(l))}}},t.notifyReactiveQueriesEntityRemovedFallback=function(e){if(0!==this._reactiveQueries.size)for(var t,n=a(this._reactiveQueries.values());!(t=n()).done;){t.value.notifyEntityRemoved(e)}},t.notifyReactiveQueriesEntityChanged=function(e){if(0!==this._reactiveQueries.size){for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value.constructor,o=this._reactiveQueriesByComponent.get(r);if(o)for(var s,c=a(o);!(s=c()).done;){var u=s.value;n.has(u)||(u.notifyEntityChanged(e),n.add(u))}}for(var l,h=a(this._reactiveQueries.values());!(l=h()).done;){var d=l.value;n.has(d)||d.notifyEntityChanged(e)}}},s(e,[{key:"version",get:function(){return this._version}}])}(),Mt=function(){function e(e){this._logger=Z("QueryBuilder"),this.conditions=[],this.querySystem=e}var t=e.prototype;return t.withAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:_t.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this},t.withAny=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:_t.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this},t.without=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:_t.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case _t.ALL:return(e=this.querySystem).queryAll.apply(e,r.componentTypes);case _t.ANY:return(t=this.querySystem).queryAny.apply(t,r.componentTypes);case _t.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=q.clone(q.ZERO),i=a(e);!(t=i()).done;){var r=t.value;try{var o=$.getBitMask(r);q.orInPlace(n,o)}catch(e){this._logger.warn("组件类型 "+H(r)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),At=function(){function e(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}var t=e.prototype;return t.on=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,n)},t.once=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,c({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,c({},n,{async:!0}))},t.off=function(e,t){var n=this.listeners.get(e);if(!n)return!1;var i=n.findIndex(function(e){return e.id===t});return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)},t.offAll=function(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)},t.emit=function(){var e=i(d().m(function e(t,n){var i;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.isEnabled){e.n=1;break}return e.a(2);case 1:if(null==(i=this.batchConfigs.get(t))||!i.enabled){e.n=2;break}return this.addToBatch(t,n),e.a(2);case 2:return e.n=3,this.executeEvent(t,n);case 3:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.emitSync=function(t,n){if(this.isEnabled){var i=this.listeners.get(t);if(i&&0!==i.length){for(var r,o=performance.now(),s=[],c=a(this.sortListenersByPriority(i));!(r=c()).done;){var u=r.value;if(!u.config.async)try{u.config.thisArg?u.handler.call(u.config.thisArg,n):u.handler(n),u.config.once&&s.push(u.id)}catch(n){e._logger.error("事件处理器执行错误 "+t+":",n)}}this.removeListeners(t,s),this.updateStats(t,performance.now()-o)}}},t.setBatchConfig=function(e,t){this.batchConfigs.set(e,t)},t.flushBatch=function(e){var t=this.batchQueue.get(e);if(t&&0!==t.length){var n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}},t.getStats=function(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)},t.resetStats=function(e){e?this.stats.delete(e):this.stats.clear()},t.setEnabled=function(e){this.isEnabled=e},t.hasListeners=function(e){var t=this.listeners.get(e);return!!t&&t.length>0},t.getListenerCount=function(e){var t=this.listeners.get(e);return t?t.length:0},t.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},t.setMaxListeners=function(e){this.maxListeners=e},t.addListener=function(t,n,i){var r=this.listeners.get(t);if(r||(r=[],this.listeners.set(t,r)),r.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var o="listener_"+this.nextListenerId++,s={handler:n,config:c({priority:0},i),id:o};return r.push(s),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),o},t.executeEvent=function(){var t=i(d().m(function t(n,r){var o,s,c,u,l,h,f,p,m,v;return d().w(function(t){for(;;)switch(t.n){case 0:if((o=this.listeners.get(n))&&0!==o.length){t.n=1;break}return t.a(2);case 1:for(s=performance.now(),c=[],u=this.sortListenersByPriority(o),l=u.filter(function(e){return!e.config.async}),h=u.filter(function(e){return e.config.async}),f=a(l);!(p=f()).done;){m=p.value;try{m.config.thisArg?m.handler.call(m.config.thisArg,r):m.handler(r),m.config.once&&c.push(m.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+n+":",t)}}return v=h.map(function(){var t=i(d().m(function t(i){var o;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!i.config.thisArg){t.n=2;break}return t.n=1,i.handler.call(i.config.thisArg,r);case 1:t.n=3;break;case 2:return t.n=3,i.handler(r);case 3:i.config.once&&c.push(i.id),t.n=5;break;case 4:t.p=4,o=t.v,e._logger.error("异步事件处理器执行错误 "+n+":",o);case 5:return t.a(2)}},t,null,[[0,4]])}));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(v);case 2:this.removeListeners(n,c),this.updateStats(n,performance.now()-s);case 3:return t.a(2)}},t,this)}));return function(e,n){return t.apply(this,arguments)}}(),t.sortListenersByPriority=function(e){return e.slice().sort(function(e,t){return(t.config.priority||0)-(e.config.priority||0)})},t.removeListeners=function(e,t){if(0!==t.length){var n=this.listeners.get(e);if(n){for(var i,r=function(){var e=i.value,t=n.findIndex(function(t){return t.id===e});-1!==t&&n.splice(t,1)},o=a(t);!(i=o()).done;)r();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,i=this.batchQueue.get(e);i||(i=[],this.batchQueue.set(e,i)),i.push(t);var r=this.batchConfigs.get(e);if(i.length>=r.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var o=setTimeout(function(){n.flushBatch(e)},r.delay);this.batchTimers.set(e,o)}},t.processBatch=function(){var e=i(d().m(function e(t,n){var i;return d().w(function(e){for(;;)switch(e.n){case 0:return i={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",i);case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.clearBatch=function(e){this.batchQueue.delete(e);var t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))},t.clearAllBatches=function(){this.batchQueue.clear();for(var e,t=a(this.batchTimers.values());!(e=t()).done;){var n=e.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},t.updateStats=function(e,t){var n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)},t.createEmptyStats=function(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},e}();At._logger=Z("EventSystem");var kt=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},s(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),Dt=function(){function e(e,t,n,i,r){this._all=e||[],this._any=t||[],this._none=n||[],void 0!==i&&(this._tag=i),void 0!==r&&(this._name=r)}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,i=Re.complex();this._all.length>0&&(i=(e=i).all.apply(e,this._all));this._any.length>0&&(i=(t=i).any.apply(t,this._any));this._none.length>0&&(i=(n=i).none.apply(n,this._none));return void 0!==this._tag&&(i=i.withTag(this._tag)),void 0!==this._name&&(i=i.withName(this._name)),i},t.getCondition=function(){return c({all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none)},void 0!==this._tag&&{tag:this._tag},void 0!==this._name&&{name:this._name})},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var Pt=new Map;function Ot(e,t){Pt.set(e,t)}Ot("Date",{check:function(e){return e instanceof Date},serialize:function(e){return{__type:"Date",value:e.toISOString()}},deserialize:function(e){return new Date(e.value)}}),Ot("Map",{check:function(e){return e instanceof Map},serialize:function(e,t){return{__type:"Map",value:[].concat(e).map(function(e){var n=e[0],i=e[1];return[t(n),t(i)]})}},deserialize:function(e){return new Map(e.value)}}),Ot("Set",{check:function(e){return e instanceof Set},serialize:function(e,t){return{__type:"Set",value:[].concat(e).map(t)}},deserialize:function(e){return new Set(e.value)}});var xt,Rt={serialize:function e(t,n){if(void 0===n&&(n=new WeakSet),null==t)return t;var i=typeof t;if("string"===i||"number"===i||"boolean"===i)return t;if("function"!==i){var r=t;if(!n.has(r)){n.add(r);for(var o,s=a(Pt);!(o=s()).done;){var c=o.value[1];if(c.check(t))return c.serialize(t,function(t){return e(t,n)})}if(Array.isArray(t))return t.map(function(t){return e(t,n)});for(var u={},l=0,h=Object.keys(t);l<h.length;l++){var d=h[l];u[d]=e(t[d],n)}return u}}},deserialize:function e(t){if(null==t)return t;var n=typeof t;if("string"===n||"number"===n||"boolean"===n)return t;if(function(e){if(null===e||"object"!=typeof e)return!1;return"__type"in e}(t)){var i=Pt.get(t.__type);return i?i.deserialize(t):t}if(Array.isArray(t))return t.map(e);for(var r={},o=0,s=Object.keys(t);o<s.length;o++){var a=s[o];r[a]=e(t[a])}return r},register:Ot},zt=Z("ComponentSerializer"),Nt=function(){function e(){}return e.serialize=function(e){var t=xe(e);if(!t)return null;for(var n,i=e.constructor,r=t.options.typeId||H(i),o={},s=a(t.fields);!(n=s()).done;){var c=n.value,u=c[0],l=c[1];if(!t.ignoredFields.has(u)){var h="symbol"==typeof u?u.toString():u,d=e[u],f=void 0;f=ve(e,h)?this.serializeEntityRef(d):l.serializer?l.serializer(d):Rt.serialize(d),o[l.alias||h]=f}}return{type:r,version:t.options.version,data:o}},e.deserialize=function(e,t,n){var i=t.get(e.type);if(!i)return zt.warn("Component type not found: "+e.type+" | 未找到组件类型: "+e.type),null;var r=xe(i);if(!r)return zt.warn("Component "+e.type+" is not serializable | 组件 "+e.type+" 不可序列化"),null;for(var o,s=new i,c=a(r.fields);!(o=c()).done;){var u=o.value,l=u[0],h=u[1],d="symbol"==typeof l?l.toString():l,f=h.alias||d,p=e.data[f];if(void 0!==p)if(this.isSerializedEntityRef(p)){if(n){var m=p.__entityRef;n.registerPendingRef(s,d,m.id,m.guid)}s[l]=null}else{var v=h.deserializer?h.deserializer(p):Rt.deserialize(p);s[l]=v}}return s},e.serializeComponents=function(e){var t=this;return e.map(function(e){return t.serialize(e)}).filter(function(e){return null!==e})},e.deserializeComponents=function(e,t,n){var i=this;return e.map(function(e){return i.deserialize(e,t,n)}).filter(function(e){return null!==e})},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=xe(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||H(n),version:t.options.version,fields:Array.from(t.fields.keys()).map(function(e){return"symbol"==typeof e?e.toString():e}),ignoredFields:Array.from(t.ignoredFields).map(function(e){return"symbol"==typeof e?e.toString():e}),isSerializable:!0}},e.serializeEntityRef=function(e){return e?{__entityRef:{id:e.id,guid:e.persistentId}}:null},e.isSerializedEntityRef=function(e){return"object"==typeof e&&null!==e&&"__entityRef"in e},e}(),Ft=function(){function t(){}return t.serialize=function(t,n,i){void 0===n&&(n=!0);var r=Nt.serializeComponents(Array.from(t.components)),o={id:t.id,guid:t.persistentId,name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,components:r,children:[]},s=t.getComponent(e.HierarchyComponent);if(null!==(null==s?void 0:s.parentId)&&void 0!==(null==s?void 0:s.parentId)&&(o.parentId=s.parentId),n&&s&&s.childIds.length>0){var c,u=null!==(c=null==i?void 0:i.scene)&&void 0!==c?c:t.scene;if(u)for(var l,h=a(s.childIds);!(l=h()).done;){var d=l.value,f=u.findEntityById(d);f&&o.children.push(this.serialize(f,!0,i))}}return o},t.deserialize=function(t,n,i,r,o,s,c,u){void 0===r&&(r=!1);var l=r?t.id:i(),h=new ht(t.name,l,t.guid);null==c||c.set(h.id,h),u&&u.registerEntity(h,t.id,t.guid),o&&(h.scene=o),h.tag=t.tag,h.active=t.active,h.enabled=t.enabled,h.updateOrder=t.updateOrder;for(var d,f=a(Nt.deserializeComponents(t.components,n,u));!(d=f()).done;){var p=d.value;h.addComponent(p)}var m=h.getComponent(e.HierarchyComponent);m&&(m.parentId=null,m.childIds=[]);for(var v,g=a(t.children);!(v=g()).done;){var y=v.value,_=this.deserialize(y,n,i,r,o,s,c,u);null==s||s.setParent(_,h)}return h},t.serializeEntities=function(t,n,i){void 0===n&&(n=!0);for(var r,o=[],s=a(t);!(r=s()).done;){var c=r.value,u=c.getComponent(e.HierarchyComponent);null!==(null==u?void 0:u.parentId)&&void 0!==(null==u?void 0:u.parentId)&&n||o.push(this.serialize(c,n,i))}return o},t.deserializeEntities=function(e,t,n,i,r,o,s){void 0===i&&(i=!1);for(var c,u=[],l=new Map,h=a(e);!(c=h()).done;){var d=c.value,f=this.deserialize(d,t,n,i,r,o,l,s);u.push(f)}return{rootEntities:u,allEntities:l}},t.clone=function(e,t,n){var i=this.serialize(e,!0);return this.deserialize(i,t,n,!1)},t}(),Bt=function(){function e(){}return e.stringToUtf8=function(e){for(var t=e.length,n=0,i=[],r=0;r<t;r++){var o=e.charCodeAt(r);if(o>=55296&&o<=56319&&r+1<t){var s=o,a=e.charCodeAt(r+1);a>=56320&&a<=57343&&(o=65536+(s-55296<<10)+(a-56320),r++)}o<128?i[n++]=o:o<2048?(i[n++]=192|o>>6,i[n++]=128|63&o):o<65536?(i[n++]=224|o>>12,i[n++]=128|o>>6&63,i[n++]=128|63&o):(i[n++]=240|o>>18,i[n++]=128|o>>12&63,i[n++]=128|o>>6&63,i[n++]=128|63&o)}return new Uint8Array(i)},e.utf8ToString=function(e){for(var t=e.length,n="",i=0;i<t;){var r=e[i++];if(void 0===r)break;if(r<128)n+=String.fromCharCode(r);else if(192==(224&r)){var o=e[i++];if(void 0===o)break;n+=String.fromCharCode((31&r)<<6|63&o)}else if(224==(240&r)){var s=e[i++],a=e[i++];if(void 0===s||void 0===a)break;n+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&a)}else if(240==(248&r)){var c=e[i++],u=e[i++],l=e[i++];if(void 0===c||void 0===u||void 0===l)break;var h=(7&r)<<18|(63&c)<<12|(63&u)<<6|63&l;h-=65536,n+=String.fromCharCode(55296+(h>>10),56320+(1023&h))}}return n},e.encode=function(e){var t=JSON.stringify(e);return this.stringToUtf8(t)},e.decode=function(e){var t=this.utf8ToString(e);return JSON.parse(t)},e}(),Lt=function(){function e(){this._idRemapping=new Map,this._guidLookup=new Map,this._pendingRefs=[],this._preserveIds=!1}var t=e.prototype;return t.setPreserveIds=function(e){this._preserveIds=e},t.registerEntity=function(e,t,n){var i=null!=n?n:e.persistentId;this._guidLookup.set(i,e),void 0!==t&&this._idRemapping.set(t,e)},t.getEntityById=function(e){var t;return null!==(t=this._idRemapping.get(e))&&void 0!==t?t:null},t.getEntityByGuid=function(e){var t;return null!==(t=this._guidLookup.get(e))&&void 0!==t?t:null},t.resolveEntityRef=function(e){if(!e)return null;if(e.guid){var t=this._guidLookup.get(e.guid);if(t)return t}if(void 0!==e.id){var n=this._idRemapping.get(e.id);if(n)return n}return null},t.registerPendingRef=function(e,t,n,i){this._pendingRefs.push({component:e,propertyKey:t,originalId:n,originalGuid:i})},t.resolveAllReferences=function(){for(var e,t=0,n=a(this._pendingRefs);!(e=n()).done;){var i=e.value,r=this.resolveEntityRef({id:i.originalId,guid:i.originalGuid});r&&(i.component[i.propertyKey]=r,t++)}return t},t.getUnresolvedCount=function(){for(var e,t=0,n=a(this._pendingRefs);!(e=n()).done;){var i=e.value;this.resolveEntityRef({id:i.originalId,guid:i.originalGuid})||t++}return t},t.getPendingCount=function(){return this._pendingRefs.length},t.getRegisteredEntityCount=function(){return this._guidLookup.size},t.clear=function(){this._idRemapping.clear(),this._guidLookup.clear(),this._pendingRefs=[]},t.getDebugInfo=function(){return{registeredEntities:this._guidLookup.size,pendingRefs:this._pendingRefs.length,unresolvedRefs:this.getUnresolvedCount(),preserveIds:this._preserveIds}},s(e,[{key:"preserveIds",get:function(){return this._preserveIds}}])}(),Ht=Z("SceneSerializer"),Wt=function(){function t(){}return t.serialize=function(e,t){var n=c({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),i=this.filterEntities(e,n),r=e.getSystem(Ge),o=Ft.serializeEntities(i,!0,null!=r?r:void 0),s=this.buildComponentTypeRegistry(i),a=this.serializeSceneData(e.sceneData),u={name:e.name,version:this.SERIALIZATION_VERSION,entities:o,componentTypeRegistry:s};return a&&Object.keys(a).length>0&&(u.sceneData=a),n.includeMetadata&&(u.timestamp=Date.now(),u.metadata={entityCount:o.length,componentTypeCount:s.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(u,null,2):JSON.stringify(u):Bt.encode(u)},t.deserialize=function(e,t,n){var i,r=c({strategy:"replace",preserveIds:!1},n);try{i="string"==typeof t?JSON.parse(t):Bt.decode(t)}catch(e){throw new Error("Failed to parse save data: "+e)}r.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=r.migration(i.version,this.SERIALIZATION_VERSION,i));var o=r.componentRegistry||this.getGlobalComponentRegistry();"replace"===r.strategy&&e.destroyAllEntities();var s=e.getSystem(Ge),u=new Lt;u.setPreserveIds(r.preserveIds||!1);for(var l,h=Ft.deserializeEntities(i.entities,o,function(){return e.identifierPool.checkOut()},r.preserveIds||!1,e,s,u),d=h.rootEntities,f=h.allEntities,p=a(d);!(l=p()).done;){var m=l.value;e.addEntity(m,!0),this.addChildrenRecursively(m,e,s,f)}e.querySystem.clearCache(),e.clearSystemEntityCaches();var v=u.resolveAllReferences(),g=u.getUnresolvedCount();g>0&&Ht.warn(g+" EntityRef(s) could not be resolved. Resolved: "+v+", Total pending: "+u.getPendingCount()+" | "+g+" 个实体引用无法解析"),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData);for(var y,_=[],S=a(f.values());!(y=S()).done;){var C=y.value;this.callOnDeserializedForEntity(C,_)}_.length>0&&Promise.all(_).catch(function(e){Ht.error("Error in onDeserialized | onDeserialized 执行错误:",e)})},t.callOnDeserializedForEntity=function(e,t){for(var n,i=a(e.components);!(n=i()).done;){var r=n.value;try{var o=r.onDeserialized();o instanceof Promise&&t.push(o)}catch(e){var s=H(r.constructor);Ht.error("Error calling onDeserialized on component "+s+" | 调用组件 "+s+" 的 onDeserialized 时出错:",e)}}},t.addChildrenRecursively=function(t,n,i,r){var o=t.getComponent(e.HierarchyComponent);if(o&&0!==o.childIds.length)for(var s,c=a(o.childIds);!(s=c()).done;){var u,l=s.value,h=null!==(u=null==r?void 0:r.get(l))&&void 0!==u?u:n.findEntityById(l);h&&(n.addEntity(h,!0),this.addChildrenRecursively(h,n,i,r))}},t.serializeSceneData=function(e){for(var t,n={},i=a(e);!(t=i()).done;){var r=t.value,o=r[0],s=r[1];n[o]=Rt.serialize(s)}return n},t.deserializeSceneData=function(e,t){t.clear();for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],o=r[0],s=r[1];t.set(o,Rt.deserialize(s))}},t.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var i=new Set(t.components);return n.filter(function(e){return Array.from(e.components).some(function(e){return i.has(e.constructor)})})}return n},t.buildComponentTypeRegistry=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.components);!(r=o()).done;){var s=r.value,c=H(s.constructor),u=xe(s);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map(function(e){return{typeName:e[0],version:e[1]}})},t.getGlobalComponentRegistry=function(){return $.getAllComponentNames()},t.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),c({valid:0===t.length,version:n.version},t.length>0&&{errors:t})}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},t.getInfo=function(e){try{var t,n=JSON.parse(e);return c({name:n.name,version:n.version},void 0!==n.timestamp&&{timestamp:n.timestamp},{entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length})}catch(e){return null}},t}();Wt.SERIALIZATION_VERSION=1,e.ChangeOperation=void 0,(xt=e.ChangeOperation||(e.ChangeOperation={})).EntityAdded="entity_added",xt.EntityRemoved="entity_removed",xt.EntityUpdated="entity_updated",xt.ComponentAdded="component_added",xt.ComponentRemoved="component_removed",xt.ComponentUpdated="component_updated",xt.SceneDataUpdated="scene_data_updated";var Gt={deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1,format:"json",pretty:!1},jt=function(){function t(){}return t.createSnapshot=function(t,n){for(var i,r=c({},Gt,n),o={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},s=a(t.entities.buffer);!(i=s()).done;){var u=i.value;if(!r.entityFilter||r.entityFilter(u)){o.entityIds.add(u.id);var l=u.getComponent(e.HierarchyComponent),h=null==l?void 0:l.parentId;if(o.entities.set(u.id,c({name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder},null!=h&&{parentId:h})),r.deepComponentComparison){for(var d,f=new Map,p=a(u.components);!(d=p()).done;){var m=d.value,v=Nt.serialize(m);v&&f.set(v.type,JSON.stringify(v.data))}f.size>0&&o.components.set(u.id,f)}}}if(r.trackSceneData)for(var g,y=a(t.sceneData);!(g=y()).done;){var _=g.value,S=_[0],C=_[1];o.sceneData.set(S,JSON.stringify(C))}return o},t.computeIncremental=function(t,n,i){for(var r,o=c({},Gt,i),s={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:t.name,baseVersion:n.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},u=new Set,l=a(t.entities.buffer);!(r=l()).done;){var h=r.value;if(!o.entityFilter||o.entityFilter(h)){u.add(h.id);var d=h.getComponent(e.HierarchyComponent),f=null==d?void 0:d.parentId;if(n.entityIds.has(h.id)){var p=n.entities.get(h.id);(p.name!==h.name||p.tag!==h.tag||p.active!==h.active||p.enabled!==h.enabled||p.updateOrder!==h.updateOrder||p.parentId!==f)&&s.entityChanges.push({operation:e.ChangeOperation.EntityUpdated,entityId:h.id,entityData:c({name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder},null!=f&&{parentId:f})}),o.deepComponentComparison&&this.detectComponentChanges(h,n,s.componentChanges)}else{s.entityChanges.push({operation:e.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:c({id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder},null!=f&&{parentId:f},{components:[],children:[]})});for(var m,v=a(h.components);!(m=v()).done;){var g=m.value,y=Nt.serialize(g);y&&s.componentChanges.push({operation:e.ChangeOperation.ComponentAdded,entityId:h.id,componentType:y.type,componentData:y})}}}}for(var _,S=a(n.entityIds);!(_=S()).done;){var C=_.value;u.has(C)||s.entityChanges.push({operation:e.ChangeOperation.EntityRemoved,entityId:C})}return o.trackSceneData&&this.detectSceneDataChanges(t,n,s.sceneDataChanges),s},t.detectComponentChanges=function(t,n,i){for(var r,o=n.components.get(t.id),s=new Map,c=a(t.components);!(r=c()).done;){var u=r.value,l=Nt.serialize(u);l&&s.set(l.type,l)}for(var h,d=a(s);!(h=d()).done;){var f=h.value,p=f[0],m=f[1],v=JSON.stringify(m.data);o&&o.has(p)?o.get(p)!==v&&i.push({operation:e.ChangeOperation.ComponentUpdated,entityId:t.id,componentType:p,componentData:m}):i.push({operation:e.ChangeOperation.ComponentAdded,entityId:t.id,componentType:p,componentData:m})}if(o)for(var g,y=a(o.keys());!(g=y()).done;){var _=g.value;s.has(_)||i.push({operation:e.ChangeOperation.ComponentRemoved,entityId:t.id,componentType:_})}},t.detectSceneDataChanges=function(t,n,i){for(var r,o=new Set,s=a(t.sceneData);!(r=s()).done;){var c=r.value,u=c[0],l=c[1];o.add(u);var h=JSON.stringify(l),d=n.sceneData.get(u);d&&d===h||i.push({operation:e.ChangeOperation.SceneDataUpdated,key:u,value:l})}for(var f,p=a(n.sceneData.keys());!(f=p()).done;){var m=f.value;o.has(m)||i.push({operation:e.ChangeOperation.SceneDataUpdated,key:m,value:void 0,deleted:!0})}},t.applyIncremental=function(t,n,i){for(var r,o=a(n.entityChanges);!(r=o()).done;){var s=r.value;switch(s.operation){case e.ChangeOperation.EntityAdded:this.applyEntityAdded(t,s);break;case e.ChangeOperation.EntityRemoved:this.applyEntityRemoved(t,s);break;case e.ChangeOperation.EntityUpdated:this.applyEntityUpdated(t,s)}}for(var c,u=a(n.componentChanges);!(c=u()).done;){var l=c.value;switch(l.operation){case e.ChangeOperation.ComponentAdded:this.applyComponentAdded(t,l,i);break;case e.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(t,l,i);break;case e.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(t,l,i)}}for(var h,d=a(n.sceneDataChanges);!(h=d()).done;){var f=h.value;f.deleted?t.sceneData.delete(f.key):t.sceneData.set(f.key,f.value)}},t.applyEntityAdded=function(e,t){var n,i;if(t.entityData){var r=new ht(t.entityName||"Entity",t.entityId);r.tag=t.entityData.tag||0,r.active=null===(n=t.entityData.active)||void 0===n||n,r.enabled=null===(i=t.entityData.enabled)||void 0===i||i,r.updateOrder=t.entityData.updateOrder||0,e.addEntity(r)}},t.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},t.applyEntityUpdated=function(t,n){if(n.entityData){var i=t.entities.findEntityById(n.entityId);if(i){void 0!==n.entityData.name&&(i.name=n.entityData.name),void 0!==n.entityData.tag&&(i.tag=n.entityData.tag),void 0!==n.entityData.active&&(i.active=n.entityData.active),void 0!==n.entityData.enabled&&(i.enabled=n.entityData.enabled),void 0!==n.entityData.updateOrder&&(i.updateOrder=n.entityData.updateOrder);var r=t.getSystem(Ge);if(r){var o=i.getComponent(e.HierarchyComponent),s=null==o?void 0:o.parentId;if(void 0!==n.entityData.parentId){var a=t.entities.findEntityById(n.entityData.parentId);a&&s!==n.entityData.parentId&&r.setParent(i,a)}else null!=s&&r.setParent(i,null)}}}},t.applyComponentAdded=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=Nt.deserialize(t.componentData,n);r&&i.addComponent(r)}}},t.applyComponentRemoved=function(e,t,n){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);r&&i.removeComponentByType(r)}},t.applyComponentUpdated=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);if(r){i.removeComponentByType(r);var o=Nt.deserialize(t.componentData,n);o&&i.addComponent(o)}}}},t.serializeIncremental=function(e,t){var n,i,r=null!==(n=null==t?void 0:t.format)&&void 0!==n?n:"json",o=null!==(i=null==t?void 0:t.pretty)&&void 0!==i&&i;return"binary"===r?Bt.encode(e):o?JSON.stringify(e,null,2):JSON.stringify(e)},t.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):Bt.decode(e)},t.getIncrementalStats=function(t){for(var n,i={added:0,removed:0,updated:0},r={added:0,removed:0,updated:0},o=a(t.entityChanges);!(n=o()).done;){var s=n.value;s.operation===e.ChangeOperation.EntityAdded?i.added++:s.operation===e.ChangeOperation.EntityRemoved?i.removed++:s.operation===e.ChangeOperation.EntityUpdated&&i.updated++}for(var c,u=a(t.componentChanges);!(c=u()).done;){var l=c.value;l.operation===e.ChangeOperation.ComponentAdded?r.added++:l.operation===e.ChangeOperation.ComponentRemoved?r.removed++:l.operation===e.ChangeOperation.ComponentUpdated&&r.updated++}return{totalChanges:t.entityChanges.length+t.componentChanges.length+t.sceneDataChanges.length,entityChanges:t.entityChanges.length,componentChanges:t.componentChanges.length,sceneDataChanges:t.sceneDataChanges.length,addedEntities:i.added,removedEntities:i.removed,updatedEntities:i.updated,addedComponents:r.added,removedComponents:r.removed,updatedComponents:r.updated}},t.resetVersion=function(){this.snapshotVersion=0},t}();jt.snapshotVersion=0;var Ut={enabled:!0,sampleInterval:10,minDuration:.1,trackAsync:!0,excludePatterns:[/^_/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/],maxBufferSize:1e4},qt=function(){function t(e){this.wrappedObjects=new WeakMap,this.samplingProfiler=null,this.registeredClasses=new Map,this._config=c({},Ut,e)}t.getInstance=function(e){return t._instance||(t._instance=new t(e)),t._instance},t.resetInstance=function(){t._instance&&(t._instance.dispose(),t._instance=null)},t.setEnabled=function(e){t.getInstance().setEnabled(e)},t.registerClass=function(n,i,r){return void 0===i&&(i=e.ProfileCategory.Custom),t.getInstance().registerClass(n,i,r)},t.wrapInstance=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().wrapInstance(n,i,r)},t.wrapFunction=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().wrapFunction(n,i,r)},t.startSampling=function(){t.getInstance().startSampling()},t.stopSampling=function(){return t.getInstance().stopSampling()};var n=t.prototype;return n.setEnabled=function(e){this._config.enabled=e,!e&&this.samplingProfiler&&this.samplingProfiler.stop()},n.registerClass=function(t,n,i){void 0===n&&(n=e.ProfileCategory.Custom);var r=i||t.name;this.registeredClasses.set(r,{constructor:t,category:n});var o=this;return new Proxy(t,{construct:function(e,t,i){var s=Reflect.construct(e,t,i);return o._config.enabled&&o.wrapInstance(s,r,n),s}})},n.wrapInstance=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),!this._config.enabled)return t;if(this.wrappedObjects.has(t))return t;var r=new Map;this.wrappedObjects.set(t,r);for(var o,s=a(this._getAllMethodNames(t));!(o=s()).done;){var c=o.value;if(!this._shouldExcludeMethod(c)){var u=this._getPropertyDescriptor(t,c);if(u&&"function"==typeof u.value){var l=u.value,h=this._createWrappedMethod(l,n,c,i);r.set(c,{className:n,methodName:c,category:i,original:l});try{t[c]=h}catch(e){}}}}return t},n.wrapFunction=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),!this._config.enabled)return t;var r=this,o=function(){var e=et.beginSample(n,i);try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];var c=t.apply(this,s);return r._config.trackAsync&&c instanceof Promise?c.finally(function(){et.endSample(e)}):(et.endSample(e),c)}catch(t){throw et.endSample(e),t}};return Object.defineProperty(o,"name",{value:t.name||n}),Object.defineProperty(o,"length",{value:t.length}),o},n.startSampling=function(){this.samplingProfiler||(this.samplingProfiler=new Qt(this._config)),this.samplingProfiler.start()},n.stopSampling=function(){return this.samplingProfiler?this.samplingProfiler.stop():[]},n.dispose=function(){this.samplingProfiler&&(this.samplingProfiler.stop(),this.samplingProfiler=null),this.registeredClasses.clear()},n._createWrappedMethod=function(e,t,n,i){var r=this,o=t+"."+n,s=this._config.minDuration;return function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];if(!r._config.enabled||!et.isEnabled())return e.apply(this,n);var c=performance.now(),u=et.beginSample(o,i);try{var l=e.apply(this,n);return r._config.trackAsync&&l instanceof Promise?l.then(function(e){return performance.now()-c>=s&&et.endSample(u),e},function(e){throw et.endSample(u),e}):(performance.now()-c>=s&&et.endSample(u),l)}catch(e){throw et.endSample(u),e}}},n._getAllMethodNames=function(e){for(var t=new Set,n=e;n&&n!==Object.prototype;){for(var i,r=a(Object.getOwnPropertyNames(n));!(i=r()).done;){var o=i.value;"constructor"!==o&&t.add(o)}n=Object.getPrototypeOf(n)}return Array.from(t)},n._getPropertyDescriptor=function(e,t){for(var n=e;n&&n!==Object.prototype;){var i=Object.getOwnPropertyDescriptor(n,t);if(i)return i;n=Object.getPrototypeOf(n)}},n._shouldExcludeMethod=function(e){if("constructor"===e||e.startsWith("__"))return!0;for(var t,n=a(this._config.excludePatterns);!(t=n()).done;){if(t.value.test(e))return!0}return!1},t}();qt._instance=null;var Qt=function(){function e(e){this.samples=[],this.intervalId=null,this.isRunning=!1,this.config=e}var t=e.prototype;return t.start=function(){var e=this;if(!this.isRunning){this.isRunning=!0,this.samples=[];var t=function(){if(e.isRunning){var n=e.captureStack();n.length>0&&(e.samples.push({timestamp:performance.now(),stack:n}),e.samples.length>e.config.maxBufferSize&&e.samples.shift()),e.config.sampleInterval,e.intervalId=setTimeout(t,e.config.sampleInterval)}};t()}},t.stop=function(){return this.isRunning=!1,null!==this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),[].concat(this.samples)},t.captureStack=function(){try{for(var e,t=((new Error).stack||"").split("\n").slice(3),n=[],i=a(t);!(e=i()).done;){var r=e.value,o=this.parseStackFrame(r);o&&!this.isInternalFrame(o)&&n.push(o)}return n}catch(e){return[]}},t.parseStackFrame=function(e){var t=(e=e.trim()).match(/at\s+(.+?)\s+\(/);if(t&&t[1])return t[1];if((t=e.match(/at\s+(.+)/))&&t[1]){var n=t[1];if(!n.includes("("))return n}return(t=e.match(/^(.+?)@/))&&t[1]?t[1]:null},t.isInternalFrame=function(e){return["SamplingProfiler","AutoProfiler","ProfilerSDK","setTimeout","setInterval","requestAnimationFrame","<anonymous>","eval"].some(function(t){return e.includes(t)})},e}();var Vt,Yt=Z("ServiceContainer");e.ServiceLifetime=void 0,(Vt=e.ServiceLifetime||(e.ServiceLifetime={})).Singleton="singleton",Vt.Transient="transient";var Jt=function(){function t(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var n=t.prototype;return n.registerSingleton=function(t,n){this._services.has(t)?Yt.warn("Service "+t.name+" is already registered"):(this._services.set(t,c({identifier:t,type:t},n&&{factory:n},{lifetime:e.ServiceLifetime.Singleton})),Yt.debug("Registered singleton service: "+t.name))},n.registerTransient=function(t,n){this._services.has(t)?Yt.warn("Service "+t.name+" is already registered"):(this._services.set(t,c({identifier:t,type:t},n&&{factory:n},{lifetime:e.ServiceLifetime.Transient})),Yt.debug("Registered transient service: "+t.name))},n.registerInstance=function(t,n){if(this._services.has(t)){var i="symbol"==typeof t?t.description:t.name;Yt.warn("Service "+i+" is already registered")}else{if(this._services.set(t,{identifier:t,instance:n,lifetime:e.ServiceLifetime.Singleton}),"symbol"!=typeof t&&D(t)){var r,o=P(t),s=null!==(r=null==o?void 0:o.priority)&&void 0!==r?r:0;this._updatableServices.push({instance:n,priority:s}),this._updatableServices.sort(function(e,t){return e.priority-t.priority}),Yt.debug("Service "+t.name+" is updatable (priority: "+s+"), added to update list")}var a="symbol"==typeof t?t.description:t.name;Yt.debug("Registered service instance: "+a)}},n.resolve=function(t){var n=this._services.get(t),i="symbol"==typeof t?t.description:t.name;if(!n)throw new Error("Service "+i+" is not registered");if(this._resolving.has(t)){var r=Array.from(this._resolving).map(function(e){return"symbol"==typeof e?e.description:e.name}).join(" -> ");throw new Error("Circular dependency detected: "+r+" -> "+i)}if(n.lifetime===e.ServiceLifetime.Singleton&&n.instance)return n.instance;this._resolving.add(t);try{var o;if(n.factory)o=n.factory(this);else{if(!n.type)throw new Error("Service "+i+" has no factory or type to construct");o=new n.type}if(n.lifetime===e.ServiceLifetime.Singleton&&(n.instance=o,n.type&&D(n.type))){var s,a=P(n.type),c=null!==(s=null==a?void 0:a.priority)&&void 0!==s?s:0;this._updatableServices.push({instance:o,priority:c}),this._updatableServices.sort(function(e,t){return e.priority-t.priority}),Yt.debug("Service "+i+" is updatable (priority: "+c+"), added to update list")}return o}finally{this._resolving.delete(t)}},n.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},n.isRegistered=function(e){return this._services.has(e)},n.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex(function(e){return e.instance===t.instance});-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}this._services.delete(e);var i="symbol"==typeof e?e.description:e.name;return Yt.debug("Unregistered service: "+i),!0},n.clear=function(){for(var e,t=a(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],Yt.debug("Cleared all services")},n.getRegisteredServices=function(){return Array.from(this._services.keys())},n.updateAll=function(e){for(var t,n=a(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},n.getUpdatableCount=function(){return this._updatableServices.length},n.getAll=function(){for(var e,t=[],n=a(this._services.values());!(e=n()).done;){var i=e.value;i.instance&&t.push(i.instance)}return t},t}(),Zt=function(e){function t(n){var i,r="[SystemDependencyGraph] 检测到循环依赖 | Cycle dependency detected: "+n.join(" -> ");return(i=e.call(this,r)||this).name="CycleDependencyError",i.involvedNodes=n,Object.setPrototypeOf(i,(this instanceof t?this.constructor:void 0).prototype),i}return l(t,e),t}(v(Error)),Xt="set:",Kt=function(){function e(){this._nodes=new Map}var t=e.prototype;return t.addSystemNode=function(e){this.getOrCreateNode(e,!1)},t.addSetNode=function(e){var t=Xt+e;this.getOrCreateNode(t,!0)},t.addEdge=function(e,t){if(e!==t){var n=this.getOrCreateNode(e,e.startsWith(Xt)),i=this.getOrCreateNode(t,t.startsWith(Xt));n.outEdges.add(t),i.inEdges.add(e)}},t.buildFromSystems=function(e){this.clear();for(var t,n=a(e);!(t=n()).done;){var i=t.value;this.addSystemNode(i.name);for(var r,o=a(i.sets);!(r=o()).done;){var s=r.value;this.addSetNode(s)}}for(var c,u=a(e);!(c=u()).done;){for(var l,h=c.value,d=a(h.sets);!(l=d()).done;){var f=l.value,p=Xt+f;this.addEdge(p,h.name)}for(var m,v=a(h.before);!(m=v()).done;){var g=m.value,y=this.resolveTargetId(g);this.addEdge(h.name,y)}for(var _,S=a(h.after);!(_=S()).done;){var C=_.value,E=this.resolveTargetId(C);this.addEdge(E,h.name)}}},t.topologicalSort=function(){for(var e,t=new Map,n=a(this._nodes);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,o.inEdges.size)}for(var s,c=[],u=a(t);!(s=u()).done;){var l=s.value,h=l[0];0===l[1]&&c.push(h)}for(var d=[],f=0;c.length>0;){var p=c.shift();f++;var m=this._nodes.get(p);if(m){m.bIsVirtual||d.push(p);for(var v,g=a(m.outEdges);!(v=g()).done;){var y,_=v.value,S=(null!==(y=t.get(_))&&void 0!==y?y:0)-1;t.set(_,S),0===S&&c.push(_)}}}if(f<this._nodes.size){for(var C,E=[],b=a(t);!(C=b()).done;){var T=C.value,w=T[0];T[1]>0&&E.push(w)}throw new Zt(E)}return d},t.clear=function(){this._nodes.clear()},t.getOrCreateNode=function(e,t){var n=this._nodes.get(e);return n||(n={id:e,bIsVirtual:t,inEdges:new Set,outEdges:new Set},this._nodes.set(e,n)),n},t.resolveTargetId=function(e){return e.startsWith(Xt),e},s(e,[{key:"size",get:function(){return this._nodes.size}}])}(),$t=Z("SystemScheduler"),en=["startup","preUpdate","update","postUpdate","cleanup"],tn=function(){function e(){this._sortedByStage=new Map,this._dirty=!0,this._graph=new Kt,this._useDependencySort=!0}var t=e.prototype;return t.setUseDependencySort=function(e){this._useDependencySort!==e&&(this._useDependencySort=e,this._dirty=!0)},t.markDirty=function(){this._dirty=!0},t.getSortedSystems=function(e,t){var n;if(this.ensureBuilt(e),t)return null!==(n=this._sortedByStage.get(t))&&void 0!==n?n:[];for(var i=[],r=0,o=en;r<o.length;r++){var s=o[r],a=this._sortedByStage.get(s);a&&i.push.apply(i,a)}return i},t.getAllSortedSystems=function(e){return this.getSortedSystems(e)},t.ensureBuilt=function(e){this._dirty&&(this._sortedByStage.clear(),this._useDependencySort&&this.hasDependencies(e)?this.buildWithDependencyGraph(e):this.buildWithUpdateOrder(e),this._dirty=!1)},t.hasDependencies=function(e){for(var t,n=a(e);!(t=n()).done;){var i=t.value,r=this.getSchedulingMetadata(i);if(r.before.length>0||r.after.length>0||r.sets.length>0)return!0;if("update"!==r.stage)return!0}return!1},t.buildWithUpdateOrder=function(e){var t=[].concat(e).sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder});this._sortedByStage.set("update",t)},t.buildWithDependencyGraph=function(e){for(var t=new Map,n=0,i=en;n<i.length;n++){var r=i[n];t.set(r,[])}for(var o,s=a(e);!(o=s()).done;){var c=o.value,u=this.getSchedulingMetadata(c).stage,l=t.get(u);l?l.push(c):t.get("update").push(c)}for(var h,d=a(t);!(h=d()).done;){var f=h.value,p=f[0],m=f[1];if(0!==m.length){var v=this.sortSystemsInStage(m);this._sortedByStage.set(p,v)}else this._sortedByStage.set(p,[])}},t.sortSystemsInStage=function(e){for(var t,n=new Map,i=[],r=a(e);!(t=r()).done;){var o=t.value,s=o.systemName;n.set(s,o);var c=this.getSchedulingMetadata(o);i.push({name:s,before:c.before,after:c.after,sets:c.sets})}this._graph.buildFromSystems(i);try{for(var u,l=this._graph.topologicalSort(),h=[],d=a(l);!(u=d()).done;){var f=u.value,p=n.get(f);p&&h.push(p)}return this.stableSortByUpdateOrder(h)}catch(t){if(t instanceof Zt)throw t;return $t.warn("Topological sort failed, falling back to updateOrder | 拓扑排序失败,回退到 updateOrder 排序",t),this.fallbackSort(e)}},t.stableSortByUpdateOrder=function(e){return e},t.fallbackSort=function(e){return[].concat(e).sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})},t.getSchedulingMetadata=function(e){return{stage:e.getStage(),before:[].concat(e.getBefore()),after:[].concat(e.getAfter()),sets:[].concat(e.getSets())}},e}(),nn=function(){function e(e){void 0===e&&(e=1024),this._freeList=[],this._nextIndex=1,this._aliveCount=0,this._capacity=e,this._generations=new Uint32Array(e),this._alive=new Uint8Array(e),this._enabled=new Uint8Array(e),this._alive[0]=0,this._enabled[0]=0}var t=e.prototype;return t.create=function(){var e;this._freeList.length>0?e=this._freeList.pop():(e=this._nextIndex++)>=this._capacity&&this.grow(e);var t=this._generations[e];return this._alive[e]=1,this._enabled[e]=1,this._aliveCount++,at(e,t)},t.destroy=function(e){var t=ct(e),n=ut(e);if(t>=this._capacity||0===t)return!1;if(this._generations[t]!==n)return!1;if(1!==this._alive[t])return!1;this._alive[t]=0,this._enabled[t]=0,this._aliveCount--;var i=(n+1)%st;return this._generations[t]=i,this._freeList.push(t),!0},t.isAlive=function(e){var t=ct(e),n=ut(e);return!(t>=this._capacity||0===t)&&(1===this._alive[t]&&this._generations[t]===n)},t.isEnabled=function(e){if(!this.isAlive(e))return!1;var t=ct(e);return 1===this._enabled[t]},t.setEnabled=function(e,t){if(!this.isAlive(e))return!1;var n=ct(e);return this._enabled[n]=t?1:0,!0},t.validate=function(e){return this.isAlive(e)},t.grow=function(e){for(var t=this._capacity;t<=e;)t<<=1;if(t>ot&&e>=(t=ot))throw new Error("EntityHandleManager: 超过最大实体数量 "+ot);var n=new Uint32Array(t),i=new Uint8Array(t),r=new Uint8Array(t);n.set(this._generations),i.set(this._alive),r.set(this._enabled),this._generations=n,this._alive=i,this._enabled=r,this._capacity=t},t.reset=function(){this._generations.fill(0),this._alive.fill(0),this._enabled.fill(0),this._freeList.length=0,this._nextIndex=1,this._aliveCount=0},t.forEach=function(e){for(var t=1;t<this._nextIndex;t++){if(1===this._alive[t])e(at(t,this._generations[t]))}},t.getAllAlive=function(){var e=[];return this.forEach(function(t){return e.push(t)}),e},s(e,[{key:"aliveCount",get:function(){return this._aliveCount}},{key:"capacity",get:function(){return this._capacity}}])}(),rn=function(){function e(){this._current=1}var t=e.prototype;return t.increment=function(){this._current++,this._current>=Number.MAX_SAFE_INTEGER&&(this._current=1)},t.reset=function(){this._current=1},t.isChangedSince=function(e,t){return e>t},s(e,[{key:"current",get:function(){return this._current}}])}(),on=function(){function t(e){var t;this.name="",this.sceneData=new Map,this._handleToEntity=new Map,this.epochManager=new rn,this._performanceMonitor=null,this._didSceneBegin=!1,this.isEditorMode=!1,this._deferredComponentCallbacks=[],this._cachedSystems=null,this._systemsOrderDirty=!0,this._systemErrorCount=new Map,this._systemAddCounter=0,this._systemScheduler=new tn,this._componentIdToSystems=new Map,this._globalNotifySystems=new Set,this.entities=new dt(this),this.identifierPool=new ft,this.componentStorageManager=new Fe,this.componentRegistry=new K,!1!==(null==e?void 0:e.inheritGlobalRegistry)&&this.componentRegistry.cloneFrom($),this.querySystem=new It,this.eventSystem=new At,this.referenceTracker=new le,this.handleManager=new nn,this._services=new Jt,this._logger=Z("Scene"),this._maxErrorCount=null!==(t=null==e?void 0:e.maxSystemErrorCount)&&void 0!==t?t:10,null!=e&&e.name&&(this.name=e.name)}var n=t.prototype;return n._rebuildSystemsCache=function(){var e=this._services.getAll(),t=this._filterEntitySystems(e);try{return this._systemScheduler.markDirty(),this._systemScheduler.getAllSortedSystems(t)}catch(e){return e instanceof Zt?this._logger.error("[Scene] 系统存在循环依赖,回退到 updateOrder 排序 | Cycle dependency detected, falling back to updateOrder sort",e.involvedNodes):this._logger.error("[Scene] 系统排序失败 | System sorting failed",e),this._sortSystemsByUpdateOrder(t)}},n._filterEntitySystems=function(e){return e.filter(function(e){return e instanceof We})},n._sortSystemsByUpdateOrder=function(e){return e.sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})},n.getSystem=function(e){return this._services.tryResolve(e)},n.markSystemsOrderDirty=function(){this._systemsOrderDirty=!0},n.initialize=function(){},n.onStart=function(){},n.unload=function(){},n.queueDeferredComponentCallback=function(e){this._deferredComponentCallbacks.push(e)},n.begin=function(){if(this._didSceneBegin=!0,this._deferredComponentCallbacks.length>0){for(var e,t=a(this._deferredComponentCallbacks);!(e=t()).done;){var n=e.value;try{n()}catch(e){this._logger.error("Error executing deferred component callback:",e)}}this._deferredComponentCallbacks=[]}this.onStart()},n.end=function(){this._didSceneBegin=!1,this.unload(),this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this._cachedSystems=null,this._systemsOrderDirty=!0,this._componentIdToSystems.clear(),this._globalNotifySystems.clear(),this._handleToEntity.clear(),this.handleManager.reset(),this.epochManager.reset()},n.update=function(){this.epochManager.increment(),et.beginFrame();var t=et.beginSample("Scene.update",e.ProfileCategory.ECS);try{Ve.getInstance().update(),this.entities.updateLists();var n=this.systems;this._runSystemPhase(n,"update","Systems.update"),this._runSystemPhase(n,"lateUpdate","Systems.lateUpdate"),this.flushCommandBuffers(n)}finally{et.endSample(t),et.endFrame()}},n._runSystemPhase=function(t,n,i){var r=et.beginSample(i,e.ProfileCategory.ECS);try{for(var o,s=a(t);!(o=s()).done;){var c=o.value;if(this._shouldSystemRun(c)){var u="lateUpdate"===n?".late":"",l=et.beginSample(""+c.systemName+u,e.ProfileCategory.ECS);try{c[n]()}catch(e){this._handleSystemError(c,n,e)}finally{et.endSample(l)}}}}finally{et.endSample(r)}},n._shouldSystemRun=function(e){if(!e.enabled)return!1;if(!this.isEditorMode)return!0;var t=ie(e);return!1!==(null==t?void 0:t.runInEditMode)},n.flushCommandBuffers=function(t){var n=et.beginSample("Scene.flushCommandBuffers",e.ProfileCategory.ECS);try{for(var i,r=a(t);!(i=r()).done;){var o=i.value;try{o.flushCommands()}catch(e){this._logger.error("Error flushing commands for system "+o.systemName+":",e)}}}finally{et.endSample(n)}},n._handleSystemError=function(e,t,n){var i=(this._systemErrorCount.get(e)||0)+1;this._systemErrorCount.set(e,i);var r=e.systemName;this._logger.error("Error in system "+r+"."+t+"() ["+i+"/"+this._maxErrorCount+"]:",n),i>=this._maxErrorCount&&(e.enabled=!1,this._logger.error("System "+r+" has been disabled due to excessive errors ("+i+" errors)"))},n.createEntity=function(e){var t=new ht(e,this.identifierPool.checkOut()),n=this.handleManager.create();return t.setHandle(n),this._handleToEntity.set(n,t),this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)},n.clearSystemEntityCaches=function(){for(var e,t=a(this.systems);!(e=t()).done;){e.value.clearEntityCache()}},n.notifyEntityComponentChanged=function(e,t){var n=new Set;if(t&&this.componentRegistry.isRegistered(t)){var i=this.componentRegistry.getBitIndex(t),r=this._componentIdToSystems.get(i);if(r)for(var o,s=a(r);!(o=s()).done;){var c=o.value;c.handleEntityComponentChanged(e),n.add(c)}}for(var u,l=a(this._globalNotifySystems);!(u=l()).done;){var h=u.value;n.has(h)||(h.handleEntityComponentChanged(e),n.add(h))}if(!t)for(var d,f=a(this.systems);!(d=f()).done;){var p=d.value;n.has(p)||p.handleEntityComponentChanged(e)}},n.indexSystemByComponents=function(e){var t=e.matcher;if(t&&!t.isNothing()){var n=t.getCondition();if((n.none.length>0||void 0!==n.tag||void 0!==n.name)&&this._globalNotifySystems.add(e),t.isEmpty())this._globalNotifySystems.add(e);else{for(var i,r=a(n.all);!(i=r()).done;){var o=i.value;this.addSystemToComponentIndex(o,e)}for(var s,c=a(n.any);!(s=c()).done;){var u=s.value;this.addSystemToComponentIndex(u,e)}n.component&&this.addSystemToComponentIndex(n.component,e)}}},n.addSystemToComponentIndex=function(e,t){var n=this.componentRegistry.getBitIndex(e),i=this._componentIdToSystems.get(n);i||(i=new Set,this._componentIdToSystems.set(n,i)),i.add(t)},n.removeSystemFromIndex=function(e){this._globalNotifySystems.delete(e);for(var t,n=a(this._componentIdToSystems.values());!(t=n()).done;){t.value.delete(e)}},n.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},n.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],i=0;i<e;i++){var r=new ht(t+"_"+i,this.identifierPool.checkOut());r.scene=this;var o=this.handleManager.create();r.setHandle(o),this._handleToEntity.set(o,r),n.push(r)}for(var s=0,a=n;s<a.length;s++){var c=a[s];this.entities.add(c)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n},n.destroyEntities=function(e){if(0!==e.length){for(var t,n=a(e);!(t=n()).done;){t.value.setDestroyedState(!0)}for(var i,r=a(e);!(i=r()).done;){i.value.removeAllComponents()}for(var o,s=a(e);!(o=s()).done;){var c=o.value;this.entities.remove(c),this.querySystem.removeEntity(c),lt(c.handle)&&(this._handleToEntity.delete(c.handle),this.handleManager.destroy(c.handle))}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},n.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},n.findEntity=function(e){return this.entities.findEntity(e)},n.findEntityById=function(e){return this.entities.findEntityById(e)},n.findEntityByHandle=function(e){var t;return lt(e)&&this.handleManager.isAlive(e)&&null!==(t=this._handleToEntity.get(e))&&void 0!==t?t:null},n.findEntitiesByTag=function(e){for(var t,n=[],i=a(this.entities.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},n.findPersistentEntities=function(){return this.entities.buffer.filter(function(e){return e.isPersistent})},n.extractPersistentEntities=function(){for(var e,t=this.findPersistentEntities(),n=a(t);!(e=n()).done;){var i=e.value;this.entities.remove(i),this.querySystem.removeEntity(i),i.scene=null}return t},n.receiveMigratedEntities=function(e){for(var t,n=a(e);!(t=n()).done;){var i=t.value;i.scene=this,this.entities.add(i),this.querySystem.addEntity(i);for(var r,o=a(i.components);!(r=o()).done;){var s,c=r.value;this.componentStorageManager.addComponent(i.id,c),null===(s=this.referenceTracker)||void 0===s||s.registerEntityScene(i.id,this)}}e.length>0&&this.clearSystemEntityCaches()},n.getEntityByName=function(e){return this.findEntity(e)},n.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},n.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},n.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},n.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},n.query=function(){return new Dt},n.addEntityProcessor=function(t){var n,i;if("function"==typeof t){if(i=t,this._services.isRegistered(i)){var r=this._services.resolve(i);return this._logger.debug("System "+i.name+" already registered, returning existing instance"),r}n=M(i)?A(i,this._services):new i}else if(i=(n=t).constructor,this._services.isRegistered(i)){var o=this._services.resolve(i);return o===n?(this._logger.debug("System "+i.name+" instance already registered, returning it"),n):(this._logger.warn("Attempting to register a different instance of "+i.name+", but type is already registered. Returning existing instance."),o)}n.scene=this,n.addOrder=this._systemAddCounter++,n.setPerformanceMonitor(this.performanceMonitor);var s=ne(i);return void 0!==(null==s?void 0:s.updateOrder)&&n.setUpdateOrder(s.updateOrder),void 0!==(null==s?void 0:s.enabled)&&(n.enabled=s.enabled),this._services.registerInstance(i,n),this.markSystemsOrderDirty(),this.indexSystemByComponents(n),k(n,this._services),et.isEnabled()&&qt.wrapInstance(n,n.systemName,e.ProfileCategory.ECS),n.initialize(),this._logger.debug("System "+i.name+" registered and initialized"),n},n.registerSystems=function(e){for(var t,n=[],i=a(e);!(t=i()).done;){var r=t.value,o=this.addEntityProcessor(r);n.push(o)}return n},n.addSystem=function(e){return this.addEntityProcessor(e)},n.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),this.markSystemsOrderDirty(),this.removeSystemFromIndex(e),e.reset()},n.removeSystem=function(e){this.removeEntityProcessor(e)},n.getEntityProcessor=function(e){return this._services.tryResolve(e)},n.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},n.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map(function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map(function(e){return W(e)})}}),processors:e.map(function(e){return{name:oe(e),updateOrder:e.updateOrder,entityCount:e.entities.length}}),componentStats:this.componentStorageManager.getAllStats()}},n.serialize=function(e){return Wt.serialize(this,e)},n.deserialize=function(e,t){Wt.deserialize(this,e,t)},n.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=jt.createSnapshot(this,e)},n.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return jt.computeIncremental(this,this._incrementalBaseSnapshot,e)},n.applyIncremental=function(e,t){var n="string"==typeof e||e instanceof Uint8Array?jt.deserializeIncremental(e):e,i=t||this.componentRegistry.getAllComponentNames();jt.applyIncremental(this,n,i)},n.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},n.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},n.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},s(t,[{key:"systems",get:function(){return!this._systemsOrderDirty&&this._cachedSystems||(this._cachedSystems=this._rebuildSystemsCache(),this._systemsOrderDirty=!1),this._cachedSystems}},{key:"services",get:function(){return this._services}},{key:"performanceMonitor",get:function(){var e;this._performanceMonitor||(this._performanceMonitor=null!==(e=this._services.tryResolve(O))&&void 0!==e?e:new O);return this._performanceMonitor}}])}(),sn=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new ht("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.entity.addComponent(o)}return this},t.withIf=function(e,t){return e&&this.entity.addComponent(t),this},t.withFactory=function(e){var t=e();return this.entity.addComponent(t),this},t.configure=function(e,t){var n=this.entity.getComponent(e);return n&&t(n),this},t.enabled=function(e){return void 0===e&&(e=!0),this.entity.enabled=e,this},t.active=function(e){return void 0===e&&(e=!0),this.entity.active=e,this},t.withChild=function(e){var t=e.build(),n=this.scene.getSystem(Ge);return null==n||n.setParent(t,this.entity),this},t.withChildren=function(){for(var e=this.scene.getSystem(Ge),t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0,o=n;r<o.length;r++){var s=o[r].build();null==e||e.setParent(s,this.entity)}return this},t.withChildFactory=function(e){var t=e(this.entity).build(),n=this.scene.getSystem(Ge);return null==n||n.setParent(t,this.entity),this},t.withChildIf=function(e,t){if(e){var n=t.build(),i=this.scene.getSystem(Ge);null==i||i.setParent(n,this.entity)}return this},t.build=function(){return this.entity},t.spawn=function(){return this.scene.addEntity(this.entity),this.entity},t.clone=function(){var t=new e(this.scene,this.storageManager);return t.entity=this.entity,t},e}(),an=function(){function e(){this.scene=new on}var t=e.prototype;return t.named=function(e){return this.scene.name=e,this},t.withEntity=function(e){return this.scene.addEntity(e),this},t.withEntityBuilder=function(e){var t=e(new sn(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this},t.withEntities=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.scene.addEntity(o)}return this},t.withSystem=function(e){return this.scene.addSystem(e),this},t.withSystems=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.scene.addSystem(o)}return this},t.build=function(){return this.scene},e}(),cn=function(){function e(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.component=r(e,n)}var t=e.prototype;return t.set=function(e,t){return this.component[e]=t,this},t.configure=function(e){return e(this.component),this},t.setIf=function(e,t,n){return e&&(this.component[t]=n),this},t.build=function(){return this.component},e}(),un=function(){function e(e){this.entities=e}var t=e.prototype;return t.addComponent=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.addComponent(e)}return this},t.removeComponent=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.removeComponentByType(e)}return this},t.setActive=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.active=e}return this},t.setTag=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.tag=e}return this},t.forEach=function(e){return this.entities.forEach(e),this},t.filter=function(t){return new e(this.entities.filter(t))},t.toArray=function(){return this.entities.slice()},t.count=function(){return this.entities.length},e}(),ln=function(){function e(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}var t=e.prototype;return t.createEntity=function(){return new sn(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new an},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r(cn,[e].concat(n))},t.query=function(){return new Mt(this.querySystem)},t.find=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments).entities},t.findFirst=function(){var e,t=(e=this.querySystem).queryAll.apply(e,arguments);return t.entities.length>0?t.entities[0]:null},t.findByName=function(e){return this.scene.findEntity(e)},t.findByTag=function(e){return this.scene.findEntitiesByTag(e)},t.emit=function(e,t){this.eventSystem.emitSync(e,t)},t.emitAsync=function(){var e=i(d().m(function e(t,n){return d().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.eventSystem.emit(t,n);case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.on=function(e,t){return this.eventSystem.on(e,t)},t.once=function(e,t){return this.eventSystem.once(e,t)},t.off=function(e,t){this.eventSystem.off(e,t)},t.batch=function(e){return new un(e)},t.getStats=function(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}},e}();function hn(e,t,n){return new ln(e,t,n)}var dn,fn=Z("World"),pn={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,cleanupThresholdMs:3e5},mn=function(){function e(e){void 0===e&&(e={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=c({},pn,e),this.name=this._config.name,this._createdAt=Date.now(),this._services=new Jt}var t=e.prototype;return t.createScene=function(e,t){this.validateSceneName(e);var n=null!=t?t:new on;if(this._config.debug){var i=new O;i.enable(),n.services.registerInstance(O,i)}return n.id=e,n.name||(n.name=e),this._scenes.set(e,n),n.initialize(),n},t.removeScene=function(e){var t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),fn.info("从World '"+this.name+"' 中移除Scene: "+e),!0)},t.removeAllScenes=function(){var e=this;this._scenes.forEach(function(t,n){return e.removeScene(n)}),fn.info("从World '"+this.name+"' 中移除所有Scene")},t.getScene=function(e){var t;return null!==(t=this._scenes.get(e))&&void 0!==t?t:null},t.getSceneIds=function(){return Array.from(this._scenes.keys())},t.getAllScenes=function(){return Array.from(this._scenes.values())},t.setSceneActive=function(e,t){var n,i=this._scenes.get(e);i?t?(this._activeScenes.add(e),null===(n=i.begin)||void 0===n||n.call(i),fn.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),fn.debug("在World '"+this.name+"' 中停用Scene: "+e)):fn.warn("Scene '"+e+"' 不存在于World '"+this.name+"' 中")},t.isSceneActive=function(e){return this._activeScenes.has(e)},t.getActiveSceneCount=function(){return this._activeScenes.size},t.addGlobalSystem=function(e){var t;return this._globalSystems.includes(e)||(this._globalSystems.push(e),null===(t=e.initialize)||void 0===t||t.call(e),fn.debug("在World '"+this.name+"' 中添加全局System: "+e.name)),e},t.removeGlobalSystem=function(e){var t,n=this._globalSystems.indexOf(e);return-1!==n&&(this._globalSystems.splice(n,1),null===(t=e.reset)||void 0===t||t.call(e),fn.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){var t;return null!==(t=this._globalSystems.find(function(t){return t instanceof e}))&&void 0!==t?t:null},t.start=function(){this._isActive||(this._isActive=!0,this._globalSystems.forEach(function(e){var t;return null===(t=e.initialize)||void 0===t?void 0:t.call(e)}),fn.info("启动World: "+this.name))},t.stop=function(){var e=this;this._isActive&&(this._activeScenes.forEach(function(t){return e.setSceneActive(t,!1)}),this._globalSystems.forEach(function(e){var t;return null===(t=e.reset)||void 0===t?void 0:t.call(e)}),this._isActive=!1,fn.info("停止World: "+this.name))},t.destroy=function(){fn.info("销毁World: "+this.name),this.stop(),this.removeAllScenes(),this._globalSystems.forEach(function(e){var t,n,i;return null!==(t=null===(n=e.destroy)||void 0===n?void 0:n.call(e))&&void 0!==t?t:null===(i=e.reset)||void 0===i?void 0:i.call(e)}),this._globalSystems.length=0,this._services.clear(),this._scenes.clear(),this._activeScenes.clear()},t.updateGlobalSystems=function(){this._isActive&&this._globalSystems.forEach(function(e){var t;return null===(t=e.update)||void 0===t?void 0:t.call(e)})},t.updateScenes=function(){var e=this;this._isActive&&(this._activeScenes.forEach(function(t){var n,i;null===(n=e._scenes.get(t))||void 0===n||null===(i=n.update)||void 0===i||i.call(n)}),this._config.autoCleanup&&this.cleanup())},t.getStatus=function(){var e=this,t=[];return this._scenes.forEach(function(n,i){t.push({id:i,name:n.name||i,isActive:e._activeScenes.has(i)})}),{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:c({},this._config),scenes:t}},t.getStats=function(){var e=0,t=this._globalSystems.length;return this._scenes.forEach(function(n){var i,r,o,s;e+=null!==(i=null===(r=n.entities)||void 0===r?void 0:r.count)&&void 0!==i?i:0,t+=null!==(o=null===(s=n.systems)||void 0===s?void 0:s.length)&&void 0!==o?o:0}),{totalEntities:e,totalSystems:t,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}}},t.validateSceneName=function(e){if(null==e||!e.trim())throw new Error("Scene name不能为空");if(this._scenes.has(e))throw new Error("Scene name '"+e+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes)},t.isCleanupCandidate=function(e,t){var n=Date.now()-this._createdAt;return!this._activeScenes.has(e)&&null!=t.entities&&0===t.entities.count&&n>this._config.cleanupThresholdMs},t.cleanup=function(){var e=this,t=[];this._scenes.forEach(function(n,i){e.isCleanupCandidate(i,n)&&t.push(i)}),t.forEach(function(t){e.removeScene(t),fn.debug("自动清理空Scene: "+t+" from World "+e.name)})},s(e,[{key:"services",get:function(){return this._services}},{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),vn=function(){function e(e){this._nextScene=null,this._ecsAPI=null,this._logger=Z("SceneManager"),this._performanceMonitor=null,this._pendingPersistentEntities=[],this._defaultWorld=new mn({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}var t=e.prototype;return t.setSceneChangedCallback=function(e){this._onSceneChangedCallback=e},t.setScene=function(t){var n=this.currentScene;return n&&n instanceof on&&(this._pendingPersistentEntities=n.extractPersistentEntities(),this._pendingPersistentEntities.length>0&&this._logger.debug("Extracted "+this._pendingPersistentEntities.length+" persistent entities for migration")),this._defaultWorld.removeAllScenes(),this._performanceMonitor&&t.services.registerInstance(O,this._performanceMonitor),this._defaultWorld.createScene(e.DEFAULT_SCENE_ID,t),this._defaultWorld.setSceneActive(e.DEFAULT_SCENE_ID,!0),this._pendingPersistentEntities.length>0&&t instanceof on&&(t.receiveMigratedEntities(this._pendingPersistentEntities),this._logger.debug("Migrated "+this._pendingPersistentEntities.length+" persistent entities to new scene"),this._pendingPersistentEntities=[]),t.querySystem&&t.eventSystem?this._ecsAPI=hn(t,t.querySystem,t.eventSystem):this._ecsAPI=null,_.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info("Scene changed to: "+t.name),t},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()},t.destroy=function(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},s(e,[{key:"currentScene",get:function(){return this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();vn.DEFAULT_SCENE_ID="__main__",e.DebugConfigService=function(){function e(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}var t=e.prototype;return t.setConfig=function(e){this._config=e},t.getConfig=function(){return this._config},t.isEnabled=function(){return this._config.enabled},t.dispose=function(){},e}(),e.DebugConfigService=g([T(),y("design:paramtypes",[])],e.DebugConfigService),e.DebugManager=function(){function e(){this.frameCounter=0,this.lastSendTime=0,this.sendInterval=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)}}var t=e.prototype;return t.onInitialize=function(){this.config=this.configService.getConfig(),this.entityCollector=new je,this.systemCollector=new Ue,this.performanceCollector=new qe,this.componentCollector=new Ye,this.sceneCollector=new Ze,this.advancedProfilerCollector=new tt,et.setEnabled(!0),this.webSocketManager=new Xe(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var e=this.config.debugFrameRate||30;this.sendInterval=1e3/e,this.interceptConsole(),this.start()},t.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},t.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},t.interceptConsole=function(){var e=this;console.log=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).log.apply(t,i)},console.debug=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("debug",e.formatLogMessage(i)),(t=e.originalConsole).debug.apply(t,i)},console.info=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).info.apply(t,i)},console.warn=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("warn",e.formatLogMessage(i)),(t=e.originalConsole).warn.apply(t,i)},console.error=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("error",e.formatLogMessage(i)),(t=e.originalConsole).error.apply(t,i)}},t.formatLogMessage=function(e){var t=this;return e.map(function(e){if("string"==typeof e)return e;if(e instanceof Error)return e.name+": "+e.message;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return t.safeStringify(e,6)}catch(t){return Object.prototype.toString.call(e)}return String(e)}).join(" ")},t.safeStringify=function(e,t){void 0===t&&(t=6);var n=new WeakSet,i=function(e,r){if(null===e)return null;if(void 0!==e){if("object"!=typeof e)return e;if(r>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){var o=e.map(function(e){return i(e,r+1)});return n.delete(e),o}var s={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(s[a]=i(e[a],r+1));return n.delete(e),s}};return JSON.stringify(i(e,0))},t.sendLog=function(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}},t.updateConfig=function(e){this.config=e;var t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new Xe(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},t.update=function(e){if(this.isRunning&&this.config.enabled){this.frameCounter++;var t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}},t.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},t.handleMessage=function(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig(c({},this.config,e.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"get_advanced_profiler_data":this.handleGetAdvancedProfilerDataRequest(e);break;case"set_profiler_selected_function":this.handleSetProfilerSelectedFunction(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleExpandLazyObjectRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.propertyPath,r=e.requestId;if(void 0===t||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var o=this.sceneManager.currentScene,s=this.entityCollector.expandLazyObject(t,n,i,o);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:s})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetComponentPropertiesRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.sceneManager.currentScene,o=this.entityCollector.getComponentProperties(t,n,r);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:o})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetRawEntityListRequest=function(e){try{var t=e.requestId,n=this.sceneManager.currentScene,i=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:i})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetEntityDetailsRequest=function(e){try{var t=e.entityId,n=e.requestId;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.sceneManager.currentScene,r=this.entityCollector.getEntityDetails(t,i);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetAdvancedProfilerDataRequest=function(e){try{var t=e.requestId,n=et.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):this.advancedProfilerCollector.collectFromLegacyMonitor(this.performanceMonitor);this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:t,data:n})}catch(t){this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleSetProfilerSelectedFunction=function(e){try{var t=e.functionName,n=e.requestId;this.advancedProfilerCollector.setSelectedFunction(t||null),this.sendDebugData(),this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:n,success:!0})}catch(t){this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,i=this.entityCollector.collectEntityDataWithMemory(n),r=null!=n&&n.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},o=this.collectSystemMemoryStats(),s=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=i.entitiesPerArchetype.reduce(function(e,t){return e+t.memory},0);return{timestamp:e,version:"2.0",summary:{totalEntities:i.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:o.totalMemory,poolMemory:s.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:o,pools:s,performance:a}},t.collectBaseMemoryInfo=function(){var e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var t=performance;if(t.memory){var n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then(function(t){e.detailedMemory=t}).catch(function(){})}catch(e){}return e},t.collectComponentMemoryStats=function(e){for(var t,n=new Map,i=0,r=new Map,o=a(e.buffer);!(t=o()).done;){var s=t.value;if(s&&!s.destroyed&&s.components)for(var c,u=a(s.components);!(c=u()).done;){var l=W(c.value);r.set(l,(r.get(l)||0)+1)}}for(var h,d=a(r.entries());!(h=d()).done;){var f=h.value,p=f[0],m=f[1],v=this.componentCollector.calculateDetailedComponentMemory(p),g=v*m;i+=g;for(var y,_=[],S=0,C=a(e.buffer);!(y=C()).done;){var E=y.value;if(E&&!E.destroyed&&E.components){for(var b,T=a(E.components);!(b=T()).done;){if(W(b.value)===p&&(_.push({entityId:E.id,entityName:E.name||"Entity_"+E.id,memory:v}),++S>=100))break}if(S>=100)break}}n.set(p,{count:m,totalMemory:g,instances:_.slice(0,10)})}var w=Array.from(n.entries()).map(function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort(function(e,t){return t.memory-e.memory}).slice(0,3)}}).sort(function(e,t){return t.totalMemory-e.totalMemory});return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce(function(e,t){return e+t.count},0),breakdown:w}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var i=null==e?void 0:e.systems;if(i)for(var r,o=new Map,s=a(i);!(r=s()).done;){var c=r.value,u=oe(c),l=void 0;o.has(u)?l=o.get(u):(l=this.calculateQuickSystemSize(c),o.set(u,l)),t+=l,n.push({name:u,memory:l,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort(function(e,t){return t.memory-e.memory})}},t.calculateQuickSystemSize=function(e){if(!e||"object"!=typeof e)return 64;var t=128;try{for(var n=Object.keys(e),i=0;i<Math.min(n.length,15);i++){var r=n[i];if(r&&"entities"!==r&&"scene"!==r&&"constructor"!==r){var o=e[r];t+=2*r.length,"string"==typeof o?t+=Math.min(2*o.length,100):"number"==typeof o?t+=8:"boolean"==typeof o?t+=4:Array.isArray(o)?t+=40+Math.min(8*o.length,200):"object"==typeof o&&null!==o&&(t+=64)}}}catch(e){return 128}return Math.max(t,64)},t.collectPoolMemoryStats=function(){var e=0,t=[];try{for(var n,i=a(Ve.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,o=r[0],s=r[1],c=32*s.maxSize;e+=c,t.push({typeName:o,maxSize:s.maxSize,currentSize:s.currentSize||0,estimatedMemory:c,utilization:s.currentSize?s.currentSize/s.maxSize*100:0})}}catch(e){}try{for(var u=x.getAllPoolStats(),l=0,h=Object.entries(u);l<h.length;l++){var d=h[l],f=d[0],p=d[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+f,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort(function(e,t){return t.estimatedMemory-e.estimatedMemory})}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map(function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}}).sort(function(e,t){return t.averageTime-e.averageTime}).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}},e,this,[[0,2]])}));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData(),advancedProfiler:et.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):null};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error},e}(),g([I(vn),y("design:type",vn)],e.DebugManager.prototype,"sceneManager",void 0),g([I(O),y("design:type",O)],e.DebugManager.prototype,"performanceMonitor",void 0),g([I(e.DebugConfigService),y("design:type",e.DebugConfigService)],e.DebugManager.prototype,"configService",void 0),e.DebugManager=g([T(),w()],e.DebugManager),e.PluginState=void 0,(dn=e.PluginState||(e.PluginState={})).NotInstalled="not_installed",dn.Installed="installed",dn.Failed="failed";var gn=Z("PluginManager"),yn=function(){function t(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var n=t.prototype;return n.initialize=function(e,t){this._core=e,this._services=t,gn.info("PluginManager initialized")},n.install=function(){var t=i(d().m(function t(n){var i,r;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this._core&&this._services){t.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(n.name)){t.n=2;break}return gn.warn("Plugin "+n.name+" is already installed"),t.a(2);case 2:return n.dependencies&&n.dependencies.length>0&&this._checkDependencies(n),i={name:n.name,version:n.version,state:e.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(n.name,i),t.p=3,gn.info("Installing plugin: "+n.name+" v"+n.version),t.n=4,n.install(this._core,this._services);case 4:this._plugins.set(n.name,n),i.state=e.PluginState.Installed,gn.info("Plugin "+n.name+" installed successfully"),t.n=6;break;case 5:throw t.p=5,r=t.v,i.state=e.PluginState.Failed,i.error=r instanceof Error?r.message:String(r),gn.error("Failed to install plugin "+n.name+":",r),r;case 6:return t.a(2)}},t,this,[[3,5]])}));return function(e){return t.apply(this,arguments)}}(),n.uninstall=function(){var e=i(d().m(function e(t){var n,i;return d().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,gn.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),gn.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,i=e.v,gn.error("Failed to uninstall plugin "+t+":",i),i;case 5:return e.a(2)}},e,this,[[2,4]])}));return function(t){return e.apply(this,arguments)}}(),n.getPlugin=function(e){return this._plugins.get(e)},n.getMetadata=function(e){return this._metadata.get(e)},n.getAllPlugins=function(){return Array.from(this._plugins.values())},n.getAllMetadata=function(){return Array.from(this._metadata.values())},n.isInstalled=function(e){return this._plugins.has(e)},n._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],i=a(e.dependencies);!(t=i()).done;){var r=t.value;this._plugins.has(r)||n.push(r)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},n._checkDependents=function(e){for(var t,n=[],i=a(this._plugins.values());!(t=i()).done;){var r=t.value;r.dependencies&&r.dependencies.includes(e)&&n.push(r.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},n.dispose=function(){for(var e,t=a(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{gn.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){gn.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,gn.info("PluginManager disposed")},t}();function _n(e){var t="@esengine/service:"+e;return{id:Symbol.for(t),name:e}}var Sn=function(){function e(){this._services=new Map}var t=e.prototype;return t.register=function(e,t){this._services.set(e.id,t)},t.get=function(e){return this._services.get(e.id)},t.require=function(e){var t=this._services.get(e.id);if(void 0===t)throw new Error("Service not found: "+e.name);return t},t.has=function(e){return this._services.has(e.id)},t.unregister=function(e){return this._services.delete(e.id)},t.clear=function(){this._services.clear()},t.dispose=function(){this.clear()},e}(),Cn=Z("WorldManager"),En={maxWorlds:50,autoCleanup:!0,cleanupFrameInterval:1800,debug:!1},bn=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._isRunning=!0,this._framesSinceCleanup=0,this._config=c({},En,e),Cn.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupFrameInterval:this._config.cleanupFrameInterval})}var t=e.prototype;return t.createWorld=function(e,t){var n;this.validateWorldName(e);var i=c({},t,{name:e,debug:null!==(n=null==t?void 0:t.debug)&&void 0!==n?n:this._config.debug}),r=new mn(i);return this._worlds.set(e,r),r},t.removeWorld=function(e){var t=this._worlds.get(e);return!!t&&(t.destroy(),this._worlds.delete(e),Cn.info("移除World: "+e),!0)},t.getWorld=function(e){var t;return null!==(t=this._worlds.get(e))&&void 0!==t?t:null},t.getWorldIds=function(){return Array.from(this._worlds.keys())},t.getAllWorlds=function(){return Array.from(this._worlds.values())},t.setWorldActive=function(e,t){var n=this._worlds.get(e);n?t?(n.start(),Cn.debug("激活World: "+e)):(n.stop(),Cn.debug("停用World: "+e)):Cn.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){var t,n;return null!==(t=null===(n=this._worlds.get(e))||void 0===n?void 0:n.isActive)&&void 0!==t&&t},t.getActiveWorlds=function(){var e=[];return this._worlds.forEach(function(t){t.isActive&&e.push(t)}),e},t.findWorlds=function(e){var t=[];return this._worlds.forEach(function(n){e(n)&&t.push(n)}),t},t.findWorldByName=function(e){var t=null;return this._worlds.forEach(function(n){n.name===e&&(t=n)}),t},t.startAll=function(){this._isRunning=!0,this._worlds.forEach(function(e){return e.start()}),Cn.info("启动所有World")},t.stopAll=function(){this._isRunning=!1,this._worlds.forEach(function(e){return e.stop()}),Cn.info("停止所有World")},t.destroy=function(){var e=this;Cn.info("正在销毁WorldManager..."),this.stopAll(),Array.from(this._worlds.keys()).forEach(function(t){return e.removeWorld(t)}),this._worlds.clear(),this._isRunning=!1,Cn.info("WorldManager已销毁")},t.dispose=function(){this.destroy()},t.updateAll=function(){this._isRunning&&(this._worlds.forEach(function(e){e.isActive&&(e.updateGlobalSystems(),e.updateScenes())}),this.processAutoCleanup())},t.getStats=function(){var e=0,t=0,n=0,i=[];return this._worlds.forEach(function(r,o){var s=r.getStats();e+=r.sceneCount,t+=s.totalEntities,n+=s.totalSystems,i.push(c({id:o,name:r.name,isActive:r.isActive,sceneCount:r.sceneCount},s))}),{totalWorlds:this._worlds.size,activeWorlds:this.activeWorldCount,totalScenes:e,totalEntities:t,totalSystems:n,memoryUsage:0,isRunning:this._isRunning,config:c({},this._config),worlds:i}},t.getDetailedStatus=function(){var e=[];return this._worlds.forEach(function(t,n){e.push({id:n,isActive:t.isActive,status:t.getStatus()})}),c({},this.getStats(),{worlds:e})},t.cleanup=function(){var e=this,t=[];return this._worlds.forEach(function(n,i){e.isCleanupCandidate(n)&&t.push(i)}),t.forEach(function(t){return e.removeWorld(t)}),t.length>0&&Cn.debug("清理了 "+t.length+" 个World"),t.length},t.validateWorldName=function(e){if(null==e||!e.trim())throw new Error("World name不能为空");if(this._worlds.has(e))throw new Error("World name '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds)},t.processAutoCleanup=function(){this._config.autoCleanup&&(this._framesSinceCleanup++,this._framesSinceCleanup>=this._config.cleanupFrameInterval&&(this.cleanup(),this._framesSinceCleanup=0,this._config.debug&&Cn.debug("执行定期清理World (间隔: "+this._config.cleanupFrameInterval+" 帧)")))},t.isCleanupCandidate=function(e){return!e.isActive&&(!(Date.now()-e.createdAt<=6e5)&&(0===e.sceneCount||!e.getAllScenes().some(function(e){return e.entities&&e.entities.count>0})))},s(e,[{key:"worldCount",get:function(){return this._worlds.size}},{key:"activeWorldCount",get:function(){var e=0;return this._worlds.forEach(function(t){t.isActive&&e++}),e}},{key:"isRunning",get:function(){return this._isRunning}},{key:"config",get:function(){return c({},this._config)}}])}(),Tn=function(){function t(n){var i,r,o=this;if(void 0===n&&(n={}),t._instance=this,this._config=c({debug:!0},n),this._serviceContainer=new Jt,this._timerManager=new e.TimerManager,this._serviceContainer.registerInstance(e.TimerManager,this._timerManager),this._performanceMonitor=new O,this._serviceContainer.registerInstance(O,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new z,this._serviceContainer.registerInstance(z,this._poolManager),this._sceneManager=new vn(this._performanceMonitor),this._serviceContainer.registerInstance(vn,this._sceneManager),this._sceneManager.setSceneChangedCallback(function(){var e;return null===(e=o._debugManager)||void 0===e?void 0:e.onSceneChanged()}),this._worldManager=new bn(c({debug:!!this._config.debug},this._config.worldManagerConfig)),this._serviceContainer.registerInstance(bn,this._worldManager),this._pluginManager=new yn,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(yn,this._pluginManager),this._pluginServiceRegistry=new Sn,this._serviceContainer.registerInstance(Sn,this._pluginServiceRegistry),this.debug=null===(i=this._config.debug)||void 0===i||i,null!==(r=this._config.debugConfig)&&void 0!==r&&r.enabled){var s=new e.DebugConfigService;s.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(e.DebugConfigService,s),this._serviceContainer.registerSingleton(e.DebugManager,function(t){return A(e.DebugManager,t)}),this._debugManager=this._serviceContainer.resolve(e.DebugManager),this._debugManager.onInitialize()}this.initialize()}t.create=function(e){if(void 0===e&&(e=!0),null==this._instance){var n="boolean"==typeof e?{debug:e}:e;this._instance=new t(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},t.setScene=function(e){if(!this._instance)throw t._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(e)},t.loadScene=function(e){this._instance?this._instance._sceneManager.loadScene(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.update=function(e){this._instance?this._instance.updateInternal(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.schedule=function(e,t,n,i){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,i)},t.enableDebug=function(n){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(n);else{var i=new e.DebugConfigService;i.setConfig(n),this._instance._serviceContainer.registerInstance(e.DebugConfigService,i),this._instance._serviceContainer.registerSingleton(e.DebugManager,function(t){return A(e.DebugManager,t)}),this._instance._debugManager=this._instance._serviceContainer.resolve(e.DebugManager),this._instance._debugManager.onInitialize()}this._instance._config.debugConfig=n}else t._logger.warn("Core实例未创建,请先调用Core.create()")},t.disableDebug=function(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),delete this._instance._debugManager),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))},t.getDebugData=function(){var e;return null!==(e=this._instance)&&void 0!==e&&e._debugManager?this._instance._debugManager.getDebugData():null},t.installPlugin=function(){var e=i(d().m(function e(t){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),t.uninstallPlugin=function(){var e=i(d().m(function e(t){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},t.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var n=t.prototype;return n.initialize=function(){var e;t._logger.info("Core initialized",{debug:this.debug,debugEnabled:(null===(e=this._config.debugConfig)||void 0===e?void 0:e.enabled)||!1})},n.updateInternal=function(e){var n,i;if(!t.paused){var r=this._performanceMonitor.startMonitoring("Core.update");_.update(e),null===(n=(i=this._performanceMonitor).updateFPS)||void 0===n||n.call(i,_.deltaTime);var o=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",o,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",r)}},t.destroy=function(){var e;this._instance&&(null===(e=this._instance._debugManager)||void 0===e||e.stop(),this._instance._serviceContainer.clear(),t._logger.info("Core destroyed"),this._instance=null)},s(t,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"pluginServices",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._pluginServiceRegistry}},{key:"worldManager",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._worldManager}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}},{key:"performanceMonitor",get:function(){var e;return(null===(e=this._instance)||void 0===e?void 0:e._performanceMonitor)||null}}])}();Tn.paused=!1,Tn._instance=null,Tn._logger=Z("Core");var wn=_n("runtimeMode"),In=function(){function e(e){var t,n,i;void 0===e&&(e={}),this._callbacks=new Set,this._isEditor=null!==(t=e.isEditor)&&void 0!==t&&t,this._isPlaying=null!==(n=e.isPlaying)&&void 0!==n&&n,this._isPreview=null!==(i=e.isPreview)&&void 0!==i&&i}var t=e.prototype;return t.onModeChanged=function(e){var t=this;return this._callbacks.add(e),function(){t._callbacks.delete(e)}},t.setEditorMode=function(e){this._isEditor!==e&&(this._isEditor=e,this._notifyChange())},t.setPlaying=function(e){this._isPlaying!==e&&(this._isPlaying=e,this._notifyChange())},t.setPreview=function(e){this._isPreview!==e&&(this._isPreview=e,this._notifyChange())},t.updateMode=function(e){var t=!1;void 0!==e.isEditor&&this._isEditor!==e.isEditor&&(this._isEditor=e.isEditor,t=!0),void 0!==e.isPlaying&&this._isPlaying!==e.isPlaying&&(this._isPlaying=e.isPlaying,t=!0),void 0!==e.isPreview&&this._isPreview!==e.isPreview&&(this._isPreview=e.isPreview,t=!0),t&&this._notifyChange()},t._notifyChange=function(){for(var t,n=a(this._callbacks);!(t=n()).done;){var i=t.value;try{i(this)}catch(t){e._logger.error("Callback error:",t)}}},t.dispose=function(){this._callbacks.clear()},s(e,[{key:"isEditor",get:function(){return this._isEditor}},{key:"isPlaying",get:function(){return this._isPlaying}},{key:"isPreview",get:function(){return this._isPreview}},{key:"isStandalone",get:function(){return!this._isEditor}}])}();In._logger=Z("RuntimeModeService");var Mn=Z("DebugPlugin");e.DebugPlugin=function(){function e(e){var t,n;this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=null!==(t=null==e?void 0:e.autoStart)&&void 0!==t&&t,this.updateInterval=null!==(n=null==e?void 0:e.updateInterval)&&void 0!==n?n:1e3}var t=e.prototype;return t.install=function(){var e=i(d().m(function e(t,n){return d().w(function(e){for(;;)switch(e.n){case 0:this.worldManager=n.resolve(bn),Mn.info("ECS Debug Plugin installed"),this.autoStart&&this.start();case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.n){case 0:this.stop(),this.worldManager=null,Mn.info("ECS Debug Plugin uninstalled");case 1:return e.a(2)}},e,this)}));return function(){return e.apply(this,arguments)}}(),t.dispose=function(){this.stop(),this.worldManager=null},t.start=function(){var e=this;this.updateTimer?Mn.warn("Debug monitoring already started"):(Mn.info("Starting debug monitoring"),this.updateTimer=setInterval(function(){e.logStats()},this.updateInterval))},t.stop=function(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,Mn.info("Debug monitoring stopped"))},t.getStats=function(){if(!this.worldManager)throw new Error("Plugin not installed");for(var e,t=[],n=0,i=0,r=a(this.worldManager.getAllWorlds());!(e=r()).done;)for(var o,s=a(e.value.getAllScenes());!(o=s()).done;){var c=o.value,u=this.getSceneInfo(c);t.push(u),n+=u.entityCount,i+=u.systems.length}return{scenes:t,totalEntities:n,totalSystems:i,timestamp:Date.now()}},t.getSceneInfo=function(e){var t=this,n=e.entities.buffer,i=e.systems;return{name:e.name,entityCount:n.length,systems:i.map(function(e){return t.getSystemInfo(e)}),entities:n.map(function(e){return t.getEntityInfo(e)})}},t.getSystemInfo=function(e){var t=e.getPerformanceStats(),n=t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0;return c({name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length},void 0!==n&&{performance:n})},t.getEntityInfo=function(e){var t=this,n=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:n.length,components:n.map(function(e){return t.getComponentInfo(e)})}},t.getComponentInfo=function(e){for(var t=e.constructor.name,n={},i=0,r=Object.keys(e);i<r.length;i++){var o=r[i];if(!o.startsWith("_")){var s=e[o];"function"!=typeof s&&(n[o]=s)}}return{type:t,data:n}},t.queryEntities=function(e){if(!this.worldManager)throw new Error("Plugin not installed");for(var t,n=[],i=a(this.worldManager.getAllWorlds());!(t=i()).done;)for(var r,o=a(t.value.getAllScenes());!(r=o()).done;){var s=r.value;if(!e.sceneName||s.name===e.sceneName)for(var c,u=a(s.entities.buffer);!(c=u()).done;){var l=c.value;if((void 0===e.tag||l.tag===e.tag)&&(!e.name||l.name.includes(e.name))){if(e.hasComponent)if(!l.components.some(function(t){return t.constructor.name===e.hasComponent}))continue;n.push(this.getEntityInfo(l))}}}return n},t.logStats=function(){var e=this.getStats();Mn.info("=== ECS Debug Stats ==="),Mn.info("Total Entities: "+e.totalEntities),Mn.info("Total Systems: "+e.totalSystems),Mn.info("Scenes: "+e.scenes.length);for(var t,n=a(e.scenes);!(t=n()).done;){var i=t.value;Mn.info("\n[Scene: "+i.name+"]"),Mn.info(" Entities: "+i.entityCount),Mn.info(" Systems: "+i.systems.length);for(var r,o=a(i.systems);!(r=o()).done;){var s=r.value,c=s.performance?" | Avg: "+s.performance.avgExecutionTime.toFixed(2)+"ms, Max: "+s.performance.maxExecutionTime.toFixed(2)+"ms":"";Mn.info(" - "+s.name+" ("+(s.enabled?"enabled":"disabled")+") | Entities: "+s.entityCount+c)}}Mn.info("========================\n")},t.exportJSON=function(){var e=this.getStats();return JSON.stringify(e,null,2)},e}(),e.DebugPlugin=g([T(),y("design:paramtypes",[Object])],e.DebugPlugin);var An,kn,Dn=function(e,t){this.func=e,this.context=t},Pn=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,t)||i.push(new Dn(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var i=n.findIndex(function(e){return e.func==t});-1!=i&&n.splice(i,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var o,s=a(t);!(o=s()).done;){var c,u=o.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},t.hasObserver=function(e,t){var n=this._messageTable.get(e);return!!n&&n.some(function(e){return e.func===t})},t.removeAllObservers=function(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()},t.dispose=function(){this._messageTable.clear()},t.getEventTypeCount=function(){return this._messageTable.size},t.getObserverCount=function(e){var t=this._messageTable.get(e);return t?t.length:0},e}(),On=function(){function e(){this._enabled=!1}var t=e.prototype;return t.setEnabled=function(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())},t.onEnabled=function(){},t.onDisabled=function(){},t.update=function(){},s(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this.setEnabled(e)}}])}();e.ECSEventType=void 0,(An=e.ECSEventType||(e.ECSEventType={})).ENTITY_CREATED="entity:created",An.ENTITY_DESTROYED="entity:destroyed",An.ENTITY_ENABLED="entity:enabled",An.ENTITY_DISABLED="entity:disabled",An.ENTITY_TAG_ADDED="entity:tag:added",An.ENTITY_TAG_REMOVED="entity:tag:removed",An.ENTITY_NAME_CHANGED="entity:name:changed",An.COMPONENT_ADDED="component:added",An.COMPONENT_REMOVED="component:removed",An.COMPONENT_MODIFIED="component:modified",An.COMPONENT_ENABLED="component:enabled",An.COMPONENT_DISABLED="component:disabled",An.SYSTEM_ADDED="system:added",An.SYSTEM_REMOVED="system:removed",An.SYSTEM_ENABLED="system:enabled",An.SYSTEM_DISABLED="system:disabled",An.SYSTEM_PROCESSING_START="system:processing:start",An.SYSTEM_PROCESSING_END="system:processing:end",An.SYSTEM_ERROR="system:error",An.SCENE_CREATED="scene:created",An.SCENE_DESTROYED="scene:destroyed",An.SCENE_ACTIVATED="scene:activated",An.SCENE_DEACTIVATED="scene:deactivated",An.SCENE_PAUSED="scene:paused",An.SCENE_RESUMED="scene:resumed",An.QUERY_EXECUTED="query:executed",An.QUERY_CACHE_HIT="query:cache:hit",An.QUERY_CACHE_MISS="query:cache:miss",An.QUERY_OPTIMIZED="query:optimized",An.PERFORMANCE_WARNING="performance:warning",An.PERFORMANCE_CRITICAL="performance:critical",An.MEMORY_USAGE_HIGH="memory:usage:high",An.FRAME_RATE_DROP="frame:rate:drop",An.INDEX_CREATED="index:created",An.INDEX_UPDATED="index:updated",An.INDEX_OPTIMIZED="index:optimized",An.ARCHETYPE_CREATED="archetype:created",An.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",An.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",An.DIRTY_MARK_ADDED="dirty:mark:added",An.DIRTY_BATCH_PROCESSED="dirty:batch:processed",An.ERROR_OCCURRED="error:occurred",An.WARNING_ISSUED="warning:issued",An.FRAMEWORK_INITIALIZED="framework:initialized",An.FRAMEWORK_SHUTDOWN="framework:shutdown",An.DEBUG_INFO="debug:info",An.DEBUG_STATS_UPDATED="debug:stats:updated",e.EventPriority=void 0,(kn=e.EventPriority||(e.EventPriority={}))[kn.LOWEST=0]="LOWEST",kn[kn.LOW=25]="LOW",kn[kn.NORMAL=50]="NORMAL",kn[kn.HIGH=75]="HIGH",kn[kn.HIGHEST=100]="HIGHEST",kn[kn.CRITICAL=200]="CRITICAL";var xn={ENTITY:{CREATED:e.ECSEventType.ENTITY_CREATED,DESTROYED:e.ECSEventType.ENTITY_DESTROYED,ENABLED:e.ECSEventType.ENTITY_ENABLED,DISABLED:e.ECSEventType.ENTITY_DISABLED,TAG_ADDED:e.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:e.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:e.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:e.ECSEventType.COMPONENT_ADDED,REMOVED:e.ECSEventType.COMPONENT_REMOVED,MODIFIED:e.ECSEventType.COMPONENT_MODIFIED,ENABLED:e.ECSEventType.COMPONENT_ENABLED,DISABLED:e.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:e.ECSEventType.SYSTEM_ADDED,REMOVED:e.ECSEventType.SYSTEM_REMOVED,ENABLED:e.ECSEventType.SYSTEM_ENABLED,DISABLED:e.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:e.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:e.ECSEventType.SYSTEM_PROCESSING_END,ERROR:e.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:e.ECSEventType.PERFORMANCE_WARNING,CRITICAL:e.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:e.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:e.ECSEventType.FRAME_RATE_DROP}},Rn=function(){function e(){}return e.isValid=function(e){return this.validTypes.has(e)},e.getAllValidTypes=function(){return Array.from(this.validTypes)},e.addCustomType=function(e){this.validTypes.add(e)},e.removeCustomType=function(e){this.validTypes.delete(e)},e}();Rn.validTypes=new Set([].concat(Object.values(e.ECSEventType),Object.values(xn.ENTITY),Object.values(xn.COMPONENT),Object.values(xn.SYSTEM),Object.values(xn.PERFORMANCE)));var zn=function(e){function t(t){return e.call(this,t)||this}return l(t,e),t.prototype.process=function(e){this.processSystem()},t}(We),Nn=function(e){function t(t){return e.call(this,t)||this}return l(t,e),t.prototype.process=function(e){},t}(We),Fn=function(e){function t(t,n){var i;return(i=e.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=t,i}l(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=_.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(We),Bn=function(){function e(){this._adapter=null,this._logger=Z("PlatformManager")}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.getAdapter=function(){if(!this._adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this._adapter},t.registerAdapter=function(e){this._adapter=e,this._logger.info("平台适配器已注册: "+e.name,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})},t.hasAdapter=function(){return null!==this._adapter},t.getAdapterInfo=function(){return this._adapter?{name:this._adapter.name,version:this._adapter.version,config:this._adapter.getPlatformConfig()}:null},t.supportsFeature=function(e){if(!this._adapter)return!1;var t=this._adapter.getPlatformConfig();switch(e){case"worker":return this._adapter.isWorkerSupported();case"shared-array-buffer":return this._adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}},t.getBasicWorkerConfig=function(){if(!this._adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};var e=this._adapter.getPlatformConfig();return{platformSupportsWorker:this._adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this._adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}},t.getFullPlatformConfig=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._adapter){e.n=1;break}throw new Error("平台适配器未注册");case 1:if("function"!=typeof this._adapter.getPlatformConfigAsync){e.n=3;break}return e.n=2,this._adapter.getPlatformConfigAsync();case 2:return e.a(2,e.v);case 3:return e.a(2,this._adapter.getPlatformConfig())}},e,this)}));return function(){return e.apply(this,arguments)}}(),e}(),Ln="Worker pool has been destroyed",Hn=function(){function e(e,t){this.workerStates=new Map,this.pendingTasks=new Map,this.taskQueue=[],this.taskCounter=0,this._isDestroyed=!1,this.workers=e,this.initializeWorkers(t)}var t=e.prototype;return t.executeSharedBuffer=function(e){return this.createTask("shared-"+ ++this.taskCounter,c({},e,{type:"shared"}),function(){})},t.execute=function(e){return this.createTask("task-"+ ++this.taskCounter,e,function(e){return e})},t.getStatus=function(){for(var e,t={idle:0,busy:0,initializing:0},n=a(this.workerStates.values());!(e=n()).done;){var i=e.value;1===i?t.idle++:2===i?t.busy++:0===i&&t.initializing++}return c({total:this.workers.length},t,{queuedTasks:this.taskQueue.length})},t.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0;for(var e,t=new Error(Ln),n=a(this.pendingTasks.values());!(e=n()).done;){e.value.reject(t)}for(var i,r=a(this.taskQueue);!(i=r()).done;){i.value.reject(t)}for(var o,s=a(this.workers);!(o=s()).done;){o.value.terminate()}this.workers.length=0,this.taskQueue.length=0,this.pendingTasks.clear(),this.workerStates.clear()}},t.initializeWorkers=function(e){for(var t=this,n=function(n){var i=t.workers[n];if(!i)return 1;t.workerStates.set(n,e?0:1),i.onMessage(function(e){return t.handleMessage(n,e.data)}),i.onError(function(e){return t.handleError(n,e)}),e&&i.postMessage({type:"init",sharedBuffer:e})},i=0;i<this.workers.length;i++)n(i)},t.createTask=function(e,t,n){var i=this;return new Promise(function(r,o){i._isDestroyed?o(new Error(Ln)):i.enqueueTask({id:e,data:t,resolve:function(e){return r(n(e))},reject:o})})},t.enqueueTask=function(e){this.taskQueue.push(e),this.dispatchTasks()},t.dispatchTasks=function(){for(;this.taskQueue.length>0;){var e=this.findIdleWorker();if(-1===e)break;var t=this.taskQueue.shift();this.assignTask(e,t)}},t.findIdleWorker=function(){for(var e=0;e<this.workers.length;e++)if(1===this.workerStates.get(e))return e;return-1},t.assignTask=function(e,t){var n=this.workers[e];n&&(this.workerStates.set(e,2),this.pendingTasks.set(e,t),n.postMessage(c({id:t.id},t.data)))},t.handleMessage=function(e,t){if("init"===t.type)return this.workerStates.set(e,1),void this.dispatchTasks();t.error?this.completeTask(e,new Error(t.error)):this.completeTask(e,void 0,t.result)},t.handleError=function(e,t){this.completeTask(e,new Error(t.message))},t.completeTask=function(e,t,n){var i=this.pendingTasks.get(e);i&&(this.pendingTasks.delete(e),this.workerStates.set(e,1),t?i.reject(t):i.resolve(n),this.dispatchTasks())},s(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"workerCount",get:function(){return this.workers.length}},{key:"isReady",get:function(){if(this._isDestroyed)return!1;for(var e,t=a(this.workerStates.values());!(e=t()).done;){if(0===e.value)return!1}return this.workers.length>0}},{key:"hasPendingTasks",get:function(){return this.taskQueue.length>0||this.pendingTasks.size>0}}])}(),Wn=function(e){function t(t,n){var i;return void 0===n&&(n={}),(i=e.call(this,t)||this).sharedBuffer=null,i.sharedFloatArray=null,i.workerPool=null,i.isProcessing=!1,i.hasLoggedSyncMode=!1,i.platformAdapter=Bn.getInstance().getAdapter(),i.config=i.resolveConfig(n),i.config.enableWorker&&i.isWorkerSupported()&&i.initializeWorkerSystem(),i}l(t,e);var n=t.prototype;return n.resolveConfig=function(e){var t,n,i,r,o,s=this.getMaxSystemWorkerCount(),a=null!==(t=e.workerCount)&&void 0!==t?t:s,u=Math.min(a,s);return a>s&&this.logger.warn("请求 "+a+" 个 Worker,但系统最多支持 "+s+" 个。实际使用 "+u+" 个 Worker。"),c({enableWorker:null===(n=e.enableWorker)||void 0===n||n,workerCount:u,useSharedArrayBuffer:null!==(i=e.useSharedArrayBuffer)&&void 0!==i?i:this.isSharedArrayBufferSupported(),entityDataSize:null!==(r=e.entityDataSize)&&void 0!==r?r:this.getDefaultEntityDataSize(),maxEntities:null!==(o=e.maxEntities)&&void 0!==o?o:1e4,systemConfig:e.systemConfig},void 0!==e.entitiesPerWorker&&{entitiesPerWorker:e.entitiesPerWorker},void 0!==e.workerScriptPath&&{workerScriptPath:e.workerScriptPath})},n.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},n.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},n.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},n.initializeWorkerSystem=function(){this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool()},n.initializeSharedArrayBuffer=function(){try{if(!this.isSharedArrayBufferSupported())return void this.fallbackToSingleWorker("平台不支持 SharedArrayBuffer");var e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer),this.logger.info(this.systemName+": SharedArrayBuffer 初始化成功 ("+e+" bytes)"))}catch(e){this.fallbackToSingleWorker("SharedArrayBuffer 初始化失败"),this.logger.warn(this.systemName+":",e)}},n.fallbackToSingleWorker=function(e){this.logger.warn(this.systemName+": "+e+",降级到单 Worker 模式"),this.config.useSharedArrayBuffer=!1,this.config.workerCount=1,this.sharedBuffer=null,this.sharedFloatArray=null},n.initializeWorkerPool=function(){try{var e=this.resolveWorkerScript();if(!e)return void(this.config.enableWorker=!1);var t=this.createWorkers(e);this.workerPool=new Hn(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker 池初始化失败",e),this.config.enableWorker=!1}},n.resolveWorkerScript=function(){var e,t=this.platformAdapter.getPlatformConfig();if(this.config.workerScriptPath)return this.logger.info(this.systemName+": 使用外部 Worker 文件: "+this.config.workerScriptPath),this.config.workerScriptPath;if(null!==(e=t.limitations)&&void 0!==e&&e.noEval)return this.logger.error(this.systemName+": 当前平台不支持动态 Worker 脚本,请配置 workerScriptPath 指定预编译的 Worker 文件"),null;var n=this.createWorkerScript();return(t.workerScriptPrefix||"")+n},n.createWorkers=function(e){for(var t=[],n=0;n<this.config.workerCount;n++){var i=this.platformAdapter.createWorker(e,{name:this.systemName+"-Worker-"+n});t.push(i)}return t},n.createWorkerScript=function(){var e=this.extractFunctionBody(this.workerProcess.toString()),t=this.getSharedProcessFunctionBody();return"\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+this.config.entityDataSize+";\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n try {\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n if (type === 'shared') {\n if (!sharedFloatArray) {\n self.postMessage({ id, error: 'SharedArrayBuffer not initialized' });\n return;\n }\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null });\n return;\n }\n\n if (entities) {\n function workerProcess(entities, deltaTime, systemConfig) {\n "+e+"\n }\n\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n "+t+"\n }\n "},n.extractFunctionBody=function(e){var t=e.match(/\{([\s\S]*)\}/);if(!t||void 0===t[1])throw new Error("无法解析 workerProcess 方法");return t[1]},n.getSharedProcessFunctionBody=function(){var e,t=null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this);return t?"\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n "+this.extractFunctionBody(t.toString())+"\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n ":""},n.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;var n=this.getCurrentProcessingMode();try{switch(n){case"shared-buffer":this.processWithSharedArrayBuffer(e).finally(function(){t.isProcessing=!1});break;case"worker":this.processWithWorker(e).finally(function(){t.isProcessing=!1});break;default:this.processSynchronously(e),this.isProcessing=!1}}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},n.getCurrentProcessingMode=function(){return this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray?"shared-buffer":"worker":(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker 不可用,使用同步处理"),this.hasLoggedSyncMode=!0),"sync")},n.processWithSharedArrayBuffer=function(){var e=i(d().m(function e(t){var n;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.sharedFloatArray&&this.workerPool){e.n=1;break}return e.a(2);case 1:return this.writeEntitiesToBuffer(t),n=this.createBatchTasks(t.length,!0),e.n=2,Promise.all(n);case 2:this.readResultsFromBuffer(t);case 3:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),n.processWithWorker=function(){var e=i(d().m(function e(t){var n,i,r,o,s=this;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.workerPool){e.n=1;break}return e.a(2);case 1:return n=t.map(function(e){return s.extractEntityData(e)}),i=this.createDataBatches(n),r=_.deltaTime,e.n=2,Promise.all(i.map(function(e){return s.workerPool.execute({entities:e,deltaTime:r,systemConfig:s.config.systemConfig})}));case 2:o=e.v,this.applyBatchResults(t,o);case 3:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),n.processSynchronously=function(e){var t=this,n=e.map(function(e){return t.extractEntityData(e)}),i=_.deltaTime,r=this.workerProcess(n,i,this.config.systemConfig);r&&"function"==typeof r.then?r.then(function(n){t.applyResults(e,n)}):this.applyResults(e,r)},n.createDataBatches=function(e){return this.splitIntoBatches(e.length,function(t,n){return e.slice(t,n)})},n.createBatchTasks=function(e,t){var n=this;return this.splitIntoBatches(e,function(e,i){return t?n.workerPool.executeSharedBuffer({startIndex:e,endIndex:i,deltaTime:_.deltaTime,systemConfig:n.config.systemConfig}):Promise.resolve()})},n.splitIntoBatches=function(e,t){var n=[],i=this.config,r=i.workerCount,o=i.entitiesPerWorker;if(o)for(var s=0;s<e;s+=o){var a=Math.min(s+o,e);n.push(t(s,a))}else for(var c=Math.ceil(e/r),u=0;u<r;u++){var l=u*c,h=Math.min(l+c,e);l<e&&n.push(t(l,h))}return n},n.applyBatchResults=function(e,t){for(var n,i=0,r=a(t);!(n=r()).done;)for(var o,s=a(n.value);!(o=s()).done;){var c=o.value;i<e.length&&c&&this.applyResult(e[i],c),i++}},n.applyResults=function(e,t){for(var n=0;n<e.length&&n<t.length;n++)this.applyResult(e[n],t[n])},n.writeEntitiesToBuffer=function(e){if(this.sharedFloatArray)for(var t=Math.min(e.length,this.config.maxEntities),n=0;n<t;n++){var i=this.extractEntityData(e[n]),r=n*this.config.entityDataSize;this.writeEntityToBuffer(i,r)}},n.readResultsFromBuffer=function(e){if(this.sharedFloatArray)for(var t=Math.min(e.length,this.config.maxEntities),n=0;n<t;n++){var i=n*this.config.entityDataSize,r=this.readEntityFromBuffer(i);r&&this.applyResult(e[n],r)}},n.updateConfig=function(e){var t=c({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),i=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个 Worker,但系统最多支持 "+n+" 个。实际使用 "+i+" 个 Worker。"),e.workerCount=i}Object.assign(this.config,e),t.useSharedArrayBuffer!==this.config.useSharedArrayBuffer?this.reinitializeSystem():t.workerCount!==this.config.workerCount?this.reinitializeWorkerPool():!this.config.enableWorker&&this.workerPool?this.destroyWorkerPool():this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()},n.reinitializeSystem=function(){this.destroyWorkerPool(),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()},n.reinitializeWorkerPool=function(){this.destroyWorkerPool(),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},n.destroyWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},n.getWorkerInfo=function(){return c({enabled:this.config.enableWorker,workerCount:this.config.workerCount},void 0!==this.config.entitiesPerWorker&&{entitiesPerWorker:this.config.entitiesPerWorker},{maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:this.getCurrentProcessingMode()})},n.onDestroy=function(){e.prototype.onDestroy.call(this),this.destroyWorkerPool()},n.getLoggerName=function(){return oe(this)},t}(We);e.PrefabInstanceComponent=function(e){function t(t,n,i){var r;return void 0===t&&(t=""),void 0===n&&(n=""),void 0===i&&(i=!1),(r=e.call(this)||this).sourcePrefabGuid="",r.sourcePrefabPath="",r.isRoot=!1,r.rootInstanceEntityId=null,r.modifiedProperties=[],r.instantiatedAt=0,r.originalValues={},r.sourcePrefabGuid=t,r.sourcePrefabPath=n,r.isRoot=i,r.instantiatedAt=Date.now(),r}l(t,e);var n=t.prototype;return n.markPropertyModified=function(e,t){var n=e+"."+t;this.modifiedProperties.includes(n)||this.modifiedProperties.push(n)},n.isPropertyModified=function(e,t){var n=e+"."+t;return this.modifiedProperties.includes(n)},n.clearPropertyModified=function(e,t){var n=e+"."+t,i=this.modifiedProperties.indexOf(n);-1!==i&&this.modifiedProperties.splice(i,1)},n.clearAllModifications=function(){this.modifiedProperties=[],this.originalValues={}},n.storeOriginalValue=function(e,t,n){var i=e+"."+t;i in this.originalValues||(this.originalValues[i]=this.deepClone(n))},n.getOriginalValue=function(e){return this.originalValues[e]},n.hasOriginalValue=function(e,t){return e+"."+t in this.originalValues},n.deepClone=function(e){if(null==e)return e;if("object"==typeof e)try{return JSON.parse(JSON.stringify(e))}catch(t){return e}return e},t}(Me),g([Oe(),y("design:type",String)],e.PrefabInstanceComponent.prototype,"sourcePrefabGuid",void 0),g([Oe(),y("design:type",String)],e.PrefabInstanceComponent.prototype,"sourcePrefabPath",void 0),g([Oe(),y("design:type",Boolean)],e.PrefabInstanceComponent.prototype,"isRoot",void 0),g([Oe(),y("design:type",Object)],e.PrefabInstanceComponent.prototype,"rootInstanceEntityId",void 0),g([Oe(),y("design:type",Array)],e.PrefabInstanceComponent.prototype,"modifiedProperties",void 0),g([Oe(),y("design:type",Number)],e.PrefabInstanceComponent.prototype,"instantiatedAt",void 0),g([Oe(),y("design:type",Object)],e.PrefabInstanceComponent.prototype,"originalValues",void 0),e.PrefabInstanceComponent=g([te("PrefabInstance",{editor:{hideInInspector:!0}}),Pe({version:1,typeId:"PrefabInstance"}),y("design:paramtypes",[String,String,Boolean])],e.PrefabInstanceComponent);var Gn=function(){function t(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new At,this.isDebugMode=e}var n=t.prototype;return n.emit=function(e,n,i){void 0===i&&(i=!1),this.validateEventType(e);var r=i?this.enhanceEventData(e,n):n;this.isDebugMode&&t._logger.info("发射事件: "+e,r),this.eventSystem.emitSync(e,r)},n.emitAsync=function(){var e=i(d().m(function e(n,i,r){var o;return d().w(function(e){for(;;)switch(e.n){case 0:return void 0===r&&(r=!1),this.validateEventType(n),o=r?this.enhanceEventData(n,i):i,this.isDebugMode&&t._logger.info("发射异步事件: "+n,o),e.n=1,this.eventSystem.emit(n,o);case 1:return e.a(2)}},e,this)}));return function(t,n,i){return e.apply(this,arguments)}}(),n.on=function(n,i,r){void 0===r&&(r={}),this.validateEventType(n);var o={once:r.once||!1,priority:r.priority||e.EventPriority.NORMAL,async:r.async||!1};return r.thisArg&&(o.thisArg=r.thisArg),this.isDebugMode&&t._logger.info("添加监听器: "+n,o),this.eventSystem.on(n,i,o)},n.once=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,c({},n,{once:!0}))},n.onAsync=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,c({},n,{async:!0}))},n.off=function(e,n){return this.isDebugMode&&t._logger.info("移除监听器: "+n+" 事件: "+e),this.eventSystem.off(e,n)},n.offAll=function(e){this.isDebugMode&&t._logger.info("移除所有监听器: "+e),this.eventSystem.offAll(e)},n.hasListeners=function(e){return this.eventSystem.hasListeners(e)},n.getStats=function(e){var t=this,n=this.eventSystem.getStats(e);if(n instanceof Map){var i=new Map;return n.forEach(function(e,n){i.set(n,t.convertEventStats(e))}),i}return this.convertEventStats(n)},n.clear=function(){this.isDebugMode&&t._logger.info("清空所有监听器"),this.eventSystem.clear()},n.setEnabled=function(e){this.eventSystem.setEnabled(e)},n.setDebugMode=function(e){this.isDebugMode=e},n.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},n.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},n.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},n.flushBatch=function(e){this.eventSystem.flushBatch(e)},n.resetStats=function(e){this.eventSystem.resetStats(e)},n.emitEntityCreated=function(t){this.emit(e.ECSEventType.ENTITY_CREATED,t)},n.emitEntityDestroyed=function(t){this.emit(e.ECSEventType.ENTITY_DESTROYED,t)},n.emitComponentAdded=function(t){this.emit(e.ECSEventType.COMPONENT_ADDED,t)},n.emitComponentRemoved=function(t){this.emit(e.ECSEventType.COMPONENT_REMOVED,t)},n.emitSystemAdded=function(t){this.emit(e.ECSEventType.SYSTEM_ADDED,t)},n.emitSystemRemoved=function(t){this.emit(e.ECSEventType.SYSTEM_REMOVED,t)},n.emitSceneChanged=function(t){this.emit(e.ECSEventType.SCENE_ACTIVATED,t)},n.emitPerformanceWarning=function(t){this.emit(e.ECSEventType.PERFORMANCE_WARNING,t)},n.onEntityCreated=function(t,n){return this.on(e.ECSEventType.ENTITY_CREATED,t,n)},n.onComponentAdded=function(t,n){return this.on(e.ECSEventType.COMPONENT_ADDED,t,n)},n.onSystemError=function(t,n){return this.on(e.ECSEventType.SYSTEM_ERROR,t,n)},n.onPerformanceWarning=function(t,n){return this.on(e.ECSEventType.PERFORMANCE_WARNING,t,n)},n.validateEventType=function(e){this.isDebugMode&&(Rn.isValid(e)||(t._logger.warn("未知事件类型: "+e),Rn.addCustomType(e)))},n.enhanceEventData=function(e,t){if(null==t)return{timestamp:Date.now(),eventId:e+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=e+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},n.convertEventStats=function(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}},t}();Gn._logger=Z("EventBus");var jn=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this._instance||(this._instance=new Gn(e)),this._instance},e.reset=function(e){return void 0===e&&(e=!1),this._instance&&this._instance.clear(),this._instance=new Gn(e),this._instance},e}(),Un=Z("VersionMigration"),qn=function(){function e(){}return e.registerComponentMigration=function(e,t,n,i){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,i)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var i=this.componentMigrations.get(e.type);if(!i)return Un.warn("No migration path found for component "+e.type+" | 未找到组件 "+e.type+" 的迁移路径"),e;for(var r=c({},e),o=n;o<t;){var s=i.get(o);if(!s){Un.warn("Missing migration from version "+o+" to "+(o+1)+" for "+e.type+" | 缺少组件 "+e.type+" 从版本 "+o+" 到 "+(o+1)+" 的迁移");break}r.data=s(r.data,o,o+1),o++}return r.version=o,r},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var i=c({},e),r=n;r<t;){var o=this.sceneMigrations.get(r);if(!o){Un.warn("Missing scene migration from version "+r+" to "+(r+1)+" | 缺少场景从版本 "+r+" 到 "+(r+1)+" 的迁移");break}i=o(i,r,r+1),r++}return i.version=r,i=this.migrateSceneComponents(i)},e.migrateSceneComponents=function(e){var t=this,n=c({},e);return n.entities=e.entities.map(function(n){return c({},n,{components:n.components.map(function(n){var i=e.componentTypeRegistry.find(function(e){return e.typeName===n.type});return i&&i.version!==n.version?t.migrateComponent(n,i.version):n}),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})}),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map(function(e){return c({},e,{components:e.components.map(function(e){var i=t.find(function(t){return t.typeName===e.type});return i&&i.version!==e.version?n.migrateComponent(e,i.version):e}),children:n.migrateEntitiesComponents(e.children,t)})})},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort(function(e,t){return e-t}):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort(function(e,t){return e-t})},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var i=this.componentMigrations.get(e);if(!i)return!1;for(var r=t;r<n;r++)if(!i.has(r))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();qn.componentMigrations=new Map,qn.sceneMigrations=new Map;var Qn=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?qn.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):qn.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}(),Vn=function(){function t(){}return t.createPrefab=function(e,t,n){var i,r=null===(i=t.includeChildren)||void 0===i||i,o=Ft.serialize(e,r,n),s=this.toPrefabEntity(o,!0),a=this.collectComponentTypes(s),c=a.componentTypes,u=a.componentTypeRegistry,l=Date.now(),h={name:t.name,createdAt:l,modifiedAt:l,componentTypes:c,referencedAssets:[]};return t.description&&(h.description=t.description),t.tags&&(h.tags=t.tags),{version:1,metadata:h,root:s,componentTypeRegistry:u}},t.instantiate=function(e,t,n,i){var r;void 0===i&&(i={});var o=i,s=o.parentId,c=o.name,u=o.preserveIds,l=void 0!==u&&u,h=o.trackInstance,d=void 0===h||h,f=null!==(r=t.getSystem(Ge))&&void 0!==r?r:null,p=1,m=Ft.deserializeEntities([e.root],n,function(){for(;t.findEntityById(p);)p++;return p++},l,t,f),v=m.rootEntities,g=m.allEntities,y=v[0];if(!y)throw new Error("Failed to instantiate prefab: no root entity created");c&&(y.name=c);for(var _,S=a(g.values());!(_=S()).done;){var C=_.value;t.entities.add(C)}if(void 0!==s&&f){var E=t.findEntityById(s);E&&f.setParent(y,E)}if(d){var b=e.metadata.guid||"";this.addPrefabInstanceComponents(y,g,b,"",f)}return y},t.toPrefabEntity=function(e,t){var n=this;return c({},e,{isPrefabRoot:t,children:e.children.map(function(e){return n.toPrefabEntity(e,!1)})})},t.collectComponentTypes=function(e){var t=new Map,n=function(e){for(var i,r=a(e.components);!(i=r()).done;){var o=i.value;t.has(o.type)||t.set(o.type,o.version)}for(var s,c=a(e.children);!(s=c()).done;){var u=s.value;n(u)}};return n(e),{componentTypes:Array.from(t.keys()),componentTypeRegistry:Array.from(t.entries()).map(function(e){return{typeName:e[0],version:e[1]}})}},t.addPrefabInstanceComponents=function(t,n,i,r,o){var s=t.id,c=new e.PrefabInstanceComponent(i,r,!0);c.rootInstanceEntityId=s,t.addComponent(c);for(var u,l=a(n.values());!(u=l()).done;){var h=u.value;if(h.id!==s){var d=new e.PrefabInstanceComponent(i,r,!1);d.rootInstanceEntityId=s,h.addComponent(d)}}},t.isPrefabInstance=function(t){return t.hasComponent(e.PrefabInstanceComponent)},t.getSourcePrefabGuid=function(t){var n=t.getComponent(e.PrefabInstanceComponent);return(null==n?void 0:n.sourcePrefabGuid)||null},t.getPrefabInstanceRoot=function(t){var n=t.getComponent(e.PrefabInstanceComponent);if(!n||!n.rootInstanceEntityId)return null;var i=t.scene;return i&&i.findEntityById(n.rootInstanceEntityId)||null},t.serialize=function(e,t){return void 0===t&&(t=!0),JSON.stringify(e,null,t?2:void 0)},t.deserialize=function(e){var t=JSON.parse(e);if(!t.version||!t.metadata||!t.root)throw new Error("Invalid prefab data format");return t},t.validate=function(e){var t=[];return"number"!=typeof e.version&&t.push("Invalid or missing version"),e.metadata?(e.metadata.name||t.push("Missing metadata.name"),Array.isArray(e.metadata.componentTypes)||t.push("Invalid metadata.componentTypes")):t.push("Missing metadata"),e.root?this.validateEntity(e.root,t,"root"):t.push("Missing root entity"),Array.isArray(e.componentTypeRegistry)||t.push("Invalid componentTypeRegistry"),t.length>0?{valid:!1,errors:t}:{valid:!0}},t.validateEntity=function(e,t,n){var i=this;"number"!=typeof e.id&&t.push(n+": Invalid or missing id"),"string"!=typeof e.name&&t.push(n+": Invalid or missing name"),Array.isArray(e.components)||t.push(n+": Invalid or missing components"),Array.isArray(e.children)?e.children.forEach(function(e,r){i.validateEntity(e,t,n+".children["+r+"]")}):t.push(n+": Invalid or missing children")},t}(),Yn={NONE:0,FOLDER:4096,HIDDEN:8192,LOCKED:16384,EDITOR_ONLY:32768,PREFAB_INSTANCE:256,PREFAB_ROOT:512};function Jn(e,t){return 0!==(e&t)}var Zn=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){var t,n=null===(t=this._entity.scene)||void 0===t?void 0:t.getSystem(Ge);return null==n||n.setParent(e,this._entity),this},t.build=function(){return this._entity},s(e,[{key:"entity",get:function(){return this._entity}}])}();var Xn=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),Kn=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function $n(e){return"function"==typeof e&&e.prototype instanceof Me}function ei(){return globalThis}var ti=function(){function t(){}return t.detect=function(){var e,t=[],n="unknown",i=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",i=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",i=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",i=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",i=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",i=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",i=!0,e="BrowserAdapter",t.push("browser")),"undefined"!=typeof Worker&&t.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&t.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&t.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&t.push("performance.now"),"undefined"!=typeof Blob&&t.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&t.push("URL.createObjectURL"),c({platform:n,confident:i,features:t},e&&{adapterClass:e})},t.isWeChatMiniGame=function(){var e=this.miniGameGlobals.wx;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)},t.isByteDanceMiniGame=function(){var e=this.miniGameGlobals.tt;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)},t.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||void 0===e||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},t.isAlipayMiniGame=function(){var e=this.miniGameGlobals.my;return!!e&&!(!e.getSystemInfo||!e.createCanvas)},t.isBaiduMiniGame=function(){var e=this.miniGameGlobals.swan;return!!e&&!(!e.getSystemInfo||!e.createCanvas)},t.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},t.isTauriEnvironment=function(){return"undefined"!=typeof window&&("__TAURI__"in window||"__TAURI_INTERNALS__"in window)},t.isEditorEnvironment=function(){return"undefined"!=typeof window&&(!!this.isTauriEnvironment()||"__ESENGINE_EDITOR__"in window)},t.getDetailedInfo=function(){var e={},t=this.miniGameGlobals;return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==t.wx,tt:void 0!==t.tt,my:void 0!==t.my,swan:void 0!==t.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},t}();ti.miniGameGlobals=ei(),e.AdvancedProfilerCollector=tt,e.After=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=Se(e.prototype).after).push.apply(n,t),e}},e.AutoProfiler=qt,e.Before=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=Se(e.prototype).before).push.apply(n,t),e}},e.BinarySerializer=Bt,e.BitMask64Utils=q,e.Bits=mt,e.COMPONENT_DEPENDENCIES=F,e.COMPONENT_EDITOR_OPTIONS=B,e.COMPONENT_TYPE_NAME=N,e.Colors=Q,e.CommandBuffer=He,e.CompiledQuery=wt,e.Component=Me,e.ComponentDataCollector=Ye,e.ComponentPoolManager=Ve,e.ComponentRegistry=K,e.ComponentSerializer=Nt,e.ComponentSparseSet=yt,e.ComponentStorage=Ne,e.ConsoleLogger=V,e.Core=Tn,e.CycleDependencyError=Zt,e.DEFAULT_PROFILER_CONFIG=Ke,e.DEFAULT_STAGE_ORDER=en,e.DeepCopy=function(e,t){Te(e,"__deepCopyFields").add(String(t))},e.ECSComponent=te,e.ECSFluentAPI=ln,e.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");var i=n;return i[ee]=e,t&&(i.__systemMetadata__=t),n}},e.EMPTY_GUID="00000000-0000-0000-0000-000000000000",e.ENTITY_REF_METADATA=de,e.EVENT_TYPES=xn,e.Emitter=Pn,e.EnableSoA=function(e){return e.__enableSoA=!0,e},e.Entity=ht,e.EntityDataCollector=je,e.EntityHandleManager=nn,e.EntityList=dt,e.EntityProcessorList=pt,e.EntityRef=function(){return function(e,t){var n=e.constructor,i=n[de];i||(i={properties:new Set},n[de]=i);var r="symbol"==typeof t?t.toString():t;i.properties.add(r),Object.defineProperty(e,t,{get:function(){return pe(this).get(r)||null},set:function(e){var t=pe(this),n=t.get(r)||null;if(n!==e){var i=null!==this.entityId?ue(this.entityId):null;if(i&&i.referenceTracker){var o=i.referenceTracker;if(n&&o.unregisterReference(n,this,r),e){var s;if(e.scene!==i)return void he.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(s=e.scene)||void 0===s?void 0:s.name)||"null"));if(e.isDestroyed)return he.warn("Cannot reference destroyed Entity: "+e.name),void t.set(r,null);o.registerReference(e,this,r)}t.set(r,e)}else t.set(r,e)}},enumerable:!0,configurable:!0})}},e.EntitySerializer=Ft,e.EntitySystem=We,e.EntityTags=Yn,e.EpochManager=rn,e.EventBus=Gn,e.EventTypeValidator=Rn,e.Float32=function(e,t){Te(e,"__float32Fields").add(String(t))},e.Float64=function(e,t){Te(e,"__float64Fields").add(String(t))},e.FuncPack=Dn,e.GEN_BITS=20,e.GEN_MASK=rt,e.GlobalComponentRegistry=$,e.GlobalEventBus=jn,e.GlobalManager=On,e.HierarchySystem=Ge,e.INDEX_BITS=28,e.INDEX_MASK=it,e.IdentifierPool=ft,e.IgnoreSerialization=function(){return function(e,t){var n,i=e.constructor;if(Object.prototype.hasOwnProperty.call(i,Ae))n=i[Ae];else{var r=i[Ae];n={options:r?c({},r.options):{version:1},fields:r?new Map(r.fields):new Map,ignoredFields:r?new Set(r.ignoredFields):new Set},i[Ae]=n}n.ignoredFields.add(t)}},e.InSet=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=Se(e.prototype).sets).push.apply(n,t),e}},e.IncrementalSerializer=jt,e.InjectProperty=I,e.Injectable=T,e.Int16=function(e,t){Te(e,"__int16Fields").add(String(t))},e.Int32=we,e.Int8=function(e,t){Te(e,"__int8Fields").add(String(t))},e.IntervalSystem=Fn,e.Logger=J,e.LoggerManager=Y,e.MAX_ENTITIES=ot,e.MAX_GENERATION=st,e.Matcher=Re,e.MigrationBuilder=Qn,e.NULL_HANDLE=0,e.NumberExtension=Kn,e.PREFAB_FORMAT_VERSION=1,e.PROPERTY_METADATA=ye,e.PassiveSystem=Nn,e.PerformanceDataCollector=qe,e.PerformanceMonitor=O,e.PlatformDetector=ti,e.PlatformManager=Bn,e.PlatformWorkerPool=Hn,e.PluginManager=yn,e.PluginServiceRegistry=Sn,e.Pool=x,e.PoolManager=z,e.PrefabSerializer=Vn,e.ProcessingSystem=zn,e.Profile=function(t,n){return void 0===n&&(n=e.ProfileCategory.Custom),function(e,i,r){var o=r.value,s=t||e.constructor.name+"."+String(i);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(!et.isEnabled())return o.apply(this,t);var r=et.beginSample(s,n);try{var a=o.apply(this,t);return a instanceof Promise?a.finally(function(){et.endSample(r)}):(et.endSample(r),a)}catch(e){throw et.endSample(r),e}},r}},e.ProfileClass=function(t){return void 0===t&&(t=e.ProfileCategory.Custom),function(e){return qt.registerClass(e,t)}},e.ProfilerSDK=et,e.Property=function(e){return function(t,n){var i=t.constructor,r=ge.get(i)||{};r[n]=e,ge.set(i,r)}},e.QuerySystem=It,e.ReactiveQuery=Tt,e.ReferenceTracker=le,e.RuntimeModeService=In,e.RuntimeModeToken=wn,e.SCHEDULING_METADATA=_e,e.SERIALIZABLE_METADATA=Ae,e.SERIALIZE_FIELD=ke,e.SERIALIZE_OPTIONS=De,e.SYSTEM_TYPE_NAME=ee,e.Scene=on,e.SceneDataCollector=Ze,e.SceneManager=vn,e.SceneSerializer=Wt,e.Serializable=Pe,e.SerializationContext=Lt,e.Serialize=Oe,e.SerializeArray=function(e,t){Te(e,"__serializeArrayFields").add(String(t))},e.SerializeAsMap=function(){return function(e,t){Oe({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},e.SerializeAsSet=function(){return function(e,t){Oe({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},e.SerializeMap=function(e,t){Te(e,"__serializeMapFields").add(String(t))},e.SerializeSet=function(e,t){Te(e,"__serializeSetFields").add(String(t))},e.ServiceContainer=Jt,e.SoAStorage=Ie,e.SparseSet=vt,e.Stage=function(e){return function(t){return Se(t.prototype).stage=e,t}},e.SystemDataCollector=Ue,e.SystemDependencyGraph=Kt,e.SystemScheduler=tn,e.Time=_,e.Timer=C,e.TypeSafeEventSystem=At,e.TypeUtils=Xn,e.TypedEntityBuilder=Zn,e.TypedQueryBuilder=Dt,e.TypedQueryResult=kt,e.Uint16=function(e,t){Te(e,"__uint16Fields").add(String(t))},e.Uint32=function(e,t){Te(e,"__uint32Fields").add(String(t))},e.Uint8=function(e,t){Te(e,"__uint8Fields").add(String(t))},e.Uint8Clamped=function(e,t){Te(e,"__uint8ClampedFields").add(String(t))},e.Updatable=w,e.ValueSerializer=Rt,e.VersionMigrationManager=qn,e.WebSocketManager=Xe,e.WorkerEntitySystem=Wn,e.World=mn,e.WorldManager=bn,e.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},e.addEntityTag=function(e,t){return e|t},e.buildEntity=function(e){return new Zn(e)},e.createECSAPI=hn,e.createEditorModeService=function(){return new In({isEditor:!0,isPlaying:!1,isPreview:!1})},e.createInstance=A,e.createLogger=Z,e.createQuery=function(){return new Dt},e.createServiceToken=_n,e.createStandaloneModeService=function(){return new In({isEditor:!1,isPlaying:!0,isPreview:!1})},e.genOf=ut,e.generateGUID=nt,e.getBasicWorkerConfig=function(){return Bn.getInstance().getBasicWorkerConfig()},e.getComponentDependencies=function(e){return e[F]},e.getComponentEditorOptions=G,e.getComponentInstanceEditorOptions=function(e){return G(e.constructor)},e.getComponentInstanceTypeName=W,e.getComponentTypeName=H,e.getComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.map(function(t){return e.getComponent(t)})},e.getCurrentAdapter=function(){return Bn.getInstance().getAdapter()},e.getEntityRefMetadata=me,e.getEntityRefProperties=function(e){var t=me(e);return t?Array.from(t.properties):[]},e.getFullPlatformConfig=function(){return Bn.getInstance().getFullPlatformConfig()},e.getGlobalWithMiniGame=ei,e.getOrAddComponent=function(e,t,n){var i=e.getComponent(t);return i||(i=n(),e.addComponent(i)),i},e.getPerformanceWithMemory=function(){return performance},e.getPropertyInjectMetadata=function(e){var t=E.get(e);return(null==t?void 0:t.properties)||new Map},e.getPropertyMetadata=function(e){return ge.get(e)},e.getSceneByEntityId=ue,e.getSchedulingMetadata=Ce,e.getSerializationMetadata=xe,e.getSystemInstanceMetadata=ie,e.getSystemInstanceTypeName=oe,e.getSystemMetadata=ne,e.getSystemTypeName=re,e.getUpdatableMetadata=P,e.handleEquals=function(e,t){return e===t},e.handleToString=function(e){return 0===e?"Entity(NULL)":"Entity(idx="+ct(e)+", gen="+ut(e)+")"},e.hasAdapter=function(){return Bn.getInstance().hasAdapter()},e.hasAnyComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.some(function(t){return e.hasComponent(t)})},e.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.every(function(t){return e.hasComponent(t)})},e.hasECSComponentDecorator=L,e.hasEntityRef=function(e){return null!==me(e)},e.hasEntityTag=Jn,e.hasPropertyMetadata=function(e){return ge.has(e)},e.hasSchedulingMetadata=function(e){return void 0!==Ce(e)},e.indexOf=ct,e.injectProperties=k,e.isComponentArray=function(e){return e.every($n)},e.isComponentHiddenInInspector=j,e.isComponentInstanceHiddenInInspector=function(e){return j(e.constructor)},e.isComponentType=$n,e.isEntityRefProperty=ve,e.isFolder=function(e){return Jn(e,Yn.FOLDER)},e.isHidden=function(e){return Jn(e,Yn.HIDDEN)},e.isLocked=function(e){return Jn(e,Yn.LOCKED)},e.isSerializable=function(e){return null!==xe(e)},e.isUpdatable=D,e.isValidGUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)},e.isValidHandle=lt,e.makeHandle=at,e.queryFor=function(e){return new Dt([e])},e.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Dt(t)},e.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!M(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var i=function(e){return A(t,e)};n?e.registerSingleton(t,i):e.registerTransient(t,i)},e.registerPlatformAdapter=function(e){return Bn.getInstance().registerAdapter(e)},e.removeEntityTag=function(e,t){return e&~t},e.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},e.resetLoggerColors=function(){Y.getInstance().resetColors()},e.setGlobalLogLevel=function(e){Y.getInstance().setGlobalLevel(e)},e.setLoggerColors=function(e){Y.getInstance().setGlobalColors(e)},e.setLoggerFactory=function(e){Y.getInstance().setLoggerFactory(e)},e.supportsFeature=function(e){return Bn.getInstance().supportsFeature(e)},e.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},e.updateComponent=function(e,t,n){var i=e.getComponent(t);return!!i&&(Object.assign(i,n),!0)}});
3
+ var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function o(n,i,r,o){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,i,r){var o,a,c,u=0,l=r||[],h=!1,d={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,a=0,c=e,d.n=n,s}};function f(n,i){for(a=n,c=i,t=0;!h&&u&&!r&&t<l.length;t++){var r,o=l[t],f=d.p,p=o[2];n>3?(r=p===i)&&(c=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=f&&((r=n<2&&f<o[1])?(a=0,d.v=i,d.n=o[1]):f<p&&(r=n<3||o[0]>i||i>p)&&(o[4]=n,o[5]=i,d.n=p,a=0))}if(r||n>1)return s;throw h=!0,i}return function(r,l,p){if(u>1)throw TypeError("Generator is already running");for(h&&1===l&&f(l,p),a=l,c=p;(t=a<2?e:c)||!h;){o||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(u=2,o){if(a||(r="next"),t=o[r]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,a<2&&(a=0)}else 1===a&&(t=o.return)&&t.call(o),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=e}else if((t=(h=d.n<0)?c:n.call(i,d))!==s)break}catch(t){o=e,a=1,c=t}finally{u=1}}return{value:t,done:h}}}(n,r,o),!0),u}var s={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var l=[][i]?t(t([][i]())):(f(t={},i,function(){return this}),t),h=u.prototype=a.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,r,"GeneratorFunction")),e.prototype=Object.create(h),e}return c.prototype=u,f(h,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,r,"GeneratorFunction"),f(h),f(h,r,"Generator"),f(h,i,function(){return this}),f(h,"toString",function(){return"[object Generator]"}),(d=function(){return{w:o,m:p}})()}function f(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}f=function(e,t,n,i){function o(t,n){f(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},f(e,t,n,i)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function m(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function v(e){var t="function"==typeof Map?new Map:void 0;return v=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,u(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),p(n,e)},v(e)}function g(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;var _=function(){function e(){}return e.update=function(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},e.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},e.checkEvery=function(e,t){return this.totalTime-t>=e},e}();_.deltaTime=0,_.unscaledDeltaTime=0,_.totalTime=0,_.unscaledTotalTime=0,_.timeScale=1,_.frameCount=0;var S,C=function(){function e(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var t=e.prototype;return t.getContext=function(){return this.context},t.reset=function(){this._elapsedTime=0},t.stop=function(){this._isDone=!0},t.tick=function(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=_.deltaTime,this._isDone},t.initialize=function(e,t,n,i){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=i.bind(n)},t.unload=function(){this.context=null,this._onTime=null},s(e,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),E=new WeakMap,b=new WeakMap;function T(){return function(e){var t=E.get(e);E.set(e,c({injectable:!0,dependencies:[]},(null==t?void 0:t.properties)&&{properties:t.properties}))}}function w(e){return void 0===e&&(e=0),function(t){var 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.");b.set(t,{updatable:!0,priority:e})}}function I(e){return function(t,n){var i=E.get(t.constructor);i||(i={injectable:!0,dependencies:[]},E.set(t.constructor,i)),i.properties||(i.properties=new Map),i.properties.set(n,e)}}function M(e){var t,n=E.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function A(e,t){var n=new e;return k(n,t),n}function k(e,t){var n,i=e.constructor,r=(n=i,E.get(n));if(null!=r&&r.properties&&0!==r.properties.size)for(var o,s=a(r.properties);!(o=s()).done;){var c=o.value,u=c[0],l=c[1],h=t.resolve(l);null!==h&&(e[u]=h)}}function D(e){var t,n=b.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function P(e){return b.get(e)}e.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,i){var r=new C;return r.initialize(e,t,n,i),this._timers.push(r),r},t.dispose=function(){for(var e,t=a(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),e.TimerManager=g([w()],e.TimerManager),e.PerformanceWarningType=void 0,(S=e.PerformanceWarningType||(e.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",S.HIGH_MEMORY_USAGE="high_memory_usage",S.HIGH_CPU_USAGE="high_cpu_usage",S.FREQUENT_GC="frequent_gc",S.LOW_FPS="low_fps",S.HIGH_ENTITY_COUNT="high_entity_count";var O=function(){function e(){this._systemData=new Map,this._systemStats=new Map,this._isEnabled=!1,this._maxRecentSamples=60}var t=e.prototype;return t.updateFPS=function(e){},t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.startMonitoring=function(e){return this._isEnabled?performance.now():0},t.endMonitoring=function(e,t,n){if(void 0===n&&(n=0),this._isEnabled&&0!==t){var i=performance.now(),r=i-t,o={name:e,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(e,o),this.updateStats(e,r)}},t.updateStats=function(e,t){var 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)},t.calculateAdvancedStats=function(e){if(0!==e.recentTimes.length){var t=e.recentTimes.reduce(function(e,t){return e+t},0)/e.recentTimes.length,n=e.recentTimes.reduce(function(e,n){return e+Math.pow(n-t,2)},0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);var i=[].concat(e.recentTimes).sort(function(e,t){return e-t}),r=i.length;e.percentile95=i[Math.floor(.95*r)]||0,e.percentile99=i[Math.floor(.99*r)]||0}},t.getSystemData=function(e){return this._systemData.get(e)},t.getSystemStats=function(e){return this._systemStats.get(e)},t.getAllSystemData=function(){return new Map(this._systemData)},t.getAllSystemStats=function(){return new Map(this._systemStats)},t.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var e=[];e.push("=== ECS Performance Report ==="),e.push("");for(var t,n=a(Array.from(this._systemStats.entries()).sort(function(e,t){return t[1].averageTime-e[1].averageTime}));!(t=n()).done;){var i=t.value,r=i[0],o=i[1],s=this._systemData.get(r);e.push("System: "+r),e.push(" Current: "+(null==s?void 0:s.executionTime.toFixed(2))+"ms ("+(null==s?void 0:s.entityCount)+" entities)"),e.push(" Average: "+o.averageTime.toFixed(2)+"ms"),e.push(" Min/Max: "+o.minTime.toFixed(2)+"ms / "+o.maxTime.toFixed(2)+"ms"),e.push(" Total: "+o.totalTime.toFixed(2)+"ms ("+o.executionCount+" calls)"),null!=s&&s.averageTimePerEntity&&s.averageTimePerEntity>0&&e.push(" Per Entity: "+s.averageTimePerEntity.toFixed(4)+"ms"),e.push("")}var c=Array.from(this._systemData.values()).reduce(function(e,t){return e+t.executionTime},0);return e.push("Total Frame Time: "+c.toFixed(2)+"ms"),e.push("Systems Count: "+this._systemData.size),e.join("\n")},t.reset=function(){this._systemData.clear(),this._systemStats.clear()},t.resetSystem=function(e){this._systemData.delete(e),this._systemStats.delete(e)},t.getPerformanceWarnings=function(e){void 0===e&&(e=16.67);for(var t,n=[],i=a(this._systemData.entries());!(t=i()).done;){var r=t.value,o=r[0],s=r[1];s.executionTime>e&&n.push(o+": "+s.executionTime.toFixed(2)+"ms (>"+e+"ms)")}return n},t.setMaxRecentSamples=function(e){this._maxRecentSamples=e;for(var t,n=a(this._systemStats.values());!(t=n()).done;)for(var i=t.value;i.recentTimes.length>e;)i.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._isEnabled=!1},s(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),x=function(){function e(e,t,n){void 0===t&&(t=100),void 0===n&&(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}}e.getPool=function(t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(t);return r||(r=new e(function(){return new t},n,i),this._pools.set(t,r)),r};var t=e.prototype;return t.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},t.release=function(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))},t.getStats=function(){return c({},this._stats)},t.clear=function(){for(var e,t=a(this._objects);!(e=t()).done;){e.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},t.compact=function(e){for(var t=null!=e?e:Math.floor(this._objects.length/2);this._objects.length>t;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},t.prewarm=function(e){for(var t=Math.min(e,this._maxSize-this._objects.length),n=0;n<t;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},t.setMaxSize=function(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)},t.getAvailableCount=function(){return this._objects.length},t.isEmpty=function(){return 0===this._objects.length},t.isFull=function(){return this._objects.length>=this._maxSize},e.getAllPoolTypes=function(){return Array.from(this._pools.keys())},e.getAllPoolStats=function(){for(var e,t={},n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t[r.name||r.toString()]=o.getStats()}return t},e.compactAllPools=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.compact()}},e.clearAllPools=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.clear()}this._pools.clear()},e.getGlobalStatsString=function(){var e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],o=r[0],s=r[1];t.push(o+":"),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")},t._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}},t._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},e}();x._pools=new Map;var R,z=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(e);return r||(r=new x(t,n,i),this.pools.set(e,r)),r},t.removePool=function(e){var t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)},t.getPoolNames=function(){return Array.from(this.pools.keys())},t.getPoolCount=function(){return this.pools.size},t.compactAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){e.value.compact()}},t.clearAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){e.value.clear()}},t.getAllStats=function(){for(var e,t=new Map,n=a(this.pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,o.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,i=0,r=0,o=0,s=0,c=a(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,o+=u.totalReleased,s+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:o,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:s}},t.getStatsString=function(){var e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");var 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(var n,i=a(this.pools);!(n=i()).done;){var r=n.value,o=r[0],s=r[1].getStats();e.push(o+":"),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")},t.setAutoCompactInterval=function(e){this.autoCompactInterval=e},t.prewarmAllPools=function(){for(var e,t=a(this.pools.values());!(e=t()).done;){var n=e.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}(),N=Symbol("ComponentTypeName"),F=Symbol("ComponentDependencies"),B=Symbol("ComponentEditorOptions");function L(e){return void 0!==e[N]}function H(e){var t=e[N];return t||(e.name||"UnknownComponent")}function W(e){return H(e.constructor)}function U(e){return e[B]}function G(e){var t,n=U(e);return null!==(t=null==n?void 0:n.hideInInspector)&&void 0!==t&&t}!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(R||(R={}));var j,q=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0]};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0]}},e.hasAny=function(e,t){var n=t.base,i=e.base,r=t.segments,o=e.segments,s=0!==(i[R.LOW]&n[R.LOW])||0!==(i[R.HIGH]&n[R.HIGH]);return!s&&r&&o?o.some(function(e,t){var n=r[t];return n&&(0!==(e[R.LOW]&n[R.LOW])||0!==(e[R.HIGH]&n[R.HIGH]))}):s},e.hasAll=function(e,t){var n,i=e.base,r=t.base,o=e.segments,s=t.segments,a=(i[R.LOW]&r[R.LOW])===r[R.LOW]&&(i[R.HIGH]&r[R.HIGH])===r[R.HIGH];if(!a||!s)return a;var c=null!==(n=null==o?void 0:o.length)&&void 0!==n?n:0;if(o)for(var u=0;u<Math.min(c,s.length);u++){var l=o[u],h=s[u];if((l[R.LOW]&h[R.LOW])!==h[R.LOW]||(l[R.HIGH]&h[R.HIGH])!==h[R.HIGH])return!1}for(var d=c;d<s.length;d++){var f=s[d];if(0!==f[R.LOW]||0!==f[R.HIGH])return!1}return!0},e.hasNone=function(e,t){var n=e.base,i=t.base,r=e.segments,o=t.segments,s=0===(n[R.LOW]&i[R.LOW])&&0===(n[R.HIGH]&i[R.HIGH]);return r&&s&&o?r.every(function(e,t){var n=o[t];return!n||0===(e[R.LOW]&n[R.LOW])&&0===(e[R.HIGH]&n[R.HIGH])}):s},e.isZero=function(e){var t=0===e.base[R.LOW]&&0===e.base[R.HIGH];return e.segments&&t?e.segments.every(function(e){return 0===e[R.LOW]&&0===e[R.HIGH]}):t},e.equals=function(e,t){var n,i,r=e.base[R.LOW]===t.base[R.LOW]&&e.base[R.HIGH]===t.base[R.HIGH];if(!r||!e.segments&&!t.segments)return r;for(var o=null!==(n=e.segments)&&void 0!==n?n:[],s=null!==(i=t.segments)&&void 0!==i?i:[],a=0;a<Math.max(o.length,s.length);a++){var c=o[a],u=s[a];if(c&&!u){if(0!==c[R.LOW]||0!==c[R.HIGH])return!1}else if(!c&&u){if(0!==u[R.LOW]||0!==u[R.HIGH])return!1}else if(c&&u&&(c[R.LOW]!==u[R.LOW]||c[R.HIGH]!==u[R.HIGH]))return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n),r=63&n;r<32?i[R.LOW]|=1<<r:i[R.HIGH]|=1<<r-32},e.getBit=function(t,n){if(n<0)return!1;var i=e.getSegmentByBitIndex(t,n,!1);if(!i)return!1;var r=63&n;return r<32?!!(i[R.LOW]&1<<r):!!(i[R.HIGH]&1<<r-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n,!1);if(i){var r=63&n;r<32?i[R.LOW]&=~(1<<r):i[R.HIGH]&=~(1<<r-32)}},e.orInPlace=function(e,t){e.base[R.LOW]|=t.base[R.LOW],e.base[R.HIGH]|=t.base[R.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]|=s[R.LOW],o[R.HIGH]|=s[R.HIGH]}}},e.andInPlace=function(e,t){e.base[R.LOW]&=t.base[R.LOW],e.base[R.HIGH]&=t.base[R.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]&=s[R.LOW],o[R.HIGH]&=s[R.HIGH]}}},e.xorInPlace=function(e,t){e.base[R.LOW]^=t.base[R.LOW],e.base[R.HIGH]^=t.base[R.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++){var o=i[r],s=n[r];o[R.LOW]^=s[R.LOW],o[R.HIGH]^=s[R.HIGH]}}},e.clear=function(e){if(e.base[R.LOW]=0,e.base[R.HIGH]=0,e.segments)for(var t=0;t<e.segments.length;t++){var n=e.segments[t];n[R.LOW]=0,n[R.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[R.LOW]=t.base[R.LOW],n.base[R.HIGH]=t.base[R.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var i=t.segments.length-n.segments.length,r=0;r<i;r++)n.segments.push([0,0]);for(var o=n.segments,s=t.segments,a=0;a<s.length;a++){var c=o[a],u=s[a];c[R.LOW]=u[R.LOW],c[R.HIGH]=u[R.HIGH]}}else n.segments=t.segments.map(function(e){return[].concat(e)})},e.clone=function(e){return c({base:e.base.slice()},e.segments&&{segments:e.segments.map(function(e){return[].concat(e)})})},e.toString=function(e,t,n){var i,r;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var o=null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0,s="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=o;c++){s+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}s+="\n"}for(var u=-1;u<o;u++){var l="",h=-1==u?e.base:e.segments[u],d=h[R.HIGH],f=h[R.LOW];if(2==t){l=d.toString(2).padStart(32,"0")+"_"+f.toString(2).padStart(32,"0")}else{var p=d?d.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var m=f.toString(16).toUpperCase();p&&(m=m.padStart(8,"0")),l="0x"+p+m}s+=-1===u?l:" "+l}return s},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0);n++){for(var i,r,o=-1==n?e.base:e.segments[n],s=o[R.LOW],a=o[R.HIGH];s;)s&=s-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var i,r=e.segments;if(!r){if(!n)return null;r=e.segments=[]}var o=(t>>6)-1;if(r.length<=o){if(!n)return null;for(var s=o-r.length+1,a=0;a<s;a++)r.push([0,0])}return null!==(i=r[o])&&void 0!==i?i:null},e}();q.ZERO={base:[0,0]},e.LogLevel=void 0,(j=e.LogLevel||(e.LogLevel={}))[j.Debug=0]="Debug",j[j.Info=1]="Info",j[j.Warn=2]="Warn",j[j.Error=3]="Error",j[j.Fatal=4]="Fatal",j[j.None=5]="None";var V={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""},Q=function(){function t(t){void 0===t&&(t={}),this._config=c({level:e.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},t)}var n=t.prototype;return n.debug=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Debug,t].concat(i))},n.info=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Info,t].concat(i))},n.warn=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Warn,t].concat(i))},n.error=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Error,t].concat(i))},n.fatal=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];this.log.apply(this,[e.LogLevel.Fatal,t].concat(i))},n.setLevel=function(e){this._config.level=e},n.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=c({},this._config.colors,e)},n.setPrefix=function(e){this._config.prefix=e},n.log=function(t,n){if(!(t<this._config.level)){var i=n;if(this._config.enableTimestamp)i="["+(new Date).toISOString()+"] "+i;if(this._config.prefix&&(i="["+this._config.prefix+"] "+i),i="["+e.LogLevel[t].toUpperCase()+"] "+i,this._config.output)this._config.output(t,i);else{for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];this.outputToConsole.apply(this,[t,i].concat(o))}}},n.outputToConsole=function(t,n){for(var i=this._config.enableColors?this.getColors():null,r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];switch(t){case e.LogLevel.Debug:var a,c;if(i)(a=console).debug.apply(a,[""+i.debug+n+i.reset].concat(o));else(c=console).debug.apply(c,[n].concat(o));break;case e.LogLevel.Info:var u,l;if(i)(u=console).info.apply(u,[""+i.info+n+i.reset].concat(o));else(l=console).info.apply(l,[n].concat(o));break;case e.LogLevel.Warn:var h,d;if(i)(h=console).warn.apply(h,[""+i.warn+n+i.reset].concat(o));else(d=console).warn.apply(d,[n].concat(o));break;case e.LogLevel.Error:var f,p;if(i)(f=console).error.apply(f,[""+i.error+n+i.reset].concat(o));else(p=console).error.apply(p,[n].concat(o));break;case e.LogLevel.Fatal:var m,v;if(i)(m=console).error.apply(m,[""+i.fatal+n+i.reset].concat(o));else(v=console).error.apply(v,[n].concat(o))}},n.getColors=function(){return c({},{debug:V.BRIGHT_BLACK,info:V.GREEN,warn:V.YELLOW,error:V.RED,fatal:V.BRIGHT_RED,reset:V.RESET},this._config.colors)},t}(),Y=function(){function t(){this._loggers=new Map,this._defaultLevel=e.LogLevel.Info}var n=t.prototype;return n.createDefaultLogger=function(){return this._loggerFactory?this._loggerFactory():new Q({level:this._defaultLevel})},t.getInstance=function(){return t._instance||(t._instance=new t),t._instance},n.getLogger=function(e){return e?this._loggerFactory?this._loggerFactory(e):(this._loggers.has(e)||this._loggers.set(e,new Q({prefix:e,level:this._defaultLevel})),this._loggers.get(e)):this.defaultLogger},n.setLogger=function(e,t){this._loggers.set(e,t)},n.setGlobalLevel=function(e){this._defaultLevel=e,this._defaultLogger instanceof Q&&this._defaultLogger.setLevel(e);for(var t,n=a(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof Q&&i.setLevel(e)}},n.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},n.setGlobalColors=function(e){this._defaultLogger instanceof Q&&this._defaultLogger.setColors(e);for(var t,n=a(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof Q&&i.setColors(e)}},n.resetColors=function(){this._defaultLogger instanceof Q&&this._defaultLogger.setColors({});for(var e,t=a(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof Q&&n.setColors({})}},n.setLoggerFactory=function(e){this._loggerFactory=e,delete this._defaultLogger,this._loggers.clear()},s(t,[{key:"defaultLogger",get:function(){return this._defaultLogger||(this._defaultLogger=this.createDefaultLogger()),this._defaultLogger}}])}(),J=Y.getInstance().getLogger();function Z(e){return Y.getInstance().getLogger(e)}var X,K=Z("ComponentRegistry"),$=function(){function e(){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}var t=e.prototype;return t.register=function(e){var t=H(e);if(L(e)||this._warnedComponents.has(e)||(this._warnedComponents.add(e),K.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)){var n=this._componentNameToType.get(t);if(n!==e){var i=this._componentTypes.get(n);return this._componentTypes.delete(n),this._componentTypes.set(e,i),this._bitIndexToType.set(i,e),this._componentNameToType.set(t,e),K.debug('Hot reload: replaced component "'+t+'"'),i}}var r=this._nextBitIndex++;return this._componentTypes.set(e,r),this._bitIndexToType.set(r,e),this._componentNameToType.set(t,e),this._componentNameToId.set(t,r),r},t.getBitMask=function(e){var t=this._componentTypes.get(e);if(void 0===t){var n=H(e);throw new Error("Component type "+n+" is not registered")}return q.create(t)},t.getBitIndex=function(e){var t=this._componentTypes.get(e);if(void 0===t){var n=H(e);throw new Error("Component type "+n+" is not registered")}return t},t.isRegistered=function(e){return this._componentTypes.has(e)},t.getTypeByBitIndex=function(e){return this._bitIndexToType.get(e)||null},t.getRegisteredCount=function(){return this._nextBitIndex},t.getComponentType=function(e){return this._componentNameToType.get(e)||null},t.getAllRegisteredTypes=function(){return new Map(this._componentTypes)},t.getAllComponentNames=function(){return new Map(this._componentNameToType)},t.getComponentId=function(e){return this._componentNameToId.get(e)},t.registerComponentByName=function(e){if(this._componentNameToId.has(e))return this._componentNameToId.get(e);var t=this._nextBitIndex++;return this._componentNameToId.set(e,t),t},t.createSingleComponentMask=function(e){var t="single:"+e;if(this._maskCache.has(t))return this._maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var i=q.create(n);return this._maskCache.set(t,i),i},t.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this._maskCache.has(t))return this._maskCache.get(t);for(var n,i=q.clone(q.ZERO),r=a(e);!(n=r()).done;){var o=n.value,s=this.getComponentId(o);if(void 0!==s){var c=q.create(s);q.orInPlace(i,c)}}return this._maskCache.set(t,i),i},t.clearMaskCache=function(){this._maskCache.clear()},t.enableHotReload=function(){this._hotReloadEnabled=!0},t.disableHotReload=function(){this._hotReloadEnabled=!1},t.isHotReloadEnabled=function(){return this._hotReloadEnabled},t.unregister=function(e){var t=this._componentNameToType.get(e);if(t){var 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(),K.debug("Component unregistered: "+e)}},t.getRegisteredComponents=function(){for(var e,t=[],n=a(this._componentNameToType);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=this._componentTypes.get(o);void 0!==s&&t.push({name:r,type:o,bitIndex:s})}return t},t.reset=function(){this._componentTypes.clear(),this._bitIndexToType.clear(),this._componentNameToType.clear(),this._componentNameToId.clear(),this._maskCache.clear(),this._warnedComponents.clear(),this._nextBitIndex=0,this._hotReloadEnabled=!1},t.cloneFrom=function(e){for(var t,n=a(e.getAllRegisteredTypes());!(t=n()).done;){var i=t.value,r=i[0],o=i[1];this._componentTypes.set(r,o),this._bitIndexToType.set(o,r);var s=H(r);this._componentNameToType.set(s,r),this._componentNameToId.set(s,o)}this._nextBitIndex=e.getRegisteredCount(),this._hotReloadEnabled=e.isHotReloadEnabled()},e}(),ee=new $;e.SyncOperation=void 0,(X=e.SyncOperation||(e.SyncOperation={}))[X.FULL=0]="FULL",X[X.DELTA=1]="DELTA",X[X.SPAWN=2]="SPAWN",X[X.DESPAWN=3]="DESPAWN";var te=Symbol("SyncMetadata"),ne=Symbol("ChangeTracker"),ie=Symbol("SystemTypeName");function re(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");var i=n;i[N]=e,null!=t&&t.requires&&(i[F]=t.requires),null!=t&&t.editor&&(i[B]=t.editor);var r=n[te];return r&&(r.typeId=e),ee.register(n),n}}function oe(e){return e.__systemMetadata__}function se(e){return oe(e.constructor)}function ae(e){var t=e[ie];return t||(e.name||"UnknownSystem")}function ce(e){return ae(e.constructor)}var ue=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),le="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||ue,he=new Map;function de(e){var t=he.get(e);return(null==t?void 0:t.deref())||null}var fe=function(){function e(){this._references=new Map}var t=e.prototype;return t.registerReference=function(e,t,n){var i=e.id,r=this._references.get(i);r||(r=new Set,this._references.set(i,r)),this._findRecord(r,t,n)||r.add({component:new le(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var i=e.id,r=this._references.get(i);if(r){var o=this._findRecord(r,t,n);o&&(r.delete(o),0===r.size&&this._references.delete(i))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;o.component.deref()&&i.push(o)}for(var s=0,c=i;s<c.length;s++){var u=c[s],l=u.component.deref();l&&(l[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=a(this._references.entries());!(t=n()).done;){for(var i,r=t.value,o=r[0],s=r[1],c=[],u=a(s);!(i=u()).done;){var l=i.value,h=l.component.deref();h&&h!==e||c.push(l)}for(var d=0,f=c;d<f.length;d++){var p=f[d];s.delete(p)}0===s.size&&this._references.delete(o)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;o.component.deref()&&i.push(o)}return i},t.cleanup=function(){for(var e,t=[],n=a(this._references.entries());!(e=n()).done;){for(var i,r=e.value,o=r[0],s=r[1],c=[],u=a(s);!(i=u()).done;){var l=i.value;l.component.deref()||c.push(l)}for(var h=0,d=c;h<d.length;h++){var f=d[h];s.delete(f)}0===s.size&&t.push(o)}for(var p=0,m=t;p<m.length;p++){var v=m[p];this._references.delete(v)}},t.registerEntityScene=function(e,t){he.set(e,new le(t))},t.unregisterEntityScene=function(e){he.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=a(this._references.entries());!(e=n()).done;){for(var i,r=e.value,o=r[0],s=[],c=a(r[1]);!(i=c()).done;){var u=i.value,l=u.component.deref();l&&s.push({componentId:l.id,propertyKey:u.propertyKey})}s.length>0&&(t["entity_"+o]=s)}return t},t._findRecord=function(e,t,n){for(var i,r=a(e);!(i=r()).done;){var o=i.value;if(o.component.deref()===t&&o.propertyKey===n)return o}},e}(),pe=Z("EntityRefDecorator"),me=Symbol("EntityRefMetadata"),ve=Symbol("EntityRefValues");function ge(e){var t=e[ve];return t||(t=new Map,e[ve]=t),t}function ye(e){return e&&("function"==typeof e?e:e.constructor)[me]||null}function _e(e,t){var n=ye(e);return!!n&&n.properties.has(t)}var Se=new WeakMap,Ce=Symbol.for("@esengine/property:metadata");var Ee=Symbol("schedulingMetadata");function be(e){var t=e;return t[Ee]||(t[Ee]={stage:"update",before:[],after:[],sets:[]}),t[Ee]}function Te(e){for(var t=Object.getPrototypeOf(e);t;){var n=t[Ee];if(n)return n;t=Object.getPrototypeOf(t)}}var we=function(){function e(){}return e.getConstructor=function(e){return this.TYPE_CONSTRUCTORS[e]||Float32Array},e.getBytesPerElement=function(e){return this.TYPE_BYTES[e]||4},e.getTypeName=function(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"},e.createSameType=function(e,t){var n=this.getTypeName(e);return new(this.getConstructor(n))(t)},e.extractFieldMetadata=function(e){var t=new e,n=new Map,i=e,r=new Map,o=function(e,t){if(e)for(var n,i=a(e);!(n=i()).done;){var o=n.value;r.set(o,t)}};o(i.__float64Fields,"float64"),o(i.__float32Fields,"float32"),o(i.__int32Fields,"int32"),o(i.__uint32Fields,"uint32"),o(i.__int16Fields,"int16"),o(i.__uint16Fields,"uint16"),o(i.__int8Fields,"int8"),o(i.__uint8Fields,"uint8"),o(i.__uint8ClampedFields,"uint8clamped");for(var s,c=Object.keys(t).filter(function(e){return"id"!==e}),u=a(c);!(s=u()).done;){var l,h,d,f,p=s.value,m=typeof t[p];if("function"!==m){var v={name:p,type:m},g=r.get(p);g?v.arrayType=g:"number"===m?v.arrayType="float32":"boolean"===m&&(v.arrayType="uint8"),null!==(l=i.__serializeMapFields)&&void 0!==l&&l.has(p)&&(v.isSerializedMap=!0),null!==(h=i.__serializeSetFields)&&void 0!==h&&h.has(p)&&(v.isSerializedSet=!0),null!==(d=i.__serializeArrayFields)&&void 0!==d&&d.has(p)&&(v.isSerializedArray=!0),null!==(f=i.__deepCopyFields)&&void 0!==f&&f.has(p)&&(v.isDeepCopy=!0),n.set(p,v)}}return n},e}();we.TYPE_CONSTRUCTORS={float32:Float32Array,float64:Float64Array,int32:Int32Array,uint32:Uint32Array,int16:Int16Array,uint16:Uint16Array,int8:Int8Array,uint8:Uint8Array,uint8clamped:Uint8ClampedArray},we.TYPE_BYTES={float32:4,float64:8,int32:4,uint32:4,int16:2,uint16:2,int8:1,uint8:1,uint8clamped:1};var Ie=function(){function e(){}return e.serialize=function(e,t,n){void 0===n&&(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),"{}"}},e.deserialize=function(e,t,n){void 0===n&&(n={});try{var i=JSON.parse(e);return n.isMap?new Map(i):n.isSet?new Set(i):i}catch(e){return this._logger.warn("SoA反序列化字段 "+t+" 失败:",e),null}},e.deepClone=function(e){var t=this;if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(function(e){return t.deepClone(e)});if(e instanceof Map){for(var n,i=new Map,r=a(e.entries());!(n=r()).done;){var o=n.value,s=o[0],c=o[1];i.set(s,this.deepClone(c))}return i}if(e instanceof Set){for(var u,l=new Set,h=a(e.values());!(u=h()).done;){var d=u.value;l.add(this.deepClone(d))}return l}var f={};for(var p in e)Object.prototype.hasOwnProperty.call(e,p)&&(f[p]=this.deepClone(e[p]));return f},e}();function Me(e,t){var n=e.constructor,i=n[t];return i||(i=new Set,n[t]=i),i}function Ae(e,t){Me(e,"__int32Fields").add(String(t))}Ie._logger=Z("SoASerializer");var ke=function(){function e(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)}var t=e.prototype;return t.initializeFields=function(e){var t=new e,n=e,i=n.__float64Fields||new Set,r=n.__float32Fields||new Set,o=n.__int32Fields||new Set,s=n.__uint32Fields||new Set,c=n.__int16Fields||new Set,u=n.__uint16Fields||new Set,l=n.__int8Fields||new Set,h=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;for(var f,p=new Map,m=a(i);!(f=m()).done;){var v=f.value;p.set(v,"float64")}for(var g,y=a(r);!(g=y()).done;){var _=g.value;p.set(_,"float32")}for(var S,C=a(o);!(S=C()).done;){var E=S.value;p.set(E,"int32")}for(var b,T=a(s);!(b=T()).done;){var w=b.value;p.set(w,"uint32")}for(var I,M=a(c);!(I=M()).done;){var A=I.value;p.set(A,"int16")}for(var k,D=a(u);!(k=D()).done;){var P=k.value;p.set(P,"uint16")}for(var O,x=a(l);!(O=x()).done;){var R=O.value;p.set(R,"int8")}for(var z,N=a(h);!(z=N()).done;){var F=z.value;p.set(F,"uint8")}for(var B,L=a(d);!(B=L()).done;){var H=B.value;p.set(H,"uint8clamped")}for(var W,U=Object.keys(t).filter(function(e){return"id"!==e}),G=a(U);!(W=G()).done;){var j=W.value,q=t[j],V=typeof q;if("function"!==V){var Q=p.get(j),Y=Q?"number":V;if(this.fieldTypes.set(j,Y),Q){var J=we.getConstructor(Q);this.fields.set(j,new J(this._capacity))}else"number"===V?this.fields.set(j,new Float32Array(this._capacity)):"boolean"===V?this.fields.set(j,new Uint8Array(this._capacity)):"string"===V?this.stringFields.set(j,new Array(this._capacity)):"object"===V&&null!==q&&(this.serializeMapFields.has(j)||this.serializeSetFields.has(j)||this.serializeArrayFields.has(j))&&this.serializedFields.set(j,new Array(this._capacity))}}},t.addComponent=function(e,t){if(this.entityToIndex.has(e)){var n=this.entityToIndex.get(e);this.updateComponentAtIndex(n,t)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,i),this.indexToEntity[i]=e,this.updateComponentAtIndex(i,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],i=new Map,r=this.type,o=r.__highPrecisionFields||new Set,s=r.__serializeMapFields||new Set,a=r.__serializeSetFields||new Set,c=r.__serializeArrayFields||new Set,u=r.__deepCopyFields||new Set,l=t;for(var h in t)if(Object.prototype.hasOwnProperty.call(t,h)&&"id"!==h){var d=l[h],f=typeof d;if("number"===f){var p=d;if(o.has(h)||!this.fields.has(h))i.set(h,p);else this.fields.get(h)[e]=p}else if("boolean"===f&&this.fields.has(h)){this.fields.get(h)[e]=d?1:0}else if(this.stringFields.has(h)){this.stringFields.get(h)[e]=String(d)}else if(this.serializedFields.has(h)){this.serializedFields.get(h)[e]=Ie.serialize(d,h,{isMap:s.has(h),isSet:a.has(h),isArray:c.has(h)})}else u.has(h)?i.set(h,Ie.deepClone(d)):i.set(h,d)}i.size>0&&this.complexFields.set(n,i)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0===t?null:this.createProxyView(e,t)},t.createProxyView=function(e,t){var n=this;return new Proxy({},{get:function(i,r){var o=String(r),s=n.fields.get(o);if(s)return"boolean"===n.getFieldType(o)?1===s[t]:s[t];var a=n.stringFields.get(o);if(a)return a[t];var c=n.serializedFields.get(o);if(c){var u=c[t];return u?Ie.deserialize(u,o,{isMap:n.serializeMapFields.has(o),isSet:n.serializeSetFields.has(o),isArray:n.serializeArrayFields.has(o)}):void 0}var l=n.complexFields.get(e);return null!=l&&l.has(o)?l.get(o):void 0},set:function(i,r,o){var s=String(r);if("entityId"===s)return!1;var a=n.fields.get(s);if(a){var c=n.getFieldType(s);return a[t]="boolean"===c?o?1:0:o,!0}var u=n.stringFields.get(s);if(u)return u[t]=String(o),!0;if(n.serializedFields.has(s))return n.serializedFields.get(s)[t]=Ie.serialize(o,s,{isMap:n.serializeMapFields.has(s),isSet:n.serializeSetFields.has(s),isArray:n.serializeArrayFields.has(s)}),!0;var l=n.complexFields.get(e);return l||(l=new Map,n.complexFields.set(e,l)),l.set(s,o),!0},has:function(t,i){var r,o=String(i);return n.fields.has(o)||n.stringFields.has(o)||n.serializedFields.has(o)||(null===(r=n.complexFields.get(e))||void 0===r?void 0:r.has(o))||!1},ownKeys:function(){for(var t,i=[],r=a(n.fields.keys());!(t=r()).done;){var o=t.value;i.push(o)}for(var s,c=a(n.stringFields.keys());!(s=c()).done;){var u=s.value;i.push(u)}for(var l,h=a(n.serializedFields.keys());!(l=h()).done;){var d=l.value;i.push(d)}var f=n.complexFields.get(e);if(f)for(var p,m=a(f.keys());!(p=m()).done;){var v=p.value;i.push(v)}return i},getOwnPropertyDescriptor:function(t,i){var r,o=String(i);if(n.fields.has(o)||n.stringFields.has(o)||n.serializedFields.has(o)||null!==(r=n.complexFields.get(e))&&void 0!==r&&r.has(o))return{enumerable:!0,configurable:!0,writable:"entityId"!==o}}})},t.getComponentSnapshot=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,i=new this.type,r=i,o=a(this.fields.entries());!(n=o()).done;){var s=n.value,c=s[0],u=s[1][t],l=this.getFieldType(c);r[c]="boolean"===l?1===u:u}for(var h,d=a(this.stringFields.entries());!(h=d()).done;){var f=h.value,p=f[0],m=f[1];r[p]=m[t]}for(var v,g=a(this.serializedFields.entries());!(v=g()).done;){var y=v.value,_=y[0],S=y[1][t];S&&(r[_]=Ie.deserialize(S,_,{isMap:this.serializeMapFields.has(_),isSet:this.serializeSetFields.has(_),isArray:this.serializeArrayFields.has(_)}))}var C=this.complexFields.get(e);if(C)for(var E,b=a(C.entries());!(E=b()).done;){var T=E.value,w=T[0],I=T[1];r[w]=I}return i},t.getFieldType=function(e){return this.fieldTypes.get(e)||"unknown"},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(e){for(var t,n=a(this.fields.entries());!(t=n()).done;){var i=t.value,r=i[0],o=i[1],s=we.createSameType(o,e);s.set(o),this.fields.set(r,s)}for(var c,u=a(this.stringFields.entries());!(c=u()).done;){for(var l=c.value,h=l[0],d=l[1],f=new Array(e),p=0;p<d.length;p++)f[p]=d[p];this.stringFields.set(h,f)}for(var m,v=a(this.serializedFields.entries());!(m=v()).done;){for(var g=m.value,y=g[0],_=g[1],S=new Array(e),C=0;C<_.length;C++)S[C]=_[C];this.serializedFields.set(y,S)}this._capacity=e},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=a(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,i=a(this.stringFields.values());!(n=i()).done;)for(var r=n.value,o=0;o<r.length;o++)r[o]=void 0;for(var s,c=a(this.serializedFields.values());!(s=c()).done;)for(var u=s.value,l=0;l<u.length;l++)u[l]=void 0},t.compact=function(){if(0!==this.freeIndices.length){for(var e=Array.from(this.entityToIndex.entries()).sort(function(e,t){return e[1]-t[1]}),t=new Map,n=[],i=0;i<e.length;i++){var r=e[i];if(r){var o=r[0],s=r[1];if(t.set(o,i),n[i]=o,i!==s){for(var c,u=a(this.fields.entries());!(c=u()).done;){var l=c.value[1],h=l[s];void 0!==h&&(l[i]=h)}for(var d,f=a(this.stringFields.entries());!(d=f()).done;){var p=d.value[1],m=p[s];void 0!==m&&(p[i]=m)}for(var v,g=a(this.serializedFields.entries());!(v=g()).done;){var y=v.value[1],_=y[s];void 0!==_&&(y[i]=_)}}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,i=a(this.fields.entries());!(e=i()).done;){var r=e.value,o=r[0],s=r[1],c=we.getTypeName(s),u=we.getBytesPerElement(c),l=s.length*u;t+=l,n.set(o,{size:this._size,capacity:s.length,type:c,memory:l})}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:t,fieldStats:n}},t.performVectorizedOperation=function(e){var t=this.getActiveIndices();e(this.fields,t)},e}(),De=function(){function e(){this.entityId=null,this._lastWriteEpoch=0,this.id=e._idGenerator++}var t=e.prototype;return t.markDirty=function(e){this._lastWriteEpoch=e},t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},t.onDeserialized=function(){},s(e,[{key:"lastWriteEpoch",get:function(){return this._lastWriteEpoch}}])}();De._idGenerator=0,g([Ae,y("design:type",Object)],De.prototype,"entityId",void 0);var Pe=Symbol("SerializableMetadata"),Oe=Symbol("SerializeField"),xe=Symbol("SerializeOptions");function Re(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n;if(Object.prototype.hasOwnProperty.call(t,Pe))(n=t[Pe]).options=e;else{var i=t[Pe];n={options:e,fields:i?new Map(i.fields):new Map,ignoredFields:i?new Set(i.ignoredFields):new Set},t[Pe]=n}return t}}function ze(e){return function(t,n){var i,r=t.constructor;if(Object.prototype.hasOwnProperty.call(r,Pe))i=r[Pe];else{var o=r[Pe];i={options:o?c({},o.options):{version:1},fields:o?new Map(o.fields):new Map,ignoredFields:o?new Set(o.ignoredFields):new Set},r[Pe]=i}i.fields.set(n,e||{})}}function Ne(e){return e&&("function"==typeof e?e:e.constructor)[Pe]||null}e.HierarchyComponent=function(e){function t(){var t;return(t=e.apply(this,arguments)||this).parentId=null,t.childIds=[],t.depth=0,t.bActiveInHierarchy=!0,t.bCacheDirty=!0,t}return l(t,e),t}(De),g([ze(),y("design:type",Object)],e.HierarchyComponent.prototype,"parentId",void 0),g([ze(),y("design:type",Array)],e.HierarchyComponent.prototype,"childIds",void 0),e.HierarchyComponent=g([re("Hierarchy",{editor:{hideInInspector:!0}}),Re({version:1,typeId:"Hierarchy"})],e.HierarchyComponent);var Fe=function(){function e(){this.condition={all:[],any:[],none:[]}}e.all=function(){var t=new e;return t.all.apply(t,arguments)},e.any=function(){var t=new e;return t.any.apply(t,arguments)},e.none=function(){var t=new e;return t.none.apply(t,arguments)},e.byTag=function(t){return(new e).withTag(t)},e.byName=function(t){return(new e).withName(t)},e.byComponent=function(t){return(new e).withComponent(t)},e.complex=function(){return new e},e.empty=function(){return new e},e.nothing=function(){var t=new e;return t.condition.matchNothing=!0,t};var t=e.prototype;return t.all=function(){var e;return(e=this.condition.all).push.apply(e,arguments),this},t.any=function(){var e;return(e=this.condition.any).push.apply(e,arguments),this},t.none=function(){var e;return(e=this.condition.none).push.apply(e,arguments),this},t.exclude=function(){return this.none.apply(this,arguments)},t.one=function(){return this.any.apply(this,arguments)},t.withTag=function(e){return this.condition.tag=e,this},t.withName=function(e){return this.condition.name=e,this},t.withComponent=function(e){return this.condition.component=e,this},t.withoutTag=function(){return delete this.condition.tag,this},t.withoutName=function(){return delete this.condition.name,this},t.withoutComponent=function(){return delete this.condition.component,this},t.getCondition=function(){return c({all:[].concat(this.condition.all),any:[].concat(this.condition.any),none:[].concat(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})},t.isEmpty=function(){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},t.isNothing=function(){return!0===this.condition.matchNothing},t.reset=function(){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},t.clone=function(){var t,n,i,r=new e;return(t=r.condition.all).push.apply(t,this.condition.all),(n=r.condition.any).push.apply(n,this.condition.any),(i=r.condition.none).push.apply(i,this.condition.none),void 0!==this.condition.tag&&(r.condition.tag=this.condition.tag),void 0!==this.condition.name&&(r.condition.name=this.condition.name),void 0!==this.condition.component&&(r.condition.component=this.condition.component),this.condition.matchNothing&&(r.condition.matchNothing=!0),r},t.toString=function(){if(this.condition.matchNothing)return"Matcher[nothing]";var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map(function(e){return H(e)}).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map(function(e){return H(e)}).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map(function(e){return H(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("+H(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),Be=function(){function e(){this._frameCache=null,this._persistentCache=null,this._trackedEntities=new Set}var t=e.prototype;return t.getFrame=function(){return this._frameCache},t.setFrame=function(e){this._frameCache=e},t.getPersistent=function(){return this._persistentCache},t.setPersistent=function(e){this._persistentCache=e},t.getTracked=function(){return this._trackedEntities},t.addTracked=function(e){this._trackedEntities.add(e)},t.removeTracked=function(e){this._trackedEntities.delete(e)},t.isTracked=function(e){return this._trackedEntities.has(e)},t.invalidate=function(){this._persistentCache=null},t.clearFrame=function(){this._frameCache=null},t.clearAll=function(){this._frameCache=null,this._persistentCache=null,this._trackedEntities.clear()},t.hasPersistent=function(){return null!==this._persistentCache},t.hasFrame=function(){return null!==this._frameCache},t.getStats=function(){var e,t,n,i;return{hasFrame:null!==this._frameCache,hasPersistent:null!==this._persistentCache,trackedCount:this._trackedEntities.size,frameEntityCount:null!==(e=null===(t=this._frameCache)||void 0===t?void 0:t.length)&&void 0!==e?e:0,persistentEntityCount:null!==(n=null===(i=this._persistentCache)||void 0===i?void 0:i.length)&&void 0!==n?n:0}},e}(),Le=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e}var t=e.prototype;return t.addComponent=function(e,t){if(this.entityToIndex.has(e))throw new Error("Entity "+e+" already has component "+H(this.componentType));var n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.dense[t],i=this.dense.length-1;if(t!==i){var r=this.dense[i],o=this.entityIds[i];this.dense[t]=r,this.entityIds[t]=o,this.entityToIndex.set(o,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n},t.forEach=function(e){for(var t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)},t.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},t.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},t.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(e,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),He=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof ke},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof ke?t:null},t.getFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getFieldArray(t):null},t.getTypedFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null},t.getActiveIndices=function(e){var t=this.getSoAStorage(e);return t?t.getActiveIndices():[]},t.getEntityIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0},t.getEntityIdByIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0},t.getStorage=function(t){var n=this.storages.get(t);n||(t.__enableSoA?(n=new ke(t),e._logger.info("为 "+H(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new Le(t),this.storages.set(t,n));return n},t.addComponent=function(e,t){var n=t.constructor;this.getStorage(n).addComponent(e,t)},t.getComponent=function(e,t){var n=this.storages.get(t);return n?n.getComponent(e):null},t.hasComponent=function(e,t){var n=this.storages.get(t);return!!n&&n.hasComponent(e)},t.removeComponent=function(e,t){var n=this.storages.get(t);return n?n.removeComponent(e):null},t.removeAllComponents=function(e){for(var t,n=a(this.storages.values());!(t=n()).done;){t.value.removeComponent(e)}},t.getComponentMask=function(e,t){void 0===t&&(t=ee);for(var n,i=q.clone(q.ZERO),r=a(this.storages.entries());!(n=r()).done;){var o=n.value,s=o[0];if(o[1].hasComponent(e)){var c=t.getBitMask(s);q.orInPlace(i,c)}}return i},t.getAllStats=function(){for(var e,t=new Map,n=a(this.storages.entries());!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=H(r);t.set(s,o.getStats())}return t},t.clear=function(){for(var e,t=a(this.storages.values());!(e=t()).done;){e.value.clear()}this.storages.clear()},e}();He._logger=Z("ComponentStorage");var We,Ue=Z("CommandBuffer");e.CommandType=void 0,(We=e.CommandType||(e.CommandType={})).ADD_COMPONENT="add_component",We.REMOVE_COMPONENT="remove_component",We.DESTROY_ENTITY="destroy_entity",We.SET_ENTITY_ACTIVE="set_entity_active";var Ge=function(){function t(e,t){void 0===t&&(t=!1),this._pending=new Map,this._commands=[],this._scene=null,this._debug=!1,this._useDeduplication=!0,this._scene=null!=e?e:null,this._debug=t}var n=t.prototype;return n.setScene=function(e){this._scene=e},n.setDeduplication=function(e){this._useDeduplication=e},n.getPending=function(e){var t=this._pending.get(e);return t||(t={},this._pending.set(e,t)),t},n.getTypeId=function(e){return"function"==typeof e?ee.getBitIndex(e):ee.getBitIndex(e.constructor)},n.addComponent=function(t,n){if(this._useDeduplication){var i,r=this.getPending(t);if(r.bDestroy)return void(this._debug&&Ue.debug("CommandBuffer: 忽略添加组件,实体 "+t.name+" 已标记销毁"));var o=this.getTypeId(n);if(null===(i=r.removes)||void 0===i||i.delete(o),r.adds||(r.adds=new Map),r.adds.set(o,n),this._debug){var s=H(n.constructor);Ue.debug("CommandBuffer: 延迟添加组件 "+s+" 到实体 "+t.name)}}else this._commands.push({type:e.CommandType.ADD_COMPONENT,entity:t,component:n})},n.removeComponent=function(t,n){if(this._useDeduplication){var i,r=this.getPending(t);if(r.bDestroy)return void(this._debug&&Ue.debug("CommandBuffer: 忽略移除组件,实体 "+t.name+" 已标记销毁"));var o=this.getTypeId(n);null===(i=r.adds)||void 0===i||i.delete(o),r.removes||(r.removes=new Set),r.removes.add(o),this._debug&&Ue.debug("CommandBuffer: 延迟移除组件 "+n.name+" 从实体 "+t.name)}else this._commands.push({type:e.CommandType.REMOVE_COMPONENT,entity:t,componentType:n})},n.destroyEntity=function(t){if(this._useDeduplication){var n,i,r=this.getPending(t);null===(n=r.adds)||void 0===n||n.clear(),null===(i=r.removes)||void 0===i||i.clear(),delete r.active,r.bDestroy=!0,this._debug&&Ue.debug("CommandBuffer: 延迟销毁实体 "+t.name)}else this._commands.push({type:e.CommandType.DESTROY_ENTITY,entity:t})},n.setEntityActive=function(t,n){if(this._useDeduplication){var i=this.getPending(t);if(i.bDestroy)return void(this._debug&&Ue.debug("CommandBuffer: 忽略设置激活状态,实体 "+t.name+" 已标记销毁"));i.active=n,this._debug&&Ue.debug("CommandBuffer: 延迟设置实体 "+t.name+" 激活状态为 "+n)}else this._commands.push({type:e.CommandType.SET_ENTITY_ACTIVE,entity:t,value:n})},n.flush=function(){return this._useDeduplication?this.flushDeduplication():this.flushLegacy()},n.flushDeduplication=function(){if(0===this._pending.size)return 0;var e=this._pending.size,t=0;this._debug&&Ue.debug("CommandBuffer: 开始执行 "+e+" 个实体的延迟命令");var n=this._pending;this._pending=new Map;for(var i,r=a(n);!(i=r()).done;){var o=i.value,s=o[0],c=o[1];if(!c.bDestroy&&s.scene&&(c.removes&&c.removes.size>0))for(var u,l=a(c.removes);!(u=l()).done;){var h=u.value;try{var d=ee.getTypeByBitIndex(h);d&&(s.removeComponentByType(d),t++)}catch(e){Ue.error("CommandBuffer: 移除组件失败",{entity:s.name,typeId:h,error:e})}}}for(var f,p=a(n);!(f=p()).done;){var m=f.value,v=m[0],g=m[1];if(!g.bDestroy&&v.scene&&(g.adds&&g.adds.size>0))for(var y,_=a(g.adds.values());!(y=_()).done;){var S=y.value;try{v.addComponent(S),t++}catch(e){var C=H(S.constructor);Ue.error("CommandBuffer: 添加组件失败",{entity:v.name,component:C,error:e})}}}for(var E,b=a(n);!(E=b()).done;){var T=E.value,w=T[0],I=T[1];if(!I.bDestroy&&w.scene&&void 0!==I.active)try{w.active=I.active,t++}catch(e){Ue.error("CommandBuffer: 设置激活状态失败",{entity:w.name,error:e})}}for(var M,A=a(n);!(M=A()).done;){var k=M.value,D=k[0];if(k[1].bDestroy&&D.scene)try{D.destroy(),t++}catch(e){Ue.error("CommandBuffer: 销毁实体失败",{entity:D.name,error:e})}}return this._debug&&Ue.debug("CommandBuffer: 完成执行 "+t+" 个延迟命令"),t},n.flushLegacy=function(){if(0===this._commands.length)return 0;var e=this._commands.length;this._debug&&Ue.debug("CommandBuffer: 开始执行 "+e+" 个延迟命令");var t=this._commands;this._commands=[];for(var n,i=a(t);!(n=i()).done;){var r=n.value;this.executeCommand(r)}return this._debug&&Ue.debug("CommandBuffer: 完成执行 "+e+" 个延迟命令"),e},n.executeCommand=function(t){if(t.entity.scene)try{switch(t.type){case e.CommandType.ADD_COMPONENT:t.component&&t.entity.addComponent(t.component);break;case e.CommandType.REMOVE_COMPONENT:t.componentType&&t.entity.removeComponentByType(t.componentType);break;case e.CommandType.DESTROY_ENTITY:t.entity.destroy();break;case e.CommandType.SET_ENTITY_ACTIVE:void 0!==t.value&&(t.entity.active=t.value)}}catch(e){Ue.error("CommandBuffer: 执行命令失败",{command:t,error:e})}else this._debug&&Ue.debug("CommandBuffer: 跳过命令,实体 "+t.entity.name+" 已无效")},n.clear=function(){if(this._debug){var e=this._useDeduplication?this._pending.size:this._commands.length;e>0&&Ue.debug("CommandBuffer: 清空 "+e+" 个未执行的命令")}this._pending.clear(),this._commands.length=0},n.dispose=function(){this.clear(),this._scene=null},s(t,[{key:"scene",get:function(){return this._scene}},{key:"pendingCount",get:function(){if(this._useDeduplication){for(var e,t=0,n=a(this._pending.values());!(e=n()).done;){var i=e.value;i.bDestroy&&t++,void 0!==i.active&&t++,i.adds&&(t+=i.adds.size),i.removes&&(t+=i.removes.size)}return t}return this._commands.length}},{key:"hasPending",get:function(){return this._useDeduplication?this._pending.size>0:this._commands.length>0}}])}(),je=function(){function e(e){this.commands=new Ge,this._lastProcessEpoch=0,this._shouldProcessThisFrame=!1,this._updateOrder=0,this._addOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=ce(this),this._initialized=!1,this._matcher=e||Fe.empty(),this._eventListeners=[],this._scene=null,this._destroyed=!1,this._entityIdMap=null,this._entityIdMapVersion=-1,this.logger=Z(this.getLoggerName()),this._entityCache=new Be;var t=Te(this);this._schedulingMetadata=t?c({},t):{stage:"update",before:[],after:[],sets:[]}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){var t;this._updateOrder!==e&&(this._updateOrder=e,null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty())},t.stage=function(e){var t;return this._schedulingMetadata.stage=e,null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.before=function(){var e,t;return(e=this._schedulingMetadata.before).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.after=function(){var e,t;return(e=this._schedulingMetadata.after).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.inSet=function(){var e,t;return(e=this._schedulingMetadata.sets).push.apply(e,arguments),null===(t=this._scene)||void 0===t||t.markSystemsOrderDirty(),this},t.getStage=function(){return this._schedulingMetadata.stage},t.getBefore=function(){return this._schedulingMetadata.before},t.getAfter=function(){return this._schedulingMetadata.after},t.getSets=function(){return this._schedulingMetadata.sets},t.initialize=function(){if(!this._initialized){if(this._initialized=!0,this.scene){this._entityCache.invalidate();for(var e,t=a(this.queryEntities());!(e=t()).done;){var n=e.value;this.onAdded(n)}}this.onInitialize()}},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.resetEntityTracking=function(){this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1},t.reset=function(){this._destroyed||(this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this.destroy())},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return this._matcher.isNothing()?[]:(i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(i),i)},t.isSingleCondition=function(e){var t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)},t.executeSingleConditionQuery=function(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll.apply(t,e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny.apply(t,e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone.apply(t,e.none).entities:[]},t.executeComplexQueryWithIdSets=function(e,t){var n=null;if(void 0!==e.tag){var i=t.queryByTag(e.tag);n=this.extractEntityIds(i.entities)}if(void 0!==e.name){var r=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==e.component){var o=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,o):o}if(e.all.length>0){var s=this.extractEntityIds(t.queryAll.apply(t,e.all).entities);n=n?this.intersectIdSets(n,s):s}if(e.any.length>0){var a=this.extractEntityIds(t.queryAny.apply(t,e.any).entities);n=n?this.intersectIdSets(n,a):a}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));var c=t.queryAny.apply(t,e.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]},t.extractEntityIds=function(e){for(var t=e.length,n=new Set,i=0;i<t;i=i+1|0)n.add(0|e[i].id);return n},t.intersectIdSets=function(e,t){var n,i;e.size<=t.size?(n=e,i=t):(n=t,i=e);for(var r,o=new Set,s=a(n);!(r=s()).done;){var c=r.value;i.has(c)&&o.add(c)}return o},t.differenceIdSets=function(e,t){for(var n,i=new Set,r=a(e);!(n=r()).done;){var o=n.value;t.has(o)||i.add(o)}return i},t.getEntityIdMap=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n||null===(n=n.querySystem)||void 0===n?void 0:n.version)&&void 0!==t?t:0;return null!==this._entityIdMap&&this._entityIdMapVersion===i?this._entityIdMap:this.rebuildEntityIdMap(e,i)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var i=e.length,r=0;r<i;r=r+1|0){var o=e[r];n.set(0|o.id,o)}return this._entityIdMap=n,this._entityIdMapVersion=t,n},t.idSetToEntityArray=function(e,t){for(var n,i=this.getEntityIdMap(t),r=e.size,o=new Array(r),s=0,c=a(e);!(n=c()).done;){var u=n.value,l=i.get(u);void 0!==l&&(o[s]=l,s=s+1|0)}return s<r&&(o.length=s),o},t.executeComplexQuery=function(e,t){return this.executeComplexQueryWithIdSets(e,t)},t.update=function(){if(this._shouldProcessThisFrame=this._enabled&&this.onCheckProcessing(),this._shouldProcessThisFrame){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin();var i=this.queryEntities();this._entityCache.setFrame(i),n=i.length,this.process(i)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._shouldProcessThisFrame){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var i=this.queryEntities();this._entityCache.setFrame(i),n=i.length,this.lateProcess(i),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.flushCommands=function(){return this.commands.flush()},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.matchesEntity=function(e){if(!this._matcher)return!1;if(this._matcher.isNothing())return!1;if(this._matcher.isEmpty())return!0;for(var t,n=this._matcher.getCondition(),i=a(n.all);!(t=i()).done;){var r=t.value;if(!e.hasComponent(r))return!1}if(n.any.length>0){for(var o,s=!1,c=a(n.any);!(o=c()).done;){var u=o.value;if(e.hasComponent(u)){s=!0;break}}if(!s)return!1}for(var l,h=a(n.none);!(l=h()).done;){var d=l.value;if(e.hasComponent(d))return!1}return(void 0===n.tag||e.tag===n.tag)&&((void 0===n.name||e.name===n.name)&&!(void 0!==n.component&&!e.hasComponent(n.component)))},t.isTracking=function(e){return this._entityCache.isTracked(e)},t.handleEntityComponentChanged=function(e){if(this._matcher&&this._enabled){var t=this._entityCache.isTracked(e),n=this.matchesEntity(e);!t&&n?(this._entityCache.addTracked(e),this._entityCache.invalidate(),this.onAdded(e)):t&&!n&&(this._entityCache.removeTracked(e),this._entityCache.invalidate(),this.onRemoved(e))}},t.updateEntityTracking=function(e){for(var t,n=new Set(e),i=!1,r=a(e);!(t=r()).done;){var o=t.value;this._entityCache.isTracked(o)||(this._entityCache.addTracked(o),i=!0)}for(var s,c=a(this._entityCache.getTracked());!(s=c()).done;){var u=s.value;n.has(u)||(this._entityCache.removeTracked(u),i=!0)}i&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this._destroyed||(this.cleanupManualEventListeners(),this.onDestroy(),this._entityCache.clearAll(),this._entityIdMap=null,this.commands.dispose(),this._initialized=!1,this._scene=null,this._destroyed=!0,this.logger.debug("System "+this._systemName+" disposed"))},t.addEventListener=function(e,t,n){var i;if(null===(i=this.scene)||void 0===i||!i.eventSystem)return this.logger.warn(this.systemName+": 无法添加事件监听器,scene.eventSystem 不可用"),null;var r=this.scene.eventSystem.on(e,t,n);return r&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,listenerRef:r}),r},t.removeEventListener=function(e,t){var n=this._eventListeners.findIndex(function(n){return n.eventType===e&&n.listenerRef===t});if(n>=0){var i=this._eventListeners[n];if(!i)return;i.eventSystem.off(e,i.listenerRef),this._eventListeners.splice(n,1)}},t.cleanupManualEventListeners=function(){for(var e,t=a(this._eventListeners);!(e=t()).done;){var n=e.value;try{n.eventSystem.off(n.eventType,n.listenerRef)}catch(e){this.logger.warn(this.systemName+': 移除事件监听器失败 "'+n.eventType+'"',e)}}this._eventListeners.length=0},t.destroy=function(){this._destroyed||(this.cleanupManualEventListeners(),this._destroyed=!0,this.onDestroy())},t.getLoggerName=function(){return ce(this)},t.onDestroy=function(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.map(function(n){return t.requireComponent(e,n)})},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},t.saveEpoch=function(){this._lastProcessEpoch=this.currentEpoch},t.forEachChanged=function(e,t,n,i){for(var r=null!=i?i:this._lastProcessEpoch,o=0;o<e.length;o++){for(var s,c=e[o],u=!1,l=a(t);!(s=l()).done;){var h=s.value,d=c.getComponent(h);if(d&&d.lastWriteEpoch>r){u=!0;break}}u&&n(c,o)}this._lastProcessEpoch=this.currentEpoch},t.filterChanged=function(e,t,n){for(var i=null!=n?n:this._lastProcessEpoch,r=[],o=0;o<e.length;o++)for(var s,c=e[o],u=a(t);!(s=u()).done;){var l=s.value,h=c.getComponent(l);if(h&&h.lastWriteEpoch>i){r.push(c);break}}return r},t.hasChanged=function(e,t,n){for(var i,r=null!=n?n:this._lastProcessEpoch,o=a(t);!(i=o()).done;){var s=i.value,c=e.getComponent(s);if(c&&c.lastWriteEpoch>r)return!0}return!1},s(e,[{key:"entities",get:function(){var e=this._entityCache.getFrame();return null!==e?e:(this._entityCache.hasPersistent()||this._entityCache.setPersistent(this.queryEntities()),this._entityCache.getPersistent())}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this.setUpdateOrder(e)}},{key:"addOrder",get:function(){return this._addOrder},set:function(e){this._addOrder=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(e){this._scene=e,this.commands.setScene(e)}},{key:"matcher",get:function(){return this._matcher}},{key:"lastProcessEpoch",get:function(){return this._lastProcessEpoch}},{key:"currentEpoch",get:function(){var e,t;return null!==(e=null===(t=this._scene)||void 0===t||null===(t=t.epochManager)||void 0===t?void 0:t.current)&&void 0!==e?e:0}}])}(),qe=function(t){function n(){var n;return(n=t.call(this,Fe.empty().all(e.HierarchyComponent))||this).dirtyEntities=new Set,n}l(n,t);var i=n.prototype;return i.process=function(e){if(0!==this.dirtyEntities.size){for(var t,n=a(this.dirtyEntities);!(t=n()).done;){var i=t.value;i.scene&&this.updateHierarchyCache(i)}this.dirtyEntities.clear()}},i.setParent=function(t,n){var i,r=t.getComponent(e.HierarchyComponent);r||(r=new e.HierarchyComponent,t.addComponent(r));var o=r.parentId;if(o!==(null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null)){if(n&&this.isAncestorOf(t,n))throw new Error("Cannot set parent: would create circular reference");if(null!==o){var s,a=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(o);if(a){var c=a.getComponent(e.HierarchyComponent);if(c){var u=c.childIds.indexOf(t.id);-1!==u&&c.childIds.splice(u,1)}}}if(n){var l=n.getComponent(e.HierarchyComponent);l||(l=new e.HierarchyComponent,n.addComponent(l)),r.parentId=n.id,l.childIds.push(t.id)}else r.parentId=null;this.markCacheDirty(t)}},i.insertChildAt=function(t,n,i){var r=n.getComponent(e.HierarchyComponent),o=t.getComponent(e.HierarchyComponent);if(r||(r=new e.HierarchyComponent,n.addComponent(r)),o||(o=new e.HierarchyComponent,t.addComponent(o)),this.isAncestorOf(n,t))throw new Error("Cannot set parent: would create circular reference");if(null!==r.parentId&&r.parentId!==t.id){var s,a=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(r.parentId);if(a){var c=a.getComponent(e.HierarchyComponent);if(c){var u=c.childIds.indexOf(n.id);-1!==u&&c.childIds.splice(u,1)}}}r.parentId=t.id;var l=o.childIds.indexOf(n.id);-1!==l&&o.childIds.splice(l,1),i<0||i>=o.childIds.length?o.childIds.push(n.id):o.childIds.splice(i,0,n.id),this.markCacheDirty(n)},i.removeChild=function(t,n){var i=t.getComponent(e.HierarchyComponent),r=n.getComponent(e.HierarchyComponent);if(!i||!r)return!1;if(r.parentId!==t.id)return!1;var o=i.childIds.indexOf(n.id);return-1!==o&&i.childIds.splice(o,1),r.parentId=null,this.markCacheDirty(n),!0},i.removeAllChildren=function(t){var n=t.getComponent(e.HierarchyComponent);if(n)for(var i,r=a([].concat(n.childIds));!(i=r()).done;){var o,s=i.value,c=null===(o=this.scene)||void 0===o?void 0:o.findEntityById(s);c&&this.removeChild(t,c)}},i.getParent=function(t){var n,i,r=t.getComponent(e.HierarchyComponent);return r&&null!==r.parentId&&null!==(n=null===(i=this.scene)||void 0===i?void 0:i.findEntityById(r.parentId))&&void 0!==n?n:null},i.getChildren=function(t){var n=t.getComponent(e.HierarchyComponent);if(!n)return[];for(var i,r=[],o=a(n.childIds);!(i=o()).done;){var s,c=i.value,u=null===(s=this.scene)||void 0===s?void 0:s.findEntityById(c);u&&r.push(u)}return r},i.getChildCount=function(t){var n,i=t.getComponent(e.HierarchyComponent);return null!==(n=null==i?void 0:i.childIds.length)&&void 0!==n?n:0},i.hasChildren=function(e){return this.getChildCount(e)>0},i.isAncestorOf=function(e,t){for(var i=this.getParent(t),r=0;i&&r<n.MAX_DEPTH;){if(i.id===e.id)return!0;i=this.getParent(i),r++}return!1},i.isDescendantOf=function(e,t){return this.isAncestorOf(t,e)},i.getRoot=function(e){for(var t=e,i=this.getParent(t),r=0;i&&r<n.MAX_DEPTH;)t=i,i=this.getParent(t),r++;return t},i.getDepth=function(t){var i=t.getComponent(e.HierarchyComponent);if(!i)return 0;if(!i.bCacheDirty)return i.depth;for(var r=0,o=this.getParent(t);o&&r<n.MAX_DEPTH;)r++,o=this.getParent(o);return i.depth=r,r},i.isActiveInHierarchy=function(t){if(!t.active)return!1;var n=t.getComponent(e.HierarchyComponent);if(!n)return t.active;if(!n.bCacheDirty)return n.bActiveInHierarchy;var i=this.getParent(t);return n.bActiveInHierarchy=i?t.active&&this.isActiveInHierarchy(i):t.active,n.bActiveInHierarchy},i.getRootEntities=function(){for(var t,n=[],i=a(this.entities);!(t=i()).done;){var r=t.value,o=r.getComponent(e.HierarchyComponent);o&&null===o.parentId&&n.push(r)}return n},i.findChild=function(e,t,n){void 0===n&&(n=!1);for(var i,r=this.getChildren(e),o=a(r);!(i=o()).done;){var s=i.value;if(s.name===t)return s}if(n)for(var c,u=a(r);!(c=u()).done;){var l=c.value,h=this.findChild(l,t,!0);if(h)return h}return null},i.findChildrenByTag=function(e,t,n){void 0===n&&(n=!1);for(var i,r=[],o=a(this.getChildren(e));!(i=o()).done;){var s=i.value;0!==(s.tag&t)&&r.push(s),n&&r.push.apply(r,this.findChildrenByTag(s,t,!0))}return r},i.forEachChild=function(e,t,n){void 0===n&&(n=!1);for(var i,r=a(this.getChildren(e));!(i=r()).done;){var o=i.value;t(o),n&&this.forEachChild(o,t,!0)}},i.flattenHierarchy=function(e){for(var t,n=this,i=[],r=function(t,o){var s=n.hasChildren(t),c=e.has(t.id);if(i.push({entity:t,depth:o,bHasChildren:s,bIsExpanded:c}),s&&c)for(var u,l=a(n.getChildren(t));!(u=l()).done;){var h=u.value;r(h,o+1)}},o=a(this.getRootEntities());!(t=o()).done;){var s=t.value;r(s,0)}return i},i.markCacheDirty=function(t){var n=t.getComponent(e.HierarchyComponent);if(n&&!n.bCacheDirty){n.bCacheDirty=!0,this.dirtyEntities.add(t);for(var i,r=a(n.childIds);!(i=r()).done;){var o,s=i.value,c=null===(o=this.scene)||void 0===o?void 0:o.findEntityById(s);c&&this.markCacheDirty(c)}}},i.updateHierarchyCache=function(t){var n=t.getComponent(e.HierarchyComponent);n&&(n.depth=this.getDepth(t),n.bActiveInHierarchy=this.isActiveInHierarchy(t),n.bCacheDirty=!1)},i.onAdded=function(t){var n=t.getComponent(e.HierarchyComponent);n&&n.bCacheDirty&&this.dirtyEntities.add(t)},i.onRemoved=function(t){this.dirtyEntities.delete(t);var n=t.getComponent(e.HierarchyComponent);if(n){if(null!==n.parentId){var i,r=null===(i=this.scene)||void 0===i?void 0:i.findEntityById(n.parentId);if(r){var o=r.getComponent(e.HierarchyComponent);if(o){var s=o.childIds.indexOf(t.id);-1!==s&&o.childIds.splice(s,1)}}}for(var c,u=a(n.childIds);!(c=u()).done;){var l,h=c.value,d=null===(l=this.scene)||void 0===l?void 0:l.findEntityById(h);if(d){var f=d.getComponent(e.HierarchyComponent);f&&(f.parentId=null,this.markCacheDirty(d))}}}},i.dispose=function(){this.dirtyEntities.clear()},s(n,[{key:"updateOrder",get:function(){return-1e3}}])}(je);qe.MAX_DEPTH=32;var Ve=function(){function t(){}var n=t.prototype;return n.collectEntityData=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},n.getRawEntityList=function(t){if(!t)return[];var n=t.entities;if(null==n||!n.buffer)return[];var i=t.getSystem(qe);return n.buffer.map(function(t){var n,r,o,s,a=t.getComponent(e.HierarchyComponent),c=null!==(n=null==i?void 0:i.isActiveInHierarchy(t))&&void 0!==n?n:t.active,u=null!==(r=null==i?void 0:i.getDepth(t))&&void 0!==r?r:0;return{id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:c,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),parentId:null!==(o=null==a?void 0:a.parentId)&&void 0!==o?o:null,childIds:null!==(s=null==a?void 0:a.childIds)&&void 0!==s?s:[],depth:u,tag:t.tag||0,updateOrder:t.updateOrder||0}})},n.getEntityDetails=function(e,t){try{var n,i,r;if(!t)return null;var o=t.entities;if(null==o||!o.buffer)return null;var s=o.buffer.find(function(t){return t.id===e});if(!s)return null;var a=t.getSystem(qe),u=null==a?void 0:a.getParent(s),l=null!==(n=null==u?void 0:u.name)&&void 0!==n?n:null,h=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t,a),d=this.extractComponentDetails(s.components),f=this.getSceneInfo(t);return c({},h,{scene:f.name,sceneName:f.name,sceneType:f.type,parentName:l,components:d||[],componentCount:(null===(i=s.components)||void 0===i?void 0:i.length)||0,componentTypes:(null===(r=s.components)||void 0===r?void 0:r.map(function(e){return W(e)}))||[]})}catch(e){return{error:"获取实体详情失败: "+(e instanceof Error?e.message:String(e)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},n.getSceneInfo=function(e){var t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(e))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(t=r,n=r)}}catch(e){t="场景名获取失败"}return{name:t,type:n}},n.collectEntityDataWithMemory=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n,e),entityDetailsMap:this.buildEntityDetailsMap(n,e)}},n.collectArchetypeData=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},n.getArchetypeDistributionFast=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach(function(e){var n,i=(null===(n=e.components)||void 0===n?void 0:n.map(function(e){return W(e)}))||[],r=i.length>0?i.sort().join(", "):"无组件",o=t.get(r);o?o.count++:t.set(r,{count:1,componentTypes:i})}),Array.from(t.entries()).map(function(e){return{signature:e[0],count:e[1].count,memory:0}}).sort(function(e,t){return t.count-e.count}).slice(0,20)},n.getTopEntitiesByComponentsFast=function(e){return e&&e.entities?e.entities.map(function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}}).sort(function(e,t){return t.componentCount-e.componentCount}):[]},n.collectArchetypeDataWithMemory=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},n.extractArchetypeStatistics=function(e){var t=e.getAllArchetypes(),n=[],i=[];return t.forEach(function(e){var t,r,o=(null===(t=e.componentTypes)||void 0===t?void 0:t.map(function(e){return e.name}).join(","))||"Unknown",s=(null===(r=e.entities)||void 0===r?void 0:r.length)||0;n.push({signature:o,count:s,memory:0}),e.entities&&e.entities.forEach(function(e){var t;i.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0})})}),n.sort(function(e,t){return t.count-e.count}),i.sort(function(e,t){return t.componentCount-e.componentCount}),{distribution:n,topEntities:i}},n.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),i=[],r=[];return n.forEach(function(e){var n,o,s=(null===(n=e.componentTypes)||void 0===n?void 0:n.map(function(e){return e.name}).join(","))||"Unknown",a=(null===(o=e.entities)||void 0===o?void 0:o.length)||0,c=0;if(e.entities&&e.entities.length>0){for(var u=Math.min(5,e.entities.length),l=0,h=0;h<u;h++)l+=t.estimateEntityMemoryUsage(e.entities[h]);c=l/u*a}i.push({signature:s,count:a,memory:c}),e.entities&&e.entities.forEach(function(e){var n;r.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)})})}),i.sort(function(e,t){return t.count-e.count}),r.sort(function(e,t){return t.componentCount-e.componentCount}),{distribution:i,topEntities:r}},n.getArchetypeDistributionWithMemory=function(e){var t=this,n=new Map;return e&&e.entities&&e.entities.forEach(function(e){var i,r=(null===(i=e.components)||void 0===i?void 0:i.map(function(e){return W(e)}))||[],o=r.length>0?r.sort().join(", "):"无组件",s=n.get(o),a=t.estimateEntityMemoryUsage(e);(isNaN(a)||a<0)&&(a=0),s?(s.count++,s.memory+=a):n.set(o,{count:1,memory:a,componentTypes:r})}),Array.from(n.entries()).map(function(e){var t=e[0],n=e[1];return{signature:t,count:n.count,memory:isNaN(n.memory)?0:n.memory}}).sort(function(e,t){return t.count-e.count})},n.getTopEntitiesByComponentsWithMemory=function(e){var t=this;return e&&e.entities?e.entities.map(function(e){var n;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)}}).sort(function(e,t){return t.componentCount-e.componentCount}):[]},n.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},n.calculateFallbackEntityStats=function(e){var t=e.buffer||[],n=t.filter(function(e){return e.enabled&&!e.isDestroyed});return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce(function(e,t){var n;return e+((null===(n=t.components)||void 0===n?void 0:n.length)||0)},0)/n.length:0}},n.estimateEntityMemoryUsage=function(e){var t=this;try{var n=0,i=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),e.components&&Array.isArray(e.components)&&e.components.forEach(function(e){var i=t.calculateObjectSize(e,["entity"]);!isNaN(i)&&i>0&&(n+=i)}),isNaN(n)||n<0?0:n}catch(e){return 0}},n.calculateObjectSize=function(e,t){if(void 0===t&&(t=[]),!e||"object"!=typeof e)return 0;var n=new WeakSet,i=function(e,r){if(void 0===r&&(r=0),!e||"object"!=typeof e||r>=2)return 0;if(n.has(e))return 0;n.add(e);var o=32;try{for(var s=Object.keys(e),a=Math.min(s.length,20),c=0;c<a;c++){var u=s[c];if(u&&!t.includes(u)&&"constructor"!==u&&"__proto__"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__")){var l=e[u];o+=2*u.length,"string"==typeof l?o+=Math.min(2*l.length,200):"number"==typeof l?o+=8:"boolean"==typeof l?o+=4:Array.isArray(l)?o+=40+Math.min(8*l.length,160):"object"==typeof l&&null!==l&&(o+=i(l,r+1))}}}catch(e){return 64}return o};try{var r=i(e);return Math.max(r,32)}catch(e){return 64}},n.buildEntityHierarchyTree=function(t,n){var i=this;if(null==t||!t.buffer)return[];var r=null==n?void 0:n.getSystem(qe),o=[];return t.buffer.forEach(function(t){var n=t.getComponent(e.HierarchyComponent);if(null===(null==n?void 0:n.parentId)||void 0===(null==n?void 0:n.parentId)){var s=i.buildEntityHierarchyNode(t,r);o.push(s)}}),o.sort(function(e,t){return e.name<t.name?-1:e.name>t.name?1:e.id-t.id}),o},n.buildEntityHierarchyNode=function(t,n){var i,r,o,s=this,a=t.getComponent(e.HierarchyComponent),u=null!==(i=null==n?void 0:n.isActiveInHierarchy(t))&&void 0!==i?i:t.active,l=null!==(r=null==n?void 0:n.getDepth(t))&&void 0!==r?r:0,h={id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:u,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),parentId:null!==(o=null==a?void 0:a.parentId)&&void 0!==o?o:null,children:[],depth:l,tag:t.tag||0,updateOrder:t.updateOrder||0};if(n){var d=n.getChildren(t);d.length>0&&(h.children=d.map(function(e){return s.buildEntityHierarchyNode(e,n)}))}"function"==typeof t.getDebugInfo&&(h=c({},h,t.getDebugInfo()));return t.components&&t.components.length>0&&(h.componentDetails=this.extractComponentDetails(t.components)),h},n.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var i=null==t?void 0:t.getSystem(qe),r={},o=e.buffer,s=0;s<o.length;s+=100){o.slice(s,s+100).forEach(function(e){var o,s=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t,i),a=e.getComponentCacheStats?e.getComponentCacheStats():null,u=n.extractComponentDetails(e.components),l=null==i?void 0:i.getParent(e),h=null!==(o=null==l?void 0:l.name)&&void 0!==o?o:null;r[e.id]=c({},s,{parentName:h,components:u,componentTypes:s.componentTypes||u.map(function(e){return e.typeName}),cachePerformance:a?{hitRate:a.cacheStats.hitRate,size:a.cacheStats.size,maxSize:a.cacheStats.maxSize}:null})})}return r},n.buildFallbackEntityInfo=function(t,n,i){var r,o,s,a,c,u,l,h=this.getSceneInfo(n),d=t.getComponent(e.HierarchyComponent),f=null!==(r=null==i?void 0:i.isActiveInHierarchy(t))&&void 0!==r?r:t.active,p=null!==(o=null==i?void 0:i.getDepth(t))&&void 0!==o?o:0;return{name:t.name||"Entity_"+t.id,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:f,destroyed:t.isDestroyed||!1,scene:h.name,sceneName:h.name,sceneType:h.type,componentCount:t.components.length,componentTypes:t.components.map(function(e){return W(e)}),componentMask:(null===(s=t.componentMask)||void 0===s?void 0:s.toString())||"0",parentId:null!==(a=null==d?void 0:d.parentId)&&void 0!==a?a:null,childCount:null!==(c=null==d||null===(u=d.childIds)||void 0===u?void 0:u.length)&&void 0!==c?c:0,childIds:null!==(l=null==d?void 0:d.childIds)&&void 0!==l?l:[],depth:p,tag:t.tag||0,updateOrder:t.updateOrder||0}},n.extractComponentDetails=function(e){var t=this;return e.map(function(e){var n=W(e),i={};try{Object.keys(e).forEach(function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(i[n]=t.formatPropertyValue(r))}}),0===Object.keys(i).length&&(i._info="该组件没有公开属性",i._componentId=W(e))}catch(t){i._error="属性提取失败",i._componentId=W(e)}return{typeName:n,properties:i}})},n.getComponentProperties=function(e,t,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var o=r.buffer.find(function(t){return t.id===e});if(!o||t>=o.components.length)return{};var s=o.components[t];if(!s)return{};var a={};return Object.keys(s).forEach(function(e){if(!e.startsWith("_")&&"entity"!==e){var t=s[e];null!=t&&(a[e]=i.formatPropertyValue(t))}}),a}catch(e){return{_error:"属性提取失败"}}},n.formatPropertyValue=function(e,t){return void 0===t&&(t=0),null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?"[长字符串: "+e.length+"字符] "+e.substring(0,100)+"...":e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)},n.formatObjectFirstLevel=function(e){var t=this;try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){var n=e.slice(0,3).map(function(e){return t.formatPropertyValue(e,1)});return{_isLazyArray:!0,_arrayLength:e.length,_sample:n,_summary:"数组["+e.length+"个元素]"}}return e.map(function(e){return t.formatPropertyValue(e,1)})}var i=Object.keys(e);if(0===i.length)return{};for(var r={},o=0,s=0,a=i;s<a.length;s++){var c=a[s];if(o>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-o;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),o++)}catch(e){r[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",o++}}return r}catch(e){return"[对象解析失败: "+(e instanceof Error?e.message:String(e))+"]"}},n.createLazyLoadPlaceholder=function(e){try{var t,n=(null===(t=e.constructor)||void 0===t?void 0:t.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(e,n),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(e instanceof Error?e.message:String(e)),_objectId:Math.random().toString(36).substr(2,9)}}},n.getObjectSummary=function(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){var n=void 0!==e.z?e.z:"";return t+"("+e.x+", "+e.y+(n?", "+n:"")+")"}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){var i=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+i+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var r,o,s=(null===(r=e.node)||void 0===r?void 0:r.name)||(null===(o=e.node)||void 0===o?void 0:o._name)||"";return t+(s?" on "+s:"")}var a=Object.keys(e);return 0===a.length?t+" (空对象)":t+" ("+a.length+"个属性)"}catch(e){return t+" (无法分析)"}},n.generateObjectId=function(e){try{return void 0!==e.id?"obj_"+e.id:void 0!==e._id?"obj_"+e._id:void 0!==e.uuid?"obj_"+e.uuid:void 0!==e._uuid?"obj_"+e._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(e){return"obj_"+Math.random().toString(36).substr(2,9)}},n.expandLazyObject=function(e,t,n,i){try{if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var o=r.buffer.find(function(t){return t.id===e});if(!o)return null;if(t>=o.components.length)return null;var s=o.components[t],a=this.getObjectByPath(s,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:"展开失败: "+(e instanceof Error?e.message:String(e))}}},n.getObjectByPath=function(e,t){if(!t)return e;for(var n,i=e,r=a(t.split("."));!(n=r()).done;){var o=n.value;if(null==i)return null;if(o.includes("[")&&o.includes("]")){var s=o.substring(0,o.indexOf("[")),c=parseInt(o.substring(o.indexOf("[")+1,o.indexOf("]")));if(s&&(i=i[s]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[o]}return i},t}(),Qe=function(){function e(){}return e.prototype.collectSystemData=function(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};var n=t.systems||[],i=new Map,r=new Map;if(e)try{i=e.getAllSystemStats(),r=e.getAllSystemData()}catch(e){}return{totalSystems:n.length,systemsInfo:n.map(function(e){var t,n=e.systemName||ce(e),o=i.get(n),s=r.get(n);return{name:n,type:ce(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==o?void 0:o.averageTime)||(null==s?void 0:s.executionTime)||0,minExecutionTime:(null==o?void 0:o.minTime)===Number.MAX_VALUE?0:(null==o?void 0:o.minTime)||0,maxExecutionTime:(null==o?void 0:o.maxTime)||0,executionTimeHistory:(null==o?void 0:o.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==s?void 0:s.lastUpdateTime)||0}})}},e}(),Ye=function(){function e(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.gcCollections=0,this.lastMemoryCheck=0}var t=e.prototype;return t.collectPerformanceData=function(e){var t=_.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,s=n>0?o/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter(function(e){return e>=0});return{frameTime:o,engineFrameTime:n,ecsPercentage:s,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce(function(e,t){return e+t},0)/c.length:o,minFrameTime:c.length>0?Math.min.apply(Math,c):o,maxFrameTime:c.length>0?Math.max.apply(Math,c):o,frameTimeHistory:[].concat(this.frameTimeHistory),systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},t.getECSPerformanceData=function(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var t=0,n=[],i=e.getAllSystemStats();if(0===i.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var r,o=a(i.entries());!(r=o()).done;){var s=r.value,c=s[0],u=s[1],l=u.recentTimes&&u.recentTimes.length>0?u.recentTimes[u.recentTimes.length-1]:u.averageTime||0;t+=l,n.push({systemName:c,executionTime:l,percentage:0})}return n.forEach(function(e){e.percentage=t>0?e.executionTime/t*100:0}),n.sort(function(e,t){return t.executionTime-e.executionTime}),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}},t.getSystemPerformance=function(e){if(!e)return[];try{var t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map(function(e){var t=e[0],i=e[1],r=n.get(t);return{systemName:t,averageTime:i.averageTime||0,maxTime:i.maxTime||0,minTime:i.minTime===Number.MAX_VALUE?0:i.minTime||0,samples:i.executionCount||0,percentage:0,entityCount:(null==r?void 0:r.entityCount)||0,lastExecutionTime:(null==r?void 0:r.executionTime)||0}})}catch(e){return[]}},t.getMemoryDetails=function(){var e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e},t.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}},e}(),Je=function(){function e(e,t,n,i){void 0===n&&(n=1e3),void 0===i&&(i=10),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,t&&(this.resetFn=t),this.maxSize=n,this.minSize=Math.max(1,i)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var i=this.createFn();this.resetFn&&this.resetFn(i),this.pool.push(i),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),Ze=function(){function e(){this._pools=new Map,this._usageTracker=new Map,this._autoCleanupInterval=6e4,this._lastCleanupTime=0}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.registerPool=function(e,t,n,i,r){this._pools.set(e,new Je(t,n,i,r)),this._usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this._pools.get(e);return this._trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this._pools.get(e);this._trackUsage(e,"release"),n&&n.release(t)},t._trackUsage=function(e,t){var n=this._usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this._usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this._lastCleanupTime<this._autoCleanupInterval)){for(var t,n=a(this._usageTracker.entries());!(t=n()).done;){var i=t.value,r=i[0];if(e-i[1].lastAccessTime>12e4){var o=this._pools.get(r);o&&o.shrink()}}this._lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this._usageTracker.entries()).filter(function(t){return t[0],t[1].createCount>e}).map(function(e){return e[0]})},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=a(this._pools.values());!(t=n()).done;){t.value.prewarm(e)}},t.clearAll=function(){for(var e,t=a(this._pools.values());!(e=t()).done;){e.value.clear()}},t.reset=function(){this._pools.clear(),this._usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=a(this._pools.entries());!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.push({componentName:r,poolStats:o.getStats(),usage:this._usageTracker.get(r)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,{available:o.getAvailableCount(),maxSize:o.getMaxSize()})}return t},t.getPoolUtilization=function(){for(var e,t=new Map,n=a(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],s=o.getAvailableCount(),c=o.getMaxSize(),u=c-s,l=c>0?u/c*100:0;t.set(r,{used:u,total:c,utilization:l})}return t},t.getComponentUtilization=function(e){var t=this._pools.get(e);if(!t)return 0;var n=t.getAvailableCount(),i=t.getMaxSize();return i>0?(i-n)/i*100:0},e}(),Xe=function(){function e(){}var t=e.prototype;return t.collectComponentData=function(e){var t=this;if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=e.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach(function(e){e.components&&e.components.forEach(function(e){var t=W(e),n=i.get(t)||{count:0,entities:0};n.count++,r++,i.set(t,n)})});var o=new Map,s=new Map;try{for(var c,u=Ze.getInstance(),l=u.getPoolStats(),h=u.getPoolUtilization(),d=a(l.entries());!(c=d()).done;){var f=c.value,p=f[0],m=f[1];s.set(p,m.maxSize)}for(var v,g=a(h.entries());!(v=g()).done;){var y=v.value,_=y[0],S=y[1];o.set(_,S.utilization)}}catch(e){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map(function(i){var r=i[0],a=i[1],c=s.get(r)||0,u=o.get(r)||0,l=t.getEstimatedComponentSize(r,e);return{typeName:r,instanceCount:a.count,memoryPerInstance:l,totalMemory:a.count*l,poolSize:c,poolUtilization:u,averagePerEntity:a.count/n.buffer.length}})}},t.getEstimatedComponentSize=function(t,n){if(e.componentSizeCache.has(t))return e.componentSizeCache.get(t);if(!n)return 64;var i=n.entities;if(null==i||!i.buffer)return 64;var r=64;try{for(var o,s=a(i.buffer);!(o=s()).done;){var c=o.value;if(c.components){var u=c.components.find(function(e){return W(e)===t});if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(e){r=64}return e.componentSizeCache.set(t,r),r},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,i=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var r=0;try{for(var o=Object.keys(e),s=0;s<Math.min(o.length,20);s++){var a=o[s];if(a&&"entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=e[a];r+=2*a.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:"object"==typeof c&&null!==c&&(r+=i(c,t+1))}}}catch(e){return 32}return r};return t+=i(e),Math.max(t,32)},t.calculateDetailedComponentMemory=function(e,t){if(!t)return this.getEstimatedComponentSize(e,t);var n=t.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(e,t);try{for(var i,r=a(n.buffer);!(i=r()).done;){var o=i.value;if(o.components){var s=o.components.find(function(t){return W(t)===e});if(s)return this.estimateObjectSize(s)}}}catch(e){}return this.getEstimatedComponentSize(e,t)},t.estimateObjectSize=function(e,t,n){if(void 0===t&&(t=new WeakSet),void 0===n&&(n=0),null==e||n>10)return 0;if(t.has(e))return 0;var i=0;switch(typeof e){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){i=40+8*e.length;for(var r=Math.min(e.length,50),o=0;o<r;o++)i+=this.estimateObjectSize(e[o],t,n+1)}else{i=32;try{for(var s=Object.getOwnPropertyNames(e),a=Math.min(s.length,30),c=0;c<a;c++){var u=s[c];if(u&&("constructor"!==u&&"__proto__"!==u&&"entity"!==u&&"_entity"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__")))try{i+=16+2*u.length;var l=e[u];null!=l&&(i+=this.estimateObjectSize(l,t,n+1))}catch(e){continue}}}catch(e){i=128}}}return 8*Math.ceil(i/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();Xe.componentSizeCache=new Map;var Ke,$e=function(){function e(){this.sceneStartTime=Date.now()}var t=e.prototype;return t.collectSceneData=function(e){if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneUptime:0};var t=(Date.now()-this.sceneStartTime)/1e3,n=e.getStats();return{currentSceneName:e.name||"Unnamed Scene",isInitialized:!0,sceneRunTime:t,sceneEntityCount:n.entityCount,sceneSystemCount:n.processorCount,sceneUptime:t}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),et=function(){function e(e,t){void 0===t&&(t=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.url=e,this.autoReconnect=t}var t=e.prototype;return t.setMessageHandler=function(e){this.messageHandler=e},t.connect=function(){var e=this;return new Promise(function(t,n){try{e.ws=new WebSocket(e.url),e.ws.onopen=function(n){e.handleOpen(n),t()},e.ws.onclose=function(t){e.handleClose(t)},e.ws.onerror=function(t){e.handleError(t),n(t)},e.ws.onmessage=function(t){e.handleMessage(t)}}catch(t){e.handleConnectionFailure(t),n(t)}})},t.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),delete this.ws),this.isConnected=!1},t.send=function(e){if(this.isConnected&&this.ws)try{var t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}},t.getConnectionStatus=function(){return this.isConnected},t.setMaxReconnectAttempts=function(e){this.maxReconnectAttempts=e},t.scheduleReconnect=function(){var e=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(function(){e.connect().catch(function(t){e.reconnectAttempts<e.maxReconnectAttempts&&e.scheduleReconnect()})},t)},t.handleMessage=function(e){try{var t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}},t.handleOpen=function(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)},t.handleClose=function(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},t.handleError=function(e){this.onError&&this.onError(e)},t.handleConnectionFailure=function(e){this.onError&&this.onError(e)},e}();e.ProfileCategory=void 0,(Ke=e.ProfileCategory||(e.ProfileCategory={})).ECS="ECS",Ke.Rendering="Rendering",Ke.Physics="Physics",Ke.Audio="Audio",Ke.Network="Network",Ke.Script="Script",Ke.Memory="Memory",Ke.Animation="Animation",Ke.AI="AI",Ke.Input="Input",Ke.Loading="Loading",Ke.Custom="Custom";var tt={enabled:!1,maxFrameHistory:300,maxSampleDepth:32,collectMemory:!0,memorySampleInterval:100,detectLongTasks:!0,longTaskThreshold:50,enabledCategories:new Set(Object.values(e.ProfileCategory))},nt=0;var it=function(){function t(e){this.currentFrame=null,this.frameHistory=[],this.frameNumber=0,this.activeSamples=new Map,this.sampleStack=[],this.counters=new Map,this.callGraph=new Map,this.gcCount=0,this.previousHeapSize=0,this.longTasks=[],this.performanceObserver=null,this._config=c({},tt,e),this._config.detectLongTasks&&this._setupLongTaskObserver()}t.getInstance=function(e){return t._instance||(t._instance=new t(e)),t._instance},t.resetInstance=function(){t._instance&&(t._instance.dispose(),t._instance=null)},t.beginSample=function(n,i){return void 0===i&&(i=e.ProfileCategory.Custom),t.getInstance().beginSample(n,i)},t.endSample=function(e){e&&t.getInstance().endSample(e)},t.measure=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().measure(n,i,r)},t.measureAsync=function(){var n=i(d().m(function n(i,r,o){return d().w(function(n){for(;;)if(0===n.n)return void 0===o&&(o=e.ProfileCategory.Custom),n.a(2,t.getInstance().measureAsync(i,r,o))},n)}));return function(e,t,i){return n.apply(this,arguments)}}(),t.beginFrame=function(){t.getInstance().beginFrame()},t.endFrame=function(){t.getInstance().endFrame()},t.incrementCounter=function(n,i,r){void 0===i&&(i=1),void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().incrementCounter(n,i,r)},t.setGauge=function(n,i,r){void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().setGauge(n,i,r)},t.setEnabled=function(e){t.getInstance().setEnabled(e)},t.isEnabled=function(){return t.getInstance()._config.enabled},t.getCurrentFrame=function(){return t.getInstance().currentFrame},t.getFrameHistory=function(){return t.getInstance().frameHistory},t.getReport=function(e){return t.getInstance().generateReport(e)},t.reset=function(){t.getInstance().reset()};var n=t.prototype;return n.beginSample=function(t,n){if(void 0===n&&(n=e.ProfileCategory.Custom),!this._config.enabled||!this._config.enabledCategories.has(n))return null;var i=this.sampleStack.length>0?this.sampleStack[this.sampleStack.length-1]:void 0;if(i&&this.sampleStack.length>=this._config.maxSampleDepth)return null;var r={id:"sample_"+ ++nt+"_"+Date.now(),name:t,category:n,startTime:performance.now(),depth:this.sampleStack.length,parentId:null==i?void 0:i.id};return this.activeSamples.set(r.id,r),this.sampleStack.push(r),r},n.endSample=function(e){if(this._config.enabled&&this.activeSamples.has(e.id)){var t=performance.now(),n=t-e.startTime,i=e.parentId?this.activeSamples.get(e.parentId):void 0,r={id:e.id,name:e.name,category:e.category,startTime:e.startTime,endTime:t,duration:n,selfTime:n,parentId:e.parentId,parentName:null==i?void 0:i.name,depth:e.depth,callCount:1};this.currentFrame&&this.currentFrame.samples.push(r),this._updateCallGraph(e.name,e.category,n,i),this.activeSamples.delete(e.id);var o=this.sampleStack.indexOf(e);-1!==o&&this.sampleStack.splice(o,1)}},n.measure=function(t,n,i){void 0===i&&(i=e.ProfileCategory.Custom);var r=this.beginSample(t,i);try{return n()}finally{r&&this.endSample(r)}},n.measureAsync=function(){var t=i(d().m(function t(n,i,r){var o;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:return void 0===r&&(r=e.ProfileCategory.Custom),o=this.beginSample(n,r),t.p=1,t.n=2,i();case 2:return t.a(2,t.v);case 3:return t.p=3,o&&this.endSample(o),t.f(3);case 4:return t.a(2)}},t,this,[[1,,3,4]])}));return function(e,n,i){return t.apply(this,arguments)}}(),n.beginFrame=function(){this._config.enabled&&(this.frameNumber++,this.currentFrame={frameNumber:this.frameNumber,startTime:performance.now(),endTime:0,duration:0,samples:[],sampleStats:[],counters:new Map(this.counters),memory:this._captureMemory(),categoryStats:new Map},this._resetFrameCounters())},n.endFrame=function(){if(this._config.enabled&&this.currentFrame){for(this.currentFrame.endTime=performance.now(),this.currentFrame.duration=this.currentFrame.endTime-this.currentFrame.startTime,this._calculateSampleStats(),this._calculateCategoryStats(),this.frameHistory.push(this.currentFrame);this.frameHistory.length>this._config.maxFrameHistory;)this.frameHistory.shift();this.sampleStack=[],this.activeSamples.clear()}},n.incrementCounter=function(t,n,i){if(void 0===n&&(n=1),void 0===i&&(i=e.ProfileCategory.Custom),this._config.enabled){var r=this.counters.get(t);r||(r={name:t,category:i,value:0,type:"counter",history:[]},this.counters.set(t,r)),r.value+=n,r.history.push({time:performance.now(),value:r.value}),r.history.length>100&&r.history.shift()}},n.setGauge=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),this._config.enabled){var r=this.counters.get(t);r||(r={name:t,category:i,value:0,type:"gauge",history:[]},this.counters.set(t,r)),r.value=n,r.history.push({time:performance.now(),value:n}),r.history.length>100&&r.history.shift()}},n.setEnabled=function(e){this._config.enabled=e,e&&this._config.detectLongTasks&&!this.performanceObserver&&this._setupLongTaskObserver()},n.reset=function(){this.frameHistory=[],this.currentFrame=null,this.frameNumber=0,this.activeSamples.clear(),this.sampleStack=[],this.counters.clear(),this.callGraph.clear(),this.gcCount=0,this.longTasks=[]},n.generateReport=function(e){var t,n,i=e?this.frameHistory.slice(-e):this.frameHistory;if(0===i.length)return this._createEmptyReport();var r=i.map(function(e){return e.duration}),o=[].concat(r).sort(function(e,t){return e-t}),s=this._aggregateSampleStats(i).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}).slice(0,20),a=this._aggregateCategoryStats(i),c=this._buildCallGraphFromFrames(i),u=i[0],l=i[i.length-1];return{startTime:null!==(t=null==u?void 0:u.startTime)&&void 0!==t?t:0,endTime:null!==(n=null==l?void 0:l.endTime)&&void 0!==n?n:0,totalFrames:i.length,averageFrameTime:r.reduce(function(e,t){return e+t},0)/r.length,minFrameTime:Math.min.apply(Math,r),maxFrameTime:Math.max.apply(Math,r),p95FrameTime:o[Math.floor(.95*o.length)]||0,p99FrameTime:o[Math.floor(.99*o.length)]||0,hotspots:s,callGraph:c,categoryBreakdown:a,memoryTrend:i.map(function(e){return e.memory}),longTasks:[].concat(this.longTasks)}},n._buildCallGraphFromFrames=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.samples);!(r=o()).done;){var s=r.value,c=n.get(s.name);if(c||(c={category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},n.set(s.name,c)),c.callCount++,c.totalTime+=s.duration,s.parentName){var u=c.callers.get(s.parentName)||{count:0,totalTime:0};u.count++,u.totalTime+=s.duration,c.callers.set(s.parentName,u);var l=n.get(s.parentName);l||(l={category:s.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},n.set(s.parentName,l));var h=l.callees.get(s.name)||{count:0,totalTime:0};h.count++,h.totalTime+=s.duration,l.callees.set(s.name,h)}}for(var d,f=new Map,p=a(n);!(d=p()).done;){for(var m,v=d.value,g=v[0],y=v[1],_=new Map,S=a(y.callers);!(m=S()).done;){var C=m.value,E=C[0],b=C[1];_.set(E,{count:b.count,totalTime:b.count>0?b.totalTime/b.count:0})}for(var T,w=new Map,I=a(y.callees);!(T=I()).done;){var M=T.value,A=M[0],k=M[1];w.set(A,{count:k.count,totalTime:k.count>0?k.totalTime/k.count:0})}f.set(g,{name:g,category:y.category,callCount:y.callCount,totalTime:y.callCount>0?y.totalTime/y.callCount:0,callers:_,callees:w})}return f},n.getCallGraph=function(){return new Map(this.callGraph)},n.getFunctionCallInfo=function(e){var t=this.callGraph.get(e);return t?{callers:Array.from(t.callers.entries()).map(function(e){return c({name:e[0]},e[1])}),callees:Array.from(t.callees.entries()).map(function(e){return c({name:e[0]},e[1])})}:null},n.dispose=function(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.reset()},n._captureMemory=function(){var e=performance.now(),t=0,n=0,i=0,r=performance;return r.memory&&(t=r.memory.usedJSHeapSize||0,n=r.memory.totalJSHeapSize||0,i=r.memory.jsHeapSizeLimit||0,this.previousHeapSize>0&&t<this.previousHeapSize-1048576&&this.gcCount++,this.previousHeapSize=t),{timestamp:e,usedHeapSize:t,totalHeapSize:n,heapSizeLimit:i,utilizationPercent:i>0?t/i*100:0,gcCount:this.gcCount}},n._resetFrameCounters=function(){for(var e,t=a(this.counters.values());!(e=t()).done;){var n=e.value;"counter"===n.type&&(n.value=0)}},n._calculateSampleStats=function(){var e=this;if(this.currentFrame){for(var t,n=new Map,i=a(this.currentFrame.samples);!(t=i()).done;){var r=t.value,o=n.get(r.name);o||(o={name:r.name,category:r.category,inclusiveTime:0,exclusiveTime:0,callCount:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,percentOfFrame:0,percentOfParent:0,children:[],depth:r.depth},n.set(r.name,o)),o.inclusiveTime+=r.duration,o.callCount+=1,o.minTime=Math.min(o.minTime,r.duration),o.maxTime=Math.max(o.maxTime,r.duration)}for(var s,c=function(){var t=s.value;if(t.parentId){var i=e.currentFrame.samples.find(function(e){return e.id===t.parentId});if(i){var r=n.get(i.name);if(r){r.exclusiveTime=r.inclusiveTime;for(var o,c=a(e.currentFrame.samples);!(o=c()).done;){var u=o.value;u.parentId===i.id&&(r.exclusiveTime-=u.duration)}}}}},u=a(this.currentFrame.samples);!(s=u()).done;)c();for(var l,h=this.currentFrame.duration||1,d=a(n.values());!(l=d()).done;){var f=l.value;f.averageTime=f.inclusiveTime/f.callCount,f.percentOfFrame=f.inclusiveTime/h*100,0===f.exclusiveTime&&(f.exclusiveTime=f.inclusiveTime)}this.currentFrame.sampleStats=Array.from(n.values()).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime})}},n._calculateCategoryStats=function(){if(this.currentFrame){for(var e,t=new Map,n=a(this.currentFrame.samples);!(e=n()).done;){var i=e.value;if(0===i.depth){var r=t.get(i.category);r||(r={totalTime:0,sampleCount:0},t.set(i.category,r)),r.totalTime+=i.duration,r.sampleCount+=1}}for(var o,s=this.currentFrame.duration||1,u=a(t);!(o=u()).done;){var l=o.value,h=l[0],d=l[1];this.currentFrame.categoryStats.set(h,c({},d,{percentOfFrame:d.totalTime/s*100}))}}},n._updateCallGraph=function(e,t,n,i){var r=this.callGraph.get(e);if(r||(r={name:e,category:t,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(e,r)),r.callCount++,r.totalTime+=n,i){var o=r.callers.get(i.name)||{count:0,totalTime:0};o.count++,o.totalTime+=n,r.callers.set(i.name,o);var s=this.callGraph.get(i.name);s||(s={name:i.name,category:i.category,callCount:0,totalTime:0,callers:new Map,callees:new Map},this.callGraph.set(i.name,s));var a=s.callees.get(e)||{count:0,totalTime:0};a.count++,a.totalTime+=n,s.callees.set(e,a)}},n._aggregateSampleStats=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.sampleStats);!(r=o()).done;){var s=r.value,u=n.get(s.name);u?(u.inclusiveTime+=s.inclusiveTime,u.exclusiveTime+=s.exclusiveTime,u.callCount+=s.callCount,u.minTime=Math.min(u.minTime,s.minTime),u.maxTime=Math.max(u.maxTime,s.maxTime)):(u=c({},s,{minTime:Number.MAX_VALUE}),n.set(s.name,u))}for(var l,h=e.reduce(function(e,t){return e+t.duration},0),d=a(n.values());!(l=d()).done;){var f=l.value;f.averageTime=f.inclusiveTime/f.callCount,f.percentOfFrame=f.inclusiveTime/h*100}return Array.from(n.values())},n._aggregateCategoryStats=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.categoryStats);!(r=o()).done;){var s=r.value,c=s[0],u=s[1],l=n.get(c);l||(l={totalTime:0,frameCount:0},n.set(c,l)),l.totalTime+=u.totalTime,l.frameCount++}for(var h,d=e.reduce(function(e,t){return e+t.duration},0),f=new Map,p=a(n);!(h=p()).done;){var m=h.value,v=m[0],g=m[1];f.set(v,{totalTime:g.totalTime,averageTime:g.frameCount>0?g.totalTime/g.frameCount:0,percentOfTotal:d>0?g.totalTime/d*100:0})}return f},n._setupLongTaskObserver=function(){var e=this;if("undefined"!=typeof PerformanceObserver)try{this.performanceObserver=new PerformanceObserver(function(t){for(var n,i=a(t.getEntries());!(n=i()).done;){var r,o=n.value;if(o.duration>e._config.longTaskThreshold)e.longTasks.push({startTime:o.startTime,duration:o.duration,attribution:(null===(r=o.attribution)||void 0===r?void 0:r.map(function(e){return e.name}))||[]}),e.longTasks.length>100&&e.longTasks.shift()}}),this.performanceObserver.observe({entryTypes:["longtask"]})}catch(e){}},n._createEmptyReport=function(){return{startTime:0,endTime:0,totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,hotspots:[],callGraph:new Map,categoryBreakdown:new Map,memoryTrend:[],longTasks:[]}},t}();it._instance=null;var rt=function(){function t(){this.selectedFunction=null,this.peakMemory=0}var n=t.prototype;return n.setSelectedFunction=function(e){this.selectedFunction=e},n.collectAdvancedData=function(e){var t=it.getFrameHistory(),n=it.getCurrentFrame(),i=it.getReport(300),r=(null==n?void 0:n.memory)||this.getDefaultMemory();return r.usedHeapSize>this.peakMemory&&(this.peakMemory=r.usedHeapSize),{currentFrame:this.buildCurrentFrameData(n),frameTimeHistory:this.buildFrameTimeHistory(t),categoryStats:this.buildCategoryStats(n,e),hotspots:this.buildHotspots(i),callGraph:this.buildCallGraph(i),longTasks:i.longTasks,memoryTrend:this.buildMemoryTrend(i.memoryTrend),summary:this.buildSummary(i,r)}},n.collectFromLegacyMonitor=function(e){var t,n;if(!e)return this.createEmptyData();var i=(null===(t=e.getAllSystemStats)||void 0===t?void 0:t.call(e))||new Map,r=(null===(n=e.getAllSystemData)||void 0===n?void 0:n.call(e))||new Map,o=1e3*_.deltaTime,s=o>0?Math.round(1e3/o):0,a=this.buildCategoryStatsFromLegacy(i,r,o),c=this.buildHotspotsFromLegacy(i,r,o);return{currentFrame:{frameNumber:0,frameTime:o,fps:s,memory:this.getCurrentMemory()},frameTimeHistory:[],categoryStats:a,hotspots:c,callGraph:{currentFunction:this.selectedFunction,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:o,minFrameTime:o,maxFrameTime:o,p95FrameTime:o,p99FrameTime:o,currentMemoryMB:this.getCurrentMemory().usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:0,longTaskCount:0}}},n.buildCurrentFrameData=function(e){if(!e){var t=1e3*_.deltaTime;return{frameNumber:0,frameTime:t,fps:t>0?Math.round(1e3/t):0,memory:this.getCurrentMemory()}}return{frameNumber:e.frameNumber,frameTime:e.duration,fps:e.duration>0?Math.round(1e3/e.duration):0,memory:e.memory}},n.buildFrameTimeHistory=function(e){return e.map(function(e){return{frameNumber:e.frameNumber,time:e.startTime,duration:e.duration}})},n.buildCategoryStats=function(e,t){var n=[];if(e&&e.categoryStats.size>0)for(var i,r=e.duration||1,o=function(){var t=i.value,o=t[0],s=t[1],a=e.sampleStats.filter(function(e){return e.category===o}).map(function(e){return{name:e.name,inclusiveTime:e.inclusiveTime,exclusiveTime:e.exclusiveTime,callCount:e.callCount,percentOfCategory:s.totalTime>0?e.inclusiveTime/s.totalTime*100:0,percentOfFrame:e.inclusiveTime/r*100}}).sort(function(e,t){return t.inclusiveTime-e.inclusiveTime});n.push({category:o,totalTime:s.totalTime,percentOfFrame:s.percentOfFrame,sampleCount:s.sampleCount,items:a})},s=a(e.categoryStats);!(i=s()).done;)o();if(t&&0===n.length){var c,u,l=(null===(c=t.getAllSystemStats)||void 0===c?void 0:c.call(t))||new Map,h=(null===(u=t.getAllSystemData)||void 0===u?void 0:u.call(t))||new Map,d=1e3*_.deltaTime||1;return this.buildCategoryStatsFromLegacy(l,h,d)}return n.sort(function(e,t){return t.totalTime-e.totalTime})},n.buildCategoryStatsFromLegacy=function(t,n,i){for(var r,o=[],s=0,c=a(t.entries());!(r=c()).done;){var u=r.value,l=u[0],h=u[1],d=n.get(l),f=(null==d?void 0:d.executionTime)||(null==h?void 0:h.averageTime)||0;s+=f,o.push({name:l,inclusiveTime:f,exclusiveTime:f,callCount:1,percentOfCategory:0,percentOfFrame:i>0?f/i*100:0})}for(var p=0,m=o;p<m.length;p++){var v=m[p];v.percentOfCategory=s>0?v.inclusiveTime/s*100:0}return o.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}),0===o.length?[]:[{category:e.ProfileCategory.ECS,totalTime:s,percentOfFrame:i>0?s/i*100:0,sampleCount:o.length,items:o}]},n.buildHotspots=function(t){for(var n,i=t.hotspots.reduce(function(e,t){return e+t.inclusiveTime},0)||1,r=new Set,o=new Set,s=a(t.callGraph);!(n=s()).done;){var c=n.value,u=c[0],l=c[1];if(0===l.callers.size)r.add(u);else{for(var h,d=!1,f=a(l.callers.keys());!(h=f()).done;){var p=h.value;if(t.callGraph.has(p)){d=!0,o.add(u);break}}d||r.add(u)}}for(var m,v=function(n,r,o){if(o.has(n))return null;o.add(n);var s=t.hotspots.find(function(e){return e.name===n}),c=t.callGraph.get(n);if(!s&&!c)return null;var u=(null==s?void 0:s.inclusiveTime)||(null==c?void 0:c.totalTime)||0,l=(null==s?void 0:s.exclusiveTime)||u,h=(null==s?void 0:s.callCount)||(null==c?void 0:c.callCount)||1,d=[];if(c&&r<5){for(var f,p=a(c.callees);!(f=p()).done;){var m=f.value[0],g=v(m,r+1,o);g&&d.push(g)}d.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime})}return{name:n,category:(null==s?void 0:s.category)||(null==c?void 0:c.category)||e.ProfileCategory.Custom,inclusiveTime:u,inclusiveTimePercent:u/i*100,exclusiveTime:l,exclusiveTimePercent:l/i*100,callCount:h,avgCallTime:h>0?u/h:0,depth:r,children:d.length>0?d:void 0}},g=[],y=new Set,_=a(r);!(m=_()).done;){var S=m.value,C=v(S,0,y);C&&g.push(C)}return g.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}),g.slice(0,50)},n.buildHotspotsFromLegacy=function(t,n,i){for(var r,o=[],s=a(t.entries());!(r=s()).done;){var c=r.value,u=c[0],l=c[1],h=n.get(u),d=(null==h?void 0:h.executionTime)||(null==l?void 0:l.averageTime)||0;o.push({name:u,category:e.ProfileCategory.ECS,inclusiveTime:d,inclusiveTimePercent:i>0?d/i*100:0,exclusiveTime:d,exclusiveTimePercent:i>0?d/i*100:0,callCount:(null==l?void 0:l.executionCount)||1,avgCallTime:(null==l?void 0:l.averageTime)||d,depth:0})}return o.sort(function(e,t){return t.inclusiveTime-e.inclusiveTime}).slice(0,50)},n.buildCallGraph=function(e){if(!this.selectedFunction)return{currentFunction:null,callers:[],callees:[]};var t=e.callGraph.get(this.selectedFunction);if(!t)return{currentFunction:this.selectedFunction,callers:[],callees:[]};for(var n,i=0,r=a(t.callers.values());!(n=r()).done;){var o=n.value;i+=o.count}var s=Array.from(t.callers.entries()).map(function(e){var t=e[0],n=e[1];return{name:t,callCount:n.count,totalTime:n.totalTime,percentOfCurrent:i>0?n.count/i*100:0}}).sort(function(e,t){return t.callCount-e.callCount}),c=Array.from(t.callees.entries()).map(function(e){var n=e[0],i=e[1];return{name:n,callCount:i.count,totalTime:i.totalTime,percentOfCurrent:t.totalTime>0?i.totalTime/t.totalTime*100:0}}).sort(function(e,t){return t.totalTime-e.totalTime});return{currentFunction:this.selectedFunction,callers:s,callees:c}},n.buildMemoryTrend=function(e){return e.map(function(e){return{time:e.timestamp,usedMB:e.usedHeapSize/1048576,totalMB:e.totalHeapSize/1048576,gcCount:e.gcCount}})},n.buildSummary=function(e,t){return{totalFrames:e.totalFrames,averageFrameTime:e.averageFrameTime,minFrameTime:e.minFrameTime,maxFrameTime:e.maxFrameTime,p95FrameTime:e.p95FrameTime,p99FrameTime:e.p99FrameTime,currentMemoryMB:t.usedHeapSize/1048576,peakMemoryMB:this.peakMemory/1048576,gcCount:t.gcCount,longTaskCount:e.longTasks.length}},n.getCurrentMemory=function(){var e,t,n,i=performance,r=(null===(e=i.memory)||void 0===e?void 0:e.usedJSHeapSize)||0,o=(null===(t=i.memory)||void 0===t?void 0:t.totalJSHeapSize)||0,s=(null===(n=i.memory)||void 0===n?void 0:n.jsHeapSizeLimit)||0;return{timestamp:performance.now(),usedHeapSize:r,totalHeapSize:o,heapSizeLimit:s,utilizationPercent:s>0?r/s*100:0,gcCount:0}},n.getDefaultMemory=function(){return{timestamp:performance.now(),usedHeapSize:0,totalHeapSize:0,heapSizeLimit:0,utilizationPercent:0,gcCount:0}},n.createEmptyData=function(){return{currentFrame:{frameNumber:0,frameTime:0,fps:0,memory:this.getDefaultMemory()},frameTimeHistory:[],categoryStats:[],hotspots:[],callGraph:{currentFunction:null,callers:[],callees:[]},longTasks:[],memoryTrend:[],summary:{totalFrames:0,averageFrameTime:0,minFrameTime:0,maxFrameTime:0,p95FrameTime:0,p99FrameTime:0,currentMemoryMB:0,peakMemoryMB:0,gcCount:0,longTaskCount:0}}},t}();function ot(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){var t=Array.from(e,function(e){return e.toString(16).padStart(2,"0")}).join("");return t.slice(0,8)+"-"+t.slice(8,12)+"-"+t.slice(12,16)+"-"+t.slice(16,20)+"-"+t.slice(20)}(e)}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}()}var st=268435455,at=1048575,ct=1<<28,ut=1<<20;function lt(e,t){return(t&at)*ct+(e&st)}function ht(e){return e&st}function dt(e){return Math.floor(e/ct)&at}function ft(e){return 0!==e}var pt=function(){function e(e,t,n){this._handle=0,this.scene=null,this._isDestroyed=!1,this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=q.clone(q.ZERO),this._componentCache=null,this._lifecyclePolicy=0,this.name=e,this.id=t,this.persistentId=null!=n?n:ot()}var t=e.prototype;return t.setHandle=function(e){this._handle=e},t.setPersistent=function(){return this._lifecyclePolicy=1,this},t.setSceneLocal=function(){return this._lifecyclePolicy=0,this},t.setDestroyedState=function(e){this._isDestroyed=e},t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,i=this.scene.componentRegistry,r=i.getRegisteredCount(),o=0;o<r;o++)if(q.getBit(n,o)){var s=i.getTypeByBitIndex(o);if(s){var a=this.scene.componentStorageManager.getComponent(this.id,s);a&&t.push(a)}}this._componentCache=t}else this._componentCache=t},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];var o=r(e,n);return this.addComponent(o)},t.addComponentInternal=function(e){var t,n,i=e.constructor,r=(null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:ee).getBitMask(i);return q.orInPlace(this._componentMask,r),this._componentCache=null,e},t.notifyQuerySystems=function(e){var t,n,i;null!==(t=this.scene)&&void 0!==t&&t.querySystem&&(this.scene.querySystem.updateEntity(this),this.scene.clearSystemEntityCaches(),null===(n=(i=this.scene).notifyEntityComponentChanged)||void 0===n||n.call(i,this,e))},t.addComponent=function(e){var t,n,i=e.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+H(i));(this.addComponentInternal(e),this.scene.componentStorageManager.addComponent(this.id,e),e.entityId=this.id,null===(t=this.scene.referenceTracker)||void 0===t||t.registerEntityScene(this.id,this.scene),this.scene.isEditorMode?this.scene.queueDeferredComponentCallback(function(){return e.onAddedToEntity()}):e.onAddedToEntity(),this.scene.eventSystem)&&this.scene.eventSystem.emitSync("component:added",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:H(i),component:e});return this.notifyQuerySystems(i),e},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:ee;if(!i.isRegistered(e))return!1;var r=i.getBitMask(e);return q.hasAny(this._componentMask,r)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];t=this.createComponent.apply(this,[e].concat(i))}return t},t.markDirty=function(){if(this.scene){for(var e=this.scene.epochManager.current,t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0,o=n;r<o.length;r++){o[r].markDirty(e)}}},t.removeComponent=function(e){var t,n,i,r,o,s,a=e.constructor,c=null!==(t=null===(n=this.scene)||void 0===n?void 0:n.componentRegistry)&&void 0!==t?t:ee;if(c.isRegistered(a)){var u,l=c.getBitIndex(a);if(q.clearBit(this._componentMask,l),this._componentCache=null,null===(i=this.scene)||void 0===i||null===(i=i.componentStorageManager)||void 0===i||i.removeComponent(this.id,a),null===(r=this.scene)||void 0===r||null===(r=r.referenceTracker)||void 0===r||r.clearComponentReferences(e),null===(o=e.onRemovedFromEntity)||void 0===o||o.call(e),e.entityId=null,null!==(s=this.scene)&&void 0!==s&&s.eventSystem)this.scene.eventSystem.emitSync("component:removed",{timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(u=this.tag)||void 0===u?void 0:u.toString(),componentType:H(a),component:e});this.notifyQuerySystems(a)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var e=[].concat(this.components);q.clear(this._componentMask),this._componentCache=null;for(var t,n=a(e);!(t=n()).done;){var i,r=t.value,o=r.constructor;null===(i=this.scene)||void 0===i||null===(i=i.componentStorageManager)||void 0===i||i.removeComponent(this.id,o),r.onRemovedFromEntity()}this.notifyQuerySystems()},t.addComponents=function(t){for(var n,i=[],r=a(t);!(n=r()).done;){var o=n.value;try{i.push(this.addComponent(o))}catch(t){e._logger.warn("添加组件失败 "+W(o)+":",t)}}return i},t.removeComponentsByTypes=function(e){for(var t,n=[],i=a(e);!(t=i()).done;){var r=t.value;n.push(this.removeComponentByType(r))}return n},t.getComponents=function(e){for(var t,n=[],i=a(this.components);!(t=i()).done;){var r=t.value;r instanceof e&&n.push(r)}return n},t.getComponentByType=function(e){for(var t,n=a(this.components);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.onActiveChanged=function(){for(var e,t=a(this.components);!(e=t()).done;){var n=e.value;"onActiveChanged"in n&&"function"==typeof n.onActiveChanged&&n.onActiveChanged()}this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active})},t.destroy=function(){this._isDestroyed||(this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id)),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this)))},t.compareTo=function(e){return n=e,(t=this).updateOrder-n.updateOrder||t.id-n.id;var t,n},t.toString=function(){return"Entity["+this.name+":"+this.id+":"+this.persistentId.slice(0,8)+"]"},t.getDebugInfo=function(){return{name:this.name,id:this.id,persistentId:this.persistentId,enabled:this._enabled,active:this._active,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map(function(e){return W(e)}),componentMask:q.toString(this._componentMask,2),cacheBuilt:null!==this._componentCache}},s(e,[{key:"lifecyclePolicy",get:function(){return this._lifecyclePolicy}},{key:"isPersistent",get:function(){return 1===this._lifecyclePolicy}},{key:"handle",get:function(){return this._handle}},{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();pt._logger=Z("Entity");var mt=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();for(var n,i=a(this._entitiesToAdd);!(n=i()).done;){var r=n.value;e.push(r.id),r.destroy()}if(this._scene&&this._scene.identifierPool)for(var o,s=a(e);!(o=s()).done;){var c=o.value;this._scene.identifierPool.checkIn(c)}this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0},t.updateLists=function(){if(this._entitiesToAdd.length>0){for(var e,t=a(this._entitiesToAdd);!(e=t()).done;){var n=e.value;this.addImmediate(n)}this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(var i,r=a(this._entitiesToRemove);!(i=r()).done;){var o=i.value;this.removeImmediate(o)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],i=a(this.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],i=a(this.buffer);!(t=i()).done;){var r=t.value;r.hasComponent(e)&&n.push(r)}return n},t.forEach=function(e){for(var t,n=a(this.buffer);!(t=n()).done;){e(t.value)}},t.forEachWhere=function(e,t){for(var n,i=a(this.buffer);!(n=i()).done;){var r=n.value;e(r)&&t(r)}},t.updateNameIndex=function(e,t){if(e.name)if(t){var n=this._nameToEntities.get(e.name);n||(n=[],this._nameToEntities.set(e.name,n)),n.push(e)}else{var i=this._nameToEntities.get(e.name);if(i){var r=i.indexOf(e);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(e.name))}}},t.reorderEntity=function(e,t){var n=this._idToEntity.get(e);if(n){var i=this.buffer.indexOf(n);if(-1!==i&&i!==t){var r=Math.max(0,Math.min(t,this.buffer.length-1));this.buffer.splice(i,1),this.buffer.splice(r,0,n)}}},t.getStats=function(){for(var e,t=0,n=a(this.buffer);!(e=n()).done;){var i=e.value;i.enabled&&!i.isDestroyed&&t++}return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(e,[{key:"count",get:function(){return this.buffer.length}}])}(),vt=function(){function e(e,t){void 0===e&&(e=100),void 0===t&&(t=1024),this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}var t=e.prototype;return t.checkOut=function(){var t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>e.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+e.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}var n=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,n)},t.checkIn=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return!!this._isValidId(t,n)&&(!this._pendingRecycle.some(function(e){return e.index===t&&e.generation===n})&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},t.isValid=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)},t.getStats=function(){for(var t,n=0,i=0,r=a(this._generations);!(t=r()).done;){var o=t.value,s=o[0],c=o[1];s<this._nextAvailableIndex&&(n+=c,i++)}var u=i>0?n/i:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:e.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},t.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},t._processDelayedRecycle=function(t){if(void 0===t&&(t=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],o=[],s=a(this._pendingRecycle);!(n=s()).done;){var c=n.value;t||i-c.timestamp>=this._recycleDelay?r.push(c):o.push(c)}for(var u=0,l=r;u<l.length;u++){var h=l[u];if(this._isValidId(h.index,h.generation)){var d=h.generation+1;d>e.MAX_GENERATION&&(d=1),this._generations.set(h.index,d),this._freeIndices.push(h.index)}}this._pendingRecycle=o}},t._preAllocateGenerations=function(t,n){for(var i=0;i<n;i++){var r=t+i;r<=e.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},t._ensureGenerationCapacity=function(e){if(!this._generations.has(e)){var t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}},t._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},t._packId=function(e,t){return t<<16|e},t._unpackIndex=function(e){return 65535&e},t._unpackGeneration=function(e){return e>>>16&65535},t._isValidId=function(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;var n=this._generations.get(e);return void 0!==n&&n===t},e}();vt.MAX_INDEX=65535,vt.MAX_GENERATION=65535;var gt=function(){function e(){this._processors=[],this._isDirty=!1}var t=e.prototype;return t.setDirty=function(){this._isDirty=!0},t.add=function(e){this._processors.push(e),this.setDirty()},t.remove=function(e){var t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)},t.getProcessor=function(e){for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;try{i.reset()}catch(t){e._logger.error("Error in processor "+ce(i)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=a(this._processors);!(t=n()).done;){var i=t.value;try{i.update()}catch(t){e._logger.error("Error in processor "+ce(i)+":",t)}}},t.lateUpdate=function(){for(var e,t=a(this._processors);!(e=t()).done;){e.value.lateUpdate()}},t.sortProcessors=function(){this._isDirty&&(this._processors.sort(function(e,t){return e.updateOrder-t.updateOrder}),this._isDirty=!1)},s(e,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();gt._logger=Z("EntityProcessorList");var yt=function(){function e(e){if(e&&"object"==typeof e)this._value=q.clone(e);else if("number"==typeof e)this._value=q.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=q.fromNumber(t)}else this._value=q.clone(q.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");q.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");q.clearBit(this._value,e)},t.get=function(e){return q.getBit(this._value,e)},t.containsAll=function(e){return q.hasAll(this._value,e._value)},t.intersects=function(e){return q.hasAny(this._value,e._value)},t.excludes=function(e){return q.hasNone(this._value,e._value)},t.clearAll=function(){q.clear(this._value)},t.isEmpty=function(){return q.isZero(this._value)},t.cardinality=function(){return q.popCount(this._value)},t.and=function(t){var n=new e;return q.copy(this._value,n._value),q.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return q.copy(this._value,n._value),q.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return q.copy(this._value,n._value),q.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(q.copy(this._value,n._value),t<=32){var i=(1<<t)-1;n._value.base[R.LOW]=~n._value.base[R.LOW]&i,n._value.base[R.HIGH]=0}else if(n._value.base[R.LOW]=~n._value.base[R.LOW],t<64){var r=(1<<t-32)-1;n._value.base[R.HIGH]=~n._value.base[R.HIGH]&r}else n._value.base[R.HIGH]=~n._value.base[R.HIGH];return n},t.copyFrom=function(e){q.copy(e._value,this._value)},t.clone=function(){return new e(this._value)},t.getValue=function(){return this._value},t.setValue=function(e){if("object"==typeof e)q.copy(e,this._value);else if("number"==typeof e)this._value=q.fromNumber(e);else{var t=parseInt(e,10);this._value=q.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return q.toString(this._value,16)},e.fromBinaryString=function(t){var n,i=t.replace(/\s/g,"");if(i.length<=32){n={base:[parseInt(i,2)>>>0,0]}}else{var r=i.substring(i.length-32),o=i.substring(0,i.length-32);n={base:[parseInt(r,2)>>>0,parseInt(o,2)>>>0]}}return new e(n)},e.fromHexString=function(t){var n,i=t.replace(/^0x/i,"");if(i.length<=8){n={base:[parseInt(i,16)>>>0,0]}}else{var r=i.substring(i.length-8),o=i.substring(0,i.length-8);n={base:[parseInt(r,16)>>>0,parseInt(o,16)>>>0]}}return new e(n)},t.equals=function(e){return q.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(q.isZero(this._value))return-1;if(0!==this._value.base[R.HIGH])for(var e=31;e>=0;e--)if(this._value.base[R.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[R.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(q.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[R.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[R.HIGH]&1<<t)return t+32;return-1},e}(),_t=function(){function e(){this._dense=[],this._sparse=new Map}var t=e.prototype;return t.add=function(e){if(this._sparse.has(e))return!1;var t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0},t.remove=function(e){var t=this._sparse.get(e);if(void 0===t)return!1;var n=this._dense.length-1;if(t!==n){var i=this._dense[n];this._dense[t]=i,this._sparse.set(i,t)}return this._dense.pop(),this._sparse.delete(e),!0},t.has=function(e){return this._sparse.has(e)},t.getIndex=function(e){return this._sparse.get(e)},t.getByIndex=function(e){return this._dense[e]},t.forEach=function(e){for(var t=0;t<this._dense.length;t++)e(this._dense[t],t)},t.map=function(e){for(var t=[],n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t},t.filter=function(e){for(var t=[],n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t},t.find=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]},t.some=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1},t.every=function(e){for(var t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0},t.getDenseArray=function(){return[].concat(this._dense)},t.getDenseArrayUnsafe=function(){return this._dense},t.clear=function(){this._dense.length=0,this._sparse.clear()},t.toArray=function(){return[].concat(this._dense)},t.toSet=function(){return new Set(this._dense)},t.getMemoryStats=function(){var e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}},t.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var e=0;e<this._dense.length;e++){var t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(var n,i=a(this._sparse);!(n=i()).done;){var r=n.value,o=r[0],s=r[1];if(s>=this._dense.length||this._dense[s]!==o)return!1}return!0},s(e,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),St=function(e){function t(){return e.call(this)||this}return l(t,e),t.prototype.reset=function(){this.clear()},t}(v(Set)),Ct=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new _t}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=q.clone(q.ZERO),i=new Set,r=a(e.components);!(t=r()).done;){var o=t.value.constructor;i.add(o);var s=ee.getBitMask(o);q.orInPlace(n,s)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(q.clone(q.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,i,!0)},t.removeEntity=function(e){var t=this._entities.getIndex(e);if(void 0!==t){var n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);var i=this._componentMasks.length-1;t!==i&&(this._componentMasks[t]=this._componentMasks[i]),this._componentMasks.pop()}},t.queryByComponent=function(e){var t=this._componentToEntities.get(e);return t?new Set(t):new Set},t.queryMultipleAnd=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=q.clone(q.ZERO),o=a(t);!(i=o()).done;){var s=i.value;if(!ee.isRegistered(s))return new Set;var c=ee.getBitMask(s);q.orInPlace(r,c)}var u=e._entitySetPool.obtain();return this._entities.forEach(function(e,t){var i=n._componentMasks[t];q.hasAll(i,r)&&u.add(e)}),u},t.queryMultipleOr=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=q.clone(q.ZERO),o=a(t);!(i=o()).done;){var s=i.value;if(ee.isRegistered(s)){var c=ee.getBitMask(s);q.orInPlace(r,c)}}if(q.equals(r,q.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach(function(e,t){var i=n._componentMasks[t];q.hasAny(i,r)&&u.add(e)}),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!ee.isRegistered(t))return!1;var i=this._componentMasks[n],r=ee.getBitMask(t);return q.hasAny(i,r)},t.getEntityMask=function(e){var t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]},t.getAllEntities=function(){return this._entities.toArray()},t.forEach=function(e){var t=this;this._entities.forEach(function(n,i){e(n,t._componentMasks[i],i)})},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=a(this._componentToEntities.values());!(t=n()).done;){var i=t.value;e._entitySetPool.release(i)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=a(this._componentToEntities.values());!(e=r()).done;){i+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:t.totalMemory+n+i}},t.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var e,t=new Set,n=a(this._componentToEntities.values());!(e=n()).done;)for(var i,r=a(e.value);!(i=r()).done;){var o=i.value;t.add(o)}for(var s,c=a(t);!(s=c()).done;){var u=s.value;if(!this._entities.has(u))return!1}return!0},t.getEntityComponentTypes=function(e){for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value;n.add(r.constructor)}return n},t.updateComponentMappings=function(t,n,i){for(var r,o=a(n);!(r=o()).done;){var s=r.value,c=this._componentToEntities.get(s);i?(c||(c=e._entitySetPool.obtain(),this._componentToEntities.set(s,c)),c.add(t)):c&&(c.delete(t),0===c.size&&(this._componentToEntities.delete(s),e._entitySetPool.release(c)))}},s(e,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();Ct._entitySetPool=x.getPool(St,50,512);var Et,bt=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,i=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(i(e.base[0]>>>0),i(e.base[1]>>>0),e.segments)for(var r,o=a(e.segments);!(r=o()).done;){var s=r.value;i(s[0]>>>0),i(s[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),i=n[0],r=n[1],o=this.buckets.get(i);o||(o=[],this.buckets.set(i,o));for(var s=0;s<o.length;s++)if(o[s][0]===r)return o[s][1]=t,this;return o.push([r,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(r)for(var o=0;o<r.length;o++)if(r[o][0]===i)return r[o][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(!r)return!1;for(var o=0;o<r.length;o++)if(r[o][0]===i)return r.splice(o,1),this._size--,0===r.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=d().m(function e(){var t,n,i,r,o,s,c,u;return d().w(function(e){for(;;)switch(e.n){case 0:t=a(this.buckets);case 1:if((n=t()).done){e.n=5;break}(i=n.value)[0],r=i[1],o=a(r);case 2:if((s=o()).done){e.n=4;break}return(c=s.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}},e,this)}),t.values=d().m(function e(){var t,n,i,r,o,s,c;return d().w(function(e){for(;;)switch(e.n){case 0:t=a(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}i=n.value,r=a(i);case 2:if((o=r()).done){e.n=4;break}return(s=o.value)[0],c=s[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}},e,this)}),s(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),Tt=function(){function e(){this._archetypes=new bt,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),i=this._archetypes.get(n);i||(i=this.createArchetype(t)),i.entities.add(e),this._entityToArchetype.set(e,i)},t.removeEntity=function(e){var t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))},t.updateEntity=function(e){var t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);var n=this.getEntityComponentTypes(e),i=this.generateArchetypeId(n);if(!t||t.id!==i){t&&t.entities.delete(e);var r=this._archetypes.get(i);r||(r=this.createArchetype(n)),r.entities.add(e),this._entityToArchetype.set(e,r)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],i=0;if("AND"===t){if(0===e.length){for(var r,o=a(this._allArchetypes);!(r=o()).done;){var s=r.value;n.push(s),i+=s.entities.size}return{archetypes:n,totalEntities:i}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,l=a(c);!(u=l()).done;){var h=u.value;n.push(h),i+=h.entities.size}return{archetypes:n,totalEntities:i}}for(var d,f,p=1/0,m=a(e);!(f=m()).done;){var v=f.value,g=this._componentToArchetypes.get(v);if(!g||0===g.size)return{archetypes:[],totalEntities:0};g.size<p&&(p=g.size,d=g)}var y=this.generateArchetypeId(e);if(d)for(var _,S=a(d);!(_=S()).done;){var C=_.value;q.hasAll(C.id,y)&&(n.push(C),i+=C.entities.size)}}else{for(var E,b=new Set,T=a(e);!(E=T()).done;){var w=E.value,I=this._componentToArchetypes.get(w);if(I)for(var M,A=a(I);!(M=A()).done;){var k=M.value;b.add(k)}}for(var D,P=a(b);!(D=P()).done;){var O=D.value;n.push(O),i+=O.entities.size}}return{archetypes:n,totalEntities:i}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,i=[],r=a(t);!(n=r()).done;)for(var o,s=a(n.value.entities);!(o=s()).done;){var c=o.value;i.push(c)}return i},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=a(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map(function(e){return e.constructor}),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){for(var t,n=q.clone(q.ZERO),i=a(e);!(t=i()).done;){var r=t.value,o=ee.getBitMask(r);q.orInPlace(n,o)}return n},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var i,r=a(e);!(i=r()).done;){var o=i.value,s=this._componentToArchetypes.get(o);s||(s=new Set,this._componentToArchetypes.set(o,s)),s.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Et||(Et={}));var wt,It=Z("ReactiveQuery");e.ReactiveQueryChangeType=void 0,(wt=e.ReactiveQueryChangeType||(e.ReactiveQueryChangeType={})).ADDED="added",wt.REMOVED="removed",wt.BATCH_UPDATE="batch_update";var Mt=function(){function t(e,t){var n,i,r;void 0===t&&(t={}),this._entities=[],this._entityIdSet=new Set,this._snapshot=null,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:null===(n=t.enableBatchMode)||void 0===n||n,batchDelay:null!==(i=t.batchDelay)&&void 0!==i?i:16,debug:null!==(r=t.debug)&&void 0!==r&&r},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&It.debug("创建ReactiveQuery: "+this._id)}var n=t.prototype;return n.generateQueryId=function(){return this._condition.type+":"+this._condition.componentTypes.map(function(e){return e.name}).sort().join(",")},n.subscribe=function(e){var t=this;if(!this._active)throw new Error("Cannot subscribe to disposed ReactiveQuery "+this._id);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&It.debug("订阅ReactiveQuery: "+this._id+", 监听器数量: "+this._listeners.length),function(){var n=t._listeners.indexOf(e);-1!==n&&t._listeners.splice(n,1)}},n.unsubscribeAll=function(){this._listeners.length=0},n.getEntities=function(){return null!==this._snapshot||(this._snapshot=[].concat(this._entities)),this._snapshot},n.matches=function(e){var t=e.componentMask;switch(this._condition.type){case Et.ALL:return q.hasAll(t,this._condition.mask);case Et.ANY:return q.hasAny(t,this._condition.mask);case Et.NONE:return q.hasNone(t,this._condition.mask);default:return!1}},n.notifyEntityAdded=function(t){this._active&&this.matches(t)&&(this._entityIdSet.has(t.id)||(this._entities.push(t),this._entityIdSet.add(t.id),this._snapshot=null,this._config.enableBatchMode?this.addToBatch("added",t):this.notifyListeners({type:e.ReactiveQueryChangeType.ADDED,entity:t}),this._config.debug&&It.debug("ReactiveQuery "+this._id+": 实体添加 "+t.name+"("+t.id+")")))},n.notifyEntityRemoved=function(t){if(this._active&&this._entityIdSet.has(t.id)){var n=this._entities.indexOf(t);-1!==n&&this._entities.splice(n,1),this._entityIdSet.delete(t.id),this._snapshot=null,this._config.enableBatchMode?this.addToBatch("removed",t):this.notifyListeners({type:e.ReactiveQueryChangeType.REMOVED,entity:t}),this._config.debug&&It.debug("ReactiveQuery "+this._id+": 实体移除 "+t.name+"("+t.id+")")}},n.notifyEntityChanged=function(e){if(this._active){var t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}},n.initializeWith=function(e){this._entities.length=0,this._entityIdSet.clear(),this._snapshot=null;for(var t,n=a(e);!(t=n()).done;){var i=t.value;this.matches(i)&&(this._entities.push(i),this._entityIdSet.add(i.id))}this._config.debug&&It.debug("ReactiveQuery "+this._id+": 初始化 "+this._entities.length+" 个实体")},n.addToBatch=function(e,t){var n=this;"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout(function(){n.flushBatchChanges()},this._config.batchDelay))},n.flushBatchChanges=function(){if(0!==this._batchChanges.added.length||0!==this._batchChanges.removed.length){var t=[].concat(this._batchChanges.added),n=[].concat(this._batchChanges.removed);this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:e.ReactiveQueryChangeType.BATCH_UPDATE,added:t,removed:n,entities:this._entities}),this._config.debug&&It.debug("ReactiveQuery "+this._id+": 批量更新 +"+t.length+" -"+n.length)}else this._batchChanges.timer=null},n.notifyListeners=function(e){for(var t,n=a([].concat(this._listeners));!(t=n()).done;){var i=t.value;try{i(e)}catch(e){It.error("ReactiveQuery "+this._id+": 监听器执行出错",e)}}},n.pause=function(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0},n.resume=function(){this._active=!0},n.dispose=function(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._snapshot=null,this._config.debug&&It.debug("ReactiveQuery "+this._id+": 已销毁")},s(t,[{key:"count",get:function(){return this._entities.length}},{key:"condition",get:function(){return this._condition}},{key:"id",get:function(){return this._id}},{key:"active",get:function(){return this._active}},{key:"listenerCount",get:function(){return this._listeners.length}}])}(),At=function(){function e(e){this._lastVersion=-1,this._cachedEntities=[],this._querySystem=e;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this._componentTypes=n}var t=e.prototype;return t._refreshCache=function(){var e=this._querySystem.version;if(this._lastVersion!==e){var t,n=(t=this._querySystem).queryAll.apply(t,this._componentTypes);this._cachedEntities=n.entities,this._lastVersion=e}},t.forEach=function(e){for(var t=this.entities,n=this._componentTypes,i=n.length,r=0,o=t.length;r<o;r++){for(var s=t[r],a=new Array(i),c=0;c<i;c++){var u=s.getComponent(n[c]);u&&(a[c]=u)}e.apply(void 0,[s].concat(a))}},t.forEachChanged=function(e,t){for(var n=this.entities,i=this._componentTypes,r=i.length,o=0,s=n.length;o<s;o++){for(var a=n[o],c=new Array(r),u=!1,l=0;l<r;l++){var h=a.getComponent(i[l]);h&&(c[l]=h,h.lastWriteEpoch>e&&(u=!0))}u&&t.apply(void 0,[a].concat(c))}},t.first=function(){var e=this.entities;if(0===e.length)return null;for(var t,n=e[0],i=[],r=a(this._componentTypes);!(t=r()).done;){var o=t.value,s=n.getComponent(o);if(!s)return null;i.push(s)}return[n].concat(i)},t.toArray=function(){var e=[];return this.forEach(function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];e.push([t].concat(i))}),e},t.map=function(e){var t=[];return this.forEach(function(n){for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];t.push(e.apply(void 0,[n].concat(r)))}),t},t.filter=function(e){var t=[];return this.forEach(function(n){for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];e.apply(void 0,[n].concat(r))&&t.push(n)}),t},t.find=function(e){for(var t=this.entities,n=this._componentTypes,i=n.length,r=0,o=t.length;r<o;r++){for(var s=t[r],a=new Array(i),c=0;c<i;c++){var u=s.getComponent(n[c]);u&&(a[c]=u)}if(e.apply(void 0,[s].concat(a)))return s}},t.any=function(){return this.count>0},t.empty=function(){return 0===this.count},s(e,[{key:"componentTypes",get:function(){return this._componentTypes}},{key:"entities",get:function(){return this._refreshCache(),this._cachedEntities}},{key:"count",get:function(){return this.entities.length}}])}(),kt=function(){function e(){this._logger=Z("QuerySystem"),this._entities=[],this._version=0,this._queryCache=new Map,this._cacheMaxSize=1e3,this._cacheTimeout=5e3,this._componentMaskCache=new Map,this._queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this._entityIndex={byTag:new Map,byName:new Map},this._archetypeSystem=new Tt}var t=e.prototype;return t.setEntities=function(e){this._entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this._entities.includes(e)||(this._entities.push(e),this.addEntityToIndexes(e),this._archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)},t.addEntities=function(e){if(0!==e.length){for(var t,n=new Set(this._entities.map(function(e){return e.id})),i=0,r=a(e);!(t=r()).done;){var o=t.value;n.has(o.id)||(this._entities.push(o),this.addEntityToIndexes(o),this._archetypeSystem.addEntity(o),n.add(o.id),i++)}i>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=a(e);!(t=n()).done;){var i=t.value;this._entities.push(i)}for(var r,o=a(e);!(r=o()).done;){var s=r.value;this.addEntityToIndexes(s),this._archetypeSystem.addEntity(s)}this.clearQueryCache()}},t.removeEntity=function(e){var t=this._entities.indexOf(e);if(-1!==t){for(var n,i=[],r=a(e.components);!(n=r()).done;){var o=n.value;i.push(o.constructor)}this._entities.splice(t,1),this.removeEntityFromIndexes(e),this._archetypeSystem.removeEntity(e),i.length>0?this.notifyReactiveQueriesEntityRemoved(e,i):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}},t.updateEntity=function(e){this._entities.includes(e)?(this.removeEntityFromIndexes(e),this._archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this._entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this._entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this._entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this._entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this._entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this._entityIndex.byTag.delete(e.tag))}if(e.name){var n=this._entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this._entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this._entityIndex.byTag.clear(),this._entityIndex.byName.clear(),this._archetypeSystem.clear();for(var e,t=a(this._entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this._archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Et.ALL,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryAny=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Et.ANY,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryNone=function(){var e=performance.now();this._queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Et.NONE,n).getEntities();return this._queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryByTag=function(e){var t=performance.now();this._queryStats.totalQueries++;var n="tag:"+e,i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=Array.from(this._entityIndex.byTag.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this._queryStats.totalQueries++;var n="name:"+e,i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=Array.from(this._entityIndex.byName.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryChangedSince=function(e){var t=performance.now();this._queryStats.totalQueries++,this._queryStats.dirtyChecks++;for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var o,s=[],c=a(this.queryAll.apply(this,i).entities);!(o=c()).done;){for(var u,l=o.value,h=!1,d=a(i);!(u=d()).done;){var f=u.value,p=l.getComponent(f);if(p&&p.lastWriteEpoch>e){h=!0;break}}h&&s.push(l)}return{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this._queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),i=this.getFromCache(n);if(i)return this._queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this._queryStats.indexHits++;var r=this._archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.getFromCache=function(e){var t=this._queryCache.get(e);return t?Date.now()-t.timestamp>this._cacheTimeout||t.version!==this._version?(this._queryCache.delete(e),null):(t.hitCount++,t.entities):null},t.addToCache=function(e,t){this._queryCache.size>=this._cacheMaxSize&&this.cleanupCache(),this._queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})},t.cleanupCache=function(){for(var e,t=Date.now(),n=a(this._queryCache.entries());!(e=n()).done;){var i=e.value,r=i[0];t-i[1].timestamp>this._cacheTimeout&&this._queryCache.delete(r)}if(this._queryCache.size>=this._cacheMaxSize){for(var o,s=1/0,c="",u=1/0,l=a(this._queryCache.entries());!(o=l()).done;){var h=o.value,d=h[0],f=h[1];(f.hitCount<s||f.hitCount===s&&f.timestamp<u)&&(s=f.hitCount,c=d,u=f.timestamp)}c&&this._queryCache.delete(c)}},t.clearQueryCache=function(){this._queryCache.clear(),this._componentMaskCache.clear()},t.clearReactiveQueries=function(){for(var e,t=a(this._reactiveQueries.values());!(e=t()).done;){e.value.dispose()}this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+H(t[0]):e+":"+t.map(function(e){return H(e)}).sort().join(",")},t.clearCache=function(){this.clearQueryCache(),this.clearReactiveQueries()},t.compile=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r(At,[this].concat(t))},t.createReactiveQuery=function(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");var n=this.createComponentMask(e),i={type:Et.ALL,componentTypes:e,mask:n},r=new Mt(i,t),o=this.executeTraditionalQuery(Et.ALL,e);r.initializeWith(o);var s=this.generateCacheKey("all",e);this._reactiveQueries.set(s,r);for(var c,u=a(e);!(c=u()).done;){var l=c.value,h=this._reactiveQueriesByComponent.get(l);h||(h=new Set,this._reactiveQueriesByComponent.set(l,h)),h.add(r)}return r},t.destroyReactiveQuery=function(e){if(e){var t=e.id;this._reactiveQueries.delete(t);for(var n,i=a(e.condition.componentTypes);!(n=i()).done;){var r=n.value,o=this._reactiveQueriesByComponent.get(r);o&&(o.delete(e),0===o.size&&this._reactiveQueriesByComponent.delete(r))}e.dispose()}},t.createComponentMask=function(e){var t=e.map(function(e){return H(e)}).sort().join(","),n=this._componentMaskCache.get(t);if(n)return n;for(var i,r=q.clone(q.ZERO),o=a(e);!(i=o()).done;){var s=i.value,c=ee.getBitMask(s);q.orInPlace(r,c)}return this._componentMaskCache.set(t,r),r},t.getAllEntities=function(){return this._entities},t.getStats=function(){return{entityCount:this._entities.length,indexStats:{componentIndexSize:this._archetypeSystem.getAllArchetypes().length,tagIndexSize:this._entityIndex.byTag.size,nameIndexSize:this._entityIndex.byName.size},queryStats:c({},this._queryStats,{cacheHitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this._archetypeSystem.getAllArchetypes().map(function(e){return{id:e.id,componentTypes:e.componentTypes.map(function(e){return H(e)}),entityCount:e.entities.size}})},cacheStats:{size:this._reactiveQueries.size,hitRate:this._queryStats.totalQueries>0?(this._queryStats.cacheHits/this._queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},t.getEntityArchetype=function(e){return this._archetypeSystem.getEntityArchetype(e)},t.getOrCreateReactiveQuery=function(e,t){var n=this.generateCacheKey(e,t),i=this._reactiveQueries.get(n);if(!i){var r=this.createComponentMask(t);i=new Mt({type:e,componentTypes:t,mask:r},{enableBatchMode:!1,debug:!1});var o=this.executeTraditionalQuery(e,t);i.initializeWith(o),this._reactiveQueries.set(n,i);for(var s,c=a(t);!(s=c()).done;){var u=s.value,l=this._reactiveQueriesByComponent.get(u);l||(l=new Set,this._reactiveQueriesByComponent.set(u,l)),l.add(i)}this._logger.debug("创建内部响应式查询缓存: "+n)}return i},t.executeTraditionalQuery=function(e,t){switch(e){case Et.ALL:for(var n,i=[],r=a(this._archetypeSystem.queryArchetypes(t,"AND").archetypes);!(n=r()).done;)for(var o,s=a(n.value.entities);!(o=s()).done;){var c=o.value;i.push(c)}return i;case Et.ANY:for(var u,l=[],h=a(this._archetypeSystem.queryArchetypes(t,"OR").archetypes);!(u=h()).done;)for(var d,f=a(u.value.entities);!(d=f()).done;){var p=d.value;l.push(p)}return l;case Et.NONE:var m=this.createComponentMask(t);return this._entities.filter(function(e){return q.hasNone(e.componentMask,m)});default:return[]}},t.notifyReactiveQueriesEntityAdded=function(e){if(0!==this._reactiveQueries.size)for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value.constructor,o=this._reactiveQueriesByComponent.get(r);if(o)for(var s,c=a(o);!(s=c()).done;){var u=s.value;n.has(u)||(u.notifyEntityAdded(e),n.add(u))}}},t.notifyReactiveQueriesEntityRemoved=function(e,t){if(0!==this._reactiveQueries.size)for(var n,i=new Set,r=a(t);!(n=r()).done;){var o=n.value,s=this._reactiveQueriesByComponent.get(o);if(s)for(var c,u=a(s);!(c=u()).done;){var l=c.value;i.has(l)||(l.notifyEntityRemoved(e),i.add(l))}}},t.notifyReactiveQueriesEntityRemovedFallback=function(e){if(0!==this._reactiveQueries.size)for(var t,n=a(this._reactiveQueries.values());!(t=n()).done;){t.value.notifyEntityRemoved(e)}},t.notifyReactiveQueriesEntityChanged=function(e){if(0!==this._reactiveQueries.size){for(var t,n=new Set,i=a(e.components);!(t=i()).done;){var r=t.value.constructor,o=this._reactiveQueriesByComponent.get(r);if(o)for(var s,c=a(o);!(s=c()).done;){var u=s.value;n.has(u)||(u.notifyEntityChanged(e),n.add(u))}}for(var l,h=a(this._reactiveQueries.values());!(l=h()).done;){var d=l.value;n.has(d)||d.notifyEntityChanged(e)}}},s(e,[{key:"version",get:function(){return this._version}}])}(),Dt=function(){function e(e){this._logger=Z("QueryBuilder"),this.conditions=[],this.querySystem=e}var t=e.prototype;return t.withAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Et.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this},t.withAny=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Et.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this},t.without=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Et.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case Et.ALL:return(e=this.querySystem).queryAll.apply(e,r.componentTypes);case Et.ANY:return(t=this.querySystem).queryAny.apply(t,r.componentTypes);case Et.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=q.clone(q.ZERO),i=a(e);!(t=i()).done;){var r=t.value;try{var o=ee.getBitMask(r);q.orInPlace(n,o)}catch(e){this._logger.warn("组件类型 "+H(r)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),Pt=function(){function e(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}var t=e.prototype;return t.on=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,n)},t.once=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,c({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,c({},n,{async:!0}))},t.off=function(e,t){var n=this.listeners.get(e);if(!n)return!1;var i=n.findIndex(function(e){return e.id===t});return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)},t.offAll=function(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)},t.emit=function(){var e=i(d().m(function e(t,n){var i;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.isEnabled){e.n=1;break}return e.a(2);case 1:if(null==(i=this.batchConfigs.get(t))||!i.enabled){e.n=2;break}return this.addToBatch(t,n),e.a(2);case 2:return e.n=3,this.executeEvent(t,n);case 3:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.emitSync=function(t,n){if(this.isEnabled){var i=this.listeners.get(t);if(i&&0!==i.length){for(var r,o=performance.now(),s=[],c=a(this.sortListenersByPriority(i));!(r=c()).done;){var u=r.value;if(!u.config.async)try{u.config.thisArg?u.handler.call(u.config.thisArg,n):u.handler(n),u.config.once&&s.push(u.id)}catch(n){e._logger.error("事件处理器执行错误 "+t+":",n)}}this.removeListeners(t,s),this.updateStats(t,performance.now()-o)}}},t.setBatchConfig=function(e,t){this.batchConfigs.set(e,t)},t.flushBatch=function(e){var t=this.batchQueue.get(e);if(t&&0!==t.length){var n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}},t.getStats=function(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)},t.resetStats=function(e){e?this.stats.delete(e):this.stats.clear()},t.setEnabled=function(e){this.isEnabled=e},t.hasListeners=function(e){var t=this.listeners.get(e);return!!t&&t.length>0},t.getListenerCount=function(e){var t=this.listeners.get(e);return t?t.length:0},t.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},t.setMaxListeners=function(e){this.maxListeners=e},t.addListener=function(t,n,i){var r=this.listeners.get(t);if(r||(r=[],this.listeners.set(t,r)),r.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var o="listener_"+this.nextListenerId++,s={handler:n,config:c({priority:0},i),id:o};return r.push(s),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),o},t.executeEvent=function(){var t=i(d().m(function t(n,r){var o,s,c,u,l,h,f,p,m,v;return d().w(function(t){for(;;)switch(t.n){case 0:if((o=this.listeners.get(n))&&0!==o.length){t.n=1;break}return t.a(2);case 1:for(s=performance.now(),c=[],u=this.sortListenersByPriority(o),l=u.filter(function(e){return!e.config.async}),h=u.filter(function(e){return e.config.async}),f=a(l);!(p=f()).done;){m=p.value;try{m.config.thisArg?m.handler.call(m.config.thisArg,r):m.handler(r),m.config.once&&c.push(m.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+n+":",t)}}return v=h.map(function(){var t=i(d().m(function t(i){var o;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!i.config.thisArg){t.n=2;break}return t.n=1,i.handler.call(i.config.thisArg,r);case 1:t.n=3;break;case 2:return t.n=3,i.handler(r);case 3:i.config.once&&c.push(i.id),t.n=5;break;case 4:t.p=4,o=t.v,e._logger.error("异步事件处理器执行错误 "+n+":",o);case 5:return t.a(2)}},t,null,[[0,4]])}));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(v);case 2:this.removeListeners(n,c),this.updateStats(n,performance.now()-s);case 3:return t.a(2)}},t,this)}));return function(e,n){return t.apply(this,arguments)}}(),t.sortListenersByPriority=function(e){return e.slice().sort(function(e,t){return(t.config.priority||0)-(e.config.priority||0)})},t.removeListeners=function(e,t){if(0!==t.length){var n=this.listeners.get(e);if(n){for(var i,r=function(){var e=i.value,t=n.findIndex(function(t){return t.id===e});-1!==t&&n.splice(t,1)},o=a(t);!(i=o()).done;)r();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,i=this.batchQueue.get(e);i||(i=[],this.batchQueue.set(e,i)),i.push(t);var r=this.batchConfigs.get(e);if(i.length>=r.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var o=setTimeout(function(){n.flushBatch(e)},r.delay);this.batchTimers.set(e,o)}},t.processBatch=function(){var e=i(d().m(function e(t,n){var i;return d().w(function(e){for(;;)switch(e.n){case 0:return i={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",i);case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.clearBatch=function(e){this.batchQueue.delete(e);var t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))},t.clearAllBatches=function(){this.batchQueue.clear();for(var e,t=a(this.batchTimers.values());!(e=t()).done;){var n=e.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},t.updateStats=function(e,t){var n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)},t.createEmptyStats=function(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},e}();Pt._logger=Z("EventSystem");var Ot=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},s(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),xt=function(){function e(e,t,n,i,r){this._all=e||[],this._any=t||[],this._none=n||[],void 0!==i&&(this._tag=i),void 0!==r&&(this._name=r)}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,i=Fe.complex();this._all.length>0&&(i=(e=i).all.apply(e,this._all));this._any.length>0&&(i=(t=i).any.apply(t,this._any));this._none.length>0&&(i=(n=i).none.apply(n,this._none));return void 0!==this._tag&&(i=i.withTag(this._tag)),void 0!==this._name&&(i=i.withName(this._name)),i},t.getCondition=function(){return c({all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none)},void 0!==this._tag&&{tag:this._tag},void 0!==this._name&&{name:this._name})},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var Rt=new Map;function zt(e,t){Rt.set(e,t)}zt("Date",{check:function(e){return e instanceof Date},serialize:function(e){return{__type:"Date",value:e.toISOString()}},deserialize:function(e){return new Date(e.value)}}),zt("Map",{check:function(e){return e instanceof Map},serialize:function(e,t){return{__type:"Map",value:[].concat(e).map(function(e){var n=e[0],i=e[1];return[t(n),t(i)]})}},deserialize:function(e){return new Map(e.value)}}),zt("Set",{check:function(e){return e instanceof Set},serialize:function(e,t){return{__type:"Set",value:[].concat(e).map(t)}},deserialize:function(e){return new Set(e.value)}});var Nt,Ft={serialize:function e(t,n){if(void 0===n&&(n=new WeakSet),null==t)return t;var i=typeof t;if("string"===i||"number"===i||"boolean"===i)return t;if("function"!==i){var r=t;if(!n.has(r)){n.add(r);for(var o,s=a(Rt);!(o=s()).done;){var c=o.value[1];if(c.check(t))return c.serialize(t,function(t){return e(t,n)})}if(Array.isArray(t))return t.map(function(t){return e(t,n)});for(var u={},l=0,h=Object.keys(t);l<h.length;l++){var d=h[l];u[d]=e(t[d],n)}return u}}},deserialize:function e(t){if(null==t)return t;var n=typeof t;if("string"===n||"number"===n||"boolean"===n)return t;if(function(e){if(null===e||"object"!=typeof e)return!1;return"__type"in e}(t)){var i=Rt.get(t.__type);return i?i.deserialize(t):t}if(Array.isArray(t))return t.map(e);for(var r={},o=0,s=Object.keys(t);o<s.length;o++){var a=s[o];r[a]=e(t[a])}return r},register:zt},Bt=Z("ComponentSerializer"),Lt=function(){function e(){}return e.serialize=function(e){var t=Ne(e);if(!t)return null;for(var n,i=e.constructor,r=t.options.typeId||H(i),o={},s=a(t.fields);!(n=s()).done;){var c=n.value,u=c[0],l=c[1];if(!t.ignoredFields.has(u)){var h="symbol"==typeof u?u.toString():u,d=e[u],f=void 0;f=_e(e,h)?this.serializeEntityRef(d):l.serializer?l.serializer(d):Ft.serialize(d),o[l.alias||h]=f}}return{type:r,version:t.options.version,data:o}},e.deserialize=function(e,t,n){var i=t.get(e.type);if(!i)return Bt.warn("Component type not found: "+e.type+" | 未找到组件类型: "+e.type),null;var r=Ne(i);if(!r)return Bt.warn("Component "+e.type+" is not serializable | 组件 "+e.type+" 不可序列化"),null;for(var o,s=new i,c=a(r.fields);!(o=c()).done;){var u=o.value,l=u[0],h=u[1],d="symbol"==typeof l?l.toString():l,f=h.alias||d,p=e.data[f];if(void 0!==p)if(this.isSerializedEntityRef(p)){if(n){var m=p.__entityRef;n.registerPendingRef(s,d,m.id,m.guid)}s[l]=null}else{var v=h.deserializer?h.deserializer(p):Ft.deserialize(p);s[l]=v}}return s},e.serializeComponents=function(e){var t=this;return e.map(function(e){return t.serialize(e)}).filter(function(e){return null!==e})},e.deserializeComponents=function(e,t,n){var i=this;return e.map(function(e){return i.deserialize(e,t,n)}).filter(function(e){return null!==e})},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=Ne(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||H(n),version:t.options.version,fields:Array.from(t.fields.keys()).map(function(e){return"symbol"==typeof e?e.toString():e}),ignoredFields:Array.from(t.ignoredFields).map(function(e){return"symbol"==typeof e?e.toString():e}),isSerializable:!0}},e.serializeEntityRef=function(e){return e?{__entityRef:{id:e.id,guid:e.persistentId}}:null},e.isSerializedEntityRef=function(e){return"object"==typeof e&&null!==e&&"__entityRef"in e},e}(),Ht=function(){function t(){}return t.serialize=function(t,n,i){void 0===n&&(n=!0);var r=Lt.serializeComponents(Array.from(t.components)),o={id:t.id,guid:t.persistentId,name:t.name,tag:t.tag,active:t.active,enabled:t.enabled,updateOrder:t.updateOrder,components:r,children:[]},s=t.getComponent(e.HierarchyComponent);if(null!==(null==s?void 0:s.parentId)&&void 0!==(null==s?void 0:s.parentId)&&(o.parentId=s.parentId),n&&s&&s.childIds.length>0){var c,u=null!==(c=null==i?void 0:i.scene)&&void 0!==c?c:t.scene;if(u)for(var l,h=a(s.childIds);!(l=h()).done;){var d=l.value,f=u.findEntityById(d);f&&o.children.push(this.serialize(f,!0,i))}}return o},t.deserialize=function(t,n,i,r,o,s,c,u){void 0===r&&(r=!1);var l=r?t.id:i(),h=new pt(t.name,l,t.guid);null==c||c.set(h.id,h),u&&u.registerEntity(h,t.id,t.guid),o&&(h.scene=o),h.tag=t.tag,h.active=t.active,h.enabled=t.enabled,h.updateOrder=t.updateOrder;for(var d,f=a(Lt.deserializeComponents(t.components,n,u));!(d=f()).done;){var p=d.value;h.addComponent(p)}var m=h.getComponent(e.HierarchyComponent);m&&(m.parentId=null,m.childIds=[]);for(var v,g=a(t.children);!(v=g()).done;){var y=v.value,_=this.deserialize(y,n,i,r,o,s,c,u);null==s||s.setParent(_,h)}return h},t.serializeEntities=function(t,n,i){void 0===n&&(n=!0);for(var r,o=[],s=a(t);!(r=s()).done;){var c=r.value,u=c.getComponent(e.HierarchyComponent);null!==(null==u?void 0:u.parentId)&&void 0!==(null==u?void 0:u.parentId)&&n||o.push(this.serialize(c,n,i))}return o},t.deserializeEntities=function(e,t,n,i,r,o,s){void 0===i&&(i=!1);for(var c,u=[],l=new Map,h=a(e);!(c=h()).done;){var d=c.value,f=this.deserialize(d,t,n,i,r,o,l,s);u.push(f)}return{rootEntities:u,allEntities:l}},t.clone=function(e,t,n){var i=this.serialize(e,!0);return this.deserialize(i,t,n,!1)},t}(),Wt=function(){function e(){}return e.stringToUtf8=function(e){for(var t=e.length,n=0,i=[],r=0;r<t;r++){var o=e.charCodeAt(r);if(o>=55296&&o<=56319&&r+1<t){var s=o,a=e.charCodeAt(r+1);a>=56320&&a<=57343&&(o=65536+(s-55296<<10)+(a-56320),r++)}o<128?i[n++]=o:o<2048?(i[n++]=192|o>>6,i[n++]=128|63&o):o<65536?(i[n++]=224|o>>12,i[n++]=128|o>>6&63,i[n++]=128|63&o):(i[n++]=240|o>>18,i[n++]=128|o>>12&63,i[n++]=128|o>>6&63,i[n++]=128|63&o)}return new Uint8Array(i)},e.utf8ToString=function(e){for(var t=e.length,n="",i=0;i<t;){var r=e[i++];if(void 0===r)break;if(r<128)n+=String.fromCharCode(r);else if(192==(224&r)){var o=e[i++];if(void 0===o)break;n+=String.fromCharCode((31&r)<<6|63&o)}else if(224==(240&r)){var s=e[i++],a=e[i++];if(void 0===s||void 0===a)break;n+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&a)}else if(240==(248&r)){var c=e[i++],u=e[i++],l=e[i++];if(void 0===c||void 0===u||void 0===l)break;var h=(7&r)<<18|(63&c)<<12|(63&u)<<6|63&l;h-=65536,n+=String.fromCharCode(55296+(h>>10),56320+(1023&h))}}return n},e.encode=function(e){var t=JSON.stringify(e);return this.stringToUtf8(t)},e.decode=function(e){var t=this.utf8ToString(e);return JSON.parse(t)},e}(),Ut=function(){function e(){this._idRemapping=new Map,this._guidLookup=new Map,this._pendingRefs=[],this._preserveIds=!1}var t=e.prototype;return t.setPreserveIds=function(e){this._preserveIds=e},t.registerEntity=function(e,t,n){var i=null!=n?n:e.persistentId;this._guidLookup.set(i,e),void 0!==t&&this._idRemapping.set(t,e)},t.getEntityById=function(e){var t;return null!==(t=this._idRemapping.get(e))&&void 0!==t?t:null},t.getEntityByGuid=function(e){var t;return null!==(t=this._guidLookup.get(e))&&void 0!==t?t:null},t.resolveEntityRef=function(e){if(!e)return null;if(e.guid){var t=this._guidLookup.get(e.guid);if(t)return t}if(void 0!==e.id){var n=this._idRemapping.get(e.id);if(n)return n}return null},t.registerPendingRef=function(e,t,n,i){this._pendingRefs.push({component:e,propertyKey:t,originalId:n,originalGuid:i})},t.resolveAllReferences=function(){for(var e,t=0,n=a(this._pendingRefs);!(e=n()).done;){var i=e.value,r=this.resolveEntityRef({id:i.originalId,guid:i.originalGuid});r&&(i.component[i.propertyKey]=r,t++)}return t},t.getUnresolvedCount=function(){for(var e,t=0,n=a(this._pendingRefs);!(e=n()).done;){var i=e.value;this.resolveEntityRef({id:i.originalId,guid:i.originalGuid})||t++}return t},t.getPendingCount=function(){return this._pendingRefs.length},t.getRegisteredEntityCount=function(){return this._guidLookup.size},t.clear=function(){this._idRemapping.clear(),this._guidLookup.clear(),this._pendingRefs=[]},t.getDebugInfo=function(){return{registeredEntities:this._guidLookup.size,pendingRefs:this._pendingRefs.length,unresolvedRefs:this.getUnresolvedCount(),preserveIds:this._preserveIds}},s(e,[{key:"preserveIds",get:function(){return this._preserveIds}}])}(),Gt=Z("SceneSerializer"),jt=function(){function t(){}return t.serialize=function(e,t){var n=c({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),i=this.filterEntities(e,n),r=e.getSystem(qe),o=Ht.serializeEntities(i,!0,null!=r?r:void 0),s=this.buildComponentTypeRegistry(i),a=this.serializeSceneData(e.sceneData),u={name:e.name,version:this.SERIALIZATION_VERSION,entities:o,componentTypeRegistry:s};return a&&Object.keys(a).length>0&&(u.sceneData=a),n.includeMetadata&&(u.timestamp=Date.now(),u.metadata={entityCount:o.length,componentTypeCount:s.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(u,null,2):JSON.stringify(u):Wt.encode(u)},t.deserialize=function(e,t,n){var i,r=c({strategy:"replace",preserveIds:!1},n);try{i="string"==typeof t?JSON.parse(t):Wt.decode(t)}catch(e){throw new Error("Failed to parse save data: "+e)}r.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=r.migration(i.version,this.SERIALIZATION_VERSION,i));var o=r.componentRegistry||this.getGlobalComponentRegistry();"replace"===r.strategy&&e.destroyAllEntities();var s=e.getSystem(qe),u=new Ut;u.setPreserveIds(r.preserveIds||!1);for(var l,h=Ht.deserializeEntities(i.entities,o,function(){return e.identifierPool.checkOut()},r.preserveIds||!1,e,s,u),d=h.rootEntities,f=h.allEntities,p=a(d);!(l=p()).done;){var m=l.value;e.addEntity(m,!0),this.addChildrenRecursively(m,e,s,f)}e.querySystem.clearCache(),e.clearSystemEntityCaches();var v=u.resolveAllReferences(),g=u.getUnresolvedCount();g>0&&Gt.warn(g+" EntityRef(s) could not be resolved. Resolved: "+v+", Total pending: "+u.getPendingCount()+" | "+g+" 个实体引用无法解析"),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData);for(var y,_=[],S=a(f.values());!(y=S()).done;){var C=y.value;this.callOnDeserializedForEntity(C,_)}_.length>0&&Promise.all(_).catch(function(e){Gt.error("Error in onDeserialized | onDeserialized 执行错误:",e)})},t.callOnDeserializedForEntity=function(e,t){for(var n,i=a(e.components);!(n=i()).done;){var r=n.value;try{var o=r.onDeserialized();o instanceof Promise&&t.push(o)}catch(e){var s=H(r.constructor);Gt.error("Error calling onDeserialized on component "+s+" | 调用组件 "+s+" 的 onDeserialized 时出错:",e)}}},t.addChildrenRecursively=function(t,n,i,r){var o=t.getComponent(e.HierarchyComponent);if(o&&0!==o.childIds.length)for(var s,c=a(o.childIds);!(s=c()).done;){var u,l=s.value,h=null!==(u=null==r?void 0:r.get(l))&&void 0!==u?u:n.findEntityById(l);h&&(n.addEntity(h,!0),this.addChildrenRecursively(h,n,i,r))}},t.serializeSceneData=function(e){for(var t,n={},i=a(e);!(t=i()).done;){var r=t.value,o=r[0],s=r[1];n[o]=Ft.serialize(s)}return n},t.deserializeSceneData=function(e,t){t.clear();for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],o=r[0],s=r[1];t.set(o,Ft.deserialize(s))}},t.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var i=new Set(t.components);return n.filter(function(e){return Array.from(e.components).some(function(e){return i.has(e.constructor)})})}return n},t.buildComponentTypeRegistry=function(e){for(var t,n=new Map,i=a(e);!(t=i()).done;)for(var r,o=a(t.value.components);!(r=o()).done;){var s=r.value,c=H(s.constructor),u=Ne(s);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map(function(e){return{typeName:e[0],version:e[1]}})},t.getGlobalComponentRegistry=function(){return ee.getAllComponentNames()},t.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),c({valid:0===t.length,version:n.version},t.length>0&&{errors:t})}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},t.getInfo=function(e){try{var t,n=JSON.parse(e);return c({name:n.name,version:n.version},void 0!==n.timestamp&&{timestamp:n.timestamp},{entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length})}catch(e){return null}},t}();jt.SERIALIZATION_VERSION=1,e.ChangeOperation=void 0,(Nt=e.ChangeOperation||(e.ChangeOperation={})).EntityAdded="entity_added",Nt.EntityRemoved="entity_removed",Nt.EntityUpdated="entity_updated",Nt.ComponentAdded="component_added",Nt.ComponentRemoved="component_removed",Nt.ComponentUpdated="component_updated",Nt.SceneDataUpdated="scene_data_updated";var qt={deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1,format:"json",pretty:!1},Vt=function(){function t(){}return t.createSnapshot=function(t,n){for(var i,r=c({},qt,n),o={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},s=a(t.entities.buffer);!(i=s()).done;){var u=i.value;if(!r.entityFilter||r.entityFilter(u)){o.entityIds.add(u.id);var l=u.getComponent(e.HierarchyComponent),h=null==l?void 0:l.parentId;if(o.entities.set(u.id,c({name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder},null!=h&&{parentId:h})),r.deepComponentComparison){for(var d,f=new Map,p=a(u.components);!(d=p()).done;){var m=d.value,v=Lt.serialize(m);v&&f.set(v.type,JSON.stringify(v.data))}f.size>0&&o.components.set(u.id,f)}}}if(r.trackSceneData)for(var g,y=a(t.sceneData);!(g=y()).done;){var _=g.value,S=_[0],C=_[1];o.sceneData.set(S,JSON.stringify(C))}return o},t.computeIncremental=function(t,n,i){for(var r,o=c({},qt,i),s={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:t.name,baseVersion:n.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},u=new Set,l=a(t.entities.buffer);!(r=l()).done;){var h=r.value;if(!o.entityFilter||o.entityFilter(h)){u.add(h.id);var d=h.getComponent(e.HierarchyComponent),f=null==d?void 0:d.parentId;if(n.entityIds.has(h.id)){var p=n.entities.get(h.id);(p.name!==h.name||p.tag!==h.tag||p.active!==h.active||p.enabled!==h.enabled||p.updateOrder!==h.updateOrder||p.parentId!==f)&&s.entityChanges.push({operation:e.ChangeOperation.EntityUpdated,entityId:h.id,entityData:c({name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder},null!=f&&{parentId:f})}),o.deepComponentComparison&&this.detectComponentChanges(h,n,s.componentChanges)}else{s.entityChanges.push({operation:e.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:c({id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder},null!=f&&{parentId:f},{components:[],children:[]})});for(var m,v=a(h.components);!(m=v()).done;){var g=m.value,y=Lt.serialize(g);y&&s.componentChanges.push({operation:e.ChangeOperation.ComponentAdded,entityId:h.id,componentType:y.type,componentData:y})}}}}for(var _,S=a(n.entityIds);!(_=S()).done;){var C=_.value;u.has(C)||s.entityChanges.push({operation:e.ChangeOperation.EntityRemoved,entityId:C})}return o.trackSceneData&&this.detectSceneDataChanges(t,n,s.sceneDataChanges),s},t.detectComponentChanges=function(t,n,i){for(var r,o=n.components.get(t.id),s=new Map,c=a(t.components);!(r=c()).done;){var u=r.value,l=Lt.serialize(u);l&&s.set(l.type,l)}for(var h,d=a(s);!(h=d()).done;){var f=h.value,p=f[0],m=f[1],v=JSON.stringify(m.data);o&&o.has(p)?o.get(p)!==v&&i.push({operation:e.ChangeOperation.ComponentUpdated,entityId:t.id,componentType:p,componentData:m}):i.push({operation:e.ChangeOperation.ComponentAdded,entityId:t.id,componentType:p,componentData:m})}if(o)for(var g,y=a(o.keys());!(g=y()).done;){var _=g.value;s.has(_)||i.push({operation:e.ChangeOperation.ComponentRemoved,entityId:t.id,componentType:_})}},t.detectSceneDataChanges=function(t,n,i){for(var r,o=new Set,s=a(t.sceneData);!(r=s()).done;){var c=r.value,u=c[0],l=c[1];o.add(u);var h=JSON.stringify(l),d=n.sceneData.get(u);d&&d===h||i.push({operation:e.ChangeOperation.SceneDataUpdated,key:u,value:l})}for(var f,p=a(n.sceneData.keys());!(f=p()).done;){var m=f.value;o.has(m)||i.push({operation:e.ChangeOperation.SceneDataUpdated,key:m,value:void 0,deleted:!0})}},t.applyIncremental=function(t,n,i){for(var r,o=a(n.entityChanges);!(r=o()).done;){var s=r.value;switch(s.operation){case e.ChangeOperation.EntityAdded:this.applyEntityAdded(t,s);break;case e.ChangeOperation.EntityRemoved:this.applyEntityRemoved(t,s);break;case e.ChangeOperation.EntityUpdated:this.applyEntityUpdated(t,s)}}for(var c,u=a(n.componentChanges);!(c=u()).done;){var l=c.value;switch(l.operation){case e.ChangeOperation.ComponentAdded:this.applyComponentAdded(t,l,i);break;case e.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(t,l,i);break;case e.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(t,l,i)}}for(var h,d=a(n.sceneDataChanges);!(h=d()).done;){var f=h.value;f.deleted?t.sceneData.delete(f.key):t.sceneData.set(f.key,f.value)}},t.applyEntityAdded=function(e,t){var n,i;if(t.entityData){var r=new pt(t.entityName||"Entity",t.entityId);r.tag=t.entityData.tag||0,r.active=null===(n=t.entityData.active)||void 0===n||n,r.enabled=null===(i=t.entityData.enabled)||void 0===i||i,r.updateOrder=t.entityData.updateOrder||0,e.addEntity(r)}},t.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},t.applyEntityUpdated=function(t,n){if(n.entityData){var i=t.entities.findEntityById(n.entityId);if(i){void 0!==n.entityData.name&&(i.name=n.entityData.name),void 0!==n.entityData.tag&&(i.tag=n.entityData.tag),void 0!==n.entityData.active&&(i.active=n.entityData.active),void 0!==n.entityData.enabled&&(i.enabled=n.entityData.enabled),void 0!==n.entityData.updateOrder&&(i.updateOrder=n.entityData.updateOrder);var r=t.getSystem(qe);if(r){var o=i.getComponent(e.HierarchyComponent),s=null==o?void 0:o.parentId;if(void 0!==n.entityData.parentId){var a=t.entities.findEntityById(n.entityData.parentId);a&&s!==n.entityData.parentId&&r.setParent(i,a)}else null!=s&&r.setParent(i,null)}}}},t.applyComponentAdded=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=Lt.deserialize(t.componentData,n);r&&i.addComponent(r)}}},t.applyComponentRemoved=function(e,t,n){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);r&&i.removeComponentByType(r)}},t.applyComponentUpdated=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);if(r){i.removeComponentByType(r);var o=Lt.deserialize(t.componentData,n);o&&i.addComponent(o)}}}},t.serializeIncremental=function(e,t){var n,i,r=null!==(n=null==t?void 0:t.format)&&void 0!==n?n:"json",o=null!==(i=null==t?void 0:t.pretty)&&void 0!==i&&i;return"binary"===r?Wt.encode(e):o?JSON.stringify(e,null,2):JSON.stringify(e)},t.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):Wt.decode(e)},t.getIncrementalStats=function(t){for(var n,i={added:0,removed:0,updated:0},r={added:0,removed:0,updated:0},o=a(t.entityChanges);!(n=o()).done;){var s=n.value;s.operation===e.ChangeOperation.EntityAdded?i.added++:s.operation===e.ChangeOperation.EntityRemoved?i.removed++:s.operation===e.ChangeOperation.EntityUpdated&&i.updated++}for(var c,u=a(t.componentChanges);!(c=u()).done;){var l=c.value;l.operation===e.ChangeOperation.ComponentAdded?r.added++:l.operation===e.ChangeOperation.ComponentRemoved?r.removed++:l.operation===e.ChangeOperation.ComponentUpdated&&r.updated++}return{totalChanges:t.entityChanges.length+t.componentChanges.length+t.sceneDataChanges.length,entityChanges:t.entityChanges.length,componentChanges:t.componentChanges.length,sceneDataChanges:t.sceneDataChanges.length,addedEntities:i.added,removedEntities:i.removed,updatedEntities:i.updated,addedComponents:r.added,removedComponents:r.removed,updatedComponents:r.updated}},t.resetVersion=function(){this.snapshotVersion=0},t}();Vt.snapshotVersion=0;var Qt={enabled:!0,sampleInterval:10,minDuration:.1,trackAsync:!0,excludePatterns:[/^_/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/],maxBufferSize:1e4},Yt=function(){function t(e){this.wrappedObjects=new WeakMap,this.samplingProfiler=null,this.registeredClasses=new Map,this._config=c({},Qt,e)}t.getInstance=function(e){return t._instance||(t._instance=new t(e)),t._instance},t.resetInstance=function(){t._instance&&(t._instance.dispose(),t._instance=null)},t.setEnabled=function(e){t.getInstance().setEnabled(e)},t.registerClass=function(n,i,r){return void 0===i&&(i=e.ProfileCategory.Custom),t.getInstance().registerClass(n,i,r)},t.wrapInstance=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().wrapInstance(n,i,r)},t.wrapFunction=function(n,i,r){return void 0===r&&(r=e.ProfileCategory.Custom),t.getInstance().wrapFunction(n,i,r)},t.startSampling=function(){t.getInstance().startSampling()},t.stopSampling=function(){return t.getInstance().stopSampling()};var n=t.prototype;return n.setEnabled=function(e){this._config.enabled=e,!e&&this.samplingProfiler&&this.samplingProfiler.stop()},n.registerClass=function(t,n,i){void 0===n&&(n=e.ProfileCategory.Custom);var r=i||t.name;this.registeredClasses.set(r,{constructor:t,category:n});var o=this;return new Proxy(t,{construct:function(e,t,i){var s=Reflect.construct(e,t,i);return o._config.enabled&&o.wrapInstance(s,r,n),s}})},n.wrapInstance=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),!this._config.enabled)return t;if(this.wrappedObjects.has(t))return t;var r=new Map;this.wrappedObjects.set(t,r);for(var o,s=a(this._getAllMethodNames(t));!(o=s()).done;){var c=o.value;if(!this._shouldExcludeMethod(c)){var u=this._getPropertyDescriptor(t,c);if(u&&"function"==typeof u.value){var l=u.value,h=this._createWrappedMethod(l,n,c,i);r.set(c,{className:n,methodName:c,category:i,original:l});try{t[c]=h}catch(e){}}}}return t},n.wrapFunction=function(t,n,i){if(void 0===i&&(i=e.ProfileCategory.Custom),!this._config.enabled)return t;var r=this,o=function(){var e=it.beginSample(n,i);try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];var c=t.apply(this,s);return r._config.trackAsync&&c instanceof Promise?c.finally(function(){it.endSample(e)}):(it.endSample(e),c)}catch(t){throw it.endSample(e),t}};return Object.defineProperty(o,"name",{value:t.name||n}),Object.defineProperty(o,"length",{value:t.length}),o},n.startSampling=function(){this.samplingProfiler||(this.samplingProfiler=new Jt(this._config)),this.samplingProfiler.start()},n.stopSampling=function(){return this.samplingProfiler?this.samplingProfiler.stop():[]},n.dispose=function(){this.samplingProfiler&&(this.samplingProfiler.stop(),this.samplingProfiler=null),this.registeredClasses.clear()},n._createWrappedMethod=function(e,t,n,i){var r=this,o=t+"."+n,s=this._config.minDuration;return function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];if(!r._config.enabled||!it.isEnabled())return e.apply(this,n);var c=performance.now(),u=it.beginSample(o,i);try{var l=e.apply(this,n);return r._config.trackAsync&&l instanceof Promise?l.then(function(e){return performance.now()-c>=s&&it.endSample(u),e},function(e){throw it.endSample(u),e}):(performance.now()-c>=s&&it.endSample(u),l)}catch(e){throw it.endSample(u),e}}},n._getAllMethodNames=function(e){for(var t=new Set,n=e;n&&n!==Object.prototype;){for(var i,r=a(Object.getOwnPropertyNames(n));!(i=r()).done;){var o=i.value;"constructor"!==o&&t.add(o)}n=Object.getPrototypeOf(n)}return Array.from(t)},n._getPropertyDescriptor=function(e,t){for(var n=e;n&&n!==Object.prototype;){var i=Object.getOwnPropertyDescriptor(n,t);if(i)return i;n=Object.getPrototypeOf(n)}},n._shouldExcludeMethod=function(e){if("constructor"===e||e.startsWith("__"))return!0;for(var t,n=a(this._config.excludePatterns);!(t=n()).done;){if(t.value.test(e))return!0}return!1},t}();Yt._instance=null;var Jt=function(){function e(e){this.samples=[],this.intervalId=null,this.isRunning=!1,this.config=e}var t=e.prototype;return t.start=function(){var e=this;if(!this.isRunning){this.isRunning=!0,this.samples=[];var t=function(){if(e.isRunning){var n=e.captureStack();n.length>0&&(e.samples.push({timestamp:performance.now(),stack:n}),e.samples.length>e.config.maxBufferSize&&e.samples.shift()),e.config.sampleInterval,e.intervalId=setTimeout(t,e.config.sampleInterval)}};t()}},t.stop=function(){return this.isRunning=!1,null!==this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),[].concat(this.samples)},t.captureStack=function(){try{for(var e,t=((new Error).stack||"").split("\n").slice(3),n=[],i=a(t);!(e=i()).done;){var r=e.value,o=this.parseStackFrame(r);o&&!this.isInternalFrame(o)&&n.push(o)}return n}catch(e){return[]}},t.parseStackFrame=function(e){var t=(e=e.trim()).match(/at\s+(.+?)\s+\(/);if(t&&t[1])return t[1];if((t=e.match(/at\s+(.+)/))&&t[1]){var n=t[1];if(!n.includes("("))return n}return(t=e.match(/^(.+?)@/))&&t[1]?t[1]:null},t.isInternalFrame=function(e){return["SamplingProfiler","AutoProfiler","ProfilerSDK","setTimeout","setInterval","requestAnimationFrame","<anonymous>","eval"].some(function(t){return e.includes(t)})},e}();var Zt,Xt=Z("ServiceContainer");e.ServiceLifetime=void 0,(Zt=e.ServiceLifetime||(e.ServiceLifetime={})).Singleton="singleton",Zt.Transient="transient";var Kt=function(){function t(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var n=t.prototype;return n.registerSingleton=function(t,n){this._services.has(t)?Xt.warn("Service "+t.name+" is already registered"):(this._services.set(t,c({identifier:t,type:t},n&&{factory:n},{lifetime:e.ServiceLifetime.Singleton})),Xt.debug("Registered singleton service: "+t.name))},n.registerTransient=function(t,n){this._services.has(t)?Xt.warn("Service "+t.name+" is already registered"):(this._services.set(t,c({identifier:t,type:t},n&&{factory:n},{lifetime:e.ServiceLifetime.Transient})),Xt.debug("Registered transient service: "+t.name))},n.registerInstance=function(t,n){if(this._services.has(t)){var i="symbol"==typeof t?t.description:t.name;Xt.warn("Service "+i+" is already registered")}else{if(this._services.set(t,{identifier:t,instance:n,lifetime:e.ServiceLifetime.Singleton}),"symbol"!=typeof t&&D(t)){var r,o=P(t),s=null!==(r=null==o?void 0:o.priority)&&void 0!==r?r:0;this._updatableServices.push({instance:n,priority:s}),this._updatableServices.sort(function(e,t){return e.priority-t.priority}),Xt.debug("Service "+t.name+" is updatable (priority: "+s+"), added to update list")}var a="symbol"==typeof t?t.description:t.name;Xt.debug("Registered service instance: "+a)}},n.resolve=function(t){var n=this._services.get(t),i="symbol"==typeof t?t.description:t.name;if(!n)throw new Error("Service "+i+" is not registered");if(this._resolving.has(t)){var r=Array.from(this._resolving).map(function(e){return"symbol"==typeof e?e.description:e.name}).join(" -> ");throw new Error("Circular dependency detected: "+r+" -> "+i)}if(n.lifetime===e.ServiceLifetime.Singleton&&n.instance)return n.instance;this._resolving.add(t);try{var o;if(n.factory)o=n.factory(this);else{if(!n.type)throw new Error("Service "+i+" has no factory or type to construct");o=new n.type}if(n.lifetime===e.ServiceLifetime.Singleton&&(n.instance=o,n.type&&D(n.type))){var s,a=P(n.type),c=null!==(s=null==a?void 0:a.priority)&&void 0!==s?s:0;this._updatableServices.push({instance:o,priority:c}),this._updatableServices.sort(function(e,t){return e.priority-t.priority}),Xt.debug("Service "+i+" is updatable (priority: "+c+"), added to update list")}return o}finally{this._resolving.delete(t)}},n.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},n.isRegistered=function(e){return this._services.has(e)},n.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex(function(e){return e.instance===t.instance});-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}this._services.delete(e);var i="symbol"==typeof e?e.description:e.name;return Xt.debug("Unregistered service: "+i),!0},n.clear=function(){for(var e,t=a(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],Xt.debug("Cleared all services")},n.getRegisteredServices=function(){return Array.from(this._services.keys())},n.updateAll=function(e){for(var t,n=a(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},n.getUpdatableCount=function(){return this._updatableServices.length},n.getAll=function(){for(var e,t=[],n=a(this._services.values());!(e=n()).done;){var i=e.value;i.instance&&t.push(i.instance)}return t},t}(),$t=function(e){function t(n){var i,r="[SystemDependencyGraph] 检测到循环依赖 | Cycle dependency detected: "+n.join(" -> ");return(i=e.call(this,r)||this).name="CycleDependencyError",i.involvedNodes=n,Object.setPrototypeOf(i,(this instanceof t?this.constructor:void 0).prototype),i}return l(t,e),t}(v(Error)),en="set:",tn=function(){function e(){this._nodes=new Map}var t=e.prototype;return t.addSystemNode=function(e){this.getOrCreateNode(e,!1)},t.addSetNode=function(e){var t=en+e;this.getOrCreateNode(t,!0)},t.addEdge=function(e,t){if(e!==t){var n=this.getOrCreateNode(e,e.startsWith(en)),i=this.getOrCreateNode(t,t.startsWith(en));n.outEdges.add(t),i.inEdges.add(e)}},t.buildFromSystems=function(e){this.clear();for(var t,n=a(e);!(t=n()).done;){var i=t.value;this.addSystemNode(i.name);for(var r,o=a(i.sets);!(r=o()).done;){var s=r.value;this.addSetNode(s)}}for(var c,u=a(e);!(c=u()).done;){for(var l,h=c.value,d=a(h.sets);!(l=d()).done;){var f=l.value,p=en+f;this.addEdge(p,h.name)}for(var m,v=a(h.before);!(m=v()).done;){var g=m.value,y=this.resolveTargetId(g);this.addEdge(h.name,y)}for(var _,S=a(h.after);!(_=S()).done;){var C=_.value,E=this.resolveTargetId(C);this.addEdge(E,h.name)}}},t.topologicalSort=function(){for(var e,t=new Map,n=a(this._nodes);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,o.inEdges.size)}for(var s,c=[],u=a(t);!(s=u()).done;){var l=s.value,h=l[0];0===l[1]&&c.push(h)}for(var d=[],f=0;c.length>0;){var p=c.shift();f++;var m=this._nodes.get(p);if(m){m.bIsVirtual||d.push(p);for(var v,g=a(m.outEdges);!(v=g()).done;){var y,_=v.value,S=(null!==(y=t.get(_))&&void 0!==y?y:0)-1;t.set(_,S),0===S&&c.push(_)}}}if(f<this._nodes.size){for(var C,E=[],b=a(t);!(C=b()).done;){var T=C.value,w=T[0];T[1]>0&&E.push(w)}throw new $t(E)}return d},t.clear=function(){this._nodes.clear()},t.getOrCreateNode=function(e,t){var n=this._nodes.get(e);return n||(n={id:e,bIsVirtual:t,inEdges:new Set,outEdges:new Set},this._nodes.set(e,n)),n},t.resolveTargetId=function(e){return e.startsWith(en),e},s(e,[{key:"size",get:function(){return this._nodes.size}}])}(),nn=Z("SystemScheduler"),rn=["startup","preUpdate","update","postUpdate","cleanup"],on=function(){function e(){this._sortedByStage=new Map,this._dirty=!0,this._graph=new tn,this._useDependencySort=!0}var t=e.prototype;return t.setUseDependencySort=function(e){this._useDependencySort!==e&&(this._useDependencySort=e,this._dirty=!0)},t.markDirty=function(){this._dirty=!0},t.getSortedSystems=function(e,t){var n;if(this.ensureBuilt(e),t)return null!==(n=this._sortedByStage.get(t))&&void 0!==n?n:[];for(var i=[],r=0,o=rn;r<o.length;r++){var s=o[r],a=this._sortedByStage.get(s);a&&i.push.apply(i,a)}return i},t.getAllSortedSystems=function(e){return this.getSortedSystems(e)},t.ensureBuilt=function(e){this._dirty&&(this._sortedByStage.clear(),this._useDependencySort&&this.hasDependencies(e)?this.buildWithDependencyGraph(e):this.buildWithUpdateOrder(e),this._dirty=!1)},t.hasDependencies=function(e){for(var t,n=a(e);!(t=n()).done;){var i=t.value,r=this.getSchedulingMetadata(i);if(r.before.length>0||r.after.length>0||r.sets.length>0)return!0;if("update"!==r.stage)return!0}return!1},t.buildWithUpdateOrder=function(e){var t=[].concat(e).sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder});this._sortedByStage.set("update",t)},t.buildWithDependencyGraph=function(e){for(var t=new Map,n=0,i=rn;n<i.length;n++){var r=i[n];t.set(r,[])}for(var o,s=a(e);!(o=s()).done;){var c=o.value,u=this.getSchedulingMetadata(c).stage,l=t.get(u);l?l.push(c):t.get("update").push(c)}for(var h,d=a(t);!(h=d()).done;){var f=h.value,p=f[0],m=f[1];if(0!==m.length){var v=this.sortSystemsInStage(m);this._sortedByStage.set(p,v)}else this._sortedByStage.set(p,[])}},t.sortSystemsInStage=function(e){for(var t,n=new Map,i=[],r=a(e);!(t=r()).done;){var o=t.value,s=o.systemName;n.set(s,o);var c=this.getSchedulingMetadata(o);i.push({name:s,before:c.before,after:c.after,sets:c.sets})}this._graph.buildFromSystems(i);try{for(var u,l=this._graph.topologicalSort(),h=[],d=a(l);!(u=d()).done;){var f=u.value,p=n.get(f);p&&h.push(p)}return this.stableSortByUpdateOrder(h)}catch(t){if(t instanceof $t)throw t;return nn.warn("Topological sort failed, falling back to updateOrder | 拓扑排序失败,回退到 updateOrder 排序",t),this.fallbackSort(e)}},t.stableSortByUpdateOrder=function(e){return e},t.fallbackSort=function(e){return[].concat(e).sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})},t.getSchedulingMetadata=function(e){return{stage:e.getStage(),before:[].concat(e.getBefore()),after:[].concat(e.getAfter()),sets:[].concat(e.getSets())}},e}(),sn=function(){function e(e){void 0===e&&(e=1024),this._freeList=[],this._nextIndex=1,this._aliveCount=0,this._capacity=e,this._generations=new Uint32Array(e),this._alive=new Uint8Array(e),this._enabled=new Uint8Array(e),this._alive[0]=0,this._enabled[0]=0}var t=e.prototype;return t.create=function(){var e;this._freeList.length>0?e=this._freeList.pop():(e=this._nextIndex++)>=this._capacity&&this.grow(e);var t=this._generations[e];return this._alive[e]=1,this._enabled[e]=1,this._aliveCount++,lt(e,t)},t.destroy=function(e){var t=ht(e),n=dt(e);if(t>=this._capacity||0===t)return!1;if(this._generations[t]!==n)return!1;if(1!==this._alive[t])return!1;this._alive[t]=0,this._enabled[t]=0,this._aliveCount--;var i=(n+1)%ut;return this._generations[t]=i,this._freeList.push(t),!0},t.isAlive=function(e){var t=ht(e),n=dt(e);return!(t>=this._capacity||0===t)&&(1===this._alive[t]&&this._generations[t]===n)},t.isEnabled=function(e){if(!this.isAlive(e))return!1;var t=ht(e);return 1===this._enabled[t]},t.setEnabled=function(e,t){if(!this.isAlive(e))return!1;var n=ht(e);return this._enabled[n]=t?1:0,!0},t.validate=function(e){return this.isAlive(e)},t.grow=function(e){for(var t=this._capacity;t<=e;)t<<=1;if(t>ct&&e>=(t=ct))throw new Error("EntityHandleManager: 超过最大实体数量 "+ct);var n=new Uint32Array(t),i=new Uint8Array(t),r=new Uint8Array(t);n.set(this._generations),i.set(this._alive),r.set(this._enabled),this._generations=n,this._alive=i,this._enabled=r,this._capacity=t},t.reset=function(){this._generations.fill(0),this._alive.fill(0),this._enabled.fill(0),this._freeList.length=0,this._nextIndex=1,this._aliveCount=0},t.forEach=function(e){for(var t=1;t<this._nextIndex;t++){if(1===this._alive[t])e(lt(t,this._generations[t]))}},t.getAllAlive=function(){var e=[];return this.forEach(function(t){return e.push(t)}),e},s(e,[{key:"aliveCount",get:function(){return this._aliveCount}},{key:"capacity",get:function(){return this._capacity}}])}(),an=function(){function e(){this._current=1}var t=e.prototype;return t.increment=function(){this._current++,this._current>=Number.MAX_SAFE_INTEGER&&(this._current=1)},t.reset=function(){this._current=1},t.isChangedSince=function(e,t){return e>t},s(e,[{key:"current",get:function(){return this._current}}])}(),cn=function(){function t(e){var t;this.name="",this.sceneData=new Map,this._handleToEntity=new Map,this.epochManager=new an,this._performanceMonitor=null,this._didSceneBegin=!1,this.isEditorMode=!1,this._deferredComponentCallbacks=[],this._cachedSystems=null,this._systemsOrderDirty=!0,this._systemErrorCount=new Map,this._systemAddCounter=0,this._systemScheduler=new on,this._componentIdToSystems=new Map,this._globalNotifySystems=new Set,this.entities=new mt(this),this.identifierPool=new vt,this.componentStorageManager=new He,this.componentRegistry=new $,!1!==(null==e?void 0:e.inheritGlobalRegistry)&&this.componentRegistry.cloneFrom(ee),this.querySystem=new kt,this.eventSystem=new Pt,this.referenceTracker=new fe,this.handleManager=new sn,this._services=new Kt,this._logger=Z("Scene"),this._maxErrorCount=null!==(t=null==e?void 0:e.maxSystemErrorCount)&&void 0!==t?t:10,null!=e&&e.name&&(this.name=e.name)}var n=t.prototype;return n._rebuildSystemsCache=function(){var e=this._services.getAll(),t=this._filterEntitySystems(e);try{return this._systemScheduler.markDirty(),this._systemScheduler.getAllSortedSystems(t)}catch(e){return e instanceof $t?this._logger.error("[Scene] 系统存在循环依赖,回退到 updateOrder 排序 | Cycle dependency detected, falling back to updateOrder sort",e.involvedNodes):this._logger.error("[Scene] 系统排序失败 | System sorting failed",e),this._sortSystemsByUpdateOrder(t)}},n._filterEntitySystems=function(e){return e.filter(function(e){return e instanceof je})},n._sortSystemsByUpdateOrder=function(e){return e.sort(function(e,t){var n=e.updateOrder-t.updateOrder;return 0!==n?n:e.addOrder-t.addOrder})},n.getSystem=function(e){return this._services.tryResolve(e)},n.markSystemsOrderDirty=function(){this._systemsOrderDirty=!0},n.initialize=function(){},n.onStart=function(){},n.unload=function(){},n.queueDeferredComponentCallback=function(e){this._deferredComponentCallbacks.push(e)},n.begin=function(){if(this._didSceneBegin=!0,this._deferredComponentCallbacks.length>0){for(var e,t=a(this._deferredComponentCallbacks);!(e=t()).done;){var n=e.value;try{n()}catch(e){this._logger.error("Error executing deferred component callback:",e)}}this._deferredComponentCallbacks=[]}this.onStart()},n.end=function(){this._didSceneBegin=!1,this.unload(),this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this._cachedSystems=null,this._systemsOrderDirty=!0,this._componentIdToSystems.clear(),this._globalNotifySystems.clear(),this._handleToEntity.clear(),this.handleManager.reset(),this.epochManager.reset()},n.update=function(){this.epochManager.increment(),it.beginFrame();var t=it.beginSample("Scene.update",e.ProfileCategory.ECS);try{Ze.getInstance().update(),this.entities.updateLists();var n=this.systems;this._runSystemPhase(n,"update","Systems.update"),this._runSystemPhase(n,"lateUpdate","Systems.lateUpdate"),this.flushCommandBuffers(n)}finally{it.endSample(t),it.endFrame()}},n._runSystemPhase=function(t,n,i){var r=it.beginSample(i,e.ProfileCategory.ECS);try{for(var o,s=a(t);!(o=s()).done;){var c=o.value;if(this._shouldSystemRun(c)){var u="lateUpdate"===n?".late":"",l=it.beginSample(""+c.systemName+u,e.ProfileCategory.ECS);try{c[n]()}catch(e){this._handleSystemError(c,n,e)}finally{it.endSample(l)}}}}finally{it.endSample(r)}},n._shouldSystemRun=function(e){if(!e.enabled)return!1;if(!this.isEditorMode)return!0;var t=se(e);return!1!==(null==t?void 0:t.runInEditMode)},n.flushCommandBuffers=function(t){var n=it.beginSample("Scene.flushCommandBuffers",e.ProfileCategory.ECS);try{for(var i,r=a(t);!(i=r()).done;){var o=i.value;try{o.flushCommands()}catch(e){this._logger.error("Error flushing commands for system "+o.systemName+":",e)}}}finally{it.endSample(n)}},n._handleSystemError=function(e,t,n){var i=(this._systemErrorCount.get(e)||0)+1;this._systemErrorCount.set(e,i);var r=e.systemName;this._logger.error("Error in system "+r+"."+t+"() ["+i+"/"+this._maxErrorCount+"]:",n),i>=this._maxErrorCount&&(e.enabled=!1,this._logger.error("System "+r+" has been disabled due to excessive errors ("+i+" errors)"))},n.createEntity=function(e){var t=new pt(e,this.identifierPool.checkOut()),n=this.handleManager.create();return t.setHandle(n),this._handleToEntity.set(n,t),this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)},n.clearSystemEntityCaches=function(){for(var e,t=a(this.systems);!(e=t()).done;){e.value.clearEntityCache()}},n.notifyEntityComponentChanged=function(e,t){var n=new Set;if(t&&this.componentRegistry.isRegistered(t)){var i=this.componentRegistry.getBitIndex(t),r=this._componentIdToSystems.get(i);if(r)for(var o,s=a(r);!(o=s()).done;){var c=o.value;c.handleEntityComponentChanged(e),n.add(c)}}for(var u,l=a(this._globalNotifySystems);!(u=l()).done;){var h=u.value;n.has(h)||(h.handleEntityComponentChanged(e),n.add(h))}if(!t)for(var d,f=a(this.systems);!(d=f()).done;){var p=d.value;n.has(p)||p.handleEntityComponentChanged(e)}},n.indexSystemByComponents=function(e){var t=e.matcher;if(t&&!t.isNothing()){var n=t.getCondition();if((n.none.length>0||void 0!==n.tag||void 0!==n.name)&&this._globalNotifySystems.add(e),t.isEmpty())this._globalNotifySystems.add(e);else{for(var i,r=a(n.all);!(i=r()).done;){var o=i.value;this.addSystemToComponentIndex(o,e)}for(var s,c=a(n.any);!(s=c()).done;){var u=s.value;this.addSystemToComponentIndex(u,e)}n.component&&this.addSystemToComponentIndex(n.component,e)}}},n.addSystemToComponentIndex=function(e,t){var n=this.componentRegistry.getBitIndex(e),i=this._componentIdToSystems.get(n);i||(i=new Set,this._componentIdToSystems.set(n,i)),i.add(t)},n.removeSystemFromIndex=function(e){this._globalNotifySystems.delete(e);for(var t,n=a(this._componentIdToSystems.values());!(t=n()).done;){t.value.delete(e)}},n.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},n.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],i=0;i<e;i++){var r=new pt(t+"_"+i,this.identifierPool.checkOut());r.scene=this;var o=this.handleManager.create();r.setHandle(o),this._handleToEntity.set(o,r),n.push(r)}for(var s=0,a=n;s<a.length;s++){var c=a[s];this.entities.add(c)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n},n.destroyEntities=function(e){if(0!==e.length){for(var t,n=a(e);!(t=n()).done;){t.value.setDestroyedState(!0)}for(var i,r=a(e);!(i=r()).done;){i.value.removeAllComponents()}for(var o,s=a(e);!(o=s()).done;){var c=o.value;this.entities.remove(c),this.querySystem.removeEntity(c),ft(c.handle)&&(this._handleToEntity.delete(c.handle),this.handleManager.destroy(c.handle))}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},n.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},n.findEntity=function(e){return this.entities.findEntity(e)},n.findEntityById=function(e){return this.entities.findEntityById(e)},n.findEntityByHandle=function(e){var t;return ft(e)&&this.handleManager.isAlive(e)&&null!==(t=this._handleToEntity.get(e))&&void 0!==t?t:null},n.findEntitiesByTag=function(e){for(var t,n=[],i=a(this.entities.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},n.findPersistentEntities=function(){return this.entities.buffer.filter(function(e){return e.isPersistent})},n.extractPersistentEntities=function(){for(var e,t=this.findPersistentEntities(),n=a(t);!(e=n()).done;){var i=e.value;this.entities.remove(i),this.querySystem.removeEntity(i),i.scene=null}return t},n.receiveMigratedEntities=function(e){for(var t,n=a(e);!(t=n()).done;){var i=t.value;i.scene=this,this.entities.add(i),this.querySystem.addEntity(i);for(var r,o=a(i.components);!(r=o()).done;){var s,c=r.value;this.componentStorageManager.addComponent(i.id,c),null===(s=this.referenceTracker)||void 0===s||s.registerEntityScene(i.id,this)}}e.length>0&&this.clearSystemEntityCaches()},n.getEntityByName=function(e){return this.findEntity(e)},n.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},n.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},n.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},n.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},n.query=function(){return new xt},n.addEntityProcessor=function(t){var n,i;if("function"==typeof t){if(i=t,this._services.isRegistered(i)){var r=this._services.resolve(i);return this._logger.debug("System "+i.name+" already registered, returning existing instance"),r}n=M(i)?A(i,this._services):new i}else if(i=(n=t).constructor,this._services.isRegistered(i)){var o=this._services.resolve(i);return o===n?(this._logger.debug("System "+i.name+" instance already registered, returning it"),n):(this._logger.warn("Attempting to register a different instance of "+i.name+", but type is already registered. Returning existing instance."),o)}n.scene=this,n.addOrder=this._systemAddCounter++,n.setPerformanceMonitor(this.performanceMonitor);var s=oe(i);return void 0!==(null==s?void 0:s.updateOrder)&&n.setUpdateOrder(s.updateOrder),void 0!==(null==s?void 0:s.enabled)&&(n.enabled=s.enabled),this._services.registerInstance(i,n),this.markSystemsOrderDirty(),this.indexSystemByComponents(n),k(n,this._services),it.isEnabled()&&Yt.wrapInstance(n,n.systemName,e.ProfileCategory.ECS),n.initialize(),this._logger.debug("System "+i.name+" registered and initialized"),n},n.registerSystems=function(e){for(var t,n=[],i=a(e);!(t=i()).done;){var r=t.value,o=this.addEntityProcessor(r);n.push(o)}return n},n.addSystem=function(e){return this.addEntityProcessor(e)},n.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),this.markSystemsOrderDirty(),this.removeSystemFromIndex(e),e.reset()},n.removeSystem=function(e){this.removeEntityProcessor(e)},n.getEntityProcessor=function(e){return this._services.tryResolve(e)},n.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},n.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map(function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map(function(e){return W(e)})}}),processors:e.map(function(e){return{name:ce(e),updateOrder:e.updateOrder,entityCount:e.entities.length}}),componentStats:this.componentStorageManager.getAllStats()}},n.serialize=function(e){return jt.serialize(this,e)},n.deserialize=function(e,t){jt.deserialize(this,e,t)},n.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=Vt.createSnapshot(this,e)},n.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Vt.computeIncremental(this,this._incrementalBaseSnapshot,e)},n.applyIncremental=function(e,t){var n="string"==typeof e||e instanceof Uint8Array?Vt.deserializeIncremental(e):e,i=t||this.componentRegistry.getAllComponentNames();Vt.applyIncremental(this,n,i)},n.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},n.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},n.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},s(t,[{key:"systems",get:function(){return!this._systemsOrderDirty&&this._cachedSystems||(this._cachedSystems=this._rebuildSystemsCache(),this._systemsOrderDirty=!1),this._cachedSystems}},{key:"services",get:function(){return this._services}},{key:"performanceMonitor",get:function(){var e;this._performanceMonitor||(this._performanceMonitor=null!==(e=this._services.tryResolve(O))&&void 0!==e?e:new O);return this._performanceMonitor}}])}(),un=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new pt("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.entity.addComponent(o)}return this},t.withIf=function(e,t){return e&&this.entity.addComponent(t),this},t.withFactory=function(e){var t=e();return this.entity.addComponent(t),this},t.configure=function(e,t){var n=this.entity.getComponent(e);return n&&t(n),this},t.enabled=function(e){return void 0===e&&(e=!0),this.entity.enabled=e,this},t.active=function(e){return void 0===e&&(e=!0),this.entity.active=e,this},t.withChild=function(e){var t=e.build(),n=this.scene.getSystem(qe);return null==n||n.setParent(t,this.entity),this},t.withChildren=function(){for(var e=this.scene.getSystem(qe),t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0,o=n;r<o.length;r++){var s=o[r].build();null==e||e.setParent(s,this.entity)}return this},t.withChildFactory=function(e){var t=e(this.entity).build(),n=this.scene.getSystem(qe);return null==n||n.setParent(t,this.entity),this},t.withChildIf=function(e,t){if(e){var n=t.build(),i=this.scene.getSystem(qe);null==i||i.setParent(n,this.entity)}return this},t.build=function(){return this.entity},t.spawn=function(){return this.scene.addEntity(this.entity),this.entity},t.clone=function(){var t=new e(this.scene,this.storageManager);return t.entity=this.entity,t},e}(),ln=function(){function e(){this.scene=new cn}var t=e.prototype;return t.named=function(e){return this.scene.name=e,this},t.withEntity=function(e){return this.scene.addEntity(e),this},t.withEntityBuilder=function(e){var t=e(new un(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this},t.withEntities=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.scene.addEntity(o)}return this},t.withSystem=function(e){return this.scene.addSystem(e),this},t.withSystems=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var o=r[i];this.scene.addSystem(o)}return this},t.build=function(){return this.scene},e}(),hn=function(){function e(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.component=r(e,n)}var t=e.prototype;return t.set=function(e,t){return this.component[e]=t,this},t.configure=function(e){return e(this.component),this},t.setIf=function(e,t,n){return e&&(this.component[t]=n),this},t.build=function(){return this.component},e}(),dn=function(){function e(e){this.entities=e}var t=e.prototype;return t.addComponent=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.addComponent(e)}return this},t.removeComponent=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.removeComponentByType(e)}return this},t.setActive=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.active=e}return this},t.setTag=function(e){for(var t,n=a(this.entities);!(t=n()).done;){t.value.tag=e}return this},t.forEach=function(e){return this.entities.forEach(e),this},t.filter=function(t){return new e(this.entities.filter(t))},t.toArray=function(){return this.entities.slice()},t.count=function(){return this.entities.length},e}(),fn=function(){function e(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}var t=e.prototype;return t.createEntity=function(){return new un(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new ln},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r(hn,[e].concat(n))},t.query=function(){return new Dt(this.querySystem)},t.find=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments).entities},t.findFirst=function(){var e,t=(e=this.querySystem).queryAll.apply(e,arguments);return t.entities.length>0?t.entities[0]:null},t.findByName=function(e){return this.scene.findEntity(e)},t.findByTag=function(e){return this.scene.findEntitiesByTag(e)},t.emit=function(e,t){this.eventSystem.emitSync(e,t)},t.emitAsync=function(){var e=i(d().m(function e(t,n){return d().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.eventSystem.emit(t,n);case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.on=function(e,t){return this.eventSystem.on(e,t)},t.once=function(e,t){return this.eventSystem.once(e,t)},t.off=function(e,t){this.eventSystem.off(e,t)},t.batch=function(e){return new dn(e)},t.getStats=function(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}},e}();function pn(e,t,n){return new fn(e,t,n)}var mn,vn=Z("World"),gn={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,cleanupThresholdMs:3e5},yn=function(){function e(e){void 0===e&&(e={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=c({},gn,e),this.name=this._config.name,this._createdAt=Date.now(),this._services=new Kt}var t=e.prototype;return t.createScene=function(e,t){this.validateSceneName(e);var n=null!=t?t:new cn;if(this._config.debug){var i=new O;i.enable(),n.services.registerInstance(O,i)}return n.id=e,n.name||(n.name=e),this._scenes.set(e,n),n.initialize(),n},t.removeScene=function(e){var t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),vn.info("从World '"+this.name+"' 中移除Scene: "+e),!0)},t.removeAllScenes=function(){var e=this;this._scenes.forEach(function(t,n){return e.removeScene(n)}),vn.info("从World '"+this.name+"' 中移除所有Scene")},t.getScene=function(e){var t;return null!==(t=this._scenes.get(e))&&void 0!==t?t:null},t.getSceneIds=function(){return Array.from(this._scenes.keys())},t.getAllScenes=function(){return Array.from(this._scenes.values())},t.setSceneActive=function(e,t){var n,i=this._scenes.get(e);i?t?(this._activeScenes.add(e),null===(n=i.begin)||void 0===n||n.call(i),vn.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),vn.debug("在World '"+this.name+"' 中停用Scene: "+e)):vn.warn("Scene '"+e+"' 不存在于World '"+this.name+"' 中")},t.isSceneActive=function(e){return this._activeScenes.has(e)},t.getActiveSceneCount=function(){return this._activeScenes.size},t.addGlobalSystem=function(e){var t;return this._globalSystems.includes(e)||(this._globalSystems.push(e),null===(t=e.initialize)||void 0===t||t.call(e),vn.debug("在World '"+this.name+"' 中添加全局System: "+e.name)),e},t.removeGlobalSystem=function(e){var t,n=this._globalSystems.indexOf(e);return-1!==n&&(this._globalSystems.splice(n,1),null===(t=e.reset)||void 0===t||t.call(e),vn.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){var t;return null!==(t=this._globalSystems.find(function(t){return t instanceof e}))&&void 0!==t?t:null},t.start=function(){this._isActive||(this._isActive=!0,this._globalSystems.forEach(function(e){var t;return null===(t=e.initialize)||void 0===t?void 0:t.call(e)}),vn.info("启动World: "+this.name))},t.stop=function(){var e=this;this._isActive&&(this._activeScenes.forEach(function(t){return e.setSceneActive(t,!1)}),this._globalSystems.forEach(function(e){var t;return null===(t=e.reset)||void 0===t?void 0:t.call(e)}),this._isActive=!1,vn.info("停止World: "+this.name))},t.destroy=function(){vn.info("销毁World: "+this.name),this.stop(),this.removeAllScenes(),this._globalSystems.forEach(function(e){var t,n,i;return null!==(t=null===(n=e.destroy)||void 0===n?void 0:n.call(e))&&void 0!==t?t:null===(i=e.reset)||void 0===i?void 0:i.call(e)}),this._globalSystems.length=0,this._services.clear(),this._scenes.clear(),this._activeScenes.clear()},t.updateGlobalSystems=function(){this._isActive&&this._globalSystems.forEach(function(e){var t;return null===(t=e.update)||void 0===t?void 0:t.call(e)})},t.updateScenes=function(){var e=this;this._isActive&&(this._activeScenes.forEach(function(t){var n,i;null===(n=e._scenes.get(t))||void 0===n||null===(i=n.update)||void 0===i||i.call(n)}),this._config.autoCleanup&&this.cleanup())},t.getStatus=function(){var e=this,t=[];return this._scenes.forEach(function(n,i){t.push({id:i,name:n.name||i,isActive:e._activeScenes.has(i)})}),{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:c({},this._config),scenes:t}},t.getStats=function(){var e=0,t=this._globalSystems.length;return this._scenes.forEach(function(n){var i,r,o,s;e+=null!==(i=null===(r=n.entities)||void 0===r?void 0:r.count)&&void 0!==i?i:0,t+=null!==(o=null===(s=n.systems)||void 0===s?void 0:s.length)&&void 0!==o?o:0}),{totalEntities:e,totalSystems:t,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}}},t.validateSceneName=function(e){if(null==e||!e.trim())throw new Error("Scene name不能为空");if(this._scenes.has(e))throw new Error("Scene name '"+e+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes)},t.isCleanupCandidate=function(e,t){var n=Date.now()-this._createdAt;return!this._activeScenes.has(e)&&null!=t.entities&&0===t.entities.count&&n>this._config.cleanupThresholdMs},t.cleanup=function(){var e=this,t=[];this._scenes.forEach(function(n,i){e.isCleanupCandidate(i,n)&&t.push(i)}),t.forEach(function(t){e.removeScene(t),vn.debug("自动清理空Scene: "+t+" from World "+e.name)})},s(e,[{key:"services",get:function(){return this._services}},{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),_n=function(){function e(e){this._nextScene=null,this._ecsAPI=null,this._logger=Z("SceneManager"),this._performanceMonitor=null,this._pendingPersistentEntities=[],this._defaultWorld=new yn({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}var t=e.prototype;return t.setSceneChangedCallback=function(e){this._onSceneChangedCallback=e},t.setScene=function(t){var n=this.currentScene;return n&&n instanceof cn&&(this._pendingPersistentEntities=n.extractPersistentEntities(),this._pendingPersistentEntities.length>0&&this._logger.debug("Extracted "+this._pendingPersistentEntities.length+" persistent entities for migration")),this._defaultWorld.removeAllScenes(),this._performanceMonitor&&t.services.registerInstance(O,this._performanceMonitor),this._defaultWorld.createScene(e.DEFAULT_SCENE_ID,t),this._defaultWorld.setSceneActive(e.DEFAULT_SCENE_ID,!0),this._pendingPersistentEntities.length>0&&t instanceof cn&&(t.receiveMigratedEntities(this._pendingPersistentEntities),this._logger.debug("Migrated "+this._pendingPersistentEntities.length+" persistent entities to new scene"),this._pendingPersistentEntities=[]),t.querySystem&&t.eventSystem?this._ecsAPI=pn(t,t.querySystem,t.eventSystem):this._ecsAPI=null,_.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info("Scene changed to: "+t.name),t},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()},t.destroy=function(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},s(e,[{key:"currentScene",get:function(){return this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();_n.DEFAULT_SCENE_ID="__main__",e.DebugConfigService=function(){function e(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}var t=e.prototype;return t.setConfig=function(e){this._config=e},t.getConfig=function(){return this._config},t.isEnabled=function(){return this._config.enabled},t.dispose=function(){},e}(),e.DebugConfigService=g([T(),y("design:paramtypes",[])],e.DebugConfigService),e.DebugManager=function(){function e(){this.frameCounter=0,this.lastSendTime=0,this.sendInterval=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)}}var t=e.prototype;return t.onInitialize=function(){this.config=this.configService.getConfig(),this.entityCollector=new Ve,this.systemCollector=new Qe,this.performanceCollector=new Ye,this.componentCollector=new Xe,this.sceneCollector=new $e,this.advancedProfilerCollector=new rt,it.setEnabled(!0),this.webSocketManager=new et(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var e=this.config.debugFrameRate||30;this.sendInterval=1e3/e,this.interceptConsole(),this.start()},t.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},t.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},t.interceptConsole=function(){var e=this;console.log=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).log.apply(t,i)},console.debug=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("debug",e.formatLogMessage(i)),(t=e.originalConsole).debug.apply(t,i)},console.info=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).info.apply(t,i)},console.warn=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("warn",e.formatLogMessage(i)),(t=e.originalConsole).warn.apply(t,i)},console.error=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("error",e.formatLogMessage(i)),(t=e.originalConsole).error.apply(t,i)}},t.formatLogMessage=function(e){var t=this;return e.map(function(e){if("string"==typeof e)return e;if(e instanceof Error)return e.name+": "+e.message;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return t.safeStringify(e,6)}catch(t){return Object.prototype.toString.call(e)}return String(e)}).join(" ")},t.safeStringify=function(e,t){void 0===t&&(t=6);var n=new WeakSet,i=function(e,r){if(null===e)return null;if(void 0!==e){if("object"!=typeof e)return e;if(r>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){var o=e.map(function(e){return i(e,r+1)});return n.delete(e),o}var s={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(s[a]=i(e[a],r+1));return n.delete(e),s}};return JSON.stringify(i(e,0))},t.sendLog=function(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}},t.updateConfig=function(e){this.config=e;var t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new et(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},t.update=function(e){if(this.isRunning&&this.config.enabled){this.frameCounter++;var t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}},t.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},t.handleMessage=function(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig(c({},this.config,e.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"get_advanced_profiler_data":this.handleGetAdvancedProfilerDataRequest(e);break;case"set_profiler_selected_function":this.handleSetProfilerSelectedFunction(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleExpandLazyObjectRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.propertyPath,r=e.requestId;if(void 0===t||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var o=this.sceneManager.currentScene,s=this.entityCollector.expandLazyObject(t,n,i,o);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:s})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetComponentPropertiesRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.sceneManager.currentScene,o=this.entityCollector.getComponentProperties(t,n,r);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:o})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetRawEntityListRequest=function(e){try{var t=e.requestId,n=this.sceneManager.currentScene,i=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:i})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetEntityDetailsRequest=function(e){try{var t=e.entityId,n=e.requestId;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.sceneManager.currentScene,r=this.entityCollector.getEntityDetails(t,i);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetAdvancedProfilerDataRequest=function(e){try{var t=e.requestId,n=it.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):this.advancedProfilerCollector.collectFromLegacyMonitor(this.performanceMonitor);this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:t,data:n})}catch(t){this.webSocketManager.send({type:"get_advanced_profiler_data_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleSetProfilerSelectedFunction=function(e){try{var t=e.functionName,n=e.requestId;this.advancedProfilerCollector.setSelectedFunction(t||null),this.sendDebugData(),this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:n,success:!0})}catch(t){this.webSocketManager.send({type:"set_profiler_selected_function_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,i=this.entityCollector.collectEntityDataWithMemory(n),r=null!=n&&n.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},o=this.collectSystemMemoryStats(),s=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=i.entitiesPerArchetype.reduce(function(e,t){return e+t.memory},0);return{timestamp:e,version:"2.0",summary:{totalEntities:i.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:o.totalMemory,poolMemory:s.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:o,pools:s,performance:a}},t.collectBaseMemoryInfo=function(){var e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var t=performance;if(t.memory){var n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then(function(t){e.detailedMemory=t}).catch(function(){})}catch(e){}return e},t.collectComponentMemoryStats=function(e){for(var t,n=new Map,i=0,r=new Map,o=a(e.buffer);!(t=o()).done;){var s=t.value;if(s&&!s.destroyed&&s.components)for(var c,u=a(s.components);!(c=u()).done;){var l=W(c.value);r.set(l,(r.get(l)||0)+1)}}for(var h,d=a(r.entries());!(h=d()).done;){var f=h.value,p=f[0],m=f[1],v=this.componentCollector.calculateDetailedComponentMemory(p),g=v*m;i+=g;for(var y,_=[],S=0,C=a(e.buffer);!(y=C()).done;){var E=y.value;if(E&&!E.destroyed&&E.components){for(var b,T=a(E.components);!(b=T()).done;){if(W(b.value)===p&&(_.push({entityId:E.id,entityName:E.name||"Entity_"+E.id,memory:v}),++S>=100))break}if(S>=100)break}}n.set(p,{count:m,totalMemory:g,instances:_.slice(0,10)})}var w=Array.from(n.entries()).map(function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort(function(e,t){return t.memory-e.memory}).slice(0,3)}}).sort(function(e,t){return t.totalMemory-e.totalMemory});return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce(function(e,t){return e+t.count},0),breakdown:w}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var i=null==e?void 0:e.systems;if(i)for(var r,o=new Map,s=a(i);!(r=s()).done;){var c=r.value,u=ce(c),l=void 0;o.has(u)?l=o.get(u):(l=this.calculateQuickSystemSize(c),o.set(u,l)),t+=l,n.push({name:u,memory:l,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort(function(e,t){return t.memory-e.memory})}},t.calculateQuickSystemSize=function(e){if(!e||"object"!=typeof e)return 64;var t=128;try{for(var n=Object.keys(e),i=0;i<Math.min(n.length,15);i++){var r=n[i];if(r&&"entities"!==r&&"scene"!==r&&"constructor"!==r){var o=e[r];t+=2*r.length,"string"==typeof o?t+=Math.min(2*o.length,100):"number"==typeof o?t+=8:"boolean"==typeof o?t+=4:Array.isArray(o)?t+=40+Math.min(8*o.length,200):"object"==typeof o&&null!==o&&(t+=64)}}}catch(e){return 128}return Math.max(t,64)},t.collectPoolMemoryStats=function(){var e=0,t=[];try{for(var n,i=a(Ze.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,o=r[0],s=r[1],c=32*s.maxSize;e+=c,t.push({typeName:o,maxSize:s.maxSize,currentSize:s.currentSize||0,estimatedMemory:c,utilization:s.currentSize?s.currentSize/s.maxSize*100:0})}}catch(e){}try{for(var u=x.getAllPoolStats(),l=0,h=Object.entries(u);l<h.length;l++){var d=h[l],f=d[0],p=d[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+f,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort(function(e,t){return t.estimatedMemory-e.estimatedMemory})}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map(function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}}).sort(function(e,t){return t.averageTime-e.averageTime}).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}},e,this,[[0,2]])}));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData(),advancedProfiler:it.isEnabled()?this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor):null};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error},e}(),g([I(_n),y("design:type",_n)],e.DebugManager.prototype,"sceneManager",void 0),g([I(O),y("design:type",O)],e.DebugManager.prototype,"performanceMonitor",void 0),g([I(e.DebugConfigService),y("design:type",e.DebugConfigService)],e.DebugManager.prototype,"configService",void 0),e.DebugManager=g([T(),w()],e.DebugManager),e.PluginState=void 0,(mn=e.PluginState||(e.PluginState={})).NotInstalled="not_installed",mn.Installed="installed",mn.Failed="failed";var Sn=Z("PluginManager"),Cn=function(){function t(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var n=t.prototype;return n.initialize=function(e,t){this._core=e,this._services=t,Sn.info("PluginManager initialized")},n.install=function(){var t=i(d().m(function t(n){var i,r;return d().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this._core&&this._services){t.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(n.name)){t.n=2;break}return Sn.warn("Plugin "+n.name+" is already installed"),t.a(2);case 2:return n.dependencies&&n.dependencies.length>0&&this._checkDependencies(n),i={name:n.name,version:n.version,state:e.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(n.name,i),t.p=3,Sn.info("Installing plugin: "+n.name+" v"+n.version),t.n=4,n.install(this._core,this._services);case 4:this._plugins.set(n.name,n),i.state=e.PluginState.Installed,Sn.info("Plugin "+n.name+" installed successfully"),t.n=6;break;case 5:throw t.p=5,r=t.v,i.state=e.PluginState.Failed,i.error=r instanceof Error?r.message:String(r),Sn.error("Failed to install plugin "+n.name+":",r),r;case 6:return t.a(2)}},t,this,[[3,5]])}));return function(e){return t.apply(this,arguments)}}(),n.uninstall=function(){var e=i(d().m(function e(t){var n,i;return d().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,Sn.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),Sn.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,i=e.v,Sn.error("Failed to uninstall plugin "+t+":",i),i;case 5:return e.a(2)}},e,this,[[2,4]])}));return function(t){return e.apply(this,arguments)}}(),n.getPlugin=function(e){return this._plugins.get(e)},n.getMetadata=function(e){return this._metadata.get(e)},n.getAllPlugins=function(){return Array.from(this._plugins.values())},n.getAllMetadata=function(){return Array.from(this._metadata.values())},n.isInstalled=function(e){return this._plugins.has(e)},n._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],i=a(e.dependencies);!(t=i()).done;){var r=t.value;this._plugins.has(r)||n.push(r)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},n._checkDependents=function(e){for(var t,n=[],i=a(this._plugins.values());!(t=i()).done;){var r=t.value;r.dependencies&&r.dependencies.includes(e)&&n.push(r.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},n.dispose=function(){for(var e,t=a(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{Sn.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){Sn.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,Sn.info("PluginManager disposed")},t}();function En(e){var t="@esengine/service:"+e;return{id:Symbol.for(t),name:e}}var bn=function(){function e(){this._services=new Map}var t=e.prototype;return t.register=function(e,t){this._services.set(e.id,t)},t.get=function(e){return this._services.get(e.id)},t.require=function(e){var t=this._services.get(e.id);if(void 0===t)throw new Error("Service not found: "+e.name);return t},t.has=function(e){return this._services.has(e.id)},t.unregister=function(e){return this._services.delete(e.id)},t.clear=function(){this._services.clear()},t.dispose=function(){this.clear()},e}(),Tn=Z("WorldManager"),wn={maxWorlds:50,autoCleanup:!0,cleanupFrameInterval:1800,debug:!1},In=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._isRunning=!0,this._framesSinceCleanup=0,this._config=c({},wn,e),Tn.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupFrameInterval:this._config.cleanupFrameInterval})}var t=e.prototype;return t.createWorld=function(e,t){var n;this.validateWorldName(e);var i=c({},t,{name:e,debug:null!==(n=null==t?void 0:t.debug)&&void 0!==n?n:this._config.debug}),r=new yn(i);return this._worlds.set(e,r),r},t.removeWorld=function(e){var t=this._worlds.get(e);return!!t&&(t.destroy(),this._worlds.delete(e),Tn.info("移除World: "+e),!0)},t.getWorld=function(e){var t;return null!==(t=this._worlds.get(e))&&void 0!==t?t:null},t.getWorldIds=function(){return Array.from(this._worlds.keys())},t.getAllWorlds=function(){return Array.from(this._worlds.values())},t.setWorldActive=function(e,t){var n=this._worlds.get(e);n?t?(n.start(),Tn.debug("激活World: "+e)):(n.stop(),Tn.debug("停用World: "+e)):Tn.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){var t,n;return null!==(t=null===(n=this._worlds.get(e))||void 0===n?void 0:n.isActive)&&void 0!==t&&t},t.getActiveWorlds=function(){var e=[];return this._worlds.forEach(function(t){t.isActive&&e.push(t)}),e},t.findWorlds=function(e){var t=[];return this._worlds.forEach(function(n){e(n)&&t.push(n)}),t},t.findWorldByName=function(e){var t=null;return this._worlds.forEach(function(n){n.name===e&&(t=n)}),t},t.startAll=function(){this._isRunning=!0,this._worlds.forEach(function(e){return e.start()}),Tn.info("启动所有World")},t.stopAll=function(){this._isRunning=!1,this._worlds.forEach(function(e){return e.stop()}),Tn.info("停止所有World")},t.destroy=function(){var e=this;Tn.info("正在销毁WorldManager..."),this.stopAll(),Array.from(this._worlds.keys()).forEach(function(t){return e.removeWorld(t)}),this._worlds.clear(),this._isRunning=!1,Tn.info("WorldManager已销毁")},t.dispose=function(){this.destroy()},t.updateAll=function(){this._isRunning&&(this._worlds.forEach(function(e){e.isActive&&(e.updateGlobalSystems(),e.updateScenes())}),this.processAutoCleanup())},t.getStats=function(){var e=0,t=0,n=0,i=[];return this._worlds.forEach(function(r,o){var s=r.getStats();e+=r.sceneCount,t+=s.totalEntities,n+=s.totalSystems,i.push(c({id:o,name:r.name,isActive:r.isActive,sceneCount:r.sceneCount},s))}),{totalWorlds:this._worlds.size,activeWorlds:this.activeWorldCount,totalScenes:e,totalEntities:t,totalSystems:n,memoryUsage:0,isRunning:this._isRunning,config:c({},this._config),worlds:i}},t.getDetailedStatus=function(){var e=[];return this._worlds.forEach(function(t,n){e.push({id:n,isActive:t.isActive,status:t.getStatus()})}),c({},this.getStats(),{worlds:e})},t.cleanup=function(){var e=this,t=[];return this._worlds.forEach(function(n,i){e.isCleanupCandidate(n)&&t.push(i)}),t.forEach(function(t){return e.removeWorld(t)}),t.length>0&&Tn.debug("清理了 "+t.length+" 个World"),t.length},t.validateWorldName=function(e){if(null==e||!e.trim())throw new Error("World name不能为空");if(this._worlds.has(e))throw new Error("World name '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds)},t.processAutoCleanup=function(){this._config.autoCleanup&&(this._framesSinceCleanup++,this._framesSinceCleanup>=this._config.cleanupFrameInterval&&(this.cleanup(),this._framesSinceCleanup=0,this._config.debug&&Tn.debug("执行定期清理World (间隔: "+this._config.cleanupFrameInterval+" 帧)")))},t.isCleanupCandidate=function(e){return!e.isActive&&(!(Date.now()-e.createdAt<=6e5)&&(0===e.sceneCount||!e.getAllScenes().some(function(e){return e.entities&&e.entities.count>0})))},s(e,[{key:"worldCount",get:function(){return this._worlds.size}},{key:"activeWorldCount",get:function(){var e=0;return this._worlds.forEach(function(t){t.isActive&&e++}),e}},{key:"isRunning",get:function(){return this._isRunning}},{key:"config",get:function(){return c({},this._config)}}])}(),Mn=function(){function t(n){var i,r,o=this;if(void 0===n&&(n={}),t._instance=this,this._config=c({debug:!0},n),this._serviceContainer=new Kt,this._timerManager=new e.TimerManager,this._serviceContainer.registerInstance(e.TimerManager,this._timerManager),this._performanceMonitor=new O,this._serviceContainer.registerInstance(O,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new z,this._serviceContainer.registerInstance(z,this._poolManager),this._sceneManager=new _n(this._performanceMonitor),this._serviceContainer.registerInstance(_n,this._sceneManager),this._sceneManager.setSceneChangedCallback(function(){var e;return null===(e=o._debugManager)||void 0===e?void 0:e.onSceneChanged()}),this._worldManager=new In(c({debug:!!this._config.debug},this._config.worldManagerConfig)),this._serviceContainer.registerInstance(In,this._worldManager),this._pluginManager=new Cn,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(Cn,this._pluginManager),this._pluginServiceRegistry=new bn,this._serviceContainer.registerInstance(bn,this._pluginServiceRegistry),this.debug=null===(i=this._config.debug)||void 0===i||i,null!==(r=this._config.debugConfig)&&void 0!==r&&r.enabled){var s=new e.DebugConfigService;s.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(e.DebugConfigService,s),this._serviceContainer.registerSingleton(e.DebugManager,function(t){return A(e.DebugManager,t)}),this._debugManager=this._serviceContainer.resolve(e.DebugManager),this._debugManager.onInitialize()}this.initialize()}t.create=function(e){if(void 0===e&&(e=!0),null==this._instance){var n="boolean"==typeof e?{debug:e}:e;this._instance=new t(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},t.setScene=function(e){if(!this._instance)throw t._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(e)},t.loadScene=function(e){this._instance?this._instance._sceneManager.loadScene(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.update=function(e){this._instance?this._instance.updateInternal(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.schedule=function(e,t,n,i){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,i)},t.enableDebug=function(n){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(n);else{var i=new e.DebugConfigService;i.setConfig(n),this._instance._serviceContainer.registerInstance(e.DebugConfigService,i),this._instance._serviceContainer.registerSingleton(e.DebugManager,function(t){return A(e.DebugManager,t)}),this._instance._debugManager=this._instance._serviceContainer.resolve(e.DebugManager),this._instance._debugManager.onInitialize()}this._instance._config.debugConfig=n}else t._logger.warn("Core实例未创建,请先调用Core.create()")},t.disableDebug=function(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),delete this._instance._debugManager),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))},t.getDebugData=function(){var e;return null!==(e=this._instance)&&void 0!==e&&e._debugManager?this._instance._debugManager.getDebugData():null},t.installPlugin=function(){var e=i(d().m(function e(t){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),t.uninstallPlugin=function(){var e=i(d().m(function e(t){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},t.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var n=t.prototype;return n.initialize=function(){var e;t._logger.info("Core initialized",{debug:this.debug,debugEnabled:(null===(e=this._config.debugConfig)||void 0===e?void 0:e.enabled)||!1})},n.updateInternal=function(e){var n,i;if(!t.paused){var r=this._performanceMonitor.startMonitoring("Core.update");_.update(e),null===(n=(i=this._performanceMonitor).updateFPS)||void 0===n||n.call(i,_.deltaTime);var o=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(e),this._performanceMonitor.endMonitoring("Services.update",o,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",r)}},t.destroy=function(){var e;this._instance&&(null===(e=this._instance._debugManager)||void 0===e||e.stop(),this._instance._serviceContainer.clear(),t._logger.info("Core destroyed"),this._instance=null)},s(t,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"pluginServices",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._pluginServiceRegistry}},{key:"worldManager",get:function(){if(!this._instance)throw new Error("Core instance not created, call Core.create() first | Core实例未创建,请先调用Core.create()");return this._instance._worldManager}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}},{key:"performanceMonitor",get:function(){var e;return(null===(e=this._instance)||void 0===e?void 0:e._performanceMonitor)||null}}])}();Mn.paused=!1,Mn._instance=null,Mn._logger=Z("Core");var An=En("runtimeMode"),kn=function(){function e(e){var t,n,i;void 0===e&&(e={}),this._callbacks=new Set,this._isEditor=null!==(t=e.isEditor)&&void 0!==t&&t,this._isPlaying=null!==(n=e.isPlaying)&&void 0!==n&&n,this._isPreview=null!==(i=e.isPreview)&&void 0!==i&&i}var t=e.prototype;return t.onModeChanged=function(e){var t=this;return this._callbacks.add(e),function(){t._callbacks.delete(e)}},t.setEditorMode=function(e){this._isEditor!==e&&(this._isEditor=e,this._notifyChange())},t.setPlaying=function(e){this._isPlaying!==e&&(this._isPlaying=e,this._notifyChange())},t.setPreview=function(e){this._isPreview!==e&&(this._isPreview=e,this._notifyChange())},t.updateMode=function(e){var t=!1;void 0!==e.isEditor&&this._isEditor!==e.isEditor&&(this._isEditor=e.isEditor,t=!0),void 0!==e.isPlaying&&this._isPlaying!==e.isPlaying&&(this._isPlaying=e.isPlaying,t=!0),void 0!==e.isPreview&&this._isPreview!==e.isPreview&&(this._isPreview=e.isPreview,t=!0),t&&this._notifyChange()},t._notifyChange=function(){for(var t,n=a(this._callbacks);!(t=n()).done;){var i=t.value;try{i(this)}catch(t){e._logger.error("Callback error:",t)}}},t.dispose=function(){this._callbacks.clear()},s(e,[{key:"isEditor",get:function(){return this._isEditor}},{key:"isPlaying",get:function(){return this._isPlaying}},{key:"isPreview",get:function(){return this._isPreview}},{key:"isStandalone",get:function(){return!this._isEditor}}])}();kn._logger=Z("RuntimeModeService");var Dn=Z("DebugPlugin");e.DebugPlugin=function(){function e(e){var t,n;this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=null!==(t=null==e?void 0:e.autoStart)&&void 0!==t&&t,this.updateInterval=null!==(n=null==e?void 0:e.updateInterval)&&void 0!==n?n:1e3}var t=e.prototype;return t.install=function(){var e=i(d().m(function e(t,n){return d().w(function(e){for(;;)switch(e.n){case 0:this.worldManager=n.resolve(In),Dn.info("ECS Debug Plugin installed"),this.autoStart&&this.start();case 1:return e.a(2)}},e,this)}));return function(t,n){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.n){case 0:this.stop(),this.worldManager=null,Dn.info("ECS Debug Plugin uninstalled");case 1:return e.a(2)}},e,this)}));return function(){return e.apply(this,arguments)}}(),t.dispose=function(){this.stop(),this.worldManager=null},t.start=function(){var e=this;this.updateTimer?Dn.warn("Debug monitoring already started"):(Dn.info("Starting debug monitoring"),this.updateTimer=setInterval(function(){e.logStats()},this.updateInterval))},t.stop=function(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,Dn.info("Debug monitoring stopped"))},t.getStats=function(){if(!this.worldManager)throw new Error("Plugin not installed");for(var e,t=[],n=0,i=0,r=a(this.worldManager.getAllWorlds());!(e=r()).done;)for(var o,s=a(e.value.getAllScenes());!(o=s()).done;){var c=o.value,u=this.getSceneInfo(c);t.push(u),n+=u.entityCount,i+=u.systems.length}return{scenes:t,totalEntities:n,totalSystems:i,timestamp:Date.now()}},t.getSceneInfo=function(e){var t=this,n=e.entities.buffer,i=e.systems;return{name:e.name,entityCount:n.length,systems:i.map(function(e){return t.getSystemInfo(e)}),entities:n.map(function(e){return t.getEntityInfo(e)})}},t.getSystemInfo=function(e){var t=e.getPerformanceStats(),n=t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0;return c({name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length},void 0!==n&&{performance:n})},t.getEntityInfo=function(e){var t=this,n=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:n.length,components:n.map(function(e){return t.getComponentInfo(e)})}},t.getComponentInfo=function(e){for(var t=e.constructor.name,n={},i=0,r=Object.keys(e);i<r.length;i++){var o=r[i];if(!o.startsWith("_")){var s=e[o];"function"!=typeof s&&(n[o]=s)}}return{type:t,data:n}},t.queryEntities=function(e){if(!this.worldManager)throw new Error("Plugin not installed");for(var t,n=[],i=a(this.worldManager.getAllWorlds());!(t=i()).done;)for(var r,o=a(t.value.getAllScenes());!(r=o()).done;){var s=r.value;if(!e.sceneName||s.name===e.sceneName)for(var c,u=a(s.entities.buffer);!(c=u()).done;){var l=c.value;if((void 0===e.tag||l.tag===e.tag)&&(!e.name||l.name.includes(e.name))){if(e.hasComponent)if(!l.components.some(function(t){return t.constructor.name===e.hasComponent}))continue;n.push(this.getEntityInfo(l))}}}return n},t.logStats=function(){var e=this.getStats();Dn.info("=== ECS Debug Stats ==="),Dn.info("Total Entities: "+e.totalEntities),Dn.info("Total Systems: "+e.totalSystems),Dn.info("Scenes: "+e.scenes.length);for(var t,n=a(e.scenes);!(t=n()).done;){var i=t.value;Dn.info("\n[Scene: "+i.name+"]"),Dn.info(" Entities: "+i.entityCount),Dn.info(" Systems: "+i.systems.length);for(var r,o=a(i.systems);!(r=o()).done;){var s=r.value,c=s.performance?" | Avg: "+s.performance.avgExecutionTime.toFixed(2)+"ms, Max: "+s.performance.maxExecutionTime.toFixed(2)+"ms":"";Dn.info(" - "+s.name+" ("+(s.enabled?"enabled":"disabled")+") | Entities: "+s.entityCount+c)}}Dn.info("========================\n")},t.exportJSON=function(){var e=this.getStats();return JSON.stringify(e,null,2)},e}(),e.DebugPlugin=g([T(),y("design:paramtypes",[Object])],e.DebugPlugin);var Pn,On,xn=function(e,t){this.func=e,this.context=t},Rn=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,t)||i.push(new xn(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var i=n.findIndex(function(e){return e.func==t});-1!=i&&n.splice(i,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var o,s=a(t);!(o=s()).done;){var c,u=o.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},t.hasObserver=function(e,t){var n=this._messageTable.get(e);return!!n&&n.some(function(e){return e.func===t})},t.removeAllObservers=function(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()},t.dispose=function(){this._messageTable.clear()},t.getEventTypeCount=function(){return this._messageTable.size},t.getObserverCount=function(e){var t=this._messageTable.get(e);return t?t.length:0},e}(),zn=function(){function e(){this._enabled=!1}var t=e.prototype;return t.setEnabled=function(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())},t.onEnabled=function(){},t.onDisabled=function(){},t.update=function(){},s(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this.setEnabled(e)}}])}();e.ECSEventType=void 0,(Pn=e.ECSEventType||(e.ECSEventType={})).ENTITY_CREATED="entity:created",Pn.ENTITY_DESTROYED="entity:destroyed",Pn.ENTITY_ENABLED="entity:enabled",Pn.ENTITY_DISABLED="entity:disabled",Pn.ENTITY_TAG_ADDED="entity:tag:added",Pn.ENTITY_TAG_REMOVED="entity:tag:removed",Pn.ENTITY_NAME_CHANGED="entity:name:changed",Pn.COMPONENT_ADDED="component:added",Pn.COMPONENT_REMOVED="component:removed",Pn.COMPONENT_MODIFIED="component:modified",Pn.COMPONENT_ENABLED="component:enabled",Pn.COMPONENT_DISABLED="component:disabled",Pn.SYSTEM_ADDED="system:added",Pn.SYSTEM_REMOVED="system:removed",Pn.SYSTEM_ENABLED="system:enabled",Pn.SYSTEM_DISABLED="system:disabled",Pn.SYSTEM_PROCESSING_START="system:processing:start",Pn.SYSTEM_PROCESSING_END="system:processing:end",Pn.SYSTEM_ERROR="system:error",Pn.SCENE_CREATED="scene:created",Pn.SCENE_DESTROYED="scene:destroyed",Pn.SCENE_ACTIVATED="scene:activated",Pn.SCENE_DEACTIVATED="scene:deactivated",Pn.SCENE_PAUSED="scene:paused",Pn.SCENE_RESUMED="scene:resumed",Pn.QUERY_EXECUTED="query:executed",Pn.QUERY_CACHE_HIT="query:cache:hit",Pn.QUERY_CACHE_MISS="query:cache:miss",Pn.QUERY_OPTIMIZED="query:optimized",Pn.PERFORMANCE_WARNING="performance:warning",Pn.PERFORMANCE_CRITICAL="performance:critical",Pn.MEMORY_USAGE_HIGH="memory:usage:high",Pn.FRAME_RATE_DROP="frame:rate:drop",Pn.INDEX_CREATED="index:created",Pn.INDEX_UPDATED="index:updated",Pn.INDEX_OPTIMIZED="index:optimized",Pn.ARCHETYPE_CREATED="archetype:created",Pn.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",Pn.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",Pn.DIRTY_MARK_ADDED="dirty:mark:added",Pn.DIRTY_BATCH_PROCESSED="dirty:batch:processed",Pn.ERROR_OCCURRED="error:occurred",Pn.WARNING_ISSUED="warning:issued",Pn.FRAMEWORK_INITIALIZED="framework:initialized",Pn.FRAMEWORK_SHUTDOWN="framework:shutdown",Pn.DEBUG_INFO="debug:info",Pn.DEBUG_STATS_UPDATED="debug:stats:updated",e.EventPriority=void 0,(On=e.EventPriority||(e.EventPriority={}))[On.LOWEST=0]="LOWEST",On[On.LOW=25]="LOW",On[On.NORMAL=50]="NORMAL",On[On.HIGH=75]="HIGH",On[On.HIGHEST=100]="HIGHEST",On[On.CRITICAL=200]="CRITICAL";var Nn={ENTITY:{CREATED:e.ECSEventType.ENTITY_CREATED,DESTROYED:e.ECSEventType.ENTITY_DESTROYED,ENABLED:e.ECSEventType.ENTITY_ENABLED,DISABLED:e.ECSEventType.ENTITY_DISABLED,TAG_ADDED:e.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:e.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:e.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:e.ECSEventType.COMPONENT_ADDED,REMOVED:e.ECSEventType.COMPONENT_REMOVED,MODIFIED:e.ECSEventType.COMPONENT_MODIFIED,ENABLED:e.ECSEventType.COMPONENT_ENABLED,DISABLED:e.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:e.ECSEventType.SYSTEM_ADDED,REMOVED:e.ECSEventType.SYSTEM_REMOVED,ENABLED:e.ECSEventType.SYSTEM_ENABLED,DISABLED:e.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:e.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:e.ECSEventType.SYSTEM_PROCESSING_END,ERROR:e.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:e.ECSEventType.PERFORMANCE_WARNING,CRITICAL:e.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:e.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:e.ECSEventType.FRAME_RATE_DROP}},Fn=function(){function e(){}return e.isValid=function(e){return this.validTypes.has(e)},e.getAllValidTypes=function(){return Array.from(this.validTypes)},e.addCustomType=function(e){this.validTypes.add(e)},e.removeCustomType=function(e){this.validTypes.delete(e)},e}();Fn.validTypes=new Set([].concat(Object.values(e.ECSEventType),Object.values(Nn.ENTITY),Object.values(Nn.COMPONENT),Object.values(Nn.SYSTEM),Object.values(Nn.PERFORMANCE)));var Bn=function(e){function t(t){return e.call(this,t)||this}return l(t,e),t.prototype.process=function(e){this.processSystem()},t}(je),Ln=function(e){function t(t){return e.call(this,t)||this}return l(t,e),t.prototype.process=function(e){},t}(je),Hn=function(e){function t(t,n){var i;return(i=e.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=t,i}l(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=_.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(je),Wn=function(){function e(){this._adapter=null,this._logger=Z("PlatformManager")}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.getAdapter=function(){if(!this._adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this._adapter},t.registerAdapter=function(e){this._adapter=e,this._logger.info("平台适配器已注册: "+e.name,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})},t.hasAdapter=function(){return null!==this._adapter},t.getAdapterInfo=function(){return this._adapter?{name:this._adapter.name,version:this._adapter.version,config:this._adapter.getPlatformConfig()}:null},t.supportsFeature=function(e){if(!this._adapter)return!1;var t=this._adapter.getPlatformConfig();switch(e){case"worker":return this._adapter.isWorkerSupported();case"shared-array-buffer":return this._adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}},t.getBasicWorkerConfig=function(){if(!this._adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};var e=this._adapter.getPlatformConfig();return{platformSupportsWorker:this._adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this._adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}},t.getFullPlatformConfig=function(){var e=i(d().m(function e(){return d().w(function(e){for(;;)switch(e.n){case 0:if(this._adapter){e.n=1;break}throw new Error("平台适配器未注册");case 1:if("function"!=typeof this._adapter.getPlatformConfigAsync){e.n=3;break}return e.n=2,this._adapter.getPlatformConfigAsync();case 2:return e.a(2,e.v);case 3:return e.a(2,this._adapter.getPlatformConfig())}},e,this)}));return function(){return e.apply(this,arguments)}}(),e}(),Un="Worker pool has been destroyed",Gn=function(){function e(e,t){this.workerStates=new Map,this.pendingTasks=new Map,this.taskQueue=[],this.taskCounter=0,this._isDestroyed=!1,this.workers=e,this.initializeWorkers(t)}var t=e.prototype;return t.executeSharedBuffer=function(e){return this.createTask("shared-"+ ++this.taskCounter,c({},e,{type:"shared"}),function(){})},t.execute=function(e){return this.createTask("task-"+ ++this.taskCounter,e,function(e){return e})},t.getStatus=function(){for(var e,t={idle:0,busy:0,initializing:0},n=a(this.workerStates.values());!(e=n()).done;){var i=e.value;1===i?t.idle++:2===i?t.busy++:0===i&&t.initializing++}return c({total:this.workers.length},t,{queuedTasks:this.taskQueue.length})},t.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0;for(var e,t=new Error(Un),n=a(this.pendingTasks.values());!(e=n()).done;){e.value.reject(t)}for(var i,r=a(this.taskQueue);!(i=r()).done;){i.value.reject(t)}for(var o,s=a(this.workers);!(o=s()).done;){o.value.terminate()}this.workers.length=0,this.taskQueue.length=0,this.pendingTasks.clear(),this.workerStates.clear()}},t.initializeWorkers=function(e){for(var t=this,n=function(n){var i=t.workers[n];if(!i)return 1;t.workerStates.set(n,e?0:1),i.onMessage(function(e){return t.handleMessage(n,e.data)}),i.onError(function(e){return t.handleError(n,e)}),e&&i.postMessage({type:"init",sharedBuffer:e})},i=0;i<this.workers.length;i++)n(i)},t.createTask=function(e,t,n){var i=this;return new Promise(function(r,o){i._isDestroyed?o(new Error(Un)):i.enqueueTask({id:e,data:t,resolve:function(e){return r(n(e))},reject:o})})},t.enqueueTask=function(e){this.taskQueue.push(e),this.dispatchTasks()},t.dispatchTasks=function(){for(;this.taskQueue.length>0;){var e=this.findIdleWorker();if(-1===e)break;var t=this.taskQueue.shift();this.assignTask(e,t)}},t.findIdleWorker=function(){for(var e=0;e<this.workers.length;e++)if(1===this.workerStates.get(e))return e;return-1},t.assignTask=function(e,t){var n=this.workers[e];n&&(this.workerStates.set(e,2),this.pendingTasks.set(e,t),n.postMessage(c({id:t.id},t.data)))},t.handleMessage=function(e,t){if("init"===t.type)return this.workerStates.set(e,1),void this.dispatchTasks();t.error?this.completeTask(e,new Error(t.error)):this.completeTask(e,void 0,t.result)},t.handleError=function(e,t){this.completeTask(e,new Error(t.message))},t.completeTask=function(e,t,n){var i=this.pendingTasks.get(e);i&&(this.pendingTasks.delete(e),this.workerStates.set(e,1),t?i.reject(t):i.resolve(n),this.dispatchTasks())},s(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"workerCount",get:function(){return this.workers.length}},{key:"isReady",get:function(){if(this._isDestroyed)return!1;for(var e,t=a(this.workerStates.values());!(e=t()).done;){if(0===e.value)return!1}return this.workers.length>0}},{key:"hasPendingTasks",get:function(){return this.taskQueue.length>0||this.pendingTasks.size>0}}])}(),jn=function(e){function t(t,n){var i;return void 0===n&&(n={}),(i=e.call(this,t)||this).sharedBuffer=null,i.sharedFloatArray=null,i.workerPool=null,i.isProcessing=!1,i.hasLoggedSyncMode=!1,i.platformAdapter=Wn.getInstance().getAdapter(),i.config=i.resolveConfig(n),i.config.enableWorker&&i.isWorkerSupported()&&i.initializeWorkerSystem(),i}l(t,e);var n=t.prototype;return n.resolveConfig=function(e){var t,n,i,r,o,s=this.getMaxSystemWorkerCount(),a=null!==(t=e.workerCount)&&void 0!==t?t:s,u=Math.min(a,s);return a>s&&this.logger.warn("请求 "+a+" 个 Worker,但系统最多支持 "+s+" 个。实际使用 "+u+" 个 Worker。"),c({enableWorker:null===(n=e.enableWorker)||void 0===n||n,workerCount:u,useSharedArrayBuffer:null!==(i=e.useSharedArrayBuffer)&&void 0!==i?i:this.isSharedArrayBufferSupported(),entityDataSize:null!==(r=e.entityDataSize)&&void 0!==r?r:this.getDefaultEntityDataSize(),maxEntities:null!==(o=e.maxEntities)&&void 0!==o?o:1e4,systemConfig:e.systemConfig},void 0!==e.entitiesPerWorker&&{entitiesPerWorker:e.entitiesPerWorker},void 0!==e.workerScriptPath&&{workerScriptPath:e.workerScriptPath})},n.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},n.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},n.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},n.initializeWorkerSystem=function(){this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool()},n.initializeSharedArrayBuffer=function(){try{if(!this.isSharedArrayBufferSupported())return void this.fallbackToSingleWorker("平台不支持 SharedArrayBuffer");var e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer),this.logger.info(this.systemName+": SharedArrayBuffer 初始化成功 ("+e+" bytes)"))}catch(e){this.fallbackToSingleWorker("SharedArrayBuffer 初始化失败"),this.logger.warn(this.systemName+":",e)}},n.fallbackToSingleWorker=function(e){this.logger.warn(this.systemName+": "+e+",降级到单 Worker 模式"),this.config.useSharedArrayBuffer=!1,this.config.workerCount=1,this.sharedBuffer=null,this.sharedFloatArray=null},n.initializeWorkerPool=function(){try{var e=this.resolveWorkerScript();if(!e)return void(this.config.enableWorker=!1);var t=this.createWorkers(e);this.workerPool=new Gn(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker 池初始化失败",e),this.config.enableWorker=!1}},n.resolveWorkerScript=function(){var e,t=this.platformAdapter.getPlatformConfig();if(this.config.workerScriptPath)return this.logger.info(this.systemName+": 使用外部 Worker 文件: "+this.config.workerScriptPath),this.config.workerScriptPath;if(null!==(e=t.limitations)&&void 0!==e&&e.noEval)return this.logger.error(this.systemName+": 当前平台不支持动态 Worker 脚本,请配置 workerScriptPath 指定预编译的 Worker 文件"),null;var n=this.createWorkerScript();return(t.workerScriptPrefix||"")+n},n.createWorkers=function(e){for(var t=[],n=0;n<this.config.workerCount;n++){var i=this.platformAdapter.createWorker(e,{name:this.systemName+"-Worker-"+n});t.push(i)}return t},n.createWorkerScript=function(){var e=this.extractFunctionBody(this.workerProcess.toString()),t=this.getSharedProcessFunctionBody();return"\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+this.config.entityDataSize+";\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n try {\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n if (type === 'shared') {\n if (!sharedFloatArray) {\n self.postMessage({ id, error: 'SharedArrayBuffer not initialized' });\n return;\n }\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null });\n return;\n }\n\n if (entities) {\n function workerProcess(entities, deltaTime, systemConfig) {\n "+e+"\n }\n\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n "+t+"\n }\n "},n.extractFunctionBody=function(e){var t=e.match(/\{([\s\S]*)\}/);if(!t||void 0===t[1])throw new Error("无法解析 workerProcess 方法");return t[1]},n.getSharedProcessFunctionBody=function(){var e,t=null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this);return t?"\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n "+this.extractFunctionBody(t.toString())+"\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n ":""},n.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;var n=this.getCurrentProcessingMode();try{switch(n){case"shared-buffer":this.processWithSharedArrayBuffer(e).finally(function(){t.isProcessing=!1});break;case"worker":this.processWithWorker(e).finally(function(){t.isProcessing=!1});break;default:this.processSynchronously(e),this.isProcessing=!1}}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},n.getCurrentProcessingMode=function(){return this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray?"shared-buffer":"worker":(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker 不可用,使用同步处理"),this.hasLoggedSyncMode=!0),"sync")},n.processWithSharedArrayBuffer=function(){var e=i(d().m(function e(t){var n;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.sharedFloatArray&&this.workerPool){e.n=1;break}return e.a(2);case 1:return this.writeEntitiesToBuffer(t),n=this.createBatchTasks(t.length,!0),e.n=2,Promise.all(n);case 2:this.readResultsFromBuffer(t);case 3:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),n.processWithWorker=function(){var e=i(d().m(function e(t){var n,i,r,o,s=this;return d().w(function(e){for(;;)switch(e.n){case 0:if(this.workerPool){e.n=1;break}return e.a(2);case 1:return n=t.map(function(e){return s.extractEntityData(e)}),i=this.createDataBatches(n),r=_.deltaTime,e.n=2,Promise.all(i.map(function(e){return s.workerPool.execute({entities:e,deltaTime:r,systemConfig:s.config.systemConfig})}));case 2:o=e.v,this.applyBatchResults(t,o);case 3:return e.a(2)}},e,this)}));return function(t){return e.apply(this,arguments)}}(),n.processSynchronously=function(e){var t=this,n=e.map(function(e){return t.extractEntityData(e)}),i=_.deltaTime,r=this.workerProcess(n,i,this.config.systemConfig);r&&"function"==typeof r.then?r.then(function(n){t.applyResults(e,n)}):this.applyResults(e,r)},n.createDataBatches=function(e){return this.splitIntoBatches(e.length,function(t,n){return e.slice(t,n)})},n.createBatchTasks=function(e,t){var n=this;return this.splitIntoBatches(e,function(e,i){return t?n.workerPool.executeSharedBuffer({startIndex:e,endIndex:i,deltaTime:_.deltaTime,systemConfig:n.config.systemConfig}):Promise.resolve()})},n.splitIntoBatches=function(e,t){var n=[],i=this.config,r=i.workerCount,o=i.entitiesPerWorker;if(o)for(var s=0;s<e;s+=o){var a=Math.min(s+o,e);n.push(t(s,a))}else for(var c=Math.ceil(e/r),u=0;u<r;u++){var l=u*c,h=Math.min(l+c,e);l<e&&n.push(t(l,h))}return n},n.applyBatchResults=function(e,t){for(var n,i=0,r=a(t);!(n=r()).done;)for(var o,s=a(n.value);!(o=s()).done;){var c=o.value;i<e.length&&c&&this.applyResult(e[i],c),i++}},n.applyResults=function(e,t){for(var n=0;n<e.length&&n<t.length;n++)this.applyResult(e[n],t[n])},n.writeEntitiesToBuffer=function(e){if(this.sharedFloatArray)for(var t=Math.min(e.length,this.config.maxEntities),n=0;n<t;n++){var i=this.extractEntityData(e[n]),r=n*this.config.entityDataSize;this.writeEntityToBuffer(i,r)}},n.readResultsFromBuffer=function(e){if(this.sharedFloatArray)for(var t=Math.min(e.length,this.config.maxEntities),n=0;n<t;n++){var i=n*this.config.entityDataSize,r=this.readEntityFromBuffer(i);r&&this.applyResult(e[n],r)}},n.updateConfig=function(e){var t=c({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),i=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个 Worker,但系统最多支持 "+n+" 个。实际使用 "+i+" 个 Worker。"),e.workerCount=i}Object.assign(this.config,e),t.useSharedArrayBuffer!==this.config.useSharedArrayBuffer?this.reinitializeSystem():t.workerCount!==this.config.workerCount?this.reinitializeWorkerPool():!this.config.enableWorker&&this.workerPool?this.destroyWorkerPool():this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()},n.reinitializeSystem=function(){this.destroyWorkerPool(),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerSystem()},n.reinitializeWorkerPool=function(){this.destroyWorkerPool(),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},n.destroyWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},n.getWorkerInfo=function(){return c({enabled:this.config.enableWorker,workerCount:this.config.workerCount},void 0!==this.config.entitiesPerWorker&&{entitiesPerWorker:this.config.entitiesPerWorker},{maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:this.getCurrentProcessingMode()})},n.onDestroy=function(){e.prototype.onDestroy.call(this),this.destroyWorkerPool()},n.getLoggerName=function(){return ce(this)},t}(je);e.PrefabInstanceComponent=function(e){function t(t,n,i){var r;return void 0===t&&(t=""),void 0===n&&(n=""),void 0===i&&(i=!1),(r=e.call(this)||this).sourcePrefabGuid="",r.sourcePrefabPath="",r.isRoot=!1,r.rootInstanceEntityId=null,r.modifiedProperties=[],r.instantiatedAt=0,r.originalValues={},r.sourcePrefabGuid=t,r.sourcePrefabPath=n,r.isRoot=i,r.instantiatedAt=Date.now(),r}l(t,e);var n=t.prototype;return n.markPropertyModified=function(e,t){var n=e+"."+t;this.modifiedProperties.includes(n)||this.modifiedProperties.push(n)},n.isPropertyModified=function(e,t){var n=e+"."+t;return this.modifiedProperties.includes(n)},n.clearPropertyModified=function(e,t){var n=e+"."+t,i=this.modifiedProperties.indexOf(n);-1!==i&&this.modifiedProperties.splice(i,1)},n.clearAllModifications=function(){this.modifiedProperties=[],this.originalValues={}},n.storeOriginalValue=function(e,t,n){var i=e+"."+t;i in this.originalValues||(this.originalValues[i]=this.deepClone(n))},n.getOriginalValue=function(e){return this.originalValues[e]},n.hasOriginalValue=function(e,t){return e+"."+t in this.originalValues},n.deepClone=function(e){if(null==e)return e;if("object"==typeof e)try{return JSON.parse(JSON.stringify(e))}catch(t){return e}return e},t}(De),g([ze(),y("design:type",String)],e.PrefabInstanceComponent.prototype,"sourcePrefabGuid",void 0),g([ze(),y("design:type",String)],e.PrefabInstanceComponent.prototype,"sourcePrefabPath",void 0),g([ze(),y("design:type",Boolean)],e.PrefabInstanceComponent.prototype,"isRoot",void 0),g([ze(),y("design:type",Object)],e.PrefabInstanceComponent.prototype,"rootInstanceEntityId",void 0),g([ze(),y("design:type",Array)],e.PrefabInstanceComponent.prototype,"modifiedProperties",void 0),g([ze(),y("design:type",Number)],e.PrefabInstanceComponent.prototype,"instantiatedAt",void 0),g([ze(),y("design:type",Object)],e.PrefabInstanceComponent.prototype,"originalValues",void 0),e.PrefabInstanceComponent=g([re("PrefabInstance",{editor:{hideInInspector:!0}}),Re({version:1,typeId:"PrefabInstance"}),y("design:paramtypes",[String,String,Boolean])],e.PrefabInstanceComponent);var qn=function(){function t(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new Pt,this.isDebugMode=e}var n=t.prototype;return n.emit=function(e,n,i){void 0===i&&(i=!1),this.validateEventType(e);var r=i?this.enhanceEventData(e,n):n;this.isDebugMode&&t._logger.info("发射事件: "+e,r),this.eventSystem.emitSync(e,r)},n.emitAsync=function(){var e=i(d().m(function e(n,i,r){var o;return d().w(function(e){for(;;)switch(e.n){case 0:return void 0===r&&(r=!1),this.validateEventType(n),o=r?this.enhanceEventData(n,i):i,this.isDebugMode&&t._logger.info("发射异步事件: "+n,o),e.n=1,this.eventSystem.emit(n,o);case 1:return e.a(2)}},e,this)}));return function(t,n,i){return e.apply(this,arguments)}}(),n.on=function(n,i,r){void 0===r&&(r={}),this.validateEventType(n);var o={once:r.once||!1,priority:r.priority||e.EventPriority.NORMAL,async:r.async||!1};return r.thisArg&&(o.thisArg=r.thisArg),this.isDebugMode&&t._logger.info("添加监听器: "+n,o),this.eventSystem.on(n,i,o)},n.once=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,c({},n,{once:!0}))},n.onAsync=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,c({},n,{async:!0}))},n.off=function(e,n){return this.isDebugMode&&t._logger.info("移除监听器: "+n+" 事件: "+e),this.eventSystem.off(e,n)},n.offAll=function(e){this.isDebugMode&&t._logger.info("移除所有监听器: "+e),this.eventSystem.offAll(e)},n.hasListeners=function(e){return this.eventSystem.hasListeners(e)},n.getStats=function(e){var t=this,n=this.eventSystem.getStats(e);if(n instanceof Map){var i=new Map;return n.forEach(function(e,n){i.set(n,t.convertEventStats(e))}),i}return this.convertEventStats(n)},n.clear=function(){this.isDebugMode&&t._logger.info("清空所有监听器"),this.eventSystem.clear()},n.setEnabled=function(e){this.eventSystem.setEnabled(e)},n.setDebugMode=function(e){this.isDebugMode=e},n.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},n.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},n.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},n.flushBatch=function(e){this.eventSystem.flushBatch(e)},n.resetStats=function(e){this.eventSystem.resetStats(e)},n.emitEntityCreated=function(t){this.emit(e.ECSEventType.ENTITY_CREATED,t)},n.emitEntityDestroyed=function(t){this.emit(e.ECSEventType.ENTITY_DESTROYED,t)},n.emitComponentAdded=function(t){this.emit(e.ECSEventType.COMPONENT_ADDED,t)},n.emitComponentRemoved=function(t){this.emit(e.ECSEventType.COMPONENT_REMOVED,t)},n.emitSystemAdded=function(t){this.emit(e.ECSEventType.SYSTEM_ADDED,t)},n.emitSystemRemoved=function(t){this.emit(e.ECSEventType.SYSTEM_REMOVED,t)},n.emitSceneChanged=function(t){this.emit(e.ECSEventType.SCENE_ACTIVATED,t)},n.emitPerformanceWarning=function(t){this.emit(e.ECSEventType.PERFORMANCE_WARNING,t)},n.onEntityCreated=function(t,n){return this.on(e.ECSEventType.ENTITY_CREATED,t,n)},n.onComponentAdded=function(t,n){return this.on(e.ECSEventType.COMPONENT_ADDED,t,n)},n.onSystemError=function(t,n){return this.on(e.ECSEventType.SYSTEM_ERROR,t,n)},n.onPerformanceWarning=function(t,n){return this.on(e.ECSEventType.PERFORMANCE_WARNING,t,n)},n.validateEventType=function(e){this.isDebugMode&&(Fn.isValid(e)||(t._logger.warn("未知事件类型: "+e),Fn.addCustomType(e)))},n.enhanceEventData=function(e,t){if(null==t)return{timestamp:Date.now(),eventId:e+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=e+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},n.convertEventStats=function(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}},t}();qn._logger=Z("EventBus");var Vn=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this._instance||(this._instance=new qn(e)),this._instance},e.reset=function(e){return void 0===e&&(e=!1),this._instance&&this._instance.clear(),this._instance=new qn(e),this._instance},e}(),Qn=Z("VersionMigration"),Yn=function(){function e(){}return e.registerComponentMigration=function(e,t,n,i){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,i)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var i=this.componentMigrations.get(e.type);if(!i)return Qn.warn("No migration path found for component "+e.type+" | 未找到组件 "+e.type+" 的迁移路径"),e;for(var r=c({},e),o=n;o<t;){var s=i.get(o);if(!s){Qn.warn("Missing migration from version "+o+" to "+(o+1)+" for "+e.type+" | 缺少组件 "+e.type+" 从版本 "+o+" 到 "+(o+1)+" 的迁移");break}r.data=s(r.data,o,o+1),o++}return r.version=o,r},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var i=c({},e),r=n;r<t;){var o=this.sceneMigrations.get(r);if(!o){Qn.warn("Missing scene migration from version "+r+" to "+(r+1)+" | 缺少场景从版本 "+r+" 到 "+(r+1)+" 的迁移");break}i=o(i,r,r+1),r++}return i.version=r,i=this.migrateSceneComponents(i)},e.migrateSceneComponents=function(e){var t=this,n=c({},e);return n.entities=e.entities.map(function(n){return c({},n,{components:n.components.map(function(n){var i=e.componentTypeRegistry.find(function(e){return e.typeName===n.type});return i&&i.version!==n.version?t.migrateComponent(n,i.version):n}),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})}),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map(function(e){return c({},e,{components:e.components.map(function(e){var i=t.find(function(t){return t.typeName===e.type});return i&&i.version!==e.version?n.migrateComponent(e,i.version):e}),children:n.migrateEntitiesComponents(e.children,t)})})},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort(function(e,t){return e-t}):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort(function(e,t){return e-t})},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var i=this.componentMigrations.get(e);if(!i)return!1;for(var r=t;r<n;r++)if(!i.has(r))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();Yn.componentMigrations=new Map,Yn.sceneMigrations=new Map;var Jn=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?Yn.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):Yn.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}(),Zn=function(){function t(){}return t.createPrefab=function(e,t,n){var i,r=null===(i=t.includeChildren)||void 0===i||i,o=Ht.serialize(e,r,n),s=this.toPrefabEntity(o,!0),a=this.collectComponentTypes(s),c=a.componentTypes,u=a.componentTypeRegistry,l=Date.now(),h={name:t.name,createdAt:l,modifiedAt:l,componentTypes:c,referencedAssets:[]};return t.description&&(h.description=t.description),t.tags&&(h.tags=t.tags),{version:1,metadata:h,root:s,componentTypeRegistry:u}},t.instantiate=function(e,t,n,i){var r;void 0===i&&(i={});var o=i,s=o.parentId,c=o.name,u=o.preserveIds,l=void 0!==u&&u,h=o.trackInstance,d=void 0===h||h,f=null!==(r=t.getSystem(qe))&&void 0!==r?r:null,p=1,m=Ht.deserializeEntities([e.root],n,function(){for(;t.findEntityById(p);)p++;return p++},l,t,f),v=m.rootEntities,g=m.allEntities,y=v[0];if(!y)throw new Error("Failed to instantiate prefab: no root entity created");c&&(y.name=c);for(var _,S=a(g.values());!(_=S()).done;){var C=_.value;t.entities.add(C)}if(void 0!==s&&f){var E=t.findEntityById(s);E&&f.setParent(y,E)}if(d){var b=e.metadata.guid||"";this.addPrefabInstanceComponents(y,g,b,"",f)}return y},t.toPrefabEntity=function(e,t){var n=this;return c({},e,{isPrefabRoot:t,children:e.children.map(function(e){return n.toPrefabEntity(e,!1)})})},t.collectComponentTypes=function(e){var t=new Map,n=function(e){for(var i,r=a(e.components);!(i=r()).done;){var o=i.value;t.has(o.type)||t.set(o.type,o.version)}for(var s,c=a(e.children);!(s=c()).done;){var u=s.value;n(u)}};return n(e),{componentTypes:Array.from(t.keys()),componentTypeRegistry:Array.from(t.entries()).map(function(e){return{typeName:e[0],version:e[1]}})}},t.addPrefabInstanceComponents=function(t,n,i,r,o){var s=t.id,c=new e.PrefabInstanceComponent(i,r,!0);c.rootInstanceEntityId=s,t.addComponent(c);for(var u,l=a(n.values());!(u=l()).done;){var h=u.value;if(h.id!==s){var d=new e.PrefabInstanceComponent(i,r,!1);d.rootInstanceEntityId=s,h.addComponent(d)}}},t.isPrefabInstance=function(t){return t.hasComponent(e.PrefabInstanceComponent)},t.getSourcePrefabGuid=function(t){var n=t.getComponent(e.PrefabInstanceComponent);return(null==n?void 0:n.sourcePrefabGuid)||null},t.getPrefabInstanceRoot=function(t){var n=t.getComponent(e.PrefabInstanceComponent);if(!n||!n.rootInstanceEntityId)return null;var i=t.scene;return i&&i.findEntityById(n.rootInstanceEntityId)||null},t.serialize=function(e,t){return void 0===t&&(t=!0),JSON.stringify(e,null,t?2:void 0)},t.deserialize=function(e){var t=JSON.parse(e);if(!t.version||!t.metadata||!t.root)throw new Error("Invalid prefab data format");return t},t.validate=function(e){var t=[];return"number"!=typeof e.version&&t.push("Invalid or missing version"),e.metadata?(e.metadata.name||t.push("Missing metadata.name"),Array.isArray(e.metadata.componentTypes)||t.push("Invalid metadata.componentTypes")):t.push("Missing metadata"),e.root?this.validateEntity(e.root,t,"root"):t.push("Missing root entity"),Array.isArray(e.componentTypeRegistry)||t.push("Invalid componentTypeRegistry"),t.length>0?{valid:!1,errors:t}:{valid:!0}},t.validateEntity=function(e,t,n){var i=this;"number"!=typeof e.id&&t.push(n+": Invalid or missing id"),"string"!=typeof e.name&&t.push(n+": Invalid or missing name"),Array.isArray(e.components)||t.push(n+": Invalid or missing components"),Array.isArray(e.children)?e.children.forEach(function(e,r){i.validateEntity(e,t,n+".children["+r+"]")}):t.push(n+": Invalid or missing children")},t}(),Xn={NONE:0,FOLDER:4096,HIDDEN:8192,LOCKED:16384,EDITOR_ONLY:32768,PREFAB_INSTANCE:256,PREFAB_ROOT:512};function Kn(e,t){return 0!==(e&t)}var $n=function(){function e(){this._dirtyFields=new Set,this._hasChanges=!1,this._lastSyncTime=0}var t=e.prototype;return t.setDirty=function(e){this._dirtyFields.add(e),this._hasChanges=!0},t.hasChanges=function(){return this._hasChanges},t.isDirty=function(e){return this._dirtyFields.has(e)},t.getDirtyFields=function(){return Array.from(this._dirtyFields)},t.getDirtyCount=function(){return this._dirtyFields.size},t.clear=function(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=Date.now()},t.clearField=function(e){this._dirtyFields.delete(e),0===this._dirtyFields.size&&(this._hasChanges=!1)},t.markAllDirty=function(e){for(var t=0;t<e;t++)this._dirtyFields.add(t);this._hasChanges=e>0},t.reset=function(){this._dirtyFields.clear(),this._hasChanges=!1,this._lastSyncTime=0},s(e,[{key:"lastSyncTime",get:function(){return this._lastSyncTime}}])}();function ei(e){return e&&("function"==typeof e?e:e.constructor)[te]||null}function ti(e){return e&&e[ne]||null}function ni(e){if(e<0)throw new Error("Varint only supports non-negative integers");return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}function ii(e,t,n){if(e<0)throw new Error("Varint only supports non-negative integers");for(;e>=128;)t[n++]=127&e|128,e>>>=7;return t[n++]=e,n}function ri(e,t){var n,i=0,r=0;do{if(t>=e.length)throw new Error("Varint decode: buffer overflow");i|=(127&(n=e[t++]))<<r,r+=7}while(n>=128);return[i,t]}function oi(e){return e<<1^e>>31}function si(e){return e>>>1^-(1&e)}var ai="undefined"!=typeof TextEncoder?new TextEncoder:null,ci=function(){function e(e){void 0===e&&(e=256),this._offset=0,this._buffer=new Uint8Array(e),this._view=new DataView(this._buffer.buffer)}var t=e.prototype;return t.toUint8Array=function(){return this._buffer.slice(0,this._offset)},t.reset=function(){this._offset=0},t.ensureCapacity=function(e){var t=this._offset+e;if(t>this._buffer.length){var n=Math.max(2*this._buffer.length,t),i=new Uint8Array(n);i.set(this._buffer),this._buffer=i,this._view=new DataView(this._buffer.buffer)}},t.writeUint8=function(e){this.ensureCapacity(1),this._buffer[this._offset++]=e},t.writeInt8=function(e){this.ensureCapacity(1),this._view.setInt8(this._offset++,e)},t.writeBoolean=function(e){this.writeUint8(e?1:0)},t.writeUint16=function(e){this.ensureCapacity(2),this._view.setUint16(this._offset,e,!0),this._offset+=2},t.writeInt16=function(e){this.ensureCapacity(2),this._view.setInt16(this._offset,e,!0),this._offset+=2},t.writeUint32=function(e){this.ensureCapacity(4),this._view.setUint32(this._offset,e,!0),this._offset+=4},t.writeInt32=function(e){this.ensureCapacity(4),this._view.setInt32(this._offset,e,!0),this._offset+=4},t.writeFloat32=function(e){this.ensureCapacity(4),this._view.setFloat32(this._offset,e,!0),this._offset+=4},t.writeFloat64=function(e){this.ensureCapacity(8),this._view.setFloat64(this._offset,e,!0),this._offset+=8},t.writeVarint=function(e){this.ensureCapacity(ni(e)),this._offset=ii(e,this._buffer,this._offset)},t.writeString=function(e){if(ai){var t=ai.encode(e);this.writeVarint(t.length),this.ensureCapacity(t.length),this._buffer.set(t,this._offset),this._offset+=t.length}else{var n=this.stringToUtf8Bytes(e);this.writeVarint(n.length),this.ensureCapacity(n.length),this._buffer.set(n,this._offset),this._offset+=n.length}},t.writeBytes=function(e){this.ensureCapacity(e.length),this._buffer.set(e,this._offset),this._offset+=e.length},t.stringToUtf8Bytes=function(e){for(var t=[],n=0;n<e.length;n++){var i=e.charCodeAt(n);if(i>=55296&&i<=56319&&n+1<e.length){var r=e.charCodeAt(n+1);r>=56320&&r<=57343&&(i=65536+(i-55296<<10)+(r-56320),n++)}i<128?t.push(i):i<2048?(t.push(192|i>>6),t.push(128|63&i)):i<65536?(t.push(224|i>>12),t.push(128|i>>6&63),t.push(128|63&i)):(t.push(240|i>>18),t.push(128|i>>12&63),t.push(128|i>>6&63),t.push(128|63&i))}return new Uint8Array(t)},s(e,[{key:"offset",get:function(){return this._offset}}])}(),ui="undefined"!=typeof TextDecoder?new TextDecoder:null,li=function(){function e(e){this._offset=0,this._buffer=e,this._view=new DataView(e.buffer,e.byteOffset,e.byteLength)}var t=e.prototype;return t.hasMore=function(){return this._offset<this._buffer.length},t.readUint8=function(){return this.checkBounds(1),this._buffer[this._offset++]},t.readInt8=function(){return this.checkBounds(1),this._view.getInt8(this._offset++)},t.readBoolean=function(){return 0!==this.readUint8()},t.readUint16=function(){this.checkBounds(2);var e=this._view.getUint16(this._offset,!0);return this._offset+=2,e},t.readInt16=function(){this.checkBounds(2);var e=this._view.getInt16(this._offset,!0);return this._offset+=2,e},t.readUint32=function(){this.checkBounds(4);var e=this._view.getUint32(this._offset,!0);return this._offset+=4,e},t.readInt32=function(){this.checkBounds(4);var e=this._view.getInt32(this._offset,!0);return this._offset+=4,e},t.readFloat32=function(){this.checkBounds(4);var e=this._view.getFloat32(this._offset,!0);return this._offset+=4,e},t.readFloat64=function(){this.checkBounds(8);var e=this._view.getFloat64(this._offset,!0);return this._offset+=8,e},t.readVarint=function(){var e=ri(this._buffer,this._offset),t=e[0],n=e[1];return this._offset=n,t},t.readString=function(){var e=this.readVarint();this.checkBounds(e);var t=this._buffer.subarray(this._offset,this._offset+e);return this._offset+=e,ui?ui.decode(t):this.utf8BytesToString(t)},t.readBytes=function(e){this.checkBounds(e);var t=this._buffer.slice(this._offset,this._offset+e);return this._offset+=e,t},t.peekUint8=function(){return this.checkBounds(1),this._buffer[this._offset]},t.skip=function(e){this.checkBounds(e),this._offset+=e},t.checkBounds=function(e){if(this._offset+e>this._buffer.length)throw new Error("BinaryReader: buffer overflow (offset="+this._offset+", size="+e+", bufferLength="+this._buffer.length+")")},t.utf8BytesToString=function(e){for(var t="",n=0;n<e.length;){var i=void 0,r=e[n++];if(r<128)i=r;else if(r<224){i=(31&r)<<6|63&e[n++]}else if(r<240){i=(15&r)<<12|(63&e[n++])<<6|63&e[n++]}else{(i=(7&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])>65535&&(i-=65536,t+=String.fromCharCode(55296+(i>>10)),i=56320+(1023&i))}t+=String.fromCharCode(i)}return t},s(e,[{key:"offset",get:function(){return this._offset},set:function(e){this._offset=e}},{key:"remaining",get:function(){return this._buffer.length-this._offset}}])}();function hi(e,t,n){switch(n){case"boolean":e.writeBoolean(t);break;case"int8":e.writeInt8(t);break;case"uint8":e.writeUint8(t);break;case"int16":e.writeInt16(t);break;case"uint16":e.writeUint16(t);break;case"int32":e.writeInt32(t);break;case"uint32":e.writeUint32(t);break;case"float32":e.writeFloat32(t);break;case"float64":e.writeFloat64(t);break;case"string":e.writeString(null!=t?t:"")}}function di(e,t,n){var i=t.fields;n.writeVarint(i.length);for(var r,o=a(i);!(r=o()).done;){var s=r.value;n.writeUint8(s.index),hi(n,e[s.name],s.type)}}function fi(e,t,n,i){if(!n.hasChanges())return!1;var r=n.getDirtyFields();i.writeVarint(r.length);for(var o,s=a(r);!(o=s()).done;){var c=o.value,u=t.fields[c];if(u)i.writeUint8(u.index),hi(i,e[u.name],u.type)}return r.length>0}function pi(e,t,n){void 0===n&&(n=!1),t.writeUint32(e.id);for(var i,r=[],o=a(e.components);!(i=o()).done;){var s=i.value,c=s.constructor[te];if(c&&c.fields.length>0){var u=s[ne];if(n&&u&&!u.hasChanges())continue;r.push({component:s,metadata:c,tracker:u})}}t.writeVarint(r.length);for(var l=0,h=r;l<h.length;l++){var d=h[l],f=d.component,p=d.metadata,m=d.tracker;t.writeString(p.typeId),n&&m?fi(f,p,m,t):di(f,p,t)}return r.length}function mi(e,t){switch(t){case"boolean":return e.readBoolean();case"int8":return e.readInt8();case"uint8":return e.readUint8();case"int16":return e.readInt16();case"uint16":return e.readUint16();case"int32":return e.readInt32();case"uint32":return e.readUint32();case"float32":return e.readFloat32();case"float64":return e.readFloat64();case"string":return e.readString()}}function vi(e,t,n){for(var i=n.readVarint(),r=0;r<i;r++){var o=n.readUint8(),s=t.fields[o];if(s){var a=mi(n,s.type);e["_sync_"+s.name]=a}else console.warn("Unknown sync field index: "+o)}}function gi(e,t,n){var i=t.readUint32(),r=t.readVarint(),o=[],s=null==n?void 0:n.get(i),a=!1;s||(s=e.findEntityById(i)),s||(s=e.createEntity("entity_"+i),a=!0,null==n||n.set(i,s));for(var c=0;c<r;c++){var u=t.readString();o.push(u);var l=ee.getComponentType(u);if(l){var h=l[te];if(h){var d=s.getComponent(l);d||(d=s.addComponent(new l)),vi(d,h,t)}else console.warn("Component "+u+" has no sync metadata")}else{console.warn("Unknown component type: "+u);for(var f=t.readVarint(),p=0;p<f;p++){t.readUint8(),console.error("Cannot skip unknown component type: "+u);break}}}return{entityId:i,isNew:a,componentTypes:o}}function yi(t){var n=new li(t);if(n.readUint8()!==e.SyncOperation.DESPAWN)return null;var i=[];if(4===n.remaining)i.push(n.readUint32());else for(var r=n.readVarint(),o=0;o<r;o++)i.push(n.readUint32());return{entityIds:i}}var _i=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){var t,n=null===(t=this._entity.scene)||void 0===t?void 0:t.getSystem(qe);return null==n||n.setParent(e,this._entity),this},t.build=function(){return this._entity},s(e,[{key:"entity",get:function(){return this._entity}}])}();var Si=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),Ci=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function Ei(e){return"function"==typeof e&&e.prototype instanceof De}function bi(){return globalThis}var Ti=function(){function t(){}return t.detect=function(){var e,t=[],n="unknown",i=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",i=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",i=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",i=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",i=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",i=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",i=!0,e="BrowserAdapter",t.push("browser")),"undefined"!=typeof Worker&&t.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&t.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&t.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&t.push("performance.now"),"undefined"!=typeof Blob&&t.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&t.push("URL.createObjectURL"),c({platform:n,confident:i,features:t},e&&{adapterClass:e})},t.isWeChatMiniGame=function(){var e=this.miniGameGlobals.wx;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)},t.isByteDanceMiniGame=function(){var e=this.miniGameGlobals.tt;return!!e&&!!(e.getSystemInfo&&e.createCanvas&&e.createImage)},t.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||void 0===e||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},t.isAlipayMiniGame=function(){var e=this.miniGameGlobals.my;return!!e&&!(!e.getSystemInfo||!e.createCanvas)},t.isBaiduMiniGame=function(){var e=this.miniGameGlobals.swan;return!!e&&!(!e.getSystemInfo||!e.createCanvas)},t.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},t.isTauriEnvironment=function(){return"undefined"!=typeof window&&("__TAURI__"in window||"__TAURI_INTERNALS__"in window)},t.isEditorEnvironment=function(){return"undefined"!=typeof window&&(!!this.isTauriEnvironment()||"__ESENGINE_EDITOR__"in window)},t.getDetailedInfo=function(){var e={},t=this.miniGameGlobals;return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==t.wx,tt:void 0!==t.tt,my:void 0!==t.my,swan:void 0!==t.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},t}();Ti.miniGameGlobals=bi(),e.AdvancedProfilerCollector=rt,e.After=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=be(e.prototype).after).push.apply(n,t),e}},e.AutoProfiler=Yt,e.Before=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=be(e.prototype).before).push.apply(n,t),e}},e.BinaryReader=li,e.BinarySerializer=Wt,e.BinaryWriter=ci,e.BitMask64Utils=q,e.Bits=yt,e.CHANGE_TRACKER=ne,e.COMPONENT_DEPENDENCIES=F,e.COMPONENT_EDITOR_OPTIONS=B,e.COMPONENT_TYPE_NAME=N,e.ChangeTracker=$n,e.Colors=V,e.CommandBuffer=Ge,e.CompiledQuery=At,e.Component=De,e.ComponentDataCollector=Xe,e.ComponentPoolManager=Ze,e.ComponentRegistry=$,e.ComponentSerializer=Lt,e.ComponentSparseSet=Ct,e.ComponentStorage=Le,e.ConsoleLogger=Q,e.Core=Mn,e.CycleDependencyError=$t,e.DEFAULT_PROFILER_CONFIG=tt,e.DEFAULT_STAGE_ORDER=rn,e.DeepCopy=function(e,t){Me(e,"__deepCopyFields").add(String(t))},e.ECSComponent=re,e.ECSFluentAPI=fn,e.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");var i=n;return i[ie]=e,t&&(i.__systemMetadata__=t),n}},e.EMPTY_GUID="00000000-0000-0000-0000-000000000000",e.ENTITY_REF_METADATA=me,e.EVENT_TYPES=Nn,e.Emitter=Rn,e.EnableSoA=function(e){return e.__enableSoA=!0,e},e.Entity=pt,e.EntityDataCollector=Ve,e.EntityHandleManager=sn,e.EntityList=mt,e.EntityProcessorList=gt,e.EntityRef=function(){return function(e,t){var n=e.constructor,i=n[me];i||(i={properties:new Set},n[me]=i);var r="symbol"==typeof t?t.toString():t;i.properties.add(r),Object.defineProperty(e,t,{get:function(){return ge(this).get(r)||null},set:function(e){var t=ge(this),n=t.get(r)||null;if(n!==e){var i=null!==this.entityId?de(this.entityId):null;if(i&&i.referenceTracker){var o=i.referenceTracker;if(n&&o.unregisterReference(n,this,r),e){var s;if(e.scene!==i)return void pe.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(s=e.scene)||void 0===s?void 0:s.name)||"null"));if(e.isDestroyed)return pe.warn("Cannot reference destroyed Entity: "+e.name),void t.set(r,null);o.registerReference(e,this,r)}t.set(r,e)}else t.set(r,e)}},enumerable:!0,configurable:!0})}},e.EntitySerializer=Ht,e.EntitySystem=je,e.EntityTags=Xn,e.EpochManager=an,e.EventBus=qn,e.EventTypeValidator=Fn,e.Float32=function(e,t){Me(e,"__float32Fields").add(String(t))},e.Float64=function(e,t){Me(e,"__float64Fields").add(String(t))},e.FuncPack=xn,e.GEN_BITS=20,e.GEN_MASK=at,e.GlobalComponentRegistry=ee,e.GlobalEventBus=Vn,e.GlobalManager=zn,e.HierarchySystem=qe,e.INDEX_BITS=28,e.INDEX_MASK=st,e.IdentifierPool=vt,e.IgnoreSerialization=function(){return function(e,t){var n,i=e.constructor;if(Object.prototype.hasOwnProperty.call(i,Pe))n=i[Pe];else{var r=i[Pe];n={options:r?c({},r.options):{version:1},fields:r?new Map(r.fields):new Map,ignoredFields:r?new Set(r.ignoredFields):new Set},i[Pe]=n}n.ignoredFields.add(t)}},e.InSet=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n;return(n=be(e.prototype).sets).push.apply(n,t),e}},e.IncrementalSerializer=Vt,e.InjectProperty=I,e.Injectable=T,e.Int16=function(e,t){Me(e,"__int16Fields").add(String(t))},e.Int32=Ae,e.Int8=function(e,t){Me(e,"__int8Fields").add(String(t))},e.IntervalSystem=Hn,e.Logger=J,e.LoggerManager=Y,e.MAX_ENTITIES=ct,e.MAX_GENERATION=ut,e.Matcher=Fe,e.MigrationBuilder=Jn,e.NULL_HANDLE=0,e.NumberExtension=Ci,e.PREFAB_FORMAT_VERSION=1,e.PROPERTY_METADATA=Ce,e.PassiveSystem=Ln,e.PerformanceDataCollector=Ye,e.PerformanceMonitor=O,e.PlatformDetector=Ti,e.PlatformManager=Wn,e.PlatformWorkerPool=Gn,e.PluginManager=Cn,e.PluginServiceRegistry=bn,e.Pool=x,e.PoolManager=z,e.PrefabSerializer=Zn,e.ProcessingSystem=Bn,e.Profile=function(t,n){return void 0===n&&(n=e.ProfileCategory.Custom),function(e,i,r){var o=r.value,s=t||e.constructor.name+"."+String(i);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(!it.isEnabled())return o.apply(this,t);var r=it.beginSample(s,n);try{var a=o.apply(this,t);return a instanceof Promise?a.finally(function(){it.endSample(r)}):(it.endSample(r),a)}catch(e){throw it.endSample(r),e}},r}},e.ProfileClass=function(t){return void 0===t&&(t=e.ProfileCategory.Custom),function(e){return Yt.registerClass(e,t)}},e.ProfilerSDK=it,e.Property=function(e){return function(t,n){var i=t.constructor,r=Se.get(i)||{};r[n]=e,Se.set(i,r)}},e.QuerySystem=kt,e.ReactiveQuery=Mt,e.ReferenceTracker=fe,e.RuntimeModeService=kn,e.RuntimeModeToken=An,e.SCHEDULING_METADATA=Ee,e.SERIALIZABLE_METADATA=Pe,e.SERIALIZE_FIELD=Oe,e.SERIALIZE_OPTIONS=xe,e.SYNC_METADATA=te,e.SYSTEM_TYPE_NAME=ie,e.Scene=cn,e.SceneDataCollector=$e,e.SceneManager=_n,e.SceneSerializer=jt,e.Serializable=Re,e.SerializationContext=Ut,e.Serialize=ze,e.SerializeArray=function(e,t){Me(e,"__serializeArrayFields").add(String(t))},e.SerializeAsMap=function(){return function(e,t){ze({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},e.SerializeAsSet=function(){return function(e,t){ze({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},e.SerializeMap=function(e,t){Me(e,"__serializeMapFields").add(String(t))},e.SerializeSet=function(e,t){Me(e,"__serializeSetFields").add(String(t))},e.ServiceContainer=Kt,e.SoAStorage=ke,e.SparseSet=_t,e.Stage=function(e){return function(t){return be(t.prototype).stage=e,t}},e.SystemDataCollector=Qe,e.SystemDependencyGraph=tn,e.SystemScheduler=on,e.TYPE_SIZES={boolean:1,int8:1,uint8:1,int16:2,uint16:2,int32:4,uint32:4,float32:4,float64:8,string:-1},e.Time=_,e.Timer=C,e.TypeSafeEventSystem=Pt,e.TypeUtils=Si,e.TypedEntityBuilder=_i,e.TypedQueryBuilder=xt,e.TypedQueryResult=Ot,e.Uint16=function(e,t){Me(e,"__uint16Fields").add(String(t))},e.Uint32=function(e,t){Me(e,"__uint32Fields").add(String(t))},e.Uint8=function(e,t){Me(e,"__uint8Fields").add(String(t))},e.Uint8Clamped=function(e,t){Me(e,"__uint8ClampedFields").add(String(t))},e.Updatable=w,e.ValueSerializer=Ft,e.VersionMigrationManager=Yn,e.WebSocketManager=et,e.WorkerEntitySystem=jn,e.World=yn,e.WorldManager=In,e.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},e.addEntityTag=function(e,t){return e|t},e.buildEntity=function(e){return new _i(e)},e.clearChanges=function(e){var t=ti(e);t&&t.clear()},e.createECSAPI=pn,e.createEditorModeService=function(){return new kn({isEditor:!0,isPlaying:!1,isPreview:!1})},e.createInstance=A,e.createLogger=Z,e.createQuery=function(){return new xt},e.createServiceToken=En,e.createStandaloneModeService=function(){return new kn({isEditor:!1,isPlaying:!0,isPreview:!1})},e.decodeComponent=vi,e.decodeDespawn=yi,e.decodeEntity=gi,e.decodeSignedVarint=function(e,t){var n=ri(e,t),i=n[0],r=n[1];return[si(i),r]},e.decodeSnapshot=function(e,t,n){for(var i=new li(t),r=i.readUint8(),o=i.readVarint(),s=[],a=n||new Map,c=0;c<o;c++){var u=gi(e,i,a);s.push(u)}return{operation:r,entities:s}},e.decodeSpawn=function(t,n,i){var r=new li(n);if(r.readUint8()!==e.SyncOperation.SPAWN)return null;var o=r.readUint32(),s=r.readString(),a=r.readVarint(),c=[],u=t.createEntity("entity_"+o);null==i||i.set(o,u);for(var l=0;l<a;l++){var h=r.readString();c.push(h);var d=ee.getComponentType(h);if(d){var f=d[te];if(f)vi(u.addComponent(new d),f,r)}else{console.warn("Unknown component type: "+h);for(var p=r.readVarint(),m=0;m<p;m++)r.readUint8()}}return{entity:u,prefabType:s,componentTypes:c}},e.decodeVarint=ri,e.encodeComponentDelta=fi,e.encodeComponentFull=di,e.encodeDespawn=function(t){var n=new ci(8);return n.writeUint8(e.SyncOperation.DESPAWN),n.writeUint32(t),n.toUint8Array()},e.encodeDespawnBatch=function(t){var n=new ci(8+4*t.length);n.writeUint8(e.SyncOperation.DESPAWN),n.writeVarint(t.length);for(var i,r=a(t);!(i=r()).done;){var o=i.value;n.writeUint32(o)}return n.toUint8Array()},e.encodeEntity=pi,e.encodeSignedVarint=function(e,t,n){return ii(oi(e),t,n)},e.encodeSnapshot=function(t,n){void 0===n&&(n=e.SyncOperation.FULL);var i=new ci(1024);i.writeUint8(n),i.writeVarint(t.length);for(var r,o=n===e.SyncOperation.DELTA,s=a(t);!(r=s()).done;){pi(r.value,i,o)}return i.toUint8Array()},e.encodeSpawn=function(t,n){var i=new ci(256);i.writeUint8(e.SyncOperation.SPAWN),i.writeUint32(t.id),i.writeString(n||"");for(var r,o=[],s=a(t.components);!(r=s()).done;){var c=r.value,u=c.constructor[te];u&&u.fields.length>0&&o.push({component:c,metadata:u})}i.writeVarint(o.length);for(var l=0,h=o;l<h.length;l++){var d=h[l],f=d.component,p=d.metadata;i.writeString(p.typeId),di(f,p,i)}return i.toUint8Array()},e.encodeVarint=ii,e.genOf=dt,e.generateGUID=ot,e.getBasicWorkerConfig=function(){return Wn.getInstance().getBasicWorkerConfig()},e.getChangeTracker=ti,e.getComponentDependencies=function(e){return e[F]},e.getComponentEditorOptions=U,e.getComponentInstanceEditorOptions=function(e){return U(e.constructor)},e.getComponentInstanceTypeName=W,e.getComponentTypeName=H,e.getComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.map(function(t){return e.getComponent(t)})},e.getCurrentAdapter=function(){return Wn.getInstance().getAdapter()},e.getEntityRefMetadata=ye,e.getEntityRefProperties=function(e){var t=ye(e);return t?Array.from(t.properties):[]},e.getFullPlatformConfig=function(){return Wn.getInstance().getFullPlatformConfig()},e.getGlobalWithMiniGame=bi,e.getOrAddComponent=function(e,t,n){var i=e.getComponent(t);return i||(i=n(),e.addComponent(i)),i},e.getPerformanceWithMemory=function(){return performance},e.getPropertyInjectMetadata=function(e){var t=E.get(e);return(null==t?void 0:t.properties)||new Map},e.getPropertyMetadata=function(e){return Se.get(e)},e.getSceneByEntityId=de,e.getSchedulingMetadata=Te,e.getSerializationMetadata=Ne,e.getSyncMetadata=ei,e.getSystemInstanceMetadata=se,e.getSystemInstanceTypeName=ce,e.getSystemMetadata=oe,e.getSystemTypeName=ae,e.getUpdatableMetadata=P,e.handleEquals=function(e,t){return e===t},e.handleToString=function(e){return 0===e?"Entity(NULL)":"Entity(idx="+ht(e)+", gen="+dt(e)+")"},e.hasAdapter=function(){return Wn.getInstance().hasAdapter()},e.hasAnyComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.some(function(t){return e.hasComponent(t)})},e.hasChanges=function(e){var t=ti(e);return!!t&&t.hasChanges()},e.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.every(function(t){return e.hasComponent(t)})},e.hasECSComponentDecorator=L,e.hasEntityRef=function(e){return null!==ye(e)},e.hasEntityTag=Kn,e.hasPropertyMetadata=function(e){return Se.has(e)},e.hasSchedulingMetadata=function(e){return void 0!==Te(e)},e.hasSyncFields=function(e){var t=ei(e);return null!==t&&t.fields.length>0},e.indexOf=ht,e.initChangeTracker=function(e){var t=ei(e);if(!t)throw new Error("Component does not have sync metadata. Use @sync decorator on fields.");var n=e[ne];return n||(n=new $n,e[ne]=n),n.markAllDirty(t.fields.length),n},e.injectProperties=k,e.isComponentArray=function(e){return e.every(Ei)},e.isComponentHiddenInInspector=G,e.isComponentInstanceHiddenInInspector=function(e){return G(e.constructor)},e.isComponentType=Ei,e.isEntityRefProperty=_e,e.isFolder=function(e){return Kn(e,Xn.FOLDER)},e.isHidden=function(e){return Kn(e,Xn.HIDDEN)},e.isLocked=function(e){return Kn(e,Xn.LOCKED)},e.isSerializable=function(e){return null!==Ne(e)},e.isUpdatable=D,e.isValidGUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)},e.isValidHandle=ft,e.makeHandle=lt,e.processDespawn=function(e,t,n){var i=yi(t);if(!i)return[];for(var r,o=a(i.entityIds);!(r=o()).done;){var s=r.value,c=(null==n?void 0:n.get(s))||e.findEntityById(s);c&&(c.destroy(),null==n||n.delete(s))}return i.entityIds},e.queryFor=function(e){return new xt([e])},e.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new xt(t)},e.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!M(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var i=function(e){return A(t,e)};n?e.registerSingleton(t,i):e.registerTransient(t,i)},e.registerPlatformAdapter=function(e){return Wn.getInstance().registerAdapter(e)},e.removeEntityTag=function(e,t){return e&~t},e.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},e.resetLoggerColors=function(){Y.getInstance().resetColors()},e.setGlobalLogLevel=function(e){Y.getInstance().setGlobalLevel(e)},e.setLoggerColors=function(e){Y.getInstance().setGlobalColors(e)},e.setLoggerFactory=function(e){Y.getInstance().setLoggerFactory(e)},e.supportsFeature=function(e){return Wn.getInstance().supportsFeature(e)},e.sync=function(e){return function(t,n){var i=function(e){var t=e.constructor;if(Object.prototype.hasOwnProperty.call(t,te))return t[te];var n=t[te],i={typeId:H(t),fields:n?[].concat(n.fields):[],fieldIndexMap:n?new Map(n.fieldIndexMap):new Map};return t[te]=i,i}(t),r=i.fields.length,o={index:r,name:n,type:e};i.fields.push(o),i.fieldIndexMap.set(n,r);var s="_sync_"+n;Object.defineProperty(t,n,{get:function(){return this[s]},set:function(e){if(this[s]!==e){this[s]=e;var t=this[ne];t&&t.setDirty(r)}},enumerable:!0,configurable:!0})}},e.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},e.updateComponent=function(e,t,n){var i=e.getComponent(t);return!!i&&(Object.assign(i,n),!0)},e.varintSize=ni,e.zigzagDecode=si,e.zigzagEncode=oi});
4
4
  //# sourceMappingURL=index.umd.js.map