@esengine/ecs-framework 2.1.30 → 2.1.32

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.
Files changed (288) hide show
  1. package/index.cjs +2 -0
  2. package/index.cjs.map +1 -0
  3. package/index.d.ts +6357 -0
  4. package/index.mjs +2 -0
  5. package/index.mjs.map +1 -0
  6. package/index.umd.js +2 -0
  7. package/index.umd.js.map +1 -0
  8. package/package.json +27 -50
  9. package/bin/Core.d.ts +0 -279
  10. package/bin/Core.d.ts.map +0 -1
  11. package/bin/Core.js +0 -400
  12. package/bin/Core.js.map +0 -1
  13. package/bin/ECS/Component.d.ts +0 -120
  14. package/bin/ECS/Component.d.ts.map +0 -1
  15. package/bin/ECS/Component.js +0 -129
  16. package/bin/ECS/Component.js.map +0 -1
  17. package/bin/ECS/Components/IUpdatable.d.ts +0 -22
  18. package/bin/ECS/Components/IUpdatable.d.ts.map +0 -1
  19. package/bin/ECS/Components/IUpdatable.js +0 -17
  20. package/bin/ECS/Components/IUpdatable.js.map +0 -1
  21. package/bin/ECS/Components/SceneComponent.d.ts +0 -40
  22. package/bin/ECS/Components/SceneComponent.d.ts.map +0 -1
  23. package/bin/ECS/Components/SceneComponent.js +0 -57
  24. package/bin/ECS/Components/SceneComponent.js.map +0 -1
  25. package/bin/ECS/Core/ArchetypeSystem.d.ts +0 -100
  26. package/bin/ECS/Core/ArchetypeSystem.d.ts.map +0 -1
  27. package/bin/ECS/Core/ArchetypeSystem.js +0 -193
  28. package/bin/ECS/Core/ArchetypeSystem.js.map +0 -1
  29. package/bin/ECS/Core/ComponentIndex.d.ts +0 -151
  30. package/bin/ECS/Core/ComponentIndex.d.ts.map +0 -1
  31. package/bin/ECS/Core/ComponentIndex.js +0 -405
  32. package/bin/ECS/Core/ComponentIndex.js.map +0 -1
  33. package/bin/ECS/Core/ComponentPool.d.ts +0 -88
  34. package/bin/ECS/Core/ComponentPool.d.ts.map +0 -1
  35. package/bin/ECS/Core/ComponentPool.js +0 -159
  36. package/bin/ECS/Core/ComponentPool.js.map +0 -1
  37. package/bin/ECS/Core/ComponentStorage/ComponentRegistry.d.ts +0 -92
  38. package/bin/ECS/Core/ComponentStorage/ComponentRegistry.d.ts.map +0 -1
  39. package/bin/ECS/Core/ComponentStorage/ComponentRegistry.js +0 -167
  40. package/bin/ECS/Core/ComponentStorage/ComponentRegistry.js.map +0 -1
  41. package/bin/ECS/Core/ComponentStorage.d.ts +0 -233
  42. package/bin/ECS/Core/ComponentStorage.d.ts.map +0 -1
  43. package/bin/ECS/Core/ComponentStorage.js +0 -463
  44. package/bin/ECS/Core/ComponentStorage.js.map +0 -1
  45. package/bin/ECS/Core/DirtyTrackingSystem.d.ts +0 -197
  46. package/bin/ECS/Core/DirtyTrackingSystem.d.ts.map +0 -1
  47. package/bin/ECS/Core/DirtyTrackingSystem.js +0 -297
  48. package/bin/ECS/Core/DirtyTrackingSystem.js.map +0 -1
  49. package/bin/ECS/Core/EntityManager.d.ts +0 -379
  50. package/bin/ECS/Core/EntityManager.d.ts.map +0 -1
  51. package/bin/ECS/Core/EntityManager.js +0 -686
  52. package/bin/ECS/Core/EntityManager.js.map +0 -1
  53. package/bin/ECS/Core/EventBus.d.ts +0 -218
  54. package/bin/ECS/Core/EventBus.d.ts.map +0 -1
  55. package/bin/ECS/Core/EventBus.js +0 -402
  56. package/bin/ECS/Core/EventBus.js.map +0 -1
  57. package/bin/ECS/Core/EventSystem.d.ts +0 -237
  58. package/bin/ECS/Core/EventSystem.d.ts.map +0 -1
  59. package/bin/ECS/Core/EventSystem.js +0 -478
  60. package/bin/ECS/Core/EventSystem.js.map +0 -1
  61. package/bin/ECS/Core/Events/index.d.ts +0 -3
  62. package/bin/ECS/Core/Events/index.d.ts.map +0 -1
  63. package/bin/ECS/Core/Events/index.js +0 -3
  64. package/bin/ECS/Core/Events/index.js.map +0 -1
  65. package/bin/ECS/Core/FluentAPI/ComponentBuilder.d.ts +0 -35
  66. package/bin/ECS/Core/FluentAPI/ComponentBuilder.d.ts.map +0 -1
  67. package/bin/ECS/Core/FluentAPI/ComponentBuilder.js +0 -48
  68. package/bin/ECS/Core/FluentAPI/ComponentBuilder.js.map +0 -1
  69. package/bin/ECS/Core/FluentAPI/ECSFluentAPI.d.ts +0 -135
  70. package/bin/ECS/Core/FluentAPI/ECSFluentAPI.d.ts.map +0 -1
  71. package/bin/ECS/Core/FluentAPI/ECSFluentAPI.js +0 -166
  72. package/bin/ECS/Core/FluentAPI/ECSFluentAPI.js.map +0 -1
  73. package/bin/ECS/Core/FluentAPI/EntityBatchOperator.d.ts +0 -58
  74. package/bin/ECS/Core/FluentAPI/EntityBatchOperator.d.ts.map +0 -1
  75. package/bin/ECS/Core/FluentAPI/EntityBatchOperator.js +0 -85
  76. package/bin/ECS/Core/FluentAPI/EntityBatchOperator.js.map +0 -1
  77. package/bin/ECS/Core/FluentAPI/EntityBuilder.d.ts +0 -110
  78. package/bin/ECS/Core/FluentAPI/EntityBuilder.d.ts.map +0 -1
  79. package/bin/ECS/Core/FluentAPI/EntityBuilder.js +0 -174
  80. package/bin/ECS/Core/FluentAPI/EntityBuilder.js.map +0 -1
  81. package/bin/ECS/Core/FluentAPI/SceneBuilder.d.ts +0 -53
  82. package/bin/ECS/Core/FluentAPI/SceneBuilder.d.ts.map +0 -1
  83. package/bin/ECS/Core/FluentAPI/SceneBuilder.js +0 -79
  84. package/bin/ECS/Core/FluentAPI/SceneBuilder.js.map +0 -1
  85. package/bin/ECS/Core/FluentAPI/index.d.ts +0 -6
  86. package/bin/ECS/Core/FluentAPI/index.d.ts.map +0 -1
  87. package/bin/ECS/Core/FluentAPI/index.js +0 -6
  88. package/bin/ECS/Core/FluentAPI/index.js.map +0 -1
  89. package/bin/ECS/Core/FluentAPI.d.ts +0 -2
  90. package/bin/ECS/Core/FluentAPI.d.ts.map +0 -1
  91. package/bin/ECS/Core/FluentAPI.js +0 -3
  92. package/bin/ECS/Core/FluentAPI.js.map +0 -1
  93. package/bin/ECS/Core/Performance/index.d.ts +0 -4
  94. package/bin/ECS/Core/Performance/index.d.ts.map +0 -1
  95. package/bin/ECS/Core/Performance/index.js +0 -4
  96. package/bin/ECS/Core/Performance/index.js.map +0 -1
  97. package/bin/ECS/Core/Query/index.d.ts +0 -4
  98. package/bin/ECS/Core/Query/index.d.ts.map +0 -1
  99. package/bin/ECS/Core/Query/index.js +0 -4
  100. package/bin/ECS/Core/Query/index.js.map +0 -1
  101. package/bin/ECS/Core/QuerySystem.d.ts +0 -438
  102. package/bin/ECS/Core/QuerySystem.d.ts.map +0 -1
  103. package/bin/ECS/Core/QuerySystem.js +0 -974
  104. package/bin/ECS/Core/QuerySystem.js.map +0 -1
  105. package/bin/ECS/Core/SoAStorage.d.ts +0 -97
  106. package/bin/ECS/Core/SoAStorage.d.ts.map +0 -1
  107. package/bin/ECS/Core/SoAStorage.js +0 -548
  108. package/bin/ECS/Core/SoAStorage.js.map +0 -1
  109. package/bin/ECS/Core/Storage/index.d.ts +0 -4
  110. package/bin/ECS/Core/Storage/index.d.ts.map +0 -1
  111. package/bin/ECS/Core/Storage/index.js +0 -4
  112. package/bin/ECS/Core/Storage/index.js.map +0 -1
  113. package/bin/ECS/CoreEvents.d.ts +0 -131
  114. package/bin/ECS/CoreEvents.d.ts.map +0 -1
  115. package/bin/ECS/CoreEvents.js +0 -163
  116. package/bin/ECS/CoreEvents.js.map +0 -1
  117. package/bin/ECS/Entity.d.ts +0 -455
  118. package/bin/ECS/Entity.d.ts.map +0 -1
  119. package/bin/ECS/Entity.js +0 -837
  120. package/bin/ECS/Entity.js.map +0 -1
  121. package/bin/ECS/Scene.d.ts +0 -225
  122. package/bin/ECS/Scene.d.ts.map +0 -1
  123. package/bin/ECS/Scene.js +0 -325
  124. package/bin/ECS/Scene.js.map +0 -1
  125. package/bin/ECS/Systems/EntitySystem.d.ts +0 -200
  126. package/bin/ECS/Systems/EntitySystem.d.ts.map +0 -1
  127. package/bin/ECS/Systems/EntitySystem.js +0 -431
  128. package/bin/ECS/Systems/EntitySystem.js.map +0 -1
  129. package/bin/ECS/Systems/IntervalSystem.d.ts +0 -33
  130. package/bin/ECS/Systems/IntervalSystem.d.ts.map +0 -1
  131. package/bin/ECS/Systems/IntervalSystem.js +0 -50
  132. package/bin/ECS/Systems/IntervalSystem.js.map +0 -1
  133. package/bin/ECS/Systems/PassiveSystem.d.ts +0 -17
  134. package/bin/ECS/Systems/PassiveSystem.d.ts.map +0 -1
  135. package/bin/ECS/Systems/PassiveSystem.js +0 -19
  136. package/bin/ECS/Systems/PassiveSystem.js.map +0 -1
  137. package/bin/ECS/Systems/ProcessingSystem.d.ts +0 -21
  138. package/bin/ECS/Systems/ProcessingSystem.d.ts.map +0 -1
  139. package/bin/ECS/Systems/ProcessingSystem.js +0 -20
  140. package/bin/ECS/Systems/ProcessingSystem.js.map +0 -1
  141. package/bin/ECS/Systems/index.d.ts +0 -5
  142. package/bin/ECS/Systems/index.d.ts.map +0 -1
  143. package/bin/ECS/Systems/index.js +0 -6
  144. package/bin/ECS/Systems/index.js.map +0 -1
  145. package/bin/ECS/Utils/BigIntCompatibility.d.ts +0 -164
  146. package/bin/ECS/Utils/BigIntCompatibility.d.ts.map +0 -1
  147. package/bin/ECS/Utils/BigIntCompatibility.js +0 -578
  148. package/bin/ECS/Utils/BigIntCompatibility.js.map +0 -1
  149. package/bin/ECS/Utils/Bits.d.ts +0 -163
  150. package/bin/ECS/Utils/Bits.d.ts.map +0 -1
  151. package/bin/ECS/Utils/Bits.js +0 -286
  152. package/bin/ECS/Utils/Bits.js.map +0 -1
  153. package/bin/ECS/Utils/ComponentTypeManager.d.ts +0 -50
  154. package/bin/ECS/Utils/ComponentTypeManager.d.ts.map +0 -1
  155. package/bin/ECS/Utils/ComponentTypeManager.js +0 -84
  156. package/bin/ECS/Utils/ComponentTypeManager.js.map +0 -1
  157. package/bin/ECS/Utils/EntityList.d.ts +0 -108
  158. package/bin/ECS/Utils/EntityList.d.ts.map +0 -1
  159. package/bin/ECS/Utils/EntityList.js +0 -262
  160. package/bin/ECS/Utils/EntityList.js.map +0 -1
  161. package/bin/ECS/Utils/EntityProcessorList.d.ts +0 -56
  162. package/bin/ECS/Utils/EntityProcessorList.d.ts.map +0 -1
  163. package/bin/ECS/Utils/EntityProcessorList.js +0 -102
  164. package/bin/ECS/Utils/EntityProcessorList.js.map +0 -1
  165. package/bin/ECS/Utils/IdentifierPool.d.ts +0 -203
  166. package/bin/ECS/Utils/IdentifierPool.d.ts.map +0 -1
  167. package/bin/ECS/Utils/IdentifierPool.js +0 -325
  168. package/bin/ECS/Utils/IdentifierPool.js.map +0 -1
  169. package/bin/ECS/Utils/Matcher.d.ts +0 -143
  170. package/bin/ECS/Utils/Matcher.d.ts.map +0 -1
  171. package/bin/ECS/Utils/Matcher.js +0 -249
  172. package/bin/ECS/Utils/Matcher.js.map +0 -1
  173. package/bin/ECS/Utils/index.d.ts +0 -8
  174. package/bin/ECS/Utils/index.d.ts.map +0 -1
  175. package/bin/ECS/Utils/index.js +0 -9
  176. package/bin/ECS/Utils/index.js.map +0 -1
  177. package/bin/ECS/index.d.ts +0 -12
  178. package/bin/ECS/index.d.ts.map +0 -1
  179. package/bin/ECS/index.js +0 -12
  180. package/bin/ECS/index.js.map +0 -1
  181. package/bin/Types/index.d.ts +0 -471
  182. package/bin/Types/index.d.ts.map +0 -1
  183. package/bin/Types/index.js +0 -5
  184. package/bin/Types/index.js.map +0 -1
  185. package/bin/Utils/Debug/ComponentDataCollector.d.ts +0 -28
  186. package/bin/Utils/Debug/ComponentDataCollector.d.ts.map +0 -1
  187. package/bin/Utils/Debug/ComponentDataCollector.js +0 -248
  188. package/bin/Utils/Debug/ComponentDataCollector.js.map +0 -1
  189. package/bin/Utils/Debug/DebugDataFormatter.d.ts +0 -22
  190. package/bin/Utils/Debug/DebugDataFormatter.d.ts.map +0 -1
  191. package/bin/Utils/Debug/DebugDataFormatter.js +0 -117
  192. package/bin/Utils/Debug/DebugDataFormatter.js.map +0 -1
  193. package/bin/Utils/Debug/DebugManager.d.ts +0 -104
  194. package/bin/Utils/Debug/DebugManager.d.ts.map +0 -1
  195. package/bin/Utils/Debug/DebugManager.js +0 -647
  196. package/bin/Utils/Debug/DebugManager.js.map +0 -1
  197. package/bin/Utils/Debug/EntityDataCollector.d.ts +0 -92
  198. package/bin/Utils/Debug/EntityDataCollector.d.ts.map +0 -1
  199. package/bin/Utils/Debug/EntityDataCollector.js +0 -864
  200. package/bin/Utils/Debug/EntityDataCollector.js.map +0 -1
  201. package/bin/Utils/Debug/PerformanceDataCollector.d.ts +0 -32
  202. package/bin/Utils/Debug/PerformanceDataCollector.d.ts.map +0 -1
  203. package/bin/Utils/Debug/PerformanceDataCollector.js +0 -217
  204. package/bin/Utils/Debug/PerformanceDataCollector.js.map +0 -1
  205. package/bin/Utils/Debug/SceneDataCollector.d.ts +0 -16
  206. package/bin/Utils/Debug/SceneDataCollector.d.ts.map +0 -1
  207. package/bin/Utils/Debug/SceneDataCollector.js +0 -46
  208. package/bin/Utils/Debug/SceneDataCollector.js.map +0 -1
  209. package/bin/Utils/Debug/SystemDataCollector.d.ts +0 -11
  210. package/bin/Utils/Debug/SystemDataCollector.d.ts.map +0 -1
  211. package/bin/Utils/Debug/SystemDataCollector.js +0 -59
  212. package/bin/Utils/Debug/SystemDataCollector.js.map +0 -1
  213. package/bin/Utils/Debug/WebSocketManager.d.ts +0 -59
  214. package/bin/Utils/Debug/WebSocketManager.d.ts.map +0 -1
  215. package/bin/Utils/Debug/WebSocketManager.js +0 -148
  216. package/bin/Utils/Debug/WebSocketManager.js.map +0 -1
  217. package/bin/Utils/Debug/index.d.ts +0 -8
  218. package/bin/Utils/Debug/index.d.ts.map +0 -1
  219. package/bin/Utils/Debug/index.js +0 -8
  220. package/bin/Utils/Debug/index.js.map +0 -1
  221. package/bin/Utils/Emitter.d.ts +0 -43
  222. package/bin/Utils/Emitter.d.ts.map +0 -1
  223. package/bin/Utils/Emitter.js +0 -69
  224. package/bin/Utils/Emitter.js.map +0 -1
  225. package/bin/Utils/Extensions/NumberExtension.d.ts +0 -13
  226. package/bin/Utils/Extensions/NumberExtension.d.ts.map +0 -1
  227. package/bin/Utils/Extensions/NumberExtension.js +0 -17
  228. package/bin/Utils/Extensions/NumberExtension.js.map +0 -1
  229. package/bin/Utils/Extensions/TypeUtils.d.ts +0 -13
  230. package/bin/Utils/Extensions/TypeUtils.d.ts.map +0 -1
  231. package/bin/Utils/Extensions/TypeUtils.js +0 -15
  232. package/bin/Utils/Extensions/TypeUtils.js.map +0 -1
  233. package/bin/Utils/Extensions/index.d.ts +0 -3
  234. package/bin/Utils/Extensions/index.d.ts.map +0 -1
  235. package/bin/Utils/Extensions/index.js +0 -4
  236. package/bin/Utils/Extensions/index.js.map +0 -1
  237. package/bin/Utils/GlobalManager.d.ts +0 -32
  238. package/bin/Utils/GlobalManager.d.ts.map +0 -1
  239. package/bin/Utils/GlobalManager.js +0 -53
  240. package/bin/Utils/GlobalManager.js.map +0 -1
  241. package/bin/Utils/Logger.d.ts +0 -156
  242. package/bin/Utils/Logger.d.ts.map +0 -1
  243. package/bin/Utils/Logger.js +0 -256
  244. package/bin/Utils/Logger.js.map +0 -1
  245. package/bin/Utils/PerformanceMonitor.d.ts +0 -211
  246. package/bin/Utils/PerformanceMonitor.d.ts.map +0 -1
  247. package/bin/Utils/PerformanceMonitor.js +0 -270
  248. package/bin/Utils/PerformanceMonitor.js.map +0 -1
  249. package/bin/Utils/Pool/IPoolable.d.ts +0 -29
  250. package/bin/Utils/Pool/IPoolable.d.ts.map +0 -1
  251. package/bin/Utils/Pool/IPoolable.js +0 -2
  252. package/bin/Utils/Pool/IPoolable.js.map +0 -1
  253. package/bin/Utils/Pool/Pool.d.ts +0 -109
  254. package/bin/Utils/Pool/Pool.d.ts.map +0 -1
  255. package/bin/Utils/Pool/Pool.js +0 -238
  256. package/bin/Utils/Pool/Pool.js.map +0 -1
  257. package/bin/Utils/Pool/PoolManager.d.ts +0 -91
  258. package/bin/Utils/Pool/PoolManager.d.ts.map +0 -1
  259. package/bin/Utils/Pool/PoolManager.js +0 -197
  260. package/bin/Utils/Pool/PoolManager.js.map +0 -1
  261. package/bin/Utils/Pool/index.d.ts +0 -4
  262. package/bin/Utils/Pool/index.d.ts.map +0 -1
  263. package/bin/Utils/Pool/index.js +0 -4
  264. package/bin/Utils/Pool/index.js.map +0 -1
  265. package/bin/Utils/Time.d.ts +0 -47
  266. package/bin/Utils/Time.d.ts.map +0 -1
  267. package/bin/Utils/Time.js +0 -64
  268. package/bin/Utils/Time.js.map +0 -1
  269. package/bin/Utils/Timers/ITimer.d.ts +0 -16
  270. package/bin/Utils/Timers/ITimer.d.ts.map +0 -1
  271. package/bin/Utils/Timers/ITimer.js +0 -2
  272. package/bin/Utils/Timers/ITimer.js.map +0 -1
  273. package/bin/Utils/Timers/Timer.d.ts +0 -30
  274. package/bin/Utils/Timers/Timer.d.ts.map +0 -1
  275. package/bin/Utils/Timers/Timer.js +0 -58
  276. package/bin/Utils/Timers/Timer.js.map +0 -1
  277. package/bin/Utils/Timers/TimerManager.d.ts +0 -19
  278. package/bin/Utils/Timers/TimerManager.d.ts.map +0 -1
  279. package/bin/Utils/Timers/TimerManager.js +0 -33
  280. package/bin/Utils/Timers/TimerManager.js.map +0 -1
  281. package/bin/Utils/index.d.ts +0 -9
  282. package/bin/Utils/index.d.ts.map +0 -1
  283. package/bin/Utils/index.js +0 -9
  284. package/bin/Utils/index.js.map +0 -1
  285. package/bin/index.d.ts +0 -16
  286. package/bin/index.d.ts.map +0 -1
  287. package/bin/index.js +0 -19
  288. package/bin/index.js.map +0 -1
package/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ class GlobalManager{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(t){this.setEnabled(t)}setEnabled(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}}class Time{static update(t){this.unscaledDeltaTime=t,this.deltaTime=t*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++}static sceneChanged(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0}static checkEvery(t,e){return this.totalTime-e>=t}}Time.deltaTime=0,Time.unscaledDeltaTime=0,Time.totalTime=0,Time.unscaledTotalTime=0,Time.timeScale=1,Time.frameCount=0;class Timer{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}get isDone(){return this._isDone}get elapsedTime(){return this._elapsedTime}reset(){this._elapsedTime=0}stop(){this._isDone=!0}tick(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=Time.deltaTime,this._isDone}initialize(t,e,n,s){this._timeInSeconds=t,this._repeats=e,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}class TimerManager extends GlobalManager{constructor(){super(...arguments),this._timers=[]}update(){for(let t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))}schedule(t,e,n,s){let i=new Timer;return i.initialize(t,e,n,s),this._timers.push(i),i}}var PerformanceWarningType,LogLevel;!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(PerformanceWarningType||(PerformanceWarningType={}));class PerformanceMonitor{static get instance(){return PerformanceMonitor._instance||(PerformanceMonitor._instance=new PerformanceMonitor),PerformanceMonitor._instance}constructor(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(t){return this._isEnabled?performance.now():0}endMonitoring(t,e,n=0){if(!this._isEnabled||0===e)return;const s=performance.now(),i=s-e,o={name:t,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let n=this._systemStats.get(t);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,n)),n.totalTime+=e,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,e),n.maxTime=Math.max(n.maxTime,e),n.recentTimes.push(e),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,n=t.recentTimes.reduce(((t,n)=>t+Math.pow(n-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(n);const s=[...t.recentTimes].sort(((t,e)=>t-e)),i=s.length;t.percentile95=s[Math.floor(.95*i)]||0,t.percentile99=s[Math.floor(.99*i)]||0}getSystemData(t){return this._systemData.get(t)}getSystemStats(t){return this._systemStats.get(t)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const t=[];t.push("=== ECS Performance Report ==="),t.push("");const e=Array.from(this._systemStats.entries()).sort(((t,e)=>e[1].averageTime-t[1].averageTime));for(const[n,s]of e){const e=this._systemData.get(n);t.push(`System: ${n}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${s.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),t.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const n=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${n.toFixed(2)}ms`),t.push(`Systems Count: ${this._systemData.size}`),t.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(t){this._systemData.delete(t),this._systemStats.delete(t)}getPerformanceWarnings(t=16.67){const e=[];for(const[n,s]of this._systemData.entries())s.executionTime>t&&e.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${t}ms)`);return e}setMaxRecentSamples(t){this._maxRecentSamples=t;for(const e of this._systemStats.values())for(;e.recentTimes.length>t;)e.recentTimes.shift()}}class Pool{constructor(t,e=100,n=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=n,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,n=1024){let s=this._pools.get(t);return s||(s=new Pool((()=>new t),e,n),this._pools.set(t,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(t){t&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const t of this._objects)t.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(t){const e=t??Math.floor(this._objects.length/2);for(;this._objects.length>e;){const t=this._objects.pop();t&&(t.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(t){const e=Math.min(t,this._maxSize-this._objects.length);for(let t=0;t<e;t++){const t=this._createFn();t.reset(),this._objects.push(t),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(t){this._maxSize=t,this._stats.maxSize=t,this._objects.length>t&&this.compact(t)}getAvailableCount(){return this._objects.length}isEmpty(){return 0===this._objects.length}isFull(){return this._objects.length>=this._maxSize}static getAllPoolTypes(){return Array.from(this._pools.keys())}static getAllPoolStats(){const t={};for(const[e,n]of this._pools){t[e.name||e.toString()]=n.getStats()}return t}static compactAllPools(){for(const t of this._pools.values())t.compact()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getGlobalStatsString(){const t=this.getAllPoolStats(),e=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(t).length)return e.push("No pools registered"),e.join("\n");for(const[n,s]of Object.entries(t))e.push(`${n}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Total Created: ${s.totalCreated}`),e.push(` Total Obtained: ${s.totalObtained}`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}Pool._pools=new Map;class PoolManager{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return PoolManager.instance||(PoolManager.instance=new PoolManager),PoolManager.instance}registerPool(t,e){this.pools.set(t,e)}getPool(t){return this.pools.get(t)||null}update(){const t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)}createPool(t,e,n=100,s=1024){let i=this.pools.get(t);return i||(i=new Pool(e,n,s),this.pools.set(t,i)),i}removePool(t){const e=this.pools.get(t);return!!e&&(e.clear(),this.pools.delete(t),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const t of this.pools.values())t.compact()}clearAllPools(){for(const t of this.pools.values())t.clear()}getAllStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,n.getStats());return t}getGlobalStats(){let t=0,e=0,n=0,s=0,i=0,o=0;for(const r of this.pools.values()){const a=r.getStats();t+=a.size,e+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,o+=a.estimatedMemoryUsage}return{size:t,maxSize:e,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:o}}getStatsString(){const t=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return t.push("No pools registered"),t.join("\n");const e=this.getGlobalStats();t.push(`Total Pools: ${this.pools.size}`),t.push(`Global Hit Rate: ${(100*e.hitRate).toFixed(1)}%`),t.push(`Global Memory Usage: ${(e.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");for(const[e,n]of this.pools){const s=n.getStats();t.push(`${e}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("")}return t.join("\n")}setAutoCompactInterval(t){this.autoCompactInterval=t}prewarmAllPools(){for(const t of this.pools.values()){const e=t.getStats(),n=Math.floor(.2*e.maxSize);t.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}}class NativeBigInt{constructor(t){this.value=t}valueOf(){return Number(this.value)}toString(t){if(void 0!==t&&10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");const e=this.value.toString(t);return 16===t?e.toUpperCase():e}and(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value&e)}or(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value|e)}xor(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value^e)}not(t=64){const e=(BigInt(1)<<BigInt(t))-BigInt(1);return new NativeBigInt(~this.value&e)}shiftLeft(t){return new NativeBigInt(this.value<<BigInt(t))}shiftRight(t){return new NativeBigInt(this.value>>BigInt(t))}equals(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return this.value===e}isZero(){return this.value===BigInt(0)}clone(){return new NativeBigInt(this.value)}}class ArrayBigInt{constructor(t=0){this.chunks=[],"number"==typeof t?this.fromNumber(t):"string"==typeof t?this.fromString(t):this.chunks=t.slice(),this.normalize()}fromNumber(t){if(this.chunks=[],t<0&&(t=Math.abs(t)),0!==t)for(;t>0;)this.chunks.push(t&ArrayBigInt.CHUNK_MASK),t=Math.floor(t/ArrayBigInt.CHUNK_MAX);else this.chunks=[0]}fromString(t){(t=t.trim()).startsWith("0x")||t.startsWith("0X")?this.fromHexString(t.substring(2)):t.startsWith("0b")||t.startsWith("0B")?this.fromBinaryString(t.substring(2)):this.fromDecimalString(t)}fromHexString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=8){const n=Math.max(0,e-7),s=parseInt(t.substring(n,e+1),16);this.chunks.push(s)}this.normalize()}fromBinaryString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=32){const n=Math.max(0,e-31),s=parseInt(t.substring(n,e+1),2);this.chunks.push(s)}this.normalize()}fromDecimalString(t){const e=parseInt(t,10);this.fromNumber(e)}normalize(){for(;this.chunks.length>1&&0===this.chunks[this.chunks.length-1];)this.chunks.pop();0===this.chunks.length&&(this.chunks=[0])}valueOf(){let t=0,e=1;for(const n of this.chunks)if(t+=n*e,e*=ArrayBigInt.CHUNK_MAX,e>Number.MAX_SAFE_INTEGER)break;return t}toString(t=10){if(10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");if(this.isZero())return"0";if(10===t)return this.valueOf().toString(10);if(16===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(16);t+=e===this.chunks.length-1?n:n.padStart(8,"0")}return t.toUpperCase()}if(2===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(2);t+=e===this.chunks.length-1?n:n.padStart(32,"0")}return t}return this.valueOf().toString(t)}and(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n&i)}return new ArrayBigInt(s)}or(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n|i)}return new ArrayBigInt(s)}xor(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n^i)}return new ArrayBigInt(s)}not(t=64){const e=Math.ceil(t/ArrayBigInt.CHUNK_SIZE),n=[];for(let s=0;s<e;s++){const i=s<this.chunks.length?this.chunks[s]:0;if(s===e-1){const e=t%ArrayBigInt.CHUNK_SIZE;if(e>0){const t=(1<<e)-1;n.push(~i&t)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}return new ArrayBigInt(n)}shiftLeft(t){if(0===t)return this.clone();if(t<0)return this.shiftRight(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE,s=new Array(e).fill(0);if(0===n)s.push(...this.chunks);else{let t=0;for(const e of this.chunks){const i=e<<n|t;s.push(i&ArrayBigInt.CHUNK_MASK),t=e>>>ArrayBigInt.CHUNK_SIZE-n}t>0&&s.push(t)}return new ArrayBigInt(s)}shiftRight(t){if(0===t)return this.clone();if(t<0)return this.shiftLeft(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE;if(e>=this.chunks.length)return new ArrayBigInt(0);const s=[];if(0===n)for(let t=e;t<this.chunks.length;t++)s.push(this.chunks[t]);else{let t=0;for(let i=this.chunks.length-1;i>=e;i--){const e=this.chunks[i],o=t<<ArrayBigInt.CHUNK_SIZE-n|e>>>n;s.unshift(o),t=e&(1<<n)-1}}return new ArrayBigInt(s.length>0?s:[0])}equals(t){if(!(t instanceof ArrayBigInt))return!1;if(this.chunks.length!==t.chunks.length)return!1;for(let e=0;e<this.chunks.length;e++)if(this.chunks[e]!==t.chunks[e])return!1;return!0}isZero(){return 1===this.chunks.length&&0===this.chunks[0]}clone(){return new ArrayBigInt(this.chunks.slice())}}ArrayBigInt.CHUNK_SIZE=32,ArrayBigInt.CHUNK_MASK=4294967295,ArrayBigInt.CHUNK_MAX=4294967296;class BigIntFactory{static isNativeSupported(){return null===this._supportsBigInt&&(this._supportsBigInt=this.detectBigIntSupport()),this._supportsBigInt}static detectBigIntSupport(){try{if("undefined"==typeof BigInt)return!1;const test1=BigInt(1),test2=BigInt(2),result=test1|test2,literal=eval("1n");if("bigint"!=typeof result||"bigint"!=typeof literal)return!1;const shifted=test1<<BigInt(1),compared=test1===BigInt(1);return"bigint"==typeof shifted&&!0===compared}catch(t){return!1}}static create(t=0){if(this.isNativeSupported()){let e;return e="bigint"==typeof t?t:BigInt(t),new NativeBigInt(e)}{let e;return e="bigint"==typeof t?t.toString():t,new ArrayBigInt(e)}}static zero(){return this._cachedZero||(this._cachedZero=this.create(0)),this._cachedZero}static one(){return this._cachedOne||(this._cachedOne=this.create(1)),this._cachedOne}static fromBinaryString(t){if(this.isNativeSupported()){const e=BigInt("0b"+t);return new NativeBigInt(e)}return new ArrayBigInt("0b"+t)}static fromHexString(t){if(this.isNativeSupported()){const e=t.replace(/^0x/i,""),n=BigInt("0x"+e);return new NativeBigInt(n)}return new ArrayBigInt(t)}static getEnvironmentInfo(){return{supportsBigInt:this.isNativeSupported(),environment:this.detectEnvironment(),jsEngine:this.detectJSEngine()}}static detectEnvironment(){if("undefined"!=typeof window){if("undefined"!=typeof navigator){const t=navigator.userAgent;if(t.includes("Chrome")){const e=t.match(/Chrome\/(\d+)/);return`Chrome ${e?parseInt(e[1]):0}`}if(t.includes("Firefox")){const e=t.match(/Firefox\/(\d+)/);return`Firefox ${e?parseInt(e[1]):0}`}if(t.includes("Safari")&&!t.includes("Chrome")){const e=t.match(/Version\/(\d+)/);return`Safari ${e?parseInt(e[1]):0}`}return"Browser (Unknown)"}return"Browser"}return"undefined"!=typeof global?"undefined"!=typeof process&&process.version?`Node.js ${process.version}`:"Node.js":void 0!==globalThis.wx?"WeChat MiniProgram":void 0!==globalThis.cc?"Cocos Creator":void 0!==globalThis.Laya?"Laya Engine":"Unknown"}static detectJSEngine(){try{return"undefined"!=typeof process&&process.versions&&process.versions.v8?`V8 ${process.versions.v8}`:void 0!==globalThis.Components?"SpiderMonkey":"undefined"!=typeof window&&void 0!==window.safari?"JavaScriptCore":"Unknown"}catch{return"Unknown"}}}BigIntFactory._supportsBigInt=null,BigIntFactory._cachedZero=null,BigIntFactory._cachedOne=null,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal",t[t.None=5]="None"}(LogLevel||(LogLevel={}));class ConsoleLogger{constructor(t={}){this._config={level:LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...t}}debug(t,...e){this.log(LogLevel.Debug,t,...e)}info(t,...e){this.log(LogLevel.Info,t,...e)}warn(t,...e){this.log(LogLevel.Warn,t,...e)}error(t,...e){this.log(LogLevel.Error,t,...e)}fatal(t,...e){this.log(LogLevel.Fatal,t,...e)}setLevel(t){this._config.level=t}setPrefix(t){this._config.prefix=t}log(t,e,...n){if(t<this._config.level)return;let s=e;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${LogLevel[t].toUpperCase()}] ${s}`,this._config.output?this._config.output(t,s):this.outputToConsole(t,s,...n)}outputToConsole(t,e,...n){const s=this._config.enableColors?this.getColors():null;switch(t){case LogLevel.Debug:s?console.debug(`${s.gray}${e}${s.reset}`,...n):console.debug(e,...n);break;case LogLevel.Info:s?console.info(`${s.blue}${e}${s.reset}`,...n):console.info(e,...n);break;case LogLevel.Warn:s?console.warn(`${s.yellow}${e}${s.reset}`,...n):console.warn(e,...n);break;case LogLevel.Error:case LogLevel.Fatal:s?console.error(`${s.red}${e}${s.reset}`,...n):console.error(e,...n)}}getColors(){return{reset:"",red:"",yellow:"",blue:"",gray:""}}}class LoggerManager{constructor(){this._loggers=new Map,this._defaultLogger=new ConsoleLogger}static getInstance(){return LoggerManager._instance||(LoggerManager._instance=new LoggerManager),LoggerManager._instance}getLogger(t){if(!t)return this._defaultLogger;if(!this._loggers.has(t)){const e=new ConsoleLogger({prefix:t,level:LogLevel.Info});this._loggers.set(t,e)}return this._loggers.get(t)}setLogger(t,e){this._loggers.set(t,e)}setGlobalLevel(t){this._defaultLogger instanceof ConsoleLogger&&this._defaultLogger.setLevel(t);for(const e of this._loggers.values())e instanceof ConsoleLogger&&e.setLevel(t)}createChildLogger(t,e){const n=`${t}.${e}`;return this.getLogger(n)}}const Logger=LoggerManager.getInstance().getLogger();function createLogger(t){return LoggerManager.getInstance().getLogger(t)}function setGlobalLogLevel(t){LoggerManager.getInstance().setGlobalLevel(t)}function EnableSoA(t){return t.__enableSoA=!0,t}function HighPrecision(t,e){const n=String(e);t.constructor.__highPrecisionFields||(t.constructor.__highPrecisionFields=new Set),t.constructor.__highPrecisionFields.add(n)}function Float64(t,e){const n=String(e);t.constructor.__float64Fields||(t.constructor.__float64Fields=new Set),t.constructor.__float64Fields.add(n)}function Float32(t,e){const n=String(e);t.constructor.__float32Fields||(t.constructor.__float32Fields=new Set),t.constructor.__float32Fields.add(n)}function Int32(t,e){const n=String(e);t.constructor.__int32Fields||(t.constructor.__int32Fields=new Set),t.constructor.__int32Fields.add(n)}function SerializeMap(t,e){const n=String(e);t.constructor.__serializeMapFields||(t.constructor.__serializeMapFields=new Set),t.constructor.__serializeMapFields.add(n)}class SoAStorage{constructor(t){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=t,this.initializeFields(t)}initializeFields(t){const e=new t,n=t.__highPrecisionFields||new Set,s=t.__float64Fields||new Set,i=t.__float32Fields||new Set,o=t.__int32Fields||new Set,r=t.__serializeMapFields||new Set,a=t.__serializeSetFields||new Set,c=t.__serializeArrayFields||new Set;for(const t in e)if(e.hasOwnProperty(t)&&"id"!==t){const h=e[t],l=typeof h;"number"===l?n.has(t)||(s.has(t)?this.fields.set(t,new Float64Array(this._capacity)):o.has(t)?this.fields.set(t,new Int32Array(this._capacity)):(i.has(t),this.fields.set(t,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(t,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(t,new Array(this._capacity)):"object"===l&&null!==h&&(r.has(t)||a.has(t)||c.has(t))&&this.serializedFields.set(t,new Array(this._capacity))}}addComponent(t,e){if(this.entityToIndex.has(t)){const n=this.entityToIndex.get(t);return void this.updateComponentAtIndex(n,e)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(t,n),this.indexToEntity[n]=t,this.updateComponentAtIndex(n,e),this._size++}updateComponentAtIndex(t,e){const n=this.indexToEntity[t],s=new Map,i=this.type.__highPrecisionFields||new Set,o=this.type.__serializeMapFields||new Set,r=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(const n in e)if(e.hasOwnProperty(n)&&"id"!==n){const h=e[n],l=typeof h;if("number"===l)if(i.has(n)||!this.fields.has(n))s.set(n,h);else{this.fields.get(n)[t]=h}else if("boolean"===l&&this.fields.has(n)){this.fields.get(n)[t]=h?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[t]=String(h)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[t]=this.serializeValue(h,n,o,r,a)}else c.has(n)?s.set(n,this.deepClone(h)):s.set(n,h)}s.size>0&&this.complexFields.set(n,s)}serializeValue(t,e,n,s,i){try{return n.has(e)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):s.has(e)&&t instanceof Set?JSON.stringify(Array.from(t)):(i.has(e)&&Array.isArray(t),JSON.stringify(t))}catch(t){return SoAStorage._logger.warn(`SoA序列化字段 ${e} 失败:`,t),"{}"}}deserializeValue(t,e,n,s,i){try{const o=JSON.parse(t);return n.has(e)?new Map(o):s.has(e)?new Set(o):(i.has(e),o)}catch(t){return SoAStorage._logger.warn(`SoA反序列化字段 ${e} 失败:`,t),null}}deepClone(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((t=>this.deepClone(t)));if(t instanceof Map){const e=new Map;for(const[n,s]of t.entries())e.set(n,this.deepClone(s));return e}if(t instanceof Set){const e=new Set;for(const n of t.values())e.add(this.deepClone(n));return e}const e={};for(const n in t)t.hasOwnProperty(n)&&(e[n]=this.deepClone(t[n]));return e}getComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=new this.type,s=this.type.__serializeMapFields||new Set,i=this.type.__serializeSetFields||new Set,o=this.type.__serializeArrayFields||new Set;for(const[t,s]of this.fields.entries()){const i=s[e],o=this.getFieldType(t);n[t]="boolean"===o?1===i:i}for(const[t,s]of this.stringFields.entries())n[t]=s[e];for(const[t,r]of this.serializedFields.entries()){const a=r[e];a&&(n[t]=this.deserializeValue(a,t,s,i,o))}const r=this.complexFields.get(t);if(r)for(const[t,e]of r.entries())n[t]=e;return n}getFieldType(t){return typeof(new this.type)[t]}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.getComponent(t);return this.complexFields.delete(t),this.entityToIndex.delete(t),this.freeIndices.push(e),this._size--,n}resize(t){for(const[e,n]of this.fields.entries()){let s;s=n instanceof Float32Array?new Float32Array(t):n instanceof Float64Array?new Float64Array(t):new Int32Array(t),s.set(n),this.fields.set(e,s)}for(const[e,n]of this.stringFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.stringFields.set(e,s)}for(const[e,n]of this.serializedFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.serializedFields.set(e,s)}this._capacity=t}getActiveIndices(){return Array.from(this.entityToIndex.values())}getFieldArray(t){return this.fields.get(t)||null}size(){return this._size}clear(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(const t of this.fields.values())t.fill(0);for(const t of this.stringFields.values())for(let e=0;e<t.length;e++)t[e]=void 0;for(const t of this.serializedFields.values())for(let e=0;e<t.length;e++)t[e]=void 0}compact(){if(0===this.freeIndices.length)return;const t=Array.from(this.entityToIndex.entries()).sort(((t,e)=>t[1]-e[1])),e=new Map,n=[];for(let s=0;s<t.length;s++){const[i,o]=t[s];if(e.set(i,s),n[s]=i,s!==o){for(const[,t]of this.fields.entries())t[s]=t[o];for(const[,t]of this.stringFields.entries())t[s]=t[o];for(const[,t]of this.serializedFields.entries())t[s]=t[o]}}this.entityToIndex=e,this.indexToEntity=n,this.freeIndices=[],this._size=t.length}getStats(){let t=0;const e=new Map;for(const[n,s]of this.fields.entries()){let i,o;s instanceof Float32Array?(i=4,o="float32"):s instanceof Float64Array?(i=8,o="float64"):(i=4,o="int32");const r=s.length*i;t+=r,e.set(n,{size:this._size,capacity:s.length,type:o,memory:r})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:t,fieldStats:e}}performVectorizedOperation(t){const e=this.getActiveIndices();t(this.fields,e)}}SoAStorage._logger=createLogger("SoAStorage");class ComponentRegistry{static register(t){if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentTypes.set(t,e),this.componentNameToType.set(t.name,t),this.componentNameToId.set(t.name,e),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return BigIntFactory.one().shiftLeft(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getComponentType(t){return this.componentNameToType.get(t)||null}static getAllRegisteredTypes(){return new Map(this.componentTypes)}static getAllComponentNames(){return new Map(this.componentNameToType)}static getComponentId(t){return this.componentNameToId.get(t)}static registerComponentByName(t){if(this.componentNameToId.has(t))return this.componentNameToId.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentNameToId.set(t,e),e}static createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const n=this.getComponentId(t);if(void 0===n)throw new Error(`Component type ${t} is not registered`);const s=BigIntFactory.one().shiftLeft(n);return this.maskCache.set(e,s),s}static createComponentMask(t){const e=`multi:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let n=BigIntFactory.zero();for(const e of t){const t=this.getComponentId(e);void 0!==t&&(n=n.or(BigIntFactory.one().shiftLeft(t)))}return this.maskCache.set(e,n),n}static clearMaskCache(){this.maskCache.clear()}static reset(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0}}ComponentRegistry._logger=createLogger("ComponentStorage"),ComponentRegistry.componentTypes=new Map,ComponentRegistry.componentNameToType=new Map,ComponentRegistry.componentNameToId=new Map,ComponentRegistry.maskCache=new Map,ComponentRegistry.nextBitIndex=0,ComponentRegistry.maxComponents=64;class ComponentStorage{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,ComponentRegistry.isRegistered(t)||ComponentRegistry.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${this.componentType.name}`);let n;this.freeIndices.length>0?(n=this.freeIndices.pop(),this.components[n]=e,this.indexToEntity[n]=t):(n=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,n),this._size++}getComponent(t){const e=this.entityToIndex.get(t);return void 0!==e?this.components[e]:null}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,n}forEach(t){for(let e=0;e<this.components.length;e++){const n=this.components[e];n&&t(n,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let n=0;n<this.components.length;n++){const s=this.components[n];s&&(t.push(s),e.push(this.indexToEntity[n]))}return{components:t,entityIds:e}}clear(){this.components.length=0,this.entityToIndex.clear(),this.indexToEntity.length=0,this.freeIndices.length=0,this._size=0}get size(){return this._size}get type(){return this.componentType}compact(){if(0===this.freeIndices.length)return;const t=[],e=[],n=new Map;let s=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[s]=o,e[s]=this.indexToEntity[i],n.set(this.indexToEntity[i],s),s++)}this.components=t,this.indexToEntity=e,this.entityToIndex=n,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,n=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:n,fragmentation:t>0?n/t:0}}}class ComponentStorageManager{constructor(){this.storages=new Map}getStorage(t){let e=this.storages.get(t);if(!e){t.__enableSoA?(e=new SoAStorage(t),ComponentStorageManager._logger.info(`为 ${t.name} 启用SoA优化(适用于大规模批量操作)`)):e=new ComponentStorage(t),this.storages.set(t,e)}return e}addComponent(t,e){const n=e.constructor;this.getStorage(n).addComponent(t,e)}getComponent(t,e){const n=this.storages.get(e);return n?n.getComponent(t):null}hasComponent(t,e){const n=this.storages.get(e);return!!n&&n.hasComponent(t)}removeComponent(t,e){const n=this.storages.get(e);return n?n.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigIntFactory.zero();for(const[n,s]of this.storages.entries())if(s.hasComponent(t)){const t=ComponentRegistry.getBitMask(n);e=e.or(t)}return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,n]of this.storages.entries()){const s=e.name||"Unknown";t.set(s,n.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}ComponentStorageManager._logger=createLogger("ComponentStorage");class EntityComparer{compare(t,e){let n=t.updateOrder-e.updateOrder;return 0==n&&(n=t.id-e.id),n}}class Entity{constructor(t,e){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=BigIntFactory.zero(),this._componentTypeToIndex=new Map,this.name=t,this.id=e}get isDestroyed(){return this._isDestroyed}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(t){this._active!==t&&(this._active=t,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(t){this._tag=t}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}get componentMask(){return this._componentMask}createComponent(t,...e){const n=new t(...e);return this.addComponent(n)}addComponentInternal(t){const e=t.constructor;ComponentRegistry.isRegistered(e)||ComponentRegistry.register(e),t.entity=this;const n=this.components.length;this.components.push(t),this._componentTypeToIndex.set(e,n);const s=ComponentRegistry.getBitMask(e);return this._componentMask=this._componentMask.or(s),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${e.name}`);return this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),Entity.eventBus&&Entity.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this)),t}getComponent(t){if(!ComponentRegistry.isRegistered(t))return null;const e=ComponentRegistry.getBitMask(t);if(this._componentMask.and(e).isZero())return null;const n=this._componentTypeToIndex.get(t);if(void 0!==n&&n<this.components.length){const e=this.components[n];if(e&&e.constructor===t)return e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this.rebuildComponentIndex(),e}for(let e=0;e<this.components.length;e++){const n=this.components[e];if(n instanceof t)return this._componentTypeToIndex.set(t,e),n}return null}rebuildComponentIndex(){this._componentTypeToIndex.clear();for(let t=0;t<this.components.length;t++){const e=this.components[t].constructor;this._componentTypeToIndex.set(e,t)}}hasComponent(t){if(!ComponentRegistry.isRegistered(t))return!1;const e=ComponentRegistry.getBitMask(t);return!this._componentMask.and(e).isZero()}getOrCreateComponent(t,...e){let n=this.getComponent(t);return n||(n=this.createComponent(t,...e)),n}removeComponent(t){const e=t.constructor,n=this.components.indexOf(t);if(-1!==n&&(this.components.splice(n,1),this.rebuildComponentIndex()),ComponentRegistry.isRegistered(e)){const t=ComponentRegistry.getBitMask(e);this._componentMask=this._componentMask.and(t.not())}this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity&&t.onRemovedFromEntity(),Entity.eventBus&&Entity.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),t.entity=null,this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this))}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentTypeToIndex.clear(),this._componentMask=BigIntFactory.zero();for(const e of t){const t=e.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),e.onRemovedFromEntity(),e.entity=null}this.components.length=0}addComponents(t){const e=[];for(const n of t)try{e.push(this.addComponent(n))}catch(t){Entity._logger.warn(`添加组件失败 ${n.constructor.name}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const n of t)e.push(this.removeComponentByType(n));return e}getComponents(t){const e=[];for(const n of this.components)n instanceof t&&e.push(n);return e}addChild(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)}removeAllChildren(){const t=[...this._children];for(const e of t)this.removeChild(e)}findChild(t,e=!1){for(const e of this._children)if(e.name===t)return e;if(e)for(const e of this._children){const n=e.findChild(t,!0);if(n)return n}return null}findChildrenByTag(t,e=!1){const n=[];for(const e of this._children)e.tag===t&&n.push(e);if(e)for(const e of this._children)n.push(...e.findChildrenByTag(t,!0));return n}getRoot(){let t=this;for(;t._parent;)t=t._parent;return t}isAncestorOf(t){let e=t._parent;for(;e;){if(e===this)return!0;e=e._parent}return!1}isDescendantOf(t){return t.isAncestorOf(this)}getDepth(){let t=0,e=this._parent;for(;e;)t++,e=e._parent;return t}forEachChild(t,e=!1){this._children.forEach(((n,s)=>{t(n,s),e&&n.forEachChild(t,!0)}))}onActiveChanged(){for(const t of this.components)"onActiveChanged"in t&&"function"==typeof t.onActiveChanged&&t.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}update(){if(this.activeInHierarchy&&!this._isDestroyed){for(const t of this.components)t.enabled&&t.update();for(const t of this._children)t.update()}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const t=[...this._children];for(const e of t)e.destroy();this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}compareTo(t){return EntityComparer.prototype.compare(this,t)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((t=>t.constructor.name)),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),indexMappingSize:this._componentTypeToIndex.size}}}Entity._logger=createLogger("Entity"),Entity.entityComparer=new EntityComparer,Entity.eventBus=null;class EntityBuilder{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new Entity("",t.identifierPool.checkOut())}named(t){return this.entity.name=t,this}tagged(t){return this.entity.tag=t,this}with(t){return this.entity.addComponent(t),this}withComponents(...t){for(const e of t)this.entity.addComponent(e);return this}withIf(t,e){return t&&this.entity.addComponent(e),this}withFactory(t){const e=t();return this.entity.addComponent(e),this}configure(t,e){const n=this.entity.getComponent(t);return n&&e(n),this}enabled(t=!0){return this.entity.enabled=t,this}active(t=!0){return this.entity.active=t,this}withChild(t){const e=t.build();return this.entity.addChild(e),this}withChildren(...t){for(const e of t){const t=e.build();this.entity.addChild(t)}return this}withChildFactory(t){const e=t(this.entity).build();return this.entity.addChild(e),this}withChildIf(t,e){if(t){const t=e.build();this.entity.addChild(t)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const t=new EntityBuilder(this.scene,this.storageManager);return t.entity=this.entity,t}}class EntityList{get count(){return this.buffer.length}constructor(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}add(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)}addImmediate(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))}remove(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)}removeImmediate(t){const e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(t.id))}removeAllEntities(){const t=[];for(let e=this.buffer.length-1;e>=0;e--)t.push(this.buffer[e].id),this.buffer[e].destroy();if(this._scene&&this._scene.identifierPool)for(const e of t)this._scene.identifierPool.checkIn(e);this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0}updateLists(){if(this._entitiesToAdd.length>0){for(const t of this._entitiesToAdd)this.addImmediate(t);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const t of this._entitiesToRemove)this.removeImmediate(t);this._entitiesToRemove.length=0}}update(){this._isUpdating=!0;try{for(let t=0;t<this.buffer.length;t++){const e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()}findEntity(t){const e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null}findEntitiesByName(t){return this._nameToEntities.get(t)||[]}findEntityById(t){return this._idToEntity.get(t)||null}findEntitiesByTag(t){const e=[];for(const n of this.buffer)n.tag===t&&e.push(n);return e}findEntitiesWithComponent(t){const e=[];for(const n of this.buffer)n.hasComponent(t)&&e.push(n);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const n of this.buffer)t(n)&&e(n)}updateNameIndex(t,e){if(t.name)if(e){let e=this._nameToEntities.get(t.name);e||(e=[],this._nameToEntities.set(t.name,e)),e.push(t)}else{const e=this._nameToEntities.get(t.name);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._nameToEntities.delete(t.name))}}}getStats(){let t=0;for(const e of this.buffer)e.enabled&&!e.isDestroyed&&t++;return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class EntityProcessorList{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(t){this._processors.push(t),this.setDirty()}remove(t){const e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)}getProcessor(t){for(const e of this._processors)if(e instanceof t)return e;return null}begin(){this.sortProcessors()}end(){}update(){this.sortProcessors();for(const t of this._processors)try{t.update()}catch(e){EntityProcessorList._logger.error(`Error in processor ${t.constructor.name}:`,e)}}lateUpdate(){for(const t of this._processors)t.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((t,e)=>t.updateOrder-e.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}EntityProcessorList._logger=createLogger("EntityProcessorList");class IdentifierPool{constructor(t=100,e=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=t,this._expansionBlockSize=e,this._preAllocateGenerations(0,this._expansionBlockSize)}checkOut(){let t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>IdentifierPool.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。`);t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}const e=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,e)}checkIn(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);if(!this._isValidId(e,n))return!1;return!this._pendingRecycle.some((t=>t.index===e&&t.generation===n))&&(this._pendingRecycle.push({index:e,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0)}isValid(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);return this._isValidId(e,n)}getStats(){let t=0,e=0;for(const[n,s]of this._generations)n<this._nextAvailableIndex&&(t+=s,e++);const n=e>0?t/e:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:IdentifierPool.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*n)/100,generationStorageSize:this._generations.size}}forceProcessDelayedRecycle(){this._processDelayedRecycle(!0)}_processDelayedRecycle(t=!1){if(0===this._pendingRecycle.length)return;const e=Date.now(),n=[],s=[];for(const i of this._pendingRecycle)t||e-i.timestamp>=this._recycleDelay?n.push(i):s.push(i);for(const t of n)if(this._isValidId(t.index,t.generation)){let e=t.generation+1;e>IdentifierPool.MAX_GENERATION&&(e=1),this._generations.set(t.index,e),this._freeIndices.push(t.index)}this._pendingRecycle=s}_preAllocateGenerations(t,e){for(let n=0;n<e;n++){const e=t+n;e<=IdentifierPool.MAX_INDEX&&this._generations.set(e,1)}this._stats.memoryExpansions++}_ensureGenerationCapacity(t){if(!this._generations.has(t)){const e=Math.floor(t/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(e,this._expansionBlockSize)}}_calculateMemoryUsage(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length}_packId(t,e){return e<<16|t}_unpackIndex(t){return 65535&t}_unpackGeneration(t){return t>>>16&65535}_isValidId(t,e){if(t<0||t>=this._nextAvailableIndex)return!1;const n=this._generations.get(t);return void 0!==n&&n===e}}IdentifierPool.MAX_INDEX=65535,IdentifierPool.MAX_GENERATION=65535;class ComponentPool{constructor(t,e,n=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=n}acquire(){return this.pool.length>0?this.pool.pop():this.createFn()}release(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))}prewarm(t){for(let e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}}class ComponentPoolManager{constructor(){this.pools=new Map}static getInstance(){return ComponentPoolManager.instance||(ComponentPoolManager.instance=new ComponentPoolManager),ComponentPoolManager.instance}registerPool(t,e,n,s){this.pools.set(t,new ComponentPool(e,n,s))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const n=this.pools.get(t);n&&n.release(e)}prewarmAll(t=100){for(const e of this.pools.values())e.prewarm(t)}clearAll(){for(const t of this.pools.values())t.clear()}reset(){this.pools.clear()}getPoolStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return t}getPoolUtilization(){const t=new Map;for(const[e,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),o=i-s,r=i>0?o/i*100:0;t.set(e,{used:o,total:i,utilization:r})}return t}getComponentUtilization(t){const e=this.pools.get(t);if(!e)return 0;const n=e.getAvailableCount(),s=e.getMaxSize();return s>0?(s-n)/s*100:0}}var IndexType,DirtyFlag,QueryConditionType,ECSEventType,EventPriority;!function(t){t.HASH="hash",t.BITMAP="bitmap",t.SORTED="sorted"}(IndexType||(IndexType={}));class HashComponentIndex{constructor(){this.type=IndexType.HASH,this._componentToEntities=new Map,this._entityToComponents=new Map,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._setPool=[],this._componentTypeSetPool=[]}addEntity(t){if(0===t.components.length){const e=this._componentTypeSetPool.pop()||new Set;return e.clear(),this._entityToComponents.set(t,e),void(this._lastUpdated=Date.now())}const e=this._componentTypeSetPool.pop()||new Set;e.clear();for(const n of t.components){const s=n.constructor;e.add(s);let i=this._componentToEntities.get(s);i||(i=this._setPool.pop()||new Set,i.clear(),this._componentToEntities.set(s,i)),i.add(t)}this._entityToComponents.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToComponents.get(t);if(e){for(const n of e){const e=this._componentToEntities.get(n);e&&(e.delete(t),0===e.size&&(this._componentToEntities.delete(n),this._setPool.length<50&&(e.clear(),this._setPool.push(e))))}this._entityToComponents.delete(t),this._componentTypeSetPool.length<50&&(e.clear(),this._componentTypeSetPool.push(e)),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),n=this._componentToEntities.get(t),s=n?new Set(n):new Set;return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const n=performance.now();if(0===t.length)return new Set;if(1===t.length)return this.query(t[0]);let s;if("AND"===e){let e,i=1/0;for(const s of t){const t=this._componentToEntities.get(s);if(!t||0===t.size)return this._queryCount++,this._totalQueryTime+=performance.now()-n,new Set;t.size<i&&(i=t.size,e=t)}if(s=new Set,e)for(const n of e){let e=!0;for(const s of t){const t=this._componentToEntities.get(s);if(!t||!t.has(n)){e=!1;break}}e&&s.add(n)}}else{s=new Set;for(const e of t){const t=this._componentToEntities.get(e);if(t)for(const e of t)s.add(e)}}return this._queryCount++,this._totalQueryTime+=performance.now()-n,s}clear(){this._componentToEntities.clear(),this._entityToComponents.clear(),this._lastUpdated=Date.now()}getStats(){let t=0;t+=64*this._componentToEntities.size,t+=64*this._entityToComponents.size;for(const e of this._componentToEntities.values())t+=8*e.size;for(const e of this._entityToComponents.values())t+=8*e.size;return{type:this.type,size:this._componentToEntities.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class BitmapComponentIndex{constructor(){this.type=IndexType.BITMAP,this._componentTypeToBit=new Map,this._entityToBitmap=new Map,this._bitToEntities=new Map,this._nextBit=0,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){let e=0;for(const n of t.components){const s=n.constructor;let i=this._componentTypeToBit.get(s);void 0===i&&(i=this._nextBit++,this._componentTypeToBit.set(s,i)),e|=1<<i;let o=this._bitToEntities.get(1<<i);o||(o=new Set,this._bitToEntities.set(1<<i,o)),o.add(t)}this._entityToBitmap.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToBitmap.get(t);if(void 0!==e){for(const[n,s]of this._bitToEntities)0!==(e&n)&&(s.delete(t),0===s.size&&this._bitToEntities.delete(n));this._entityToBitmap.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),n=this._componentTypeToBit.get(t);if(void 0===n)return this._queryCount++,this._totalQueryTime+=performance.now()-e,new Set;const s=new Set(this._bitToEntities.get(1<<n)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const n=performance.now();if(0===t.length)return new Set;let s=0;const i=[];for(const e of t){const t=this._componentTypeToBit.get(e);void 0!==t&&(s|=1<<t,i.push(1<<t))}const o=new Set;if("AND"===e)for(const[t,e]of this._entityToBitmap)(e&s)===s&&o.add(t);else for(const t of i){const e=this._bitToEntities.get(t);if(e)for(const t of e)o.add(t)}return this._queryCount++,this._totalQueryTime+=performance.now()-n,o}clear(){this._componentTypeToBit.clear(),this._entityToBitmap.clear(),this._bitToEntities.clear(),this._nextBit=0,this._lastUpdated=Date.now()}getStats(){let t=0;t+=12*this._componentTypeToBit.size,t+=12*this._entityToBitmap.size,t+=64*this._bitToEntities.size;for(const e of this._bitToEntities.values())t+=8*e.size;return{type:this.type,size:this._componentTypeToBit.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class ComponentIndexManager{constructor(t=IndexType.HASH){this._indexHistory=new Map,this._autoOptimize=!0,this._optimizationThreshold=1e3,this._activeIndex=this.createIndex(t)}addEntity(t){this._activeIndex.addEntity(t),this._autoOptimize&&this._activeIndex.getStats().queryCount%100==0&&this.checkOptimization()}removeEntity(t){this._activeIndex.removeEntity(t)}query(t){return this._activeIndex.query(t)}queryMultiple(t,e){return this._activeIndex.queryMultiple(t,e)}switchIndexType(t){if(t===this._activeIndex.type)return;this._indexHistory.set(this._activeIndex.type,this._activeIndex.getStats());const e=this._activeIndex;this._activeIndex=this.createIndex(t),e.clear()}setAutoOptimize(t){this._autoOptimize=t}getStats(){return this._activeIndex.getStats()}getAllStats(){const t=this._activeIndex.getStats();return new Map([...this._indexHistory,[t.type,t]])}clear(){this._activeIndex.clear()}createIndex(t){switch(t){case IndexType.HASH:return new HashComponentIndex;case IndexType.BITMAP:return new BitmapComponentIndex;case IndexType.SORTED:default:return new HashComponentIndex}}checkOptimization(){if(!this._autoOptimize)return;const t=this._activeIndex.getStats();t.queryCount<this._optimizationThreshold||(t.avgQueryTime>1&&t.type!==IndexType.HASH?this.switchIndexType(IndexType.HASH):t.memoryUsage>10485760&&t.type!==IndexType.BITMAP&&this.switchIndexType(IndexType.BITMAP))}}class ArchetypeSystem{constructor(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}addEntity(t){const e=this.getEntityComponentTypes(t),n=this.generateArchetypeId(e);let s=this._archetypes.get(n);s||(s=this.createArchetype(e)),s.entities.push(t),s.updatedAt=Date.now(),this._entityToArchetype.set(t,s),this.updateComponentIndexes(s,e,!0),this.invalidateQueryCache()}removeEntity(t){const e=this._entityToArchetype.get(t);if(!e)return;const n=e.entities.indexOf(t);-1!==n&&(e.entities.splice(n,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}queryArchetypes(t,e="AND"){const n=performance.now(),s=`${e}:${t.map((t=>t.name)).sort().join(",")}`,i=this._queryCache.get(s);if(i&&Date.now()-i.timestamp<this._cacheTimeout)return{...i.result,executionTime:performance.now()-n,fromCache:!0};const o=[];let r=0;if("AND"===e)for(const e of this._archetypes.values())this.archetypeContainsAllComponents(e,t)&&(o.push(e),r+=e.entities.length);else{const e=new Set;for(const n of t){const t=this._componentToArchetypes.get(n);if(t)for(const n of t)e.add(n)}for(const t of e)o.push(t),r+=t.entities.length}const a={archetypes:o,totalEntities:r,executionTime:performance.now()-n,fromCache:!1};return this._queryCache.set(s,{result:a,timestamp:Date.now()}),a}getEntityArchetype(t){return this._entityToArchetype.get(t)}getAllArchetypes(){return Array.from(this._archetypes.values())}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()}getEntityComponentTypes(t){return t.components.map((t=>t.constructor))}generateArchetypeId(t){return t.map((t=>t.name)).sort().join("|")}createArchetype(t){const e=this.generateArchetypeId(t),n={id:e,componentTypes:[...t],entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,n),n}archetypeContainsAllComponents(t,e){for(const n of e)if(!t.componentTypes.includes(n))return!1;return!0}updateComponentIndexes(t,e,n){for(const s of e){let e=this._componentToArchetypes.get(s);e||(e=new Set,this._componentToArchetypes.set(s,e)),n?e.add(t):(e.delete(t),0===e.size&&this._componentToArchetypes.delete(s))}}invalidateQueryCache(){this._queryCache.clear()}}!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(DirtyFlag||(DirtyFlag={}));class DirtyTrackingSystem{constructor(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}markDirty(t,e,n=[]){this._stats.totalMarkings++;let s=this._dirtyEntities.get(t);s||(s={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,s)),s.flags|=e,s.timestamp=performance.now(),s.frameNumber=this._currentFrame;for(const t of n)s.modifiedComponents.add(t);this.notifyListeners(s,e)}isDirty(t,e=DirtyFlag.ALL){const n=this._dirtyEntities.get(t);return!!n&&0!==(n.flags&e)}clearDirty(t,e=DirtyFlag.ALL){const n=this._dirtyEntities.get(t);n&&(e===DirtyFlag.ALL?this._dirtyEntities.delete(t):(n.flags&=~e,0===n.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)}getDirtyEntities(t=DirtyFlag.ALL){const e=[];for(const n of this._dirtyEntities.values())0!==(n.flags&t)&&e.push(n);return e}processDirtyEntities(){if(this._isProcessing)return;this._isProcessing=!0;const t=performance.now();0===this._processingQueue.length&&this._processingQueue.push(...this._dirtyEntities.values());let e=0;for(;this._processingQueue.length>0&&e<this._batchSize;){if(performance.now()-t>this._maxProcessingTime)break;const n=this._processingQueue.shift();this.processEntity(n),e++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}addListener(t){this._listeners.push(t),this._listeners.sort(((t,e)=>(t.priority||100)-(e.priority||100)))}removeListener(t){const e=this._listeners.findIndex((e=>e.callback===t));-1!==e&&this._listeners.splice(e,1)}beginFrame(){this._currentFrame++}endFrame(){this._isProcessing||this.processDirtyEntities()}getStats(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}}clear(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}}configureBatchProcessing(t,e){this._batchSize=t,this._maxProcessingTime=e}processEntity(t){for(const e of this._listeners)if(0!==(t.flags&e.flags))try{e.callback(t)}catch(t){DirtyTrackingSystem._logger.error("脏数据监听器错误:",t)}this.clearDirty(t.entity)}notifyListeners(t,e){for(const n of this._listeners)if(0!==(e&n.flags))try{n.callback(t)}catch(t){DirtyTrackingSystem._logger.error("脏数据监听器通知错误:",t)}}onFrameEnd(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size}estimateMemoryUsage(){let t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length,t}}DirtyTrackingSystem._logger=createLogger("DirtyTrackingSystem"),function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(QueryConditionType||(QueryConditionType={}));class QuerySystem{constructor(){this._logger=createLogger("QuerySystem"),this.entities=[],this.indexDirty=!0,this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=ComponentPoolManager.getInstance(),this.componentIndexManager=new ComponentIndexManager(IndexType.HASH),this.archetypeSystem=new ArchetypeSystem,this.dirtyTrackingSystem=new DirtyTrackingSystem}setEntities(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()}addEntity(t,e=!1){this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_ADDED),e||this.clearQueryCache(),this._version++)}addEntities(t){if(0===t.length)return;const e=new Set(this.entities.map((t=>t.id)));let n=0;for(const s of t)e.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),e.add(s.id),n++);n>0&&this.clearQueryCache()}addEntitiesUnchecked(t){if(0!==t.length){for(const e of t)this.entities.push(e);for(const e of t)this.addEntityToIndexes(e);this.clearQueryCache()}}removeEntity(t){const e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_REMOVED),this.clearQueryCache(),this._version++)}addEntityToIndexes(t){const e=t.componentMask.toString();let n=this.entityIndex.byMask.get(e);n||(n=new Set,this.entityIndex.byMask.set(e,n)),n.add(t);const s=t.components;for(let e=0;e<s.length;e++){const n=s[e].constructor;let i=this.entityIndex.byComponentType.get(n);i||(i=new Set,this.entityIndex.byComponentType.set(n,i)),i.add(t)}const i=t.tag;if(void 0!==i){let e=this.entityIndex.byTag.get(i);e||(e=new Set,this.entityIndex.byTag.set(i,e)),e.add(t)}const o=t.name;if(o){let e=this.entityIndex.byName.get(o);e||(e=new Set,this.entityIndex.byName.set(o,e)),e.add(t)}}removeEntityFromIndexes(t){const e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n&&(n.delete(t),0===n.size&&this.entityIndex.byMask.delete(e));for(const e of t.components){const n=e.constructor,s=this.entityIndex.byComponentType.get(n);s&&(s.delete(t),0===s.size&&this.entityIndex.byComponentType.delete(n))}if(void 0!==t.tag){const e=this.entityIndex.byTag.get(t.tag);e&&(e.delete(t),0===e.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){const e=this.entityIndex.byName.get(t.name);e&&(e.delete(t),0===e.size&&this.entityIndex.byName.delete(t.name))}}rebuildIndexes(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear(),this.componentIndexManager.clear();for(const t of this.entities)this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t);this.indexDirty=!1}queryAll(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`all:${t.map((t=>t.name)).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};let i=[];const o=this.archetypeSystem.queryArchetypes(t,"AND");if(o.archetypes.length>0){this.queryStats.archetypeHits++;for(const t of o.archetypes)i.push(...t.entities)}else try{if(1===t.length){this.queryStats.indexHits++;const e=this.componentIndexManager.query(t[0]);i=Array.from(e)}else{const e=this.componentIndexManager.queryMultiple(t,"AND");i=Array.from(e)}}catch(t){i=[]}return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryMultipleComponents(t){let e=null,n=1/0;for(const s of t){const t=this.entityIndex.byComponentType.get(s);if(!t||0===t.size)return[];t.size<n&&(n=t.size,e=t)}if(!e)return[];const s=this.createComponentMask(t),i=[];for(const t of e)t.componentMask.and(s).equals(s)&&i.push(t);return i}queryAny(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`any:${t.map((t=>t.name)).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};const i=this.archetypeSystem.queryArchetypes(t,"OR");let o;if(i.archetypes.length>0){this.queryStats.archetypeHits++,o=[];for(const t of i.archetypes)o.push(...t.entities)}else{const e=this.componentIndexManager.queryMultiple(t,"OR");o=Array.from(e)}return this.addToCache(n,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryNone(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`none:${t.map((t=>t.name)).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};const i=this.createComponentMask(t),o=this.entities.filter((t=>t.componentMask.and(i).isZero()));return this.addToCache(n,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryByTag(t){const e=performance.now();this.queryStats.totalQueries++;const n=`tag:${t}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByName(t){const e=performance.now();this.queryStats.totalQueries++;const n=`name:${t}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByComponent(t){const e=performance.now();this.queryStats.totalQueries++;const n=`component:${t.name}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}getFromCache(t){const e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null}addToCache(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[...e],timestamp:Date.now(),hitCount:0})}cleanupCache(){const t=Date.now();for(const[e,n]of this.queryCache.entries())t-n.timestamp>this.cacheTimeout&&this.queryCache.delete(e);if(this.queryCache.size>=this.cacheMaxSize){const t=Array.from(this.queryCache.entries());t.sort(((t,e)=>t[1].hitCount-e[1].hitCount));const e=Math.floor(.2*this.cacheMaxSize);for(let n=0;n<e&&n<t.length;n++)this.queryCache.delete(t[n][0])}}clearQueryCache(){this.queryCache.clear()}clearCache(){this.clearQueryCache()}batchUpdateComponents(t){const e=[];for(const n of t){const t=this.entities.find((t=>t.id===n.entityId));t&&(this.removeEntityFromIndexes(t),e.push(t))}for(const t of e)this.addEntityToIndexes(t);for(const t of e)this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,[]);this.clearQueryCache()}createComponentMask(t){let e=BigIntFactory.zero(),n=!1;for(const s of t)try{const t=ComponentRegistry.getBitMask(s);e=e.or(t),n=!0}catch(t){this._logger.warn(`组件类型 ${s.name} 未注册,跳过`)}return n?e:BigIntFactory.create(-1)}get version(){return this._version}getAllEntities(){return[...this.entities]}getStats(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:{...this.queryStats,cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this.dirtyTrackingSystem.getStats()},cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}switchComponentIndexType(t){this.componentIndexManager.switchIndexType(t)}configureDirtyTracking(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)}optimizePerformance(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache();const t=this.componentIndexManager.getStats();t.avgQueryTime>2&&t.type!==IndexType.HASH?this.switchComponentIndexType(IndexType.HASH):t.memoryUsage>52428800&&t.type!==IndexType.BITMAP&&this.switchComponentIndexType(IndexType.BITMAP)}beginFrame(){this.dirtyTrackingSystem.beginFrame()}endFrame(){this.dirtyTrackingSystem.endFrame()}markEntityDirty(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,e),this.clearQueryCache()}getEntityArchetype(t){return this.archetypeSystem.getEntityArchetype(t)}}class QueryBuilder{constructor(t){this._logger=createLogger("QueryBuilder"),this.conditions=[],this.querySystem=t}withAll(...t){return this.conditions.push({type:QueryConditionType.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this}withAny(...t){return this.conditions.push({type:QueryConditionType.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this}without(...t){return this.conditions.push({type:QueryConditionType.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this}execute(){const t=performance.now();if(1===this.conditions.length){const t=this.conditions[0];switch(t.type){case QueryConditionType.ALL:return this.querySystem.queryAll(...t.componentTypes);case QueryConditionType.ANY:return this.querySystem.queryAny(...t.componentTypes);case QueryConditionType.NONE:return this.querySystem.queryNone(...t.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-t,fromCache:!1}}createComponentMask(t){let e=BigIntFactory.zero();for(const n of t)try{const t=ComponentRegistry.getBitMask(n);e=e.or(t)}catch(t){this._logger.warn(`组件类型 ${n.name} 未注册,跳过`)}return e}reset(){return this.conditions=[],this}}class TypeSafeEventSystem{constructor(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}on(t,e,n={}){return this.addListener(t,e,n)}once(t,e,n={}){return this.addListener(t,e,{...n,once:!0})}onAsync(t,e,n={}){return this.addListener(t,e,{...n,async:!0})}off(t,e){const n=this.listeners.get(t);if(!n)return!1;const s=n.findIndex((t=>t.id===e));return-1!==s&&(n.splice(s,1),0===n.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)}offAll(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)}async emit(t,e){if(!this.isEnabled)return;const n=this.batchConfigs.get(t);n?.enabled?this.addToBatch(t,e):await this.executeEvent(t,e)}emitSync(t,e){if(!this.isEnabled)return;const n=this.listeners.get(t);if(!n||0===n.length)return;const s=performance.now(),i=[],o=this.sortListenersByPriority(n);for(const n of o)if(!n.config.async)try{n.config.context?n.handler.call(n.config.context,e):n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`事件处理器执行错误 ${t}:`,e)}this.removeListeners(t,i),this.updateStats(t,performance.now()-s)}setBatchConfig(t,e){this.batchConfigs.set(t,e)}flushBatch(t){const e=this.batchQueue.get(t);if(!e||0===e.length)return;const n=this.batchTimers.get(t);n&&(clearTimeout(n),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}getStats(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)}resetStats(t){t?this.stats.delete(t):this.stats.clear()}setEnabled(t){this.isEnabled=t}hasListeners(t){const e=this.listeners.get(t);return!!e&&e.length>0}getListenerCount(t){const e=this.listeners.get(t);return e?e.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(t){this.maxListeners=t}addListener(t,e,n){let s=this.listeners.get(t);if(s||(s=[],this.listeners.set(t,s)),s.length>=this.maxListeners)return TypeSafeEventSystem._logger.warn(`事件类型 ${t} 的监听器数量超过最大限制 (${this.maxListeners})`),"";const i="listener_"+this.nextListenerId++,o={handler:e,config:{priority:0,...n},id:i};return s.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),i}async executeEvent(t,e){const n=this.listeners.get(t);if(!n||0===n.length)return;const s=performance.now(),i=[],o=this.sortListenersByPriority(n),r=o.filter((t=>!t.config.async)),a=o.filter((t=>t.config.async));for(const n of r)try{n.config.context?n.handler.call(n.config.context,e):n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`同步事件处理器执行错误 ${t}:`,e)}const c=a.map((async n=>{try{n.config.context?await n.handler.call(n.config.context,e):await n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`异步事件处理器执行错误 ${t}:`,e)}}));await Promise.all(c),this.removeListeners(t,i),this.updateStats(t,performance.now()-s)}sortListenersByPriority(t){return t.slice().sort(((t,e)=>(e.config.priority||0)-(t.config.priority||0)))}removeListeners(t,e){if(0===e.length)return;const n=this.listeners.get(t);if(n){for(const t of e){const e=n.findIndex((e=>e.id===t));-1!==e&&n.splice(e,1)}0===n.length&&(this.listeners.delete(t),this.stats.delete(t))}}addToBatch(t,e){let n=this.batchQueue.get(t);n||(n=[],this.batchQueue.set(t,n)),n.push(e);const s=this.batchConfigs.get(t);if(n.length>=s.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){const e=setTimeout((()=>{this.flushBatch(t)}),s.delay);this.batchTimers.set(t,e)}}async processBatch(t,e){const n={type:t,events:e,count:e.length,timestamp:Date.now()};await this.executeEvent(`${t}:batch`,n)}clearBatch(t){this.batchQueue.delete(t);const e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))}clearAllBatches(){this.batchQueue.clear();for(const t of this.batchTimers.values())clearTimeout(t);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(t,e){let n=this.stats.get(t);n||(n=this.createEmptyStats(t),this.stats.set(t,n)),n.triggerCount++,n.totalExecutionTime+=e,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(t)}createEmptyStats(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}TypeSafeEventSystem._logger=createLogger("EventSystem"),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(ECSEventType||(ECSEventType={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(EventPriority||(EventPriority={}));const EVENT_TYPES={ENTITY:{CREATED:ECSEventType.ENTITY_CREATED,DESTROYED:ECSEventType.ENTITY_DESTROYED,ENABLED:ECSEventType.ENTITY_ENABLED,DISABLED:ECSEventType.ENTITY_DISABLED,TAG_ADDED:ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:ECSEventType.COMPONENT_ADDED,REMOVED:ECSEventType.COMPONENT_REMOVED,MODIFIED:ECSEventType.COMPONENT_MODIFIED,ENABLED:ECSEventType.COMPONENT_ENABLED,DISABLED:ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:ECSEventType.SYSTEM_ADDED,REMOVED:ECSEventType.SYSTEM_REMOVED,ENABLED:ECSEventType.SYSTEM_ENABLED,DISABLED:ECSEventType.SYSTEM_DISABLED,PROCESSING_START:ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:ECSEventType.SYSTEM_PROCESSING_END,ERROR:ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:ECSEventType.PERFORMANCE_WARNING,CRITICAL:ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:ECSEventType.FRAME_RATE_DROP}};class EventTypeValidator{static isValid(t){return this.validTypes.has(t)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(t){this.validTypes.add(t)}static removeCustomType(t){this.validTypes.delete(t)}}EventTypeValidator.validTypes=new Set([...Object.values(ECSEventType),...Object.values(EVENT_TYPES.ENTITY),...Object.values(EVENT_TYPES.COMPONENT),...Object.values(EVENT_TYPES.SYSTEM),...Object.values(EVENT_TYPES.PERFORMANCE)]);class EventBus{constructor(t=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new TypeSafeEventSystem,this.isDebugMode=t}emit(t,e){this.validateEventType(t);const n=this.enhanceEventData(t,e);this.isDebugMode&&EventBus._logger.info(`发射事件: ${t}`,n),this.eventSystem.emitSync(t,n)}async emitAsync(t,e){this.validateEventType(t);const n=this.enhanceEventData(t,e);this.isDebugMode&&EventBus._logger.info(`发射异步事件: ${t}`,n),await this.eventSystem.emit(t,n)}on(t,e,n={}){this.validateEventType(t);const s={once:n.once||!1,priority:n.priority||EventPriority.NORMAL,async:n.async||!1,context:n.context};return this.isDebugMode&&EventBus._logger.info(`添加监听器: ${t}`,s),this.eventSystem.on(t,e,s)}once(t,e,n={}){return this.on(t,e,{...n,once:!0})}onAsync(t,e,n={}){return this.on(t,e,{...n,async:!0})}off(t,e){return this.isDebugMode&&EventBus._logger.info(`移除监听器: ${e} 事件: ${t}`),this.eventSystem.off(t,e)}offAll(t){this.isDebugMode&&EventBus._logger.info(`移除所有监听器: ${t}`),this.eventSystem.offAll(t)}hasListeners(t){return this.eventSystem.hasListeners(t)}getStats(t){const e=this.eventSystem.getStats(t);if(e instanceof Map){const t=new Map;return e.forEach(((e,n)=>{t.set(n,this.convertEventStats(e))})),t}return this.convertEventStats(e)}clear(){this.isDebugMode&&EventBus._logger.info("清空所有监听器"),this.eventSystem.clear()}setEnabled(t){this.eventSystem.setEnabled(t)}setDebugMode(t){this.isDebugMode=t}setMaxListeners(t){this.eventSystem.setMaxListeners(t)}getListenerCount(t){return this.eventSystem.getListenerCount(t)}setBatchConfig(t,e,n){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:n,enabled:!0})}flushBatch(t){this.eventSystem.flushBatch(t)}resetStats(t){this.eventSystem.resetStats(t)}emitEntityCreated(t){this.emit(ECSEventType.ENTITY_CREATED,t)}emitEntityDestroyed(t){this.emit(ECSEventType.ENTITY_DESTROYED,t)}emitComponentAdded(t){this.emit(ECSEventType.COMPONENT_ADDED,t)}emitComponentRemoved(t){this.emit(ECSEventType.COMPONENT_REMOVED,t)}emitSystemAdded(t){this.emit(ECSEventType.SYSTEM_ADDED,t)}emitSystemRemoved(t){this.emit(ECSEventType.SYSTEM_REMOVED,t)}emitSceneChanged(t){this.emit(ECSEventType.SCENE_ACTIVATED,t)}emitPerformanceWarning(t){this.emit(ECSEventType.PERFORMANCE_WARNING,t)}onEntityCreated(t,e){return this.on(ECSEventType.ENTITY_CREATED,t,e)}onComponentAdded(t,e){return this.on(ECSEventType.COMPONENT_ADDED,t,e)}onSystemError(t,e){return this.on(ECSEventType.SYSTEM_ERROR,t,e)}onPerformanceWarning(t,e){return this.on(ECSEventType.PERFORMANCE_WARNING,t,e)}validateEventType(t){EventTypeValidator.isValid(t)||(this.isDebugMode&&EventBus._logger.warn(`未知事件类型: ${t}`),this.isDebugMode&&EventTypeValidator.addCustomType(t))}enhanceEventData(t,e){if(null==e)return{timestamp:Date.now(),eventId:`${t}_${++this.eventIdCounter}`,source:"EventBus"};const n=e;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=`${t}_${++this.eventIdCounter}`),n.source||(n.source="EventBus"),n}convertEventStats(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}}}EventBus._logger=createLogger("EventBus");class GlobalEventBus{static getInstance(t=!1){return this.instance||(this.instance=new EventBus(t)),this.instance}static reset(t=!1){return this.instance&&this.instance.clear(),this.instance=new EventBus(t),this.instance}}function EventHandler(t,e={}){return function(n,s,i){const o=i.value,r=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){r.call(this);GlobalEventBus.getInstance().on(t,o.bind(this),e)},i}}function AsyncEventHandler(t,e={}){return function(n,s,i){const o=i.value,r=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){r.call(this);GlobalEventBus.getInstance().onAsync(t,o.bind(this),e)},i}}class Scene{get systems(){return this.entityProcessors.processors}constructor(){this.name="",this._didSceneBegin=!1,this.entities=new EntityList(this),this.entityProcessors=new EntityProcessorList,this.identifierPool=new IdentifierPool,this.componentStorageManager=new ComponentStorageManager,this.querySystem=new QuerySystem,this.eventSystem=new TypeSafeEventSystem,Entity.eventBus||(Entity.eventBus=new EventBus(!1)),Entity.eventBus&&Entity.eventBus.onComponentAdded((t=>{this.eventSystem.emitSync("component:added",t)})),this.initialize()}initialize(){}onStart(){}unload(){}begin(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()}update(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()}createEntity(t){let e=new Entity(t,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:t,entity:e,scene:this}),this.addEntity(e)}addEntity(t,e=!1){return this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t}createEntities(t,e="Entity"){const n=[];for(let s=0;s<t;s++){const t=new Entity(`${e}_${s}`,this.identifierPool.checkOut());t.scene=this,n.push(t)}for(const t of n)this.entities.add(t);return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:t}),n}createEntitiesOld(t,e="Entity"){const n=[];for(let s=0;s<t;s++){const t=new Entity(`${e}_${s}`,this.identifierPool.checkOut());n.push(t),this.addEntity(t,!0)}return this.querySystem.clearCache(),n}destroyAllEntities(){this.entities.removeAllEntities(),this.querySystem.setEntities([])}findEntity(t){return this.entities.findEntity(t)}findEntityById(t){return this.entities.findEntityById(t)}findEntitiesByTag(t){const e=[];for(const n of this.entities.buffer)n.tag===t&&e.push(n);return e}getEntityByName(t){return this.findEntity(t)}getEntitiesByTag(t){return this.findEntitiesByTag(t)}addEntityProcessor(t){return this.entityProcessors.processors.includes(t)||(t.scene=this,this.entityProcessors.add(t),t.initialize(),t.setUpdateOrder(this.entityProcessors.count-1)),t}addSystem(t){return this.addEntityProcessor(t)}removeEntityProcessor(t){this.entityProcessors.remove(t),t.reset(),t.scene=null}getEntityProcessor(t){return this.entityProcessors.getProcessor(t)}getStats(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}}compactComponentStorage(){this.componentStorageManager.compactAll()}getDebugInfo(){return{name:this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((t=>({name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name))}))),processors:this.entityProcessors.processors.map((t=>({name:t.constructor.name,updateOrder:t.updateOrder,entityCount:t._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}}class SceneBuilder{constructor(){this.scene=new Scene}named(t){return this.scene.name=t,this}withEntity(t){return this.scene.addEntity(t),this}withEntityBuilder(t){const e=t(new EntityBuilder(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this}withEntities(...t){for(const e of t)this.scene.addEntity(e);return this}withSystem(t){return this.scene.addSystem(t),this}withSystems(...t){for(const e of t)this.scene.addSystem(e);return this}build(){return this.scene}}class ComponentBuilder{constructor(t,...e){this.component=new t(...e)}set(t,e){return this.component[t]=e,this}configure(t){return t(this.component),this}setIf(t,e,n){return t&&(this.component[e]=n),this}build(){return this.component}}class EntityBatchOperator{constructor(t){this.entities=t}addComponent(t){for(const e of this.entities)e.addComponent(t);return this}removeComponent(t){for(const e of this.entities)e.removeComponentByType(t);return this}setActive(t){for(const e of this.entities)e.active=t;return this}setTag(t){for(const e of this.entities)e.tag=t;return this}forEach(t){return this.entities.forEach(t),this}filter(t){return new EntityBatchOperator(this.entities.filter(t))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class ECSFluentAPI{constructor(t,e,n){this.scene=t,this.querySystem=e,this.eventSystem=n}createEntity(){return new EntityBuilder(this.scene,this.scene.componentStorageManager)}createScene(){return new SceneBuilder}createComponent(t,...e){return new ComponentBuilder(t,...e)}query(){return new QueryBuilder(this.querySystem)}find(...t){return this.querySystem.queryAll(...t).entities}findFirst(...t){const e=this.querySystem.queryAll(...t);return e.entities.length>0?e.entities[0]:null}findByName(t){return this.scene.getEntityByName(t)}findByTag(t){return this.scene.getEntitiesByTag(t)}emit(t,e){this.eventSystem.emitSync(t,e)}async emitAsync(t,e){await this.eventSystem.emit(t,e)}on(t,e){return this.eventSystem.on(t,e)}once(t,e){return this.eventSystem.once(t,e)}off(t,e){this.eventSystem.off(t,e)}batch(t){return new EntityBatchOperator(t)}getStats(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}}}function createECSAPI(t,e,n){return new ECSFluentAPI(t,e,n)}class EntityDataCollector{collectEntityData(){const t=Core.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let n;try{n=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeData(t);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(){const t=Core.scene;if(!t)return[];const e=t.entities;return e?.buffer?e.buffer.map((t=>({id:t.id,name:t.name||`Entity_${t.id}`,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name)),parentId:t.parent?.id||null,childIds:t.children?.map((t=>t.id))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}))):[]}getEntityDetails(t){try{const e=Core.scene;if(!e)return null;const n=e.entities;if(!n?.buffer)return null;const s=n.buffer.find((e=>e.id===t));if(!s)return null;const i=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s),o=this.extractComponentDetails(s.components),r=this.getSceneInfo(e);return{...i,scene:r.name,sceneName:r.name,sceneType:r.type,parentName:s.parent?.name||null,components:o||[],componentCount:s.components?.length||0,componentTypes:s.components?.map((t=>t.constructor.name))||[]}}catch(t){return{error:`获取实体详情失败: ${t instanceof Error?t.message:String(t)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(t){let e="当前场景",n="Scene";try{if(t.name&&"string"==typeof t.name&&t.name.trim())e=t.name.trim();else if(t.constructor&&t.constructor.name)e=t.constructor.name,n=t.constructor.name;else if(t._name&&"string"==typeof t._name&&t._name.trim())e=t._name.trim();else{const s=Object.getPrototypeOf(t)?.constructor?.name;s&&"Object"!==s&&(e=s,n=s)}}catch(t){e="场景名获取失败"}return{name:e,type:n}}collectEntityDataWithMemory(){const t=Core.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let n;try{n=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeDataWithMemory(t);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:this.buildEntityHierarchyTree(e),entityDetailsMap:this.buildEntityDetailsMap(e)}}collectArchetypeData(t){if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(t.archetypeSystem);const e={entities:t.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionFast(e),topEntities:this.getTopEntitiesByComponentsFast(e)}}getArchetypeDistributionFast(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.components?.map((t=>t.constructor.name))||[],s=n.length>0?n.sort().join(", "):"无组件",i=e.get(s);i?i.count++:e.set(s,{count:1,componentTypes:n})})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e.count,memory:0}))).sort(((t,e)=>e.count-t.count)).slice(0,20)}getTopEntitiesByComponentsFast(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0}))).sort(((t,e)=>e.componentCount-t.componentCount)).slice(0,10):[]}collectArchetypeDataWithMemory(t){if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(t.archetypeSystem);const e={entities:t.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionWithMemory(e),topEntities:this.getTopEntitiesByComponentsWithMemory(e)}}extractArchetypeStatistics(t){const e=t.getAllArchetypes(),n=[],s=[];return e.forEach((t=>{const e=t.componentTypes?.map((t=>t.name)).join(",")||"Unknown",i=t.entities?.length||0;n.push({signature:e,count:i,memory:0}),t.entities&&t.entities.slice(0,5).forEach((t=>{s.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0})}))})),n.sort(((t,e)=>e.count-t.count)),s.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:n,topEntities:s}}extractArchetypeStatisticsWithMemory(t){const e=t.getAllArchetypes(),n=[],s=[];return e.forEach((t=>{const e=t.componentTypes?.map((t=>t.name)).join(",")||"Unknown",i=t.entities?.length||0;let o=0;if(t.entities&&t.entities.length>0){const e=Math.min(5,t.entities.length);let n=0;for(let s=0;s<e;s++)n+=this.estimateEntityMemoryUsage(t.entities[s]);o=n/e*i}n.push({signature:e,count:i,memory:o}),t.entities&&t.entities.slice(0,5).forEach((t=>{s.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:this.estimateEntityMemoryUsage(t)})}))})),n.sort(((t,e)=>e.count-t.count)),s.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:n,topEntities:s}}getArchetypeDistribution(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.componentMask?.toString()||"0",s=e.get(n);e.set(n,(s||0)+1)})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e,memory:0}))).sort(((t,e)=>e.count-t.count))}getArchetypeDistributionWithMemory(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.components?.map((t=>t.constructor.name))||[],s=n.length>0?n.sort().join(", "):"无组件",i=e.get(s);let o=this.estimateEntityMemoryUsage(t);(isNaN(o)||o<0)&&(o=0),i?(i.count++,i.memory+=o):e.set(s,{count:1,memory:o,componentTypes:n})})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e.count,memory:isNaN(e.memory)?0:e.memory}))).sort(((t,e)=>e.count-t.count))}getTopEntitiesByComponents(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0}))).sort(((t,e)=>e.componentCount-t.componentCount)):[]}getTopEntitiesByComponentsWithMemory(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:this.estimateEntityMemoryUsage(t)}))).sort(((t,e)=>e.componentCount-t.componentCount)):[]}getEmptyEntityDebugData(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}calculateFallbackEntityStats(t){const e=t.buffer||[],n=e.filter((t=>t.enabled&&!t._isDestroyed));return{totalEntities:e.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?e.reduce(((t,e)=>t+(e.components?.length||0)),0)/n.length:0}}estimateEntityMemoryUsage(t){try{let e=0;const n=this.calculateObjectSize(t,["components","children","parent"]);return!isNaN(n)&&n>0&&(e+=n),t.components&&Array.isArray(t.components)&&t.components.forEach((t=>{const n=this.calculateObjectSize(t,["entity"]);!isNaN(n)&&n>0&&(e+=n)})),isNaN(e)||e<0?0:e}catch(t){return 0}}calculateObjectSize(t,e=[]){if(!t||"object"!=typeof t)return 0;const n=new WeakSet,s=(t,i=0)=>{if(!t||"object"!=typeof t||i>=2)return 0;if(n.has(t))return 0;n.add(t);let o=32;try{const n=Object.keys(t),r=Math.min(n.length,20);for(let a=0;a<r;a++){const r=n[a];if(e.includes(r)||"constructor"===r||"__proto__"===r||r.startsWith("_cc_")||r.startsWith("__"))continue;const c=t[r];o+=2*r.length,"string"==typeof c?o+=Math.min(2*c.length,200):"number"==typeof c?o+=8:"boolean"==typeof c?o+=4:Array.isArray(c)?o+=40+Math.min(8*c.length,160):"object"==typeof c&&null!==c&&(o+=s(c,i+1))}}catch(t){return 64}return o};try{const e=s(t);return Math.max(e,32)}catch(t){return 64}}buildEntityHierarchyTree(t){if(!t?.buffer)return[];const e=[];return t.buffer.forEach((t=>{if(!t.parent){const n=this.buildEntityHierarchyNode(t);e.push(n)}})),e.sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:t.id-e.id)),e}buildEntityHierarchyNode(t){let e={id:t.id,name:t.name||`Entity_${t.id}`,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name)),parentId:t.parent?.id||null,children:[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0};if(t.children&&t.children.length>0&&(e.children=t.children.map((t=>this.buildEntityHierarchyNode(t)))),"function"==typeof t.getDebugInfo){const n=t.getDebugInfo();e={...e,...n}}return t.components&&t.components.length>0&&(e.componentDetails=this.extractComponentDetails(t.components)),e}buildEntityDetailsMap(t){if(!t?.buffer)return{};const e={},n=t.buffer;for(let t=0;t<n.length;t+=100){n.slice(t,t+100).forEach((t=>{const n=t.getDebugInfo?t.getDebugInfo():this.buildFallbackEntityInfo(t),s=t.getComponentCacheStats?t.getComponentCacheStats():null,i=this.extractComponentDetails(t.components);e[t.id]={...n,parentName:t.parent?.name||null,components:i,componentTypes:n.componentTypes||i.map((t=>t.typeName)),cachePerformance:s?{hitRate:s.cacheStats.hitRate,size:s.cacheStats.size,maxSize:s.cacheStats.maxSize}:null}}))}return e}buildFallbackEntityInfo(t){const e=Core.scene,n=this.getSceneInfo(e);return{name:t.name||`Entity_${t.id}`,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:!1!==t.activeInHierarchy,destroyed:t.isDestroyed||!1,scene:n.name,sceneName:n.name,sceneType:n.type,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name)),componentMask:t.componentMask?.toString()||"0",parentId:t.parent?.id||null,childCount:t.children?.length||0,childIds:t.children.map((t=>t.id))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}}extractComponentDetails(t){return t.map((t=>{let e=t.constructor.name;if(!e||"Object"===e||"Function"===e)try{const{ComponentTypeManager:n}=require("../../ECS/Utils/ComponentTypeManager"),s=n.instance,i=t.constructor,o=s.getTypeId(i);e=s.getTypeName(o)}catch(t){e="UnknownComponent"}const n={};try{Object.keys(t).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e&&"constructor"!==e){const s=t[e];null!=s&&(n[e]=this.formatPropertyValue(s))}})),0===Object.keys(n).length&&(n._info="该组件没有公开属性",n._componentId=t.constructor.name)}catch(e){n._error="属性提取失败",n._componentId=t.constructor.name}return{typeName:e,properties:n}}))}getComponentProperties(t,e){try{const n=Core.scene;if(!n)return{};const s=n.entities;if(!s?.buffer)return{};const i=s.buffer.find((e=>e.id===t));if(!i||e>=i.components.length)return{};const o=i.components[e],r={};return Object.keys(o).forEach((t=>{if(!t.startsWith("_")&&"entity"!==t){const e=o[t];null!=e&&(r[t]=this.formatPropertyValue(e))}})),r}catch(t){return{_error:"属性提取失败"}}}formatPropertyValue(t,e=0){return null==t?t:"object"!=typeof t?"string"==typeof t&&t.length>200?`[长字符串: ${t.length}字符] ${t.substring(0,100)}...`:t:0===e?this.formatObjectFirstLevel(t):this.createLazyLoadPlaceholder(t)}formatObjectFirstLevel(t){try{if(Array.isArray(t)){if(0===t.length)return[];if(t.length>10){const e=t.slice(0,3).map((t=>this.formatPropertyValue(t,1)));return{_isLazyArray:!0,_arrayLength:t.length,_sample:e,_summary:`数组[${t.length}个元素]`}}return t.map((t=>this.formatPropertyValue(t,1)))}const e=Object.keys(t);if(0===e.length)return{};const n={};let s=0;const i=15;for(const o of e){if(s>=i){n._hasMoreProperties=!0,n._totalProperties=e.length,n._hiddenCount=e.length-s;break}if(!o.startsWith("_")&&!o.startsWith("$")&&"function"!=typeof t[o])try{const e=t[o];null!=e&&(n[o]=this.formatPropertyValue(e,1),s++)}catch(t){n[o]=`[访问失败: ${t instanceof Error?t.message:String(t)}]`,s++}}return n}catch(t){return`[对象解析失败: ${t instanceof Error?t.message:String(t)}]`}}createLazyLoadPlaceholder(t){try{const e=t.constructor?.name||"Object";return{_isLazyObject:!0,_typeName:e,_summary:this.getObjectSummary(t,e),_objectId:this.generateObjectId(t)}}catch(t){return{_isLazyObject:!0,_typeName:"Unknown",_summary:`无法分析的对象: ${t instanceof Error?t.message:String(t)}`,_objectId:Math.random().toString(36).substr(2,9)}}}getObjectSummary(t,e){try{if((e.toLowerCase().includes("vec")||e.toLowerCase().includes("vector"))&&void 0!==t.x&&void 0!==t.y){const n=void 0!==t.z?t.z:"";return`${e}(${t.x}, ${t.y}${n?", "+n:""})`}if(e.toLowerCase().includes("color")&&void 0!==t.r&&void 0!==t.g&&void 0!==t.b){const n=void 0!==t.a?t.a:1;return`${e}(${t.r}, ${t.g}, ${t.b}, ${n})`}if(e.toLowerCase().includes("node")){return`${e}: ${t.name||t._name||"未命名"}`}if(e.toLowerCase().includes("component")){const n=t.node?.name||t.node?._name||"";return`${e}${n?` on ${n}`:""}`}const n=Object.keys(t);return 0===n.length?`${e} (空对象)`:`${e} (${n.length}个属性)`}catch(t){return`${e} (无法分析)`}}generateObjectId(t){try{return void 0!==t.id?`obj_${t.id}`:void 0!==t._id?`obj_${t._id}`:void 0!==t.uuid?`obj_${t.uuid}`:void 0!==t._uuid?`obj_${t._uuid}`:`obj_${Math.random().toString(36).substr(2,9)}`}catch{return`obj_${Math.random().toString(36).substr(2,9)}`}}expandLazyObject(t,e,n){try{const s=Core.scene;if(!s)return null;const i=s.entities;if(!i?.buffer)return null;const o=i.buffer.find((e=>e.id===t));if(!o)return null;if(e>=o.components.length)return null;const r=o.components[e],a=this.getObjectByPath(r,n);return a?this.formatObjectFirstLevel(a):null}catch(t){return{error:`展开失败: ${t instanceof Error?t.message:String(t)}`}}}getObjectByPath(t,e){if(!e)return t;const n=e.split(".");let s=t;for(const t of n){if(null==s)return null;if(t.includes("[")&&t.includes("]")){const e=t.substring(0,t.indexOf("[")),n=parseInt(t.substring(t.indexOf("[")+1,t.indexOf("]")));if(e&&(s=s[e]),!(Array.isArray(s)&&n>=0&&n<s.length))return null;s=s[n]}else s=s[t]}return s}}class SystemDataCollector{collectSystemData(t){const e=Core.scene;if(!e)return{totalSystems:0,systemsInfo:[]};const n=e.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};const s=n.processors||[];let i=new Map,o=new Map;if(t)try{i=t.getAllSystemStats(),o=t.getAllSystemData()}catch(t){}return{totalSystems:s.length,systemsInfo:s.map((t=>{const e=t.systemName||t.constructor.name,n=i.get(e),s=o.get(e);return{name:e,type:t.constructor.name,entityCount:t.entities?.length||0,executionTime:n?.averageTime||s?.executionTime||0,minExecutionTime:n?.minTime===Number.MAX_VALUE?0:n?.minTime||0,maxExecutionTime:n?.maxTime||0,executionTimeHistory:n?.recentTimes||[],updateOrder:t.updateOrder||0,enabled:!1!==t.enabled,lastUpdateTime:s?.lastUpdateTime||0}}))}}}class PerformanceDataCollector{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(t){const e=Time.deltaTime,n=1e3*e,s=e>0?Math.round(1/e):0,i=this.getECSPerformanceData(t),o=i.totalExecutionTime,r=n>0?o/n*100:0;let a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const c=this.frameTimeHistory.filter((t=>t>=0));return{frameTime:o,engineFrameTime:n,ecsPercentage:r,memoryUsage:a,fps:s,averageFrameTime:c.length>0?c.reduce(((t,e)=>t+e),0)/c.length:o,minFrameTime:c.length>0?Math.min(...c):o,maxFrameTime:c.length>0?Math.max(...c):o,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(t),systemBreakdown:i.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(t){if(!t)try{const{Core:e}=require("../../Core"),n=e.Instance;if(!n||!n._performanceMonitor)return{totalExecutionTime:0,systemBreakdown:[]};t=n._performanceMonitor}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}if(!t.enabled){try{t.enabled=!0}catch(t){}return{totalExecutionTime:0,systemBreakdown:[]}}try{let e=0;const n=[],s=t.getAllSystemStats();if(0===s.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[t,i]of s.entries()){const s=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;e+=s,n.push({systemName:t,executionTime:s,percentage:0})}return n.forEach((t=>{t.percentage=e>0?t.executionTime/e*100:0})),n.sort(((t,e)=>e.executionTime-t.executionTime)),{totalExecutionTime:e,systemBreakdown:n}}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(t){if(!t)return[];try{const e=t.getAllSystemStats(),n=t.getAllSystemData();return Array.from(e.entries()).map((([t,e])=>{const s=n.get(t);return{systemName:t,averageTime:e.averageTime||0,maxTime:e.maxTime||0,minTime:e.minTime===Number.MAX_VALUE?0:e.minTime||0,samples:e.executionCount||0,percentage:0,entityCount:s?.entityCount||0,lastExecutionTime:s?.executionTime||0}}))}catch(t){return[]}}getMemoryDetails(){const t={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){const e=performance.memory;if(t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,this.lastMemoryCheck>0){this.lastMemoryCheck-t.usedMemory>1048576&&this.gcCollections++}this.lastMemoryCheck=t.usedMemory}else t.totalMemory=536870912,t.freeMemory=536870912}catch(t){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return t}updateGCCount(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(t){return this.gcCollections}}}class ComponentDataCollector{collectComponentData(){const t=Core.scene;if(!t)return{componentTypes:0,componentInstances:0,componentStats:[]};const e=t.entities;if(!e?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const n=new Map;let s=0;e.buffer.forEach((t=>{t.components&&t.components.forEach((t=>{const e=t.constructor.name,i=n.get(e)||{count:0,entities:0};i.count++,s++,n.set(e,i)}))}));let i=new Map,o=new Map;try{const{ComponentPoolManager:t}=require("../../ECS/Core/ComponentPool"),e=t.getInstance(),n=e.getPoolStats(),s=e.getPoolUtilization();for(const[t,e]of n.entries())o.set(t,e.maxSize);for(const[t,e]of s.entries())i.set(t,e.utilization)}catch(t){}return{componentTypes:n.size,componentInstances:s,componentStats:Array.from(n.entries()).map((([t,n])=>{const s=o.get(t)||0,r=i.get(t)||0,a=this.getEstimatedComponentSize(t);return{typeName:t,instanceCount:n.count,memoryPerInstance:a,totalMemory:n.count*a,poolSize:s,poolUtilization:r,averagePerEntity:n.count/e.buffer.length}}))}}getEstimatedComponentSize(t){if(ComponentDataCollector.componentSizeCache.has(t))return ComponentDataCollector.componentSizeCache.get(t);const e=Core.scene;if(!e)return 64;const n=e.entities;if(!n?.buffer)return 64;let s=64;try{for(const e of n.buffer)if(e.components){const n=e.components.find((e=>e.constructor.name===t));if(n){s=this.calculateQuickObjectSize(n);break}}}catch(t){s=64}return ComponentDataCollector.componentSizeCache.set(t,s),s}calculateQuickObjectSize(t){if(!t||"object"!=typeof t)return 8;let e=32;const n=new WeakSet,s=(t,e=0)=>{if(!t||"object"!=typeof t||n.has(t)||e>3)return 0;n.add(t);let i=0;try{const n=Object.keys(t);for(let o=0;o<Math.min(n.length,20);o++){const r=n[o];if("entity"===r||"_entity"===r||"constructor"===r)continue;const a=t[r];i+=2*r.length,"string"==typeof a?i+=Math.min(2*a.length,200):"number"==typeof a?i+=8:"boolean"==typeof a?i+=4:"object"==typeof a&&null!==a&&(i+=s(a,e+1))}}catch(t){return 32}return i};return e+=s(t),Math.max(e,32)}calculateDetailedComponentMemory(t){const e=Core.scene;if(!e)return this.getEstimatedComponentSize(t);const n=e.entities;if(!n?.buffer)return this.getEstimatedComponentSize(t);try{for(const e of n.buffer)if(e.components){const n=e.components.find((e=>e.constructor.name===t));if(n)return this.estimateObjectSize(n)}}catch(t){}return this.getEstimatedComponentSize(t)}estimateObjectSize(t,e=new WeakSet,n=0){if(null==t||n>10)return 0;if(e.has(t))return 0;let s=0;switch(typeof t){case"boolean":s=4;break;case"number":default:s=8;break;case"string":s=24+Math.min(2*t.length,1e3);break;case"object":if(e.add(t),Array.isArray(t)){s=40+8*t.length;const i=Math.min(t.length,50);for(let o=0;o<i;o++)s+=this.estimateObjectSize(t[o],e,n+1)}else{s=32;try{const i=Object.getOwnPropertyNames(t),o=Math.min(i.length,30);for(let r=0;r<o;r++){const o=i[r];if("constructor"!==o&&"__proto__"!==o&&"entity"!==o&&"_entity"!==o&&!o.startsWith("_cc_")&&!o.startsWith("__"))try{s+=16+2*o.length;const i=t[o];null!=i&&(s+=this.estimateObjectSize(i,e,n+1))}catch(t){continue}}}catch(t){s=128}}}return 8*Math.ceil(s/8)}static clearCache(){ComponentDataCollector.componentSizeCache.clear()}}ComponentDataCollector.componentSizeCache=new Map;class SceneDataCollector{constructor(){this.sceneStartTime=Date.now()}collectSceneData(){const t=Core.scene;if(!t)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};const e=(Date.now()-this.sceneStartTime)/1e3,n=t.entities,s=t.entityProcessors;return{currentSceneName:t.name||"Unnamed Scene",isInitialized:t._didSceneBegin||!1,sceneRunTime:e,sceneEntityCount:n?.buffer?.length||0,sceneSystemCount:s?.processors?.length||0,sceneMemory:0,sceneUptime:e}}setSceneStartTime(t){this.sceneStartTime=t}}class WebSocketManager{constructor(t,e=!0){this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=t,this.autoReconnect=e}setMessageHandler(t){this.messageHandler=t}connect(){return new Promise(((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=e=>{this.handleOpen(e),t()},this.ws.onclose=t=>{this.handleClose(t)},this.ws.onerror=t=>{this.handleError(t),e(t)},this.ws.onmessage=t=>{this.handleMessage(t)}}catch(t){this.handleConnectionFailure(t),e(t)}}))}disconnect(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1}send(t){if(this.isConnected&&this.ws)try{const e="string"==typeof t?t:JSON.stringify(t);this.ws.send(e)}catch(t){}}getConnectionStatus(){return this.isConnected}setMaxReconnectAttempts(t){this.maxReconnectAttempts=t}setReconnectInterval(t){this.reconnectInterval=t}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((()=>{this.connect().catch((t=>{this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}))}),t)}handleMessage(t){try{const e=JSON.parse(t.data);this.messageHandler&&this.messageHandler(e)}catch(t){}}handleOpen(t){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(t)}handleClose(t){this.isConnected=!1,this.onClose&&this.onClose(t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}handleError(t){this.onError&&this.onError(t)}handleConnectionFailure(t){this.onError&&this.onError(t)}}class DebugManager{constructor(t,e){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=e,this.entityCollector=new EntityDataCollector,this.systemCollector=new SystemDataCollector,this.performanceCollector=new PerformanceDataCollector,this.componentCollector=new ComponentDataCollector,this.sceneCollector=new SceneDataCollector,this.webSocketManager=new WebSocketManager(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const n=e.debugFrameRate||30;this.sendInterval=1e3/n,this.start()}start(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())}stop(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())}updateConfig(t){this.config=t;const e=t.debugFrameRate||30;this.sendInterval=1e3/e,this.webSocketManager&&t.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new WebSocketManager(t.websocketUrl,!1!==t.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())}onFrameUpdate(t){if(!this.isRunning||!this.config.enabled)return;this.frameCounter++;const e=Date.now();e-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=e)}onSceneChanged(){this.isRunning&&this.config.enabled&&this.sendDebugData()}handleMessage(t){try{switch(t.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":t.config&&this.updateConfig({...this.config,...t.config});break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(t);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(t);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(t);break;case"get_entity_details":this.handleGetEntityDetailsRequest(t);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(e){t.requestId&&this.webSocketManager.send({type:"error_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleExpandLazyObjectRequest(t){try{const{entityId:e,componentIndex:n,propertyPath:s,requestId:i}=t;if(void 0===e||void 0===n||!s)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});const o=this.entityCollector.expandLazyObject(e,n,s);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,data:o})}catch(e){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetComponentPropertiesRequest(t){try{const{entityId:e,componentIndex:n,requestId:s}=t;if(void 0===e||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:s,error:"缺少必要参数"});const i=this.entityCollector.getComponentProperties(e,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:s,data:i})}catch(e){this.webSocketManager.send({type:"get_component_properties_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetRawEntityListRequest(t){try{const{requestId:e}=t,n=this.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e,data:n})}catch(e){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetEntityDetailsRequest(t){try{const{entityId:e,requestId:n}=t;if(void 0===e)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});const s=this.entityCollector.getEntityDetails(e);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:s})}catch(e){this.webSocketManager.send({type:"get_entity_details_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleMemorySnapshotRequest(){try{const t=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:t})}catch(t){this.webSocketManager.send({type:"memory_snapshot_error",error:t instanceof Error?t.message:"内存快照捕获失败"})}}captureMemorySnapshot(){const t=Date.now(),e=this.entityCollector.collectEntityDataWithMemory(),n=this.collectBaseMemoryInfo(),s=this.collectComponentMemoryStats(Core.scene?.entities),i=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),r=this.collectPerformanceStats(),a=e.entitiesPerArchetype.reduce(((t,e)=>t+e.memory),0);return{timestamp:t,version:"2.0",summary:{totalEntities:e.totalEntities,totalMemoryUsage:n.usedMemory,totalMemoryLimit:n.totalMemory,memoryUtilization:n.usedMemory/n.totalMemory*100,gcCollections:n.gcCollections,entityMemory:a,componentMemory:s.totalMemory,systemMemory:i.totalMemory,poolMemory:o.totalMemory},baseMemory:n,entities:{totalMemory:a,entityCount:e.totalEntities,archetypes:e.entitiesPerArchetype,largestEntities:e.topEntitiesByComponents},components:s,systems:i,pools:o,performance:r}}collectBaseMemoryInfo(){const t={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null};try{if(performance.memory){const e=performance.memory;t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,t.heapInfo={totalJSHeapSize:e.totalJSHeapSize||0,usedJSHeapSize:e.usedJSHeapSize||0,jsHeapSizeLimit:e.jsHeapSizeLimit||0}}else t.totalMemory=536870912,t.freeMemory=536870912;performance.measureUserAgentSpecificMemory&&performance.measureUserAgentSpecificMemory().then((e=>{t.detailedMemory=e})).catch((()=>{}))}catch(t){}return t}collectComponentMemoryStats(t){const e=new Map;let n=0;const s=new Map;for(const e of t.buffer)if(e&&!e.destroyed&&e.components)for(const t of e.components){const e=t.constructor.name;s.set(e,(s.get(e)||0)+1)}for(const[i,o]of s.entries()){const s=this.componentCollector.calculateDetailedComponentMemory(i),r=s*o;n+=r;const a=[];let c=0;for(const e of t.buffer)if(e&&!e.destroyed&&e.components){for(const t of e.components)if(t.constructor.name===i&&(a.push({entityId:e.id,entityName:e.name||`Entity_${e.id}`,memory:s}),c++,c>=100))break;if(c>=100)break}e.set(i,{count:o,totalMemory:r,instances:a.slice(0,10)})}const i=Array.from(e.entries()).map((([t,e])=>({typeName:t,instanceCount:e.count,totalMemory:e.totalMemory,averageMemory:e.totalMemory/e.count,percentage:n>0?e.totalMemory/n*100:0,largestInstances:e.instances.sort(((t,e)=>e.memory-t.memory)).slice(0,3)}))).sort(((t,e)=>e.totalMemory-t.totalMemory));return{totalMemory:n,componentTypes:e.size,totalInstances:Array.from(e.values()).reduce(((t,e)=>t+e.count),0),breakdown:i}}collectSystemMemoryStats(){const t=Core.scene;let e=0;const n=[];try{const s=t.entityProcessors;if(s&&s.processors){const t=new Map;for(const i of s.processors){const s=i.constructor.name;let o;t.has(s)?o=t.get(s):(o=this.calculateQuickSystemSize(i),t.set(s,o)),e+=o,n.push({name:s,memory:o,enabled:!1!==i.enabled,updateOrder:i.updateOrder||0})}}}catch(t){}return{totalMemory:e,systemCount:n.length,breakdown:n.sort(((t,e)=>e.memory-t.memory))}}calculateQuickSystemSize(t){if(!t||"object"!=typeof t)return 64;let e=128;try{const n=Object.keys(t);for(let s=0;s<Math.min(n.length,15);s++){const i=n[s];if("entities"===i||"scene"===i||"constructor"===i)continue;const o=t[i];e+=2*i.length,"string"==typeof o?e+=Math.min(2*o.length,100):"number"==typeof o?e+=8:"boolean"==typeof o?e+=4:Array.isArray(o)?e+=40+Math.min(8*o.length,200):"object"==typeof o&&null!==o&&(e+=64)}}catch(t){return 128}return Math.max(e,64)}collectPoolMemoryStats(){let t=0;const e=[];try{const{ComponentPoolManager:n}=require("../../ECS/Core/ComponentPool"),s=n.getInstance().getPoolStats();for(const[n,i]of s.entries()){const s=i,o=32*s.maxSize;t+=o,e.push({typeName:n,maxSize:s.maxSize,currentSize:s.currentSize||0,estimatedMemory:o,utilization:s.currentSize?s.currentSize/s.maxSize*100:0})}}catch(t){}try{const{Pool:n}=require("../../Utils/Pool"),s=n.getStats();for(const[n,i]of Object.entries(s)){const s=i;t+=s.estimatedMemoryUsage,e.push({typeName:`Pool_${n}`,maxSize:s.maxSize,currentSize:s.size,estimatedMemory:s.estimatedMemoryUsage,utilization:s.size/s.maxSize*100,hitRate:100*s.hitRate})}}catch(t){}return{totalMemory:t,poolCount:e.length,breakdown:e.sort(((t,e)=>e.estimatedMemory-t.estimatedMemory))}}collectPerformanceStats(){try{const t=Core.Instance._performanceMonitor;if(!t)return{enabled:!1};const e=t.getAllSystemStats(),n=t.getPerformanceWarnings();return{enabled:t.enabled,systemCount:e.size,warnings:n.slice(0,10),topSystems:Array.from(e.entries()).map((t=>{const[e,n]=t;return{name:e,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort(((t,e)=>e.averageTime-t.averageTime)).slice(0,5)}}catch(t){return{enabled:!1,error:t.message}}}getMemorySizeCategory(t){return t<1024?"< 1KB":t<10240?"1-10KB":t<102400?"10-100KB":t<1048576?"100KB-1MB":"> 1MB"}getDebugData(){const t=Date.now(),e=Core.scene,n={timestamp:t,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:e?.name||"Unknown"};if(this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData()),this.config.channels.systems){const t=Core.Instance._performanceMonitor;n.systems=this.systemCollector.collectSystemData(t)}if(this.config.channels.performance){const t=Core.Instance._performanceMonitor;n.performance=this.performanceCollector.collectPerformanceData(t)}return this.config.channels.components&&(n.components=this.componentCollector.collectComponentData()),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData()),n}async connectWebSocket(){try{await this.webSocketManager.connect()}catch(t){}}sendDebugData(){if(this.webSocketManager.getConnectionStatus())try{const t={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(t)}catch(t){}}}class Core{constructor(t={}){this._nextScene=null,this._globalManagers=[],Core._instance=this,this._config={debug:!0,enableEntitySystems:!0,...t},this._environmentInfo=BigIntFactory.getEnvironmentInfo(),this._timerManager=new TimerManager,Core.registerGlobalManager(this._timerManager),this._performanceMonitor=PerformanceMonitor.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=PoolManager.getInstance(),Core.entitySystemsEnabled=this._config.enableEntitySystems??!0,this.debug=this._config.debug??!0,this._config.debugConfig?.enabled&&(this._debugManager=new DebugManager(this,this._config.debugConfig)),this._config.debug&&this.logCompatibilityInfo(),this.initialize()}static get Instance(){return this._instance}static get scene(){return this._instance&&this._instance._scene||null}static set scene(t){if(t){if(!t)throw new Error("场景不能为空");null==this._instance._scene?(this._instance._scene=t,this._instance.onSceneChanged(),this._instance._scene.begin()):this._instance._nextScene=t}}static create(t=!0){if(null==this._instance){const e="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new Core(e)}return this._instance}static update(t){this._instance?this._instance.updateInternal(t):Core._logger.warn("Core实例未创建,请先调用Core.create()")}static registerGlobalManager(t){this._instance._globalManagers.push(t),t.enabled=!0}static unregisterGlobalManager(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1}static getGlobalManager(t){for(const e of this._instance._globalManagers)if(e instanceof t)return e;return null}static schedule(t,e=!1,n=null,s){return this._instance._timerManager.schedule(t,e,n,s)}static get ecsAPI(){return this._instance?._ecsAPI||null}static enableDebug(t){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(t):this._instance._debugManager=new DebugManager(this._instance,t),this._instance._config.debugConfig=t):Core._logger.warn("Core实例未创建,请先调用Core.create()")}static disableDebug(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))}static getDebugData(){return this._instance?._debugManager?this._instance._debugManager.getDebugData():null}static get isDebugEnabled(){return this._instance?._config.debugConfig?.enabled||!1}static getEnvironmentInfo(){return this._instance?._environmentInfo||null}static get supportsBigInt(){return this._instance?._environmentInfo.supportsBigInt||!1}onSceneChanged(){if(Time.sceneChanged(),this._scene&&void 0!==this._scene.querySystem){const t=this._scene;this._ecsAPI=createECSAPI(t,t.querySystem,t.eventSystem)}this._debugManager&&this._debugManager.onSceneChanged()}initialize(){}logCompatibilityInfo(){const t=this._environmentInfo;Core._logger.info("ECS Framework 兼容性检测结果:"),Core._logger.info(` 环境: ${t.environment}`),Core._logger.info(` JavaScript引擎: ${t.jsEngine}`),Core._logger.info(" BigInt支持: "+(t.supportsBigInt?"支持":"不支持")),t.supportsBigInt||Core._logger.warn("BigInt兼容模式已启用")}updateInternal(t){if(Core.paused)return;const e=this._performanceMonitor.startMonitoring("Core.update");Time.update(t),"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(Time.deltaTime);const n=this._performanceMonitor.startMonitoring("GlobalManagers.update");for(const t of this._globalManagers)t.enabled&&t.update();if(this._performanceMonitor.endMonitoring("GlobalManagers.update",n,this._globalManagers.length),this._poolManager.update(),null!=this._nextScene&&(null!=this._scene&&this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this._scene.begin()),null!=this._scene&&this._scene.update){const t=this._performanceMonitor.startMonitoring("Scene.update");this._scene.update();const e=this._scene.entities?.count||0;this._performanceMonitor.endMonitoring("Scene.update",t,e)}this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",e)}}Core.paused=!1,Core._logger=createLogger("Core");class FuncPack{constructor(t,e){this.func=t,this.context=e}}class Emitter{constructor(){this._messageTable=new Map}addObserver(t,e,n){let s=this._messageTable.get(t);s||(s=[],this._messageTable.set(t,s)),this.hasObserver(t,e)||s.push(new FuncPack(e,n))}removeObserver(t,e){let n=this._messageTable.get(t);if(n){let t=n.findIndex((t=>t.func==e));-1!=t&&n.splice(t,1)}}emit(t,...e){let n=this._messageTable.get(t);if(n)for(let t of n)t.func.call(t.context,...e)}hasObserver(t,e){let n=this._messageTable.get(t);return!!n&&n.some((t=>t.func===e))}}class Component{constructor(){this._enabled=!0,this._updateOrder=0,this.id=Component._idGenerator++}get enabled(){return this.entity?this.entity.enabled&&this._enabled:this._enabled}set enabled(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}onAddedToEntity(){}onRemovedFromEntity(){}onEnabled(){}onDisabled(){}update(){}}Component._idGenerator=0;class Matcher{constructor(){this.condition={all:[],any:[],none:[]}}static all(...t){return(new Matcher).all(...t)}static any(...t){return(new Matcher).any(...t)}static none(...t){return(new Matcher).none(...t)}static byTag(t){return(new Matcher).withTag(t)}static byName(t){return(new Matcher).withName(t)}static byComponent(t){return(new Matcher).withComponent(t)}static complex(){return new Matcher}static empty(){return new Matcher}all(...t){return this.condition.all.push(...t),this}any(...t){return this.condition.any.push(...t),this}none(...t){return this.condition.none.push(...t),this}exclude(...t){return this.none(...t)}one(...t){return this.any(...t)}withTag(t){return this.condition.tag=t,this}withName(t){return this.condition.name=t,this}withComponent(t){return this.condition.component=t,this}withoutTag(){return delete this.condition.tag,this}withoutName(){return delete this.condition.name,this}withoutComponent(){return delete this.condition.component,this}getCondition(){return{all:[...this.condition.all],any:[...this.condition.any],none:[...this.condition.none],tag:this.condition.tag,name:this.condition.name,component:this.condition.component}}isEmpty(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component}reset(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this}clone(){const t=new Matcher;return t.condition.all.push(...this.condition.all),t.condition.any.push(...this.condition.any),t.condition.none.push(...this.condition.none),void 0!==this.condition.tag&&(t.condition.tag=this.condition.tag),void 0!==this.condition.name&&(t.condition.name=this.condition.name),void 0!==this.condition.component&&(t.condition.component=this.condition.component),t}toString(){const t=[];return this.condition.all.length>0&&t.push(`all(${this.condition.all.map((t=>t.name)).join(", ")})`),this.condition.any.length>0&&t.push(`any(${this.condition.any.map((t=>t.name)).join(", ")})`),this.condition.none.length>0&&t.push(`none(${this.condition.none.map((t=>t.name)).join(", ")})`),void 0!==this.condition.tag&&t.push(`tag(${this.condition.tag})`),void 0!==this.condition.name&&t.push(`name(${this.condition.name})`),void 0!==this.condition.component&&t.push(`component(${this.condition.component.name})`),`Matcher[${t.join(" & ")}]`}}class EntitySystem{get entities(){return this.queryEntities()}get updateOrder(){return this._updateOrder}set updateOrder(t){this.setUpdateOrder(t)}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get systemName(){return this._systemName}constructor(t){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=PerformanceMonitor.instance,this._initialized=!1,this._trackedEntities=new Set,this._lastQueryResult=[],this._scene=null,this._matcher=t||Matcher.empty(),this._systemName=this.constructor.name}get scene(){return this._scene}set scene(t){this._scene=t}get matcher(){return this._matcher}setUpdateOrder(t){this._updateOrder=t,this.scene&&this.scene.entityProcessors&&this.scene.entityProcessors.setDirty()}initialize(){this._initialized||(this._initialized=!0,this.onInitialize())}onInitialize(){this.scene&&this.queryEntities()}reset(){this._initialized=!1,this._trackedEntities.clear(),this._lastQueryResult=[]}queryEntities(){if(!this.scene?.querySystem||!this._matcher)return this._lastQueryResult=[],[];const t=this._matcher.getCondition(),e=this.scene.querySystem;let n=[];return n=this._matcher.isEmpty()?e.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,e):this.executeComplexQuery(t,e),this.updateEntityTracking(n),this._lastQueryResult=n,n}isSingleCondition(t){return 1===(t.all.length>0?1:0)+(t.any.length>0?1:0)+(t.none.length>0?1:0)+(void 0!==t.tag?1:0)+(void 0!==t.name?1:0)+(void 0!==t.component?1:0)}executeSingleConditionQuery(t,e){return void 0!==t.tag?e.queryByTag(t.tag).entities:void 0!==t.name?e.queryByName(t.name).entities:void 0!==t.component?e.queryByComponent(t.component).entities:t.all.length>0&&0===t.any.length&&0===t.none.length?e.queryAll(...t.all).entities:0===t.all.length&&t.any.length>0&&0===t.none.length?e.queryAny(...t.any).entities:0===t.all.length&&0===t.any.length&&t.none.length>0?e.queryNone(...t.none).entities:[]}executeComplexQuery(t,e){let n=null;if(void 0!==t.tag){const s=e.queryByTag(t.tag);n=new Set(s.entities)}if(void 0!==t.name){const s=e.queryByName(t.name),i=new Set(s.entities);n=n?new Set([...n].filter((t=>i.has(t)))):i}if(void 0!==t.component){const s=e.queryByComponent(t.component),i=new Set(s.entities);n=n?new Set([...n].filter((t=>i.has(t)))):i}if(t.all.length>0){const s=e.queryAll(...t.all),i=new Set(s.entities);n=n?new Set([...n].filter((t=>i.has(t)))):i}if(t.any.length>0){const s=e.queryAny(...t.any),i=new Set(s.entities);n=n?new Set([...n].filter((t=>i.has(t)))):i}if(t.none.length>0){n||(n=new Set(e.getAllEntities()));const s=e.queryAny(...t.none),i=new Set(s.entities);n=new Set([...n].filter((t=>!i.has(t))))}return n?Array.from(n):[]}update(){if(!this._enabled||!this.onCheckProcessing())return;const t=this._performanceMonitor.startMonitoring(this._systemName);let e=0;try{this.onBegin();const t=this.queryEntities();e=t.length,this.process(t)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,e)}}lateUpdate(){if(!this._enabled||!this.onCheckProcessing())return;const t=this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);let e=0;try{const t=this.queryEntities();e=t.length,this.lateProcess(t),this.onEnd()}finally{this._performanceMonitor.endMonitoring(`${this._systemName}_Late`,t,e)}}onBegin(){}process(t){}lateProcess(t){}onEnd(){}onCheckProcessing(){return!0}getPerformanceData(){return this._performanceMonitor.getSystemData(this._systemName)}getPerformanceStats(){return this._performanceMonitor.getSystemStats(this._systemName)}resetPerformanceData(){this._performanceMonitor.resetSystem(this._systemName)}toString(){const t=this.entities.length,e=this.getPerformanceData(),n=e?` (${e.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${t} entities]${n}`}updateEntityTracking(t){const e=new Set(t);for(const e of t)this._trackedEntities.has(e)||(this._trackedEntities.add(e),this.onAdded(e));for(const t of this._trackedEntities)e.has(t)||(this._trackedEntities.delete(t),this.onRemoved(t))}onAdded(t){}onRemoved(t){}}class ProcessingSystem extends EntitySystem{constructor(t){super(t)}process(t){this.processSystem()}}class PassiveSystem extends EntitySystem{constructor(t){super(t)}process(t){}}class IntervalSystem extends EntitySystem{constructor(t,e){super(e),this.acc=0,this.intervalRemainder=0,this.interval=t}onCheckProcessing(){return this.acc+=Time.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class Bits{constructor(t){this._value=t&&"object"==typeof t?t:BigIntFactory.create(t||0)}set(t){if(t<0)throw new Error("Bit index cannot be negative");const e=BigIntFactory.one().shiftLeft(t);this._value=this._value.or(e)}clear(t){if(t<0)throw new Error("Bit index cannot be negative");const e=BigIntFactory.one().shiftLeft(t).not();this._value=this._value.and(e)}get(t){if(t<0)return!1;const e=BigIntFactory.one().shiftLeft(t);return!this._value.and(e).isZero()}containsAll(t){return this._value.and(t._value).equals(t._value)}intersects(t){return!this._value.and(t._value).isZero()}excludes(t){return!this.intersects(t)}clearAll(){this._value=BigIntFactory.zero()}isEmpty(){return this._value.isZero()}cardinality(){let t=0,e=this._value.clone();for(;!e.isZero();){const n=BigIntFactory.one();e.and(n).isZero()||t++,e=e.shiftRight(1)}return t}and(t){return new Bits(this._value.and(t._value))}or(t){return new Bits(this._value.or(t._value))}xor(t){return new Bits(this._value.xor(t._value))}not(t=64){return new Bits(this._value.not(t))}copyFrom(t){this._value=t._value.clone()}clone(){return new Bits(this._value.clone())}getValue(){return this._value}setValue(t){this._value="object"==typeof t?t:BigIntFactory.create(t)}toString(){const t=[];let e=0,n=this._value.clone();for(;!n.isZero();){const s=BigIntFactory.one();n.and(s).isZero()||t.push(e.toString()),n=n.shiftRight(1),e++}return`Bits[${t.join(", ")}]`}toBinaryString(t=64){let e="";for(let n=t-1;n>=0;n--)e+=this.get(n)?"1":"0",n%8==0&&n>0&&(e+=" ");return e}toHexString(){return"0x"+this._value.toString(16).toUpperCase()}static fromBinaryString(t){const e=t.replace(/\s/g,""),n=BigIntFactory.fromBinaryString(e);return new Bits(n)}static fromHexString(t){const e=BigIntFactory.fromHexString(t);return new Bits(e)}equals(t){return this._value.equals(t._value)}getHighestBitIndex(){if(this._value.isZero())return-1;let t=0,e=this._value.clone();for(;!e.shiftRight(1).isZero();)e=e.shiftRight(1),t++;return t}getLowestBitIndex(){if(this._value.isZero())return-1;let t=0,e=this._value.clone();const n=BigIntFactory.one();for(;e.and(n).isZero();)e=e.shiftRight(1),t++;return t}}class ComponentTypeManager{static get instance(){return ComponentTypeManager._instance||(ComponentTypeManager._instance=new ComponentTypeManager),ComponentTypeManager._instance}constructor(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}getTypeId(t){let e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,t.name)),e}getTypeName(t){return this._typeNames.get(t)||"Unknown"}createBits(...t){const e=new Bits;for(const n of t){const t=this.getTypeId(n);e.set(t)}return e}getEntityBits(t){const e=new Bits;for(const n of t){const t=this.getTypeId(n.constructor);e.set(t)}return e}reset(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0}get registeredTypeCount(){return this._componentTypes.size}}class EntityQueryBuilder{constructor(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}withAll(...t){return this._allComponents.push(...t),this}withAny(...t){return this._anyComponents.push(...t),this}without(...t){return this._withoutComponents.push(...t),this}withTag(t){return this._withTags.push(t),this}withoutTag(t){return this._withoutTags.push(t),this}active(){return this._activeOnly=!0,this}enabled(){return this._enabledOnly=!0,this}where(t){return this._customPredicates.push(t),this}execute(){let t=[];if(this._allComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");t=Array.from(e)}else if(this._anyComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");t=Array.from(e)}else t=this.entityManager.getAllEntities();return t.filter((t=>this.matchesEntity(t)))}first(){return this.entityManager.getAllEntities().find((t=>this.matchesEntity(t)))||null}count(){return this.entityManager.getAllEntities().filter((t=>this.matchesEntity(t))).length}forEach(t){this.entityManager.getAllEntities().forEach((e=>{this.matchesEntity(e)&&t(e)}))}matchesEntity(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(const e of this._allComponents)if(!t.hasComponent(e))return!1;if(this._anyComponents.length>0){let e=!1;for(const n of this._anyComponents)if(t.hasComponent(n)){e=!0;break}if(!e)return!1}if(this._withoutComponents.length>0)for(const e of this._withoutComponents)if(t.hasComponent(e))return!1;if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(const e of this._customPredicates)if(!e(t))return!1;return!0}}class EntityManager{constructor(){this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new IdentifierPool,this._componentIndexManager=new ComponentIndexManager(IndexType.HASH),this._archetypeSystem=new ArchetypeSystem,this._dirtyTrackingSystem=new DirtyTrackingSystem,this._eventBus=new EventBus(!1),Entity.eventBus=this._eventBus,this._eventBus.on("component:added",(t=>{const e=this._entities.get(t.entityId);e&&(this._componentIndexManager.addEntity(e),this._archetypeSystem.addEntity(e))})),this._eventBus.on("component:removed",(t=>{const e=this._entities.get(t.entityId);e&&(this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e))}))}get entityCount(){return this._entities.size}get activeEntityCount(){let t=0;for(const e of this._entities.values())e.active&&!e.isDestroyed&&t++;return t}createEntity(t){const e=this._identifierPool.checkOut();t||(t=`Entity_${e}`);const n=new Entity(t,e);return this._entities.set(e,n),this.updateNameIndex(n,!0),this.updateTagIndex(n,!0),n.components.length>0&&(this._componentIndexManager.addEntity(n),this._archetypeSystem.addEntity(n),this._dirtyTrackingSystem.markDirty(n,DirtyFlag.COMPONENT_ADDED)),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:n.id,entityName:n.name,entityTag:n.tag?.toString()}),n}createEntitiesBatch(t,e="Entity",n=!1){if(t<=0)return[];const s=[];for(let n=0;n<t;n++){const t=this._identifierPool.checkOut(),n=new Entity(`${e}_${t}`,t);s.push(n),this._entities.set(t,n)}for(const t of s)this.updateNameIndex(t,!0),this.updateTagIndex(t,!0),t.components.length>0&&(this._componentIndexManager.addEntity(t),this._archetypeSystem.addEntity(t),this._dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_ADDED));if(!n){const t=Date.now();for(const e of s)this._eventBus.emitEntityCreated({timestamp:t,source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()})}return s}destroyEntity(t){let e=null;return e="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null,!!e&&(this._destroyedEntities.add(e.id),this.updateNameIndex(e,!1),this.updateTagIndex(e,!1),this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e),this._dirtyTrackingSystem.markDirty(e,DirtyFlag.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()}),e.destroy(),this._entities.delete(e.id),this._identifierPool.checkIn(e.id),!0)}getAllEntities(){return Array.from(this._entities.values())}getEntity(t){const e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null}getEntityByName(t){const e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null}getEntitiesByTag(t){return Array.from(this._entities.values()).filter((e=>e.tag===t))}getEntitiesWithComponent(t){const e=this._componentIndexManager.query(t);return Array.from(e)}query(){return new EntityQueryBuilder(this)}queryWithComponentIndex(t,e){return this._componentIndexManager.queryMultiple(t,e)}markEntityDirty(t,e){this._dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,e)}getOptimizationStats(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this._dirtyTrackingSystem.getStats()}}get eventBus(){return this._eventBus}updateNameIndex(t,e){if(t.name)if(e){let e=this._entitiesByName.get(t.name);e||(e=[],this._entitiesByName.set(t.name,e)),e.push(t)}else{const e=this._entitiesByName.get(t.name);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._entitiesByName.delete(t.name))}}}updateTagIndex(t,e){if(e){let e=this._entitiesByTag.get(t.tag);e||(e=[],this._entitiesByTag.set(t.tag,e)),e.push(t)}else{const e=this._entitiesByTag.get(t.tag);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._entitiesByTag.delete(t.tag))}}}}class TypeUtils{static getType(t){return t.constructor}}class NumberExtension{static toNumber(t){return null==t?0:Number(t)}}export{ArchetypeSystem,AsyncEventHandler,BigIntFactory,BitmapComponentIndex,Bits,Component,ComponentDataCollector,ComponentIndexManager,ComponentPool,ComponentPoolManager,ComponentRegistry,ComponentStorage,ComponentTypeManager,ConsoleLogger,Core,DebugManager,DirtyFlag,DirtyTrackingSystem,ECSEventType,ECSFluentAPI,EVENT_TYPES,Emitter,EnableSoA,Entity,EntityDataCollector,EntityList,EntityManager,EntityProcessorList,EntityQueryBuilder,EntitySystem,EventBus,EventHandler,EventPriority,EventTypeValidator,Float32,Float64,FuncPack,GlobalEventBus,GlobalManager,HashComponentIndex,HighPrecision,IdentifierPool,IndexType,Int32,IntervalSystem,LogLevel,Logger,LoggerManager,Matcher,NumberExtension,PassiveSystem,PerformanceDataCollector,PerformanceMonitor,PerformanceWarningType,Pool,PoolManager,ProcessingSystem,QuerySystem,Scene,SceneDataCollector,SerializeMap,SoAStorage,SystemDataCollector,Time,Timer,TimerManager,TypeSafeEventSystem,TypeUtils,WebSocketManager,createECSAPI,createLogger,setGlobalLogLevel};
2
+ //# sourceMappingURL=index.mjs.map