excalibur 0.28.3 → 0.28.4

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 (482) hide show
  1. package/.gitattributes +63 -63
  2. package/CHANGELOG.md +2003 -1955
  3. package/LICENSE.md +25 -25
  4. package/README.md +134 -134
  5. package/STYLEGUIDE.md +136 -136
  6. package/build/dist/Actions/Action/ActionSequence.js +31 -0
  7. package/build/dist/Actions/Action/ActionSequence.js.map +1 -0
  8. package/build/dist/Actions/Action/Blink.js +54 -0
  9. package/build/dist/Actions/Action/Blink.js.map +1 -0
  10. package/build/dist/Actions/Action/CallMethod.js +21 -0
  11. package/build/dist/Actions/Action/CallMethod.js.map +1 -0
  12. package/build/dist/Actions/Action/Delay.js +26 -0
  13. package/build/dist/Actions/Action/Delay.js.map +1 -0
  14. package/build/dist/Actions/Action/Die.js +22 -0
  15. package/build/dist/Actions/Action/Die.js.map +1 -0
  16. package/build/dist/Actions/Action/EaseBy.js +70 -0
  17. package/build/dist/Actions/Action/EaseBy.js.map +1 -0
  18. package/build/dist/Actions/Action/EaseTo.js +69 -0
  19. package/build/dist/Actions/Action/EaseTo.js.map +1 -0
  20. package/build/dist/Actions/Action/Fade.js +48 -0
  21. package/build/dist/Actions/Action/Fade.js.map +1 -0
  22. package/build/dist/Actions/Action/Follow.js +56 -0
  23. package/build/dist/Actions/Action/Follow.js.map +1 -0
  24. package/build/dist/Actions/Action/Meet.js +54 -0
  25. package/build/dist/Actions/Action/Meet.js.map +1 -0
  26. package/build/dist/Actions/Action/MoveBy.js +48 -0
  27. package/build/dist/Actions/Action/MoveBy.js.map +1 -0
  28. package/build/dist/Actions/Action/MoveTo.js +41 -0
  29. package/build/dist/Actions/Action/MoveTo.js.map +1 -0
  30. package/build/dist/Actions/Action/ParallelActions.js +23 -0
  31. package/build/dist/Actions/Action/ParallelActions.js.map +1 -0
  32. package/build/dist/Actions/Action/Repeat.js +31 -0
  33. package/build/dist/Actions/Action/Repeat.js.map +1 -0
  34. package/build/dist/Actions/Action/RepeatForever.js +37 -0
  35. package/build/dist/Actions/Action/RepeatForever.js.map +1 -0
  36. package/build/dist/Actions/Action/RotateBy.js +95 -0
  37. package/build/dist/Actions/Action/RotateBy.js.map +1 -0
  38. package/build/dist/Actions/Action/RotateTo.js +91 -0
  39. package/build/dist/Actions/Action/RotateTo.js.map +1 -0
  40. package/build/dist/Actions/Action/ScaleBy.js +46 -0
  41. package/build/dist/Actions/Action/ScaleBy.js.map +1 -0
  42. package/build/dist/Actions/Action/ScaleTo.js +58 -0
  43. package/build/dist/Actions/Action/ScaleTo.js.map +1 -0
  44. package/build/dist/Actions/Action.js +2 -0
  45. package/build/dist/Actions/Action.js.map +1 -0
  46. package/build/dist/Actions/ActionContext.js +322 -0
  47. package/build/dist/Actions/ActionContext.js.map +1 -0
  48. package/build/dist/Actions/ActionQueue.js +87 -0
  49. package/build/dist/Actions/ActionQueue.js.map +1 -0
  50. package/build/dist/Actions/Actionable.js +2 -0
  51. package/build/dist/Actions/Actionable.js.map +1 -0
  52. package/build/dist/Actions/ActionsComponent.js +195 -0
  53. package/build/dist/Actions/ActionsComponent.js.map +1 -0
  54. package/build/dist/Actions/ActionsSystem.js +30 -0
  55. package/build/dist/Actions/ActionsSystem.js.map +1 -0
  56. package/build/dist/Actions/Index.js +26 -0
  57. package/build/dist/Actions/Index.js.map +1 -0
  58. package/build/dist/Actions/RotationType.js +27 -0
  59. package/build/dist/Actions/RotationType.js.map +1 -0
  60. package/build/dist/Actor.js +629 -0
  61. package/build/dist/Actor.js.map +1 -0
  62. package/build/dist/Camera.js +660 -0
  63. package/build/dist/Camera.js.map +1 -0
  64. package/build/dist/Collision/BoundingBox.js +415 -0
  65. package/build/dist/Collision/BoundingBox.js.map +1 -0
  66. package/build/dist/Collision/ColliderComponent.js +202 -0
  67. package/build/dist/Collision/ColliderComponent.js.map +1 -0
  68. package/build/dist/Collision/Colliders/CircleCollider.js +226 -0
  69. package/build/dist/Collision/Colliders/CircleCollider.js.map +1 -0
  70. package/build/dist/Collision/Colliders/ClosestLineJumpTable.js +211 -0
  71. package/build/dist/Collision/Colliders/ClosestLineJumpTable.js.map +1 -0
  72. package/build/dist/Collision/Colliders/Collider.js +32 -0
  73. package/build/dist/Collision/Colliders/Collider.js.map +1 -0
  74. package/build/dist/Collision/Colliders/CollisionJumpTable.js +300 -0
  75. package/build/dist/Collision/Colliders/CollisionJumpTable.js.map +1 -0
  76. package/build/dist/Collision/Colliders/EdgeCollider.js +229 -0
  77. package/build/dist/Collision/Colliders/EdgeCollider.js.map +1 -0
  78. package/build/dist/Collision/Colliders/PolygonCollider.js +556 -0
  79. package/build/dist/Collision/Colliders/PolygonCollider.js.map +1 -0
  80. package/build/dist/Collision/Colliders/SeparatingAxis.js +67 -0
  81. package/build/dist/Collision/Colliders/SeparatingAxis.js.map +1 -0
  82. package/build/dist/Collision/Colliders/Shape.js +99 -0
  83. package/build/dist/Collision/Colliders/Shape.js.map +1 -0
  84. package/build/dist/Collision/CollisionType.js +33 -0
  85. package/build/dist/Collision/CollisionType.js.map +1 -0
  86. package/build/dist/Collision/Detection/CollisionContact.js +51 -0
  87. package/build/dist/Collision/Detection/CollisionContact.js.map +1 -0
  88. package/build/dist/Collision/Detection/CollisionProcessor.js +2 -0
  89. package/build/dist/Collision/Detection/CollisionProcessor.js.map +1 -0
  90. package/build/dist/Collision/Detection/DynamicTree.js +442 -0
  91. package/build/dist/Collision/Detection/DynamicTree.js.map +1 -0
  92. package/build/dist/Collision/Detection/Pair.js +92 -0
  93. package/build/dist/Collision/Detection/Pair.js.map +1 -0
  94. package/build/dist/Collision/Detection/QuadTree.js +193 -0
  95. package/build/dist/Collision/Detection/QuadTree.js.map +1 -0
  96. package/build/dist/Collision/Group/CollisionGroup.js +3 -3
  97. package/build/dist/Collision/Integrator.js +25 -0
  98. package/build/dist/Collision/Integrator.js.map +1 -0
  99. package/build/dist/Collision/MotionSystem.js +35 -0
  100. package/build/dist/Collision/MotionSystem.js.map +1 -0
  101. package/build/dist/Collision/Physics.js +163 -0
  102. package/build/dist/Collision/Physics.js.map +1 -0
  103. package/build/dist/Collision/PhysicsWorld.js +10 -0
  104. package/build/dist/Collision/PhysicsWorld.js.map +1 -0
  105. package/build/dist/Collision/Side.js +51 -0
  106. package/build/dist/Collision/Side.js.map +1 -0
  107. package/build/dist/Collision/Solver/ArcadeSolver.js +154 -0
  108. package/build/dist/Collision/Solver/ArcadeSolver.js.map +1 -0
  109. package/build/dist/Collision/Solver/ContactConstraintPoint.js +87 -0
  110. package/build/dist/Collision/Solver/ContactConstraintPoint.js.map +1 -0
  111. package/build/dist/Collision/Solver/RealisticSolver.js +293 -0
  112. package/build/dist/Collision/Solver/RealisticSolver.js.map +1 -0
  113. package/build/dist/Collision/Solver/Solver.js +2 -0
  114. package/build/dist/Collision/Solver/Solver.js.map +1 -0
  115. package/build/dist/Color.js +417 -0
  116. package/build/dist/Color.js.map +1 -0
  117. package/build/dist/Configurable.js +32 -0
  118. package/build/dist/Configurable.js.map +1 -0
  119. package/build/dist/Debug/Debug.d.ts +11 -0
  120. package/build/dist/Debug/Debug.js +385 -0
  121. package/build/dist/Debug/Debug.js.map +1 -0
  122. package/build/dist/Debug/DebugFlags.js +40 -0
  123. package/build/dist/Debug/DebugFlags.js.map +1 -0
  124. package/build/dist/Debug/DebugSystem.js +263 -0
  125. package/build/dist/Debug/DebugSystem.js.map +1 -0
  126. package/build/dist/Debug/index.js +4 -0
  127. package/build/dist/Debug/index.js.map +1 -0
  128. package/build/dist/Deprecated.js +2 -0
  129. package/build/dist/Deprecated.js.map +1 -0
  130. package/build/dist/Engine.js +986 -0
  131. package/build/dist/Engine.js.map +1 -0
  132. package/build/dist/EntityComponentSystem/Component.js +65 -0
  133. package/build/dist/EntityComponentSystem/Component.js.map +1 -0
  134. package/build/dist/EntityComponentSystem/Components/MotionComponent.js +33 -0
  135. package/build/dist/EntityComponentSystem/Components/MotionComponent.js.map +1 -0
  136. package/build/dist/EntityComponentSystem/Components/TransformComponent.js +107 -0
  137. package/build/dist/EntityComponentSystem/Components/TransformComponent.js.map +1 -0
  138. package/build/dist/EntityComponentSystem/Entity.js +487 -0
  139. package/build/dist/EntityComponentSystem/Entity.js.map +1 -0
  140. package/build/dist/EntityComponentSystem/EntityManager.js +137 -0
  141. package/build/dist/EntityComponentSystem/EntityManager.js.map +1 -0
  142. package/build/dist/EntityComponentSystem/Query.js +90 -0
  143. package/build/dist/EntityComponentSystem/Query.js.map +1 -0
  144. package/build/dist/EntityComponentSystem/QueryManager.js +90 -0
  145. package/build/dist/EntityComponentSystem/QueryManager.js.map +1 -0
  146. package/build/dist/EntityComponentSystem/System.js +76 -0
  147. package/build/dist/EntityComponentSystem/System.js.map +1 -0
  148. package/build/dist/EntityComponentSystem/SystemManager.js +104 -0
  149. package/build/dist/EntityComponentSystem/SystemManager.js.map +1 -0
  150. package/build/dist/EntityComponentSystem/Util.js +5 -0
  151. package/build/dist/EntityComponentSystem/Util.js.map +1 -0
  152. package/build/dist/EntityComponentSystem/World.js +55 -0
  153. package/build/dist/EntityComponentSystem/World.js.map +1 -0
  154. package/build/dist/EntityComponentSystem/index.js +11 -0
  155. package/build/dist/EntityComponentSystem/index.js.map +1 -0
  156. package/build/dist/EventDispatcher.js +122 -0
  157. package/build/dist/EventDispatcher.js.map +1 -0
  158. package/build/dist/EventEmitter.js +86 -0
  159. package/build/dist/EventEmitter.js.map +1 -0
  160. package/build/dist/Events/ExEvent.js +12 -0
  161. package/build/dist/Events/ExEvent.js.map +1 -0
  162. package/build/dist/Events/MediaEvents.js +75 -0
  163. package/build/dist/Events/MediaEvents.js.map +1 -0
  164. package/build/dist/Events/PointerEvents.js +52 -0
  165. package/build/dist/Events/PointerEvents.js.map +1 -0
  166. package/build/dist/Events.js +473 -0
  167. package/build/dist/Events.js.map +1 -0
  168. package/build/dist/Flags.js +67 -0
  169. package/build/dist/Flags.js.map +1 -0
  170. package/build/dist/Graphics/Animation.js +344 -0
  171. package/build/dist/Graphics/Animation.js.map +1 -0
  172. package/build/dist/Graphics/Canvas.js +38 -0
  173. package/build/dist/Graphics/Canvas.js.map +1 -0
  174. package/build/dist/Graphics/Circle.js +48 -0
  175. package/build/dist/Graphics/Circle.js.map +1 -0
  176. package/build/dist/Graphics/Context/ExcaliburGraphicsContext.js +2 -0
  177. package/build/dist/Graphics/Context/ExcaliburGraphicsContext.js.map +1 -0
  178. package/build/dist/Graphics/Context/ExcaliburGraphicsContext2DCanvas.js +237 -0
  179. package/build/dist/Graphics/Context/ExcaliburGraphicsContext2DCanvas.js.map +1 -0
  180. package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.d.ts +1 -0
  181. package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.js +481 -0
  182. package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.js.map +1 -0
  183. package/build/dist/Graphics/Context/circle-renderer/circle-renderer.frag.glsl +52 -52
  184. package/build/dist/Graphics/Context/circle-renderer/circle-renderer.js +174 -0
  185. package/build/dist/Graphics/Context/circle-renderer/circle-renderer.js.map +1 -0
  186. package/build/dist/Graphics/Context/circle-renderer/circle-renderer.vert.glsl +37 -37
  187. package/build/dist/Graphics/Context/debug-text.js +47 -0
  188. package/build/dist/Graphics/Context/debug-text.js.map +1 -0
  189. package/build/dist/Graphics/Context/draw-call.js +16 -0
  190. package/build/dist/Graphics/Context/draw-call.js.map +1 -0
  191. package/build/dist/Graphics/Context/image-renderer/image-renderer.frag.glsl +32 -32
  192. package/build/dist/Graphics/Context/image-renderer/image-renderer.js +246 -0
  193. package/build/dist/Graphics/Context/image-renderer/image-renderer.js.map +1 -0
  194. package/build/dist/Graphics/Context/image-renderer/image-renderer.vert.glsl +32 -32
  195. package/build/dist/Graphics/Context/line-renderer/line-fragment.glsl +10 -10
  196. package/build/dist/Graphics/Context/line-renderer/line-renderer.js +90 -0
  197. package/build/dist/Graphics/Context/line-renderer/line-renderer.js.map +1 -0
  198. package/build/dist/Graphics/Context/line-renderer/line-vertex.glsl +14 -14
  199. package/build/dist/Graphics/Context/material-renderer/material-renderer.js +23 -2
  200. package/build/dist/Graphics/Context/material-renderer/material-renderer.js.map +1 -1
  201. package/build/dist/Graphics/Context/material.d.ts +2 -0
  202. package/build/dist/Graphics/Context/material.js +72 -0
  203. package/build/dist/Graphics/Context/material.js.map +1 -0
  204. package/build/dist/Graphics/Context/point-renderer/point-fragment.glsl +19 -19
  205. package/build/dist/Graphics/Context/point-renderer/point-renderer.js +91 -0
  206. package/build/dist/Graphics/Context/point-renderer/point-renderer.js.map +1 -0
  207. package/build/dist/Graphics/Context/point-renderer/point-vertex.glsl +11 -11
  208. package/build/dist/Graphics/Context/quad-index-buffer.js +67 -0
  209. package/build/dist/Graphics/Context/quad-index-buffer.js.map +1 -0
  210. package/build/dist/Graphics/Context/rectangle-renderer/rectangle-renderer.frag.glsl +85 -85
  211. package/build/dist/Graphics/Context/rectangle-renderer/rectangle-renderer.js +305 -0
  212. package/build/dist/Graphics/Context/rectangle-renderer/rectangle-renderer.js.map +1 -0
  213. package/build/dist/Graphics/Context/rectangle-renderer/rectangle-renderer.vert.glsl +42 -42
  214. package/build/dist/Graphics/Context/render-source.js +16 -0
  215. package/build/dist/Graphics/Context/render-source.js.map +1 -0
  216. package/build/dist/Graphics/Context/render-target.js +65 -0
  217. package/build/dist/Graphics/Context/render-target.js.map +1 -0
  218. package/build/dist/Graphics/Context/renderer.js +2 -0
  219. package/build/dist/Graphics/Context/renderer.js.map +1 -0
  220. package/build/dist/Graphics/Context/screen-pass-painter/screen-fragment.glsl +13 -13
  221. package/build/dist/Graphics/Context/screen-pass-painter/screen-pass-painter.js +56 -0
  222. package/build/dist/Graphics/Context/screen-pass-painter/screen-pass-painter.js.map +1 -0
  223. package/build/dist/Graphics/Context/screen-pass-painter/screen-vertex.glsl +11 -11
  224. package/build/dist/Graphics/Context/state-stack.js +37 -0
  225. package/build/dist/Graphics/Context/state-stack.js.map +1 -0
  226. package/build/dist/Graphics/Context/texture-loader.js +109 -0
  227. package/build/dist/Graphics/Context/texture-loader.js.map +1 -0
  228. package/build/dist/Graphics/Context/transform-stack.js +30 -0
  229. package/build/dist/Graphics/Context/transform-stack.js.map +1 -0
  230. package/build/dist/Graphics/Context/vertex-buffer.js +53 -0
  231. package/build/dist/Graphics/Context/vertex-buffer.js.map +1 -0
  232. package/build/dist/Graphics/Context/webgl-util.js +79 -0
  233. package/build/dist/Graphics/Context/webgl-util.js.map +1 -0
  234. package/build/dist/Graphics/DebugGraphicsComponent.d.ts +3 -2
  235. package/build/dist/Graphics/DebugGraphicsComponent.js +16 -0
  236. package/build/dist/Graphics/DebugGraphicsComponent.js.map +1 -0
  237. package/build/dist/Graphics/Filtering.js +17 -0
  238. package/build/dist/Graphics/Filtering.js.map +1 -0
  239. package/build/dist/Graphics/Font.js +148 -0
  240. package/build/dist/Graphics/Font.js.map +1 -0
  241. package/build/dist/Graphics/FontCache.d.ts +1 -0
  242. package/build/dist/Graphics/FontCache.js +80 -0
  243. package/build/dist/Graphics/FontCache.js.map +1 -0
  244. package/build/dist/Graphics/FontCommon.js +109 -0
  245. package/build/dist/Graphics/FontCommon.js.map +1 -0
  246. package/build/dist/Graphics/FontTextInstance.js +230 -0
  247. package/build/dist/Graphics/FontTextInstance.js.map +1 -0
  248. package/build/dist/Graphics/Graphic.js +208 -0
  249. package/build/dist/Graphics/Graphic.js.map +1 -0
  250. package/build/dist/Graphics/GraphicsComponent.js +336 -0
  251. package/build/dist/Graphics/GraphicsComponent.js.map +1 -0
  252. package/build/dist/Graphics/GraphicsDiagnostics.js +9 -0
  253. package/build/dist/Graphics/GraphicsDiagnostics.js.map +1 -0
  254. package/build/dist/Graphics/GraphicsGroup.js +69 -0
  255. package/build/dist/Graphics/GraphicsGroup.js.map +1 -0
  256. package/build/dist/Graphics/GraphicsSystem.js +210 -0
  257. package/build/dist/Graphics/GraphicsSystem.js.map +1 -0
  258. package/build/dist/Graphics/ImageSource.js +124 -0
  259. package/build/dist/Graphics/ImageSource.js.map +1 -0
  260. package/build/dist/Graphics/Line.js +45 -0
  261. package/build/dist/Graphics/Line.js.map +1 -0
  262. package/build/dist/Graphics/OffscreenSystem.js +64 -0
  263. package/build/dist/Graphics/OffscreenSystem.js.map +1 -0
  264. package/build/dist/Graphics/ParallaxComponent.js +11 -0
  265. package/build/dist/Graphics/ParallaxComponent.js.map +1 -0
  266. package/build/dist/Graphics/Polygon.js +59 -0
  267. package/build/dist/Graphics/Polygon.js.map +1 -0
  268. package/build/dist/Graphics/PostProcessor/ColorBlindnessMode.js +7 -0
  269. package/build/dist/Graphics/PostProcessor/ColorBlindnessMode.js.map +1 -0
  270. package/build/dist/Graphics/PostProcessor/ColorBlindnessPostProcessor.js +52 -0
  271. package/build/dist/Graphics/PostProcessor/ColorBlindnessPostProcessor.js.map +1 -0
  272. package/build/dist/Graphics/PostProcessor/PostProcessor.js +2 -0
  273. package/build/dist/Graphics/PostProcessor/PostProcessor.js.map +1 -0
  274. package/build/dist/Graphics/PostProcessor/ScreenShader.js +59 -0
  275. package/build/dist/Graphics/PostProcessor/ScreenShader.js.map +1 -0
  276. package/build/dist/Graphics/PostProcessor/color-blind-fragment.glsl +64 -64
  277. package/build/dist/Graphics/Raster.js +215 -0
  278. package/build/dist/Graphics/Raster.js.map +1 -0
  279. package/build/dist/Graphics/Rectangle.js +29 -0
  280. package/build/dist/Graphics/Rectangle.js.map +1 -0
  281. package/build/dist/Graphics/Sprite.js +82 -0
  282. package/build/dist/Graphics/Sprite.js.map +1 -0
  283. package/build/dist/Graphics/SpriteFont.js +139 -0
  284. package/build/dist/Graphics/SpriteFont.js.map +1 -0
  285. package/build/dist/Graphics/SpriteSheet.js +116 -0
  286. package/build/dist/Graphics/SpriteSheet.js.map +1 -0
  287. package/build/dist/Graphics/Text.js +103 -0
  288. package/build/dist/Graphics/Text.js.map +1 -0
  289. package/build/dist/Graphics/index.js +46 -0
  290. package/build/dist/Graphics/index.js.map +1 -0
  291. package/build/dist/Id.js +8 -0
  292. package/build/dist/Id.js.map +1 -0
  293. package/build/dist/Input/CapturePointerConfig.js +5 -0
  294. package/build/dist/Input/CapturePointerConfig.js.map +1 -0
  295. package/build/dist/Input/EngineInput.js +2 -0
  296. package/build/dist/Input/EngineInput.js.map +1 -0
  297. package/build/dist/Input/Gamepad.js +422 -0
  298. package/build/dist/Input/Gamepad.js.map +1 -0
  299. package/build/dist/Input/Index.js +88 -0
  300. package/build/dist/Input/Index.js.map +1 -0
  301. package/build/dist/Input/InputMapper.js +45 -0
  302. package/build/dist/Input/InputMapper.js.map +1 -0
  303. package/build/dist/Input/Keyboard.js +348 -0
  304. package/build/dist/Input/Keyboard.js.map +1 -0
  305. package/build/dist/Input/NativePointerButton.js +12 -0
  306. package/build/dist/Input/NativePointerButton.js.map +1 -0
  307. package/build/dist/Input/PointerAbstraction.js +44 -0
  308. package/build/dist/Input/PointerAbstraction.js.map +1 -0
  309. package/build/dist/Input/PointerButton.js +12 -0
  310. package/build/dist/Input/PointerButton.js.map +1 -0
  311. package/build/dist/Input/PointerComponent.js +28 -0
  312. package/build/dist/Input/PointerComponent.js.map +1 -0
  313. package/build/dist/Input/PointerEvent.js +25 -0
  314. package/build/dist/Input/PointerEvent.js.map +1 -0
  315. package/build/dist/Input/PointerEventReceiver.js +456 -0
  316. package/build/dist/Input/PointerEventReceiver.js.map +1 -0
  317. package/build/dist/Input/PointerScope.js +16 -0
  318. package/build/dist/Input/PointerScope.js.map +1 -0
  319. package/build/dist/Input/PointerSystem.js +249 -0
  320. package/build/dist/Input/PointerSystem.js.map +1 -0
  321. package/build/dist/Input/PointerType.js +11 -0
  322. package/build/dist/Input/PointerType.js.map +1 -0
  323. package/build/dist/Input/WheelDeltaMode.js +7 -0
  324. package/build/dist/Input/WheelDeltaMode.js.map +1 -0
  325. package/build/dist/Input/WheelEvent.js +21 -0
  326. package/build/dist/Input/WheelEvent.js.map +1 -0
  327. package/build/dist/Interfaces/Audio.js +2 -0
  328. package/build/dist/Interfaces/Audio.js.map +1 -0
  329. package/build/dist/Interfaces/AudioImplementation.js +11 -0
  330. package/build/dist/Interfaces/AudioImplementation.js.map +1 -0
  331. package/build/dist/Interfaces/Clonable.js +2 -0
  332. package/build/dist/Interfaces/Clonable.js.map +1 -0
  333. package/build/dist/Interfaces/Evented.js +2 -0
  334. package/build/dist/Interfaces/Evented.js.map +1 -0
  335. package/build/dist/Interfaces/Index.js +8 -0
  336. package/build/dist/Interfaces/Index.js.map +1 -0
  337. package/build/dist/Interfaces/LifecycleEvents.js +51 -0
  338. package/build/dist/Interfaces/LifecycleEvents.js.map +1 -0
  339. package/build/dist/Interfaces/Loadable.js +2 -0
  340. package/build/dist/Interfaces/Loadable.js.map +1 -0
  341. package/build/dist/Interfaces/PointerEventHandlers.js +2 -0
  342. package/build/dist/Interfaces/PointerEventHandlers.js.map +1 -0
  343. package/build/dist/Label.js +81 -0
  344. package/build/dist/Label.js.map +1 -0
  345. package/build/dist/Loader.js +416 -0
  346. package/build/dist/Loader.js.map +1 -0
  347. package/build/dist/Math/Index.js +13 -0
  348. package/build/dist/Math/Index.js.map +1 -0
  349. package/build/dist/Math/Random.js +239 -0
  350. package/build/dist/Math/Random.js.map +1 -0
  351. package/build/dist/Math/affine-matrix.js +331 -0
  352. package/build/dist/Math/affine-matrix.js.map +1 -0
  353. package/build/dist/Math/coord-plane.js +17 -0
  354. package/build/dist/Math/coord-plane.js.map +1 -0
  355. package/build/dist/Math/global-coordinates.js +30 -0
  356. package/build/dist/Math/global-coordinates.js.map +1 -0
  357. package/build/dist/Math/line-segment.js +205 -0
  358. package/build/dist/Math/line-segment.js.map +1 -0
  359. package/build/dist/Math/matrix.js +457 -0
  360. package/build/dist/Math/matrix.js.map +1 -0
  361. package/build/dist/Math/projection.js +24 -0
  362. package/build/dist/Math/projection.js.map +1 -0
  363. package/build/dist/Math/ray.js +52 -0
  364. package/build/dist/Math/ray.js.map +1 -0
  365. package/build/dist/Math/transform.js +219 -0
  366. package/build/dist/Math/transform.js.map +1 -0
  367. package/build/dist/Math/util.js +82 -0
  368. package/build/dist/Math/util.js.map +1 -0
  369. package/build/dist/Math/vector-view.js +25 -0
  370. package/build/dist/Math/vector-view.js.map +1 -0
  371. package/build/dist/Math/vector.js +340 -0
  372. package/build/dist/Math/vector.js.map +1 -0
  373. package/build/dist/Math/watch-vector.js +26 -0
  374. package/build/dist/Math/watch-vector.js.map +1 -0
  375. package/build/dist/Particles.js +430 -0
  376. package/build/dist/Particles.js.map +1 -0
  377. package/build/dist/Polyfill.js +56 -0
  378. package/build/dist/Polyfill.js.map +1 -0
  379. package/build/dist/Resources/Gif.js +464 -0
  380. package/build/dist/Resources/Gif.js.map +1 -0
  381. package/build/dist/Resources/Index.js +4 -0
  382. package/build/dist/Resources/Index.js.map +1 -0
  383. package/build/dist/Resources/Resource.js +81 -0
  384. package/build/dist/Resources/Resource.js.map +1 -0
  385. package/build/dist/Resources/Sound/AudioContext.js +16 -0
  386. package/build/dist/Resources/Sound/AudioContext.js.map +1 -0
  387. package/build/dist/Resources/Sound/Index.js +4 -0
  388. package/build/dist/Resources/Sound/Index.js.map +1 -0
  389. package/build/dist/Resources/Sound/Sound.js +326 -0
  390. package/build/dist/Resources/Sound/Sound.js.map +1 -0
  391. package/build/dist/Resources/Sound/WebAudioInstance.js +190 -0
  392. package/build/dist/Resources/Sound/WebAudioInstance.js.map +1 -0
  393. package/build/dist/Scene.js +444 -0
  394. package/build/dist/Scene.js.map +1 -0
  395. package/build/dist/Screen.js +782 -0
  396. package/build/dist/Screen.js.map +1 -0
  397. package/build/dist/ScreenElement.js +43 -0
  398. package/build/dist/ScreenElement.js.map +1 -0
  399. package/build/dist/TileMap/IsometricEntityComponent.js +17 -0
  400. package/build/dist/TileMap/IsometricEntityComponent.js.map +1 -0
  401. package/build/dist/TileMap/IsometricEntitySystem.js +23 -0
  402. package/build/dist/TileMap/IsometricEntitySystem.js.map +1 -0
  403. package/build/dist/TileMap/IsometricMap.js +311 -0
  404. package/build/dist/TileMap/IsometricMap.js.map +1 -0
  405. package/build/dist/TileMap/TileMap.d.ts +2 -1
  406. package/build/dist/TileMap/TileMap.js +630 -0
  407. package/build/dist/TileMap/TileMap.js.map +1 -0
  408. package/build/dist/TileMap/index.js +5 -0
  409. package/build/dist/TileMap/index.js.map +1 -0
  410. package/build/dist/Timer.js +202 -0
  411. package/build/dist/Timer.js.map +1 -0
  412. package/build/dist/Trigger.js +94 -0
  413. package/build/dist/Trigger.js.map +1 -0
  414. package/build/dist/Util/Browser.js +66 -0
  415. package/build/dist/Util/Browser.js.map +1 -0
  416. package/build/dist/Util/Clock.js +219 -0
  417. package/build/dist/Util/Clock.js.map +1 -0
  418. package/build/dist/Util/Decorators.js +78 -0
  419. package/build/dist/Util/Decorators.js.map +1 -0
  420. package/build/dist/Util/Detector.js +167 -0
  421. package/build/dist/Util/Detector.js.map +1 -0
  422. package/build/dist/Util/DrawUtil.js +115 -0
  423. package/build/dist/Util/DrawUtil.js.map +1 -0
  424. package/build/dist/Util/EasingFunctions.js +102 -0
  425. package/build/dist/Util/EasingFunctions.js.map +1 -0
  426. package/build/dist/Util/Fps.js +47 -0
  427. package/build/dist/Util/Fps.js.map +1 -0
  428. package/build/dist/Util/Future.js +30 -0
  429. package/build/dist/Util/Future.js.map +1 -0
  430. package/build/dist/Util/IFrame.js +23 -0
  431. package/build/dist/Util/IFrame.js.map +1 -0
  432. package/build/dist/Util/Index.js +7 -0
  433. package/build/dist/Util/Index.js.map +1 -0
  434. package/build/dist/Util/Log.js +195 -0
  435. package/build/dist/Util/Log.js.map +1 -0
  436. package/build/dist/Util/Observable.js +66 -0
  437. package/build/dist/Util/Observable.js.map +1 -0
  438. package/build/dist/Util/Pool.js +74 -0
  439. package/build/dist/Util/Pool.js.map +1 -0
  440. package/build/dist/Util/Semaphore.js +55 -0
  441. package/build/dist/Util/Semaphore.js.map +1 -0
  442. package/build/dist/Util/Sound.js +22 -0
  443. package/build/dist/Util/Sound.js.map +1 -0
  444. package/build/dist/Util/StateMachine.js +79 -0
  445. package/build/dist/Util/StateMachine.js.map +1 -0
  446. package/build/dist/Util/Toaster.css +28 -28
  447. package/build/dist/Util/Toaster.js +84 -0
  448. package/build/dist/Util/Toaster.js.map +1 -0
  449. package/build/dist/Util/Util.d.ts +6 -0
  450. package/build/dist/Util/Util.js +95 -0
  451. package/build/dist/Util/Util.js.map +1 -0
  452. package/build/dist/Util/Watch.js +67 -0
  453. package/build/dist/Util/Watch.js.map +1 -0
  454. package/build/dist/Util/WebAudio.js +62 -0
  455. package/build/dist/Util/WebAudio.js.map +1 -0
  456. package/build/dist/excalibur.d.ts +2 -2
  457. package/build/dist/excalibur.js +389 -258
  458. package/build/dist/excalibur.js.map +1 -1
  459. package/build/dist/excalibur.min.js +1 -1
  460. package/build/dist/excalibur.min.js.LICENSE.txt +1 -1
  461. package/build/dist/excalibur.min.js.map +1 -1
  462. package/build/dist/index.js +81 -0
  463. package/build/dist/index.js.map +1 -0
  464. package/build/esm/Debug/Debug.d.ts +11 -0
  465. package/build/esm/Graphics/Context/ExcaliburGraphicsContextWebGL.d.ts +1 -0
  466. package/build/esm/Graphics/Context/material.d.ts +2 -0
  467. package/build/esm/Graphics/DebugGraphicsComponent.d.ts +3 -2
  468. package/build/esm/Graphics/FontCache.d.ts +1 -0
  469. package/build/esm/TileMap/TileMap.d.ts +2 -1
  470. package/build/esm/Util/Util.d.ts +6 -0
  471. package/build/esm/excalibur.d.ts +2 -2
  472. package/build/esm/excalibur.js +389 -258
  473. package/build/esm/excalibur.js.map +1 -1
  474. package/build/esm/excalibur.min.js +1 -1
  475. package/build/esm/excalibur.min.js.LICENSE.txt +1 -1
  476. package/build/esm/excalibur.min.js.map +1 -1
  477. package/docker-compose.yml +11 -11
  478. package/package.json +131 -131
  479. package/build/dist/Loader.css +0 -122
  480. package/build/nuget/Excalibur.0.28.3.nupkg +0 -0
  481. package/build/v0.28.3.zip +0 -0
  482. package/excalibur-0.28.3.tgz +0 -0
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see excalibur.min.js.LICENSE.txt */
2
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ex=e():t.ex=e()}(self,(()=>(()=>{"use strict";var t={1388:(t,e,i)=>{i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n","",{version:3,sources:["webpack://./Loader.css"],names:[],mappings:"AAAA,yBAAyB;;AAEzB;EACE,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,kBAAkB;EAClB,YAAY;EACZ;;+BAE6B;EAC7B,8BAA8B;EAC9B,SAAS;EACT,qBAAqB;EACrB,mBAAmB;EACnB,cAAc;EACd,uBAAuB;EACvB,eAAe;EACf,mBAAmB;EACnB,cAAc;EACd,eAAe;EACf,kBAAkB;EAClB,8DAA8D;EAC9D,wBAAwB;EACxB,qBAAqB;;EAErB,gDAAgD,EAAE,oCAAoC;EACtF,6CAA6C,EAAE,iBAAiB;EAChE,4CAA4C,EAAE,sBAAsB;EACpE,2CAA2C,EAAE,iBAAiB;EAC9D,wCAAwC;AAC1C;;AAEA;;;EAGE;;AAEF;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,uDAAuD;EACvD,UAAU;EACV,SAAS;EACT,QAAQ;EACR,SAAS;AACX;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,WAAW;EACX,YAAY;AACd;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA;EACE,uBAAuB;EACvB,oBAAoB;AACtB;;AAEA;EACE,sBAAsB;AACxB;;AAEA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,oCAAoC;AACpC;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,sBAAsB;AACtB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF",sourcesContent:["/* Buttons styles start */\r\n\r\nbutton#excalibur-play {\r\n display: inline-block;\r\n position: relative;\r\n z-index: 999;\r\n border-radius: 6px;\r\n border: none;\r\n /*border: 3px solid;\r\n border-color: white;\r\n box-shadow: 0 0 10px #ccc;*/\r\n padding: 1rem 1.5rem 1rem 4rem;\r\n margin: 0;\r\n text-decoration: none;\r\n background: #00b233;\r\n color: #ffffff;\r\n font-family: sans-serif;\r\n font-size: 2rem;\r\n white-space: nowrap;\r\n line-height: 1;\r\n cursor: pointer;\r\n text-align: center;\r\n transition: background 250ms ease-in-out, transform 150ms ease;\r\n -webkit-appearance: none;\r\n -moz-appearance: none;\r\n\r\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\r\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\r\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\r\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\r\n animation: excalibur-button-fadein 200ms;\r\n}\r\n\r\n/*\r\nbutton#excalibur-play {\r\n display: none;\r\n}*/\r\n\r\nbutton#excalibur-play:after {\r\n position: absolute;\r\n content: '';\r\n border: 8px solid;\r\n border-color: transparent transparent transparent white;\r\n left: 35px;\r\n top: 24px;\r\n width: 0;\r\n height: 0;\r\n}\r\n\r\nbutton#excalibur-play:before {\r\n position: absolute;\r\n content: '';\r\n border: 3px solid;\r\n left: 19px;\r\n top: 14px;\r\n border-radius: 20px;\r\n width: 30px;\r\n height: 30px;\r\n}\r\n\r\nbutton#excalibur-play:hover,\r\nbutton#excalibur-play:focus {\r\n background: #00982c;\r\n}\r\n\r\nbutton#excalibur-play:focus {\r\n outline: 1px solid #fff;\r\n outline-offset: -4px;\r\n}\r\n\r\nbutton#excalibur-play:active {\r\n transform: scale(0.99);\r\n}\r\n\r\n@keyframes excalibur-button-fadein {\r\n from {\r\n opacity: 0;\r\n }\r\n to {\r\n opacity: 1;\r\n }\r\n}\r\n\r\n/* Firefox < 16 */\r\n@-moz-keyframes excalibur-button-fadein {\r\n from {\r\n opacity: 0;\r\n }\r\n to {\r\n opacity: 1;\r\n }\r\n}\r\n\r\n/* Safari, Chrome and Opera > 12.1 */\r\n@-webkit-keyframes excalibur-button-fadein {\r\n from {\r\n opacity: 0;\r\n }\r\n to {\r\n opacity: 1;\r\n }\r\n}\r\n\r\n/* Internet Explorer */\r\n@-ms-keyframes excalibur-button-fadein {\r\n from {\r\n opacity: 0;\r\n }\r\n to {\r\n opacity: 1;\r\n }\r\n}\r\n\r\n/* Opera < 12.1 */\r\n@-o-keyframes excalibur-button-fadein {\r\n from {\r\n opacity: 0;\r\n }\r\n to {\r\n opacity: 1;\r\n }\r\n}\r\n"],sourceRoot:""}]);const a=o},7379:(t,e,i)=>{i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"\n#ex-toast-container {\n position: absolute;\n height: 0;\n min-width: 50%;\n left: 50%;\n top: 0;\n}\n\n.ex-toast-message {\n left: -50%;\n position: relative;\n display: flex;\n justify-content: space-between;\n\n\n padding: 10px;\n margin-top: 5px;\n font-size: 18px;\n font-family: sans-serif;\n border-radius: 6px;\n border: 3px solid #b7b779;\n background-color: rgb(253, 253, 192);\n}\n\n\n.ex-toast-message button {\n align-self: flex-start;\n}","",{version:3,sources:["webpack://./Util/Toaster.css"],names:[],mappings:";AACA;EACE,kBAAkB;EAClB,SAAS;EACT,cAAc;EACd,SAAS;EACT,MAAM;AACR;;AAEA;EACE,UAAU;EACV,kBAAkB;EAClB,aAAa;EACb,8BAA8B;;;EAG9B,aAAa;EACb,eAAe;EACf,eAAe;EACf,uBAAuB;EACvB,kBAAkB;EAClB,yBAAyB;EACzB,oCAAoC;AACtC;;;AAGA;EACE,sBAAsB;AACxB",sourcesContent:["\r\n#ex-toast-container {\r\n position: absolute;\r\n height: 0;\r\n min-width: 50%;\r\n left: 50%;\r\n top: 0;\r\n}\r\n\r\n.ex-toast-message {\r\n left: -50%;\r\n position: relative;\r\n display: flex;\r\n justify-content: space-between;\r\n\r\n\r\n padding: 10px;\r\n margin-top: 5px;\r\n font-size: 18px;\r\n font-family: sans-serif;\r\n border-radius: 6px;\r\n border: 3px solid #b7b779;\r\n background-color: rgb(253, 253, 192);\r\n}\r\n\r\n\r\n.ex-toast-message button {\r\n align-self: flex-start;\r\n}"],sourceRoot:""}]);const a=o},2609:t=>{t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var i="",s=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),s&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),s&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i})).join("")},e.i=function(t,i,s,n,r){"string"==typeof t&&(t=[[null,t,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var h=this[a][0];null!=h&&(o[h]=!0)}for(var l=0;l<t.length;l++){var c=[].concat(t[l]);s&&o[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),n&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=n):c[4]="".concat(n)),e.push(c))}},e}},272:t=>{t.exports=function(t){var e=t[1],i=t[3];if(!i)return e;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),n="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),r="/*# ".concat(n," */");return[e].concat([r]).join("\n")}return[e].join("\n")}},1324:(t,e,i)=>{i(7206);var s=i(8193);t.exports=s("Array","sort")},3571:(t,e,i)=>{i(9867);var s=i(8588);t.exports=s.Object.keys},1052:(t,e,i)=>{var s=i(688),n=i(3397),r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not a function")}},9175:(t,e,i)=>{var s=i(5309),n=String,r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not an object")}},1138:(t,e,i)=>{var s=i(6854),n=i(7352),r=i(8344),o=function(t){return function(e,i,o){var a,h=s(e),l=r(h),c=n(o,l);if(t&&i!=i){for(;l>c;)if((a=h[c++])!=a)return!0}else for(;l>c;c++)if((t||c in h)&&h[c]===i)return t||c||0;return!t&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},567:(t,e,i)=>{var s=i(4694);t.exports=function(t,e){var i=[][t];return!!i&&s((function(){i.call(null,e||function(){return 1},1)}))}},6403:(t,e,i)=>{var s=i(7352),n=i(8344),r=i(3182),o=Array,a=Math.max;t.exports=function(t,e,i){for(var h=n(t),l=s(e,h),c=s(void 0===i?h:i,h),d=o(a(c-l,0)),u=0;l<c;l++,u++)r(d,u,t[l]);return d.length=u,d}},3097:(t,e,i)=>{var s=i(6403),n=Math.floor,r=function(t,e){var i=t.length,h=n(i/2);return i<8?o(t,e):a(t,r(s(t,0,h),e),r(s(t,h),e),e)},o=function(t,e){for(var i,s,n=t.length,r=1;r<n;){for(s=r,i=t[r];s&&e(t[s-1],i)>0;)t[s]=t[--s];s!==r++&&(t[s]=i)}return t},a=function(t,e,i,s){for(var n=e.length,r=i.length,o=0,a=0;o<n||a<r;)t[o+a]=o<n&&a<r?s(e[o],i[a])<=0?e[o++]:i[a++]:o<n?e[o++]:i[a++];return t};t.exports=r},2177:(t,e,i)=>{var s=i(9668),n=s({}.toString),r=s("".slice);t.exports=function(t){return r(n(t),8,-1)}},1566:(t,e,i)=>{var s=i(2522),n=i(688),r=i(2177),o=i(2032)("toStringTag"),a=Object,h="Arguments"===r(function(){return arguments}());t.exports=s?r:function(t){var e,i,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=a(t),o))?i:h?r(e):"Object"===(s=r(e))&&n(e.callee)?"Arguments":s}},3891:(t,e,i)=>{var s=i(4678),n=i(990),r=i(7537),o=i(2131);t.exports=function(t,e,i){for(var a=n(e),h=o.f,l=r.f,c=0;c<a.length;c++){var d=a[c];s(t,d)||i&&s(i,d)||h(t,d,l(e,d))}}},2385:(t,e,i)=>{var s=i(9924),n=i(2131),r=i(7781);t.exports=s?function(t,e,i){return n.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}},7781:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},3182:(t,e,i)=>{var s=i(2358),n=i(2131),r=i(7781);t.exports=function(t,e,i){var o=s(e);o in t?n.f(t,o,r(0,i)):t[o]=i}},2470:(t,e,i)=>{var s=i(688),n=i(2131),r=i(1135),o=i(1604);t.exports=function(t,e,i,a){a||(a={});var h=a.enumerable,l=void 0!==a.name?a.name:e;if(s(i)&&r(i,l,a),a.global)h?t[e]=i:o(e,i);else{try{a.unsafe?t[e]&&(h=!0):delete t[e]}catch(t){}h?t[e]=i:n.f(t,e,{value:i,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return t}},1604:(t,e,i)=>{var s=i(2150),n=Object.defineProperty;t.exports=function(t,e){try{n(s,t,{value:e,configurable:!0,writable:!0})}catch(i){s[t]=e}return e}},955:(t,e,i)=>{var s=i(3397),n=TypeError;t.exports=function(t,e){if(!delete t[e])throw new n("Cannot delete property "+s(e)+" of "+s(t))}},9924:(t,e,i)=>{var s=i(4694);t.exports=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}))},1811:t=>{var e="object"==typeof document&&document.all,i=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:i}},1442:(t,e,i)=>{var s=i(2150),n=i(5309),r=s.document,o=n(r)&&n(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},9016:(t,e,i)=>{var s=i(1370).match(/firefox\/(\d+)/i);t.exports=!!s&&+s[1]},821:(t,e,i)=>{var s=i(1370);t.exports=/MSIE|Trident/.test(s)},1370:t=>{t.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},7067:(t,e,i)=>{var s,n,r=i(2150),o=i(1370),a=r.process,h=r.Deno,l=a&&a.versions||h&&h.version,c=l&&l.v8;c&&(n=(s=c.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1])),!n&&o&&(!(s=o.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=o.match(/Chrome\/(\d+)/))&&(n=+s[1]),t.exports=n},4389:(t,e,i)=>{var s=i(1370).match(/AppleWebKit\/(\d+)\./);t.exports=!!s&&+s[1]},8193:(t,e,i)=>{var s=i(2150),n=i(9668);t.exports=function(t,e){return n(s[t].prototype[e])}},2367:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},5532:(t,e,i)=>{var s=i(2150),n=i(7537).f,r=i(2385),o=i(2470),a=i(1604),h=i(3891),l=i(1633);t.exports=function(t,e){var i,c,d,u,p,_=t.target,g=t.global,m=t.stat;if(i=g?s:m?s[_]||a(_,{}):(s[_]||{}).prototype)for(c in e){if(u=e[c],d=t.dontCallGetSet?(p=n(i,c))&&p.value:i[c],!l(g?c:_+(m?".":"#")+c,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;h(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0),o(i,c,u,t)}}},4694:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},6398:(t,e,i)=>{var s=i(4694);t.exports=!s((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},8724:(t,e,i)=>{var s=i(6398),n=Function.prototype.call;t.exports=s?n.bind(n):function(){return n.apply(n,arguments)}},453:(t,e,i)=>{var s=i(9924),n=i(4678),r=Function.prototype,o=s&&Object.getOwnPropertyDescriptor,a=n(r,"name"),h=a&&"something"===function(){}.name,l=a&&(!s||s&&o(r,"name").configurable);t.exports={EXISTS:a,PROPER:h,CONFIGURABLE:l}},9668:(t,e,i)=>{var s=i(6398),n=Function.prototype,r=n.call,o=s&&n.bind.bind(r,r);t.exports=s?o:function(t){return function(){return r.apply(t,arguments)}}},2160:(t,e,i)=>{var s=i(2150),n=i(688);t.exports=function(t,e){return arguments.length<2?(i=s[t],n(i)?i:void 0):s[t]&&s[t][e];var i}},5383:(t,e,i)=>{var s=i(1052),n=i(5268);t.exports=function(t,e){var i=t[e];return n(i)?void 0:s(i)}},2150:function(t,e,i){var s=function(t){return t&&t.Math===Math&&t};t.exports=s("object"==typeof globalThis&&globalThis)||s("object"==typeof window&&window)||s("object"==typeof self&&self)||s("object"==typeof i.g&&i.g)||s("object"==typeof this&&this)||function(){return this}()||Function("return this")()},4678:(t,e,i)=>{var s=i(9668),n=i(298),r=s({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return r(n(t),e)}},7390:t=>{t.exports={}},7913:(t,e,i)=>{var s=i(9924),n=i(4694),r=i(1442);t.exports=!s&&!n((function(){return 7!==Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},4347:(t,e,i)=>{var s=i(9668),n=i(4694),r=i(2177),o=Object,a=s("".split);t.exports=n((function(){return!o("z").propertyIsEnumerable(0)}))?function(t){return"String"===r(t)?a(t,""):o(t)}:o},1881:(t,e,i)=>{var s=i(9668),n=i(688),r=i(6762),o=s(Function.toString);n(r.inspectSource)||(r.inspectSource=function(t){return o(t)}),t.exports=r.inspectSource},7804:(t,e,i)=>{var s,n,r,o=i(4724),a=i(2150),h=i(5309),l=i(2385),c=i(4678),d=i(6762),u=i(1962),p=i(7390),_="Object already initialized",g=a.TypeError,m=a.WeakMap;if(o||d.state){var f=d.state||(d.state=new m);f.get=f.get,f.has=f.has,f.set=f.set,s=function(t,e){if(f.has(t))throw new g(_);return e.facade=t,f.set(t,e),e},n=function(t){return f.get(t)||{}},r=function(t){return f.has(t)}}else{var v=u("state");p[v]=!0,s=function(t,e){if(c(t,v))throw new g(_);return e.facade=t,l(t,v,e),e},n=function(t){return c(t,v)?t[v]:{}},r=function(t){return c(t,v)}}t.exports={set:s,get:n,has:r,enforce:function(t){return r(t)?n(t):s(t,{})},getterFor:function(t){return function(e){var i;if(!h(e)||(i=n(e)).type!==t)throw new g("Incompatible receiver, "+t+" required");return i}}}},688:(t,e,i)=>{var s=i(1811),n=s.all;t.exports=s.IS_HTMLDDA?function(t){return"function"==typeof t||t===n}:function(t){return"function"==typeof t}},1633:(t,e,i)=>{var s=i(4694),n=i(688),r=/#|\.prototype\./,o=function(t,e){var i=h[a(t)];return i===c||i!==l&&(n(e)?s(e):!!e)},a=o.normalize=function(t){return String(t).replace(r,".").toLowerCase()},h=o.data={},l=o.NATIVE="N",c=o.POLYFILL="P";t.exports=o},5268:t=>{t.exports=function(t){return null==t}},5309:(t,e,i)=>{var s=i(688),n=i(1811),r=n.all;t.exports=n.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:s(t)||t===r}:function(t){return"object"==typeof t?null!==t:s(t)}},6555:t=>{t.exports=!1},7935:(t,e,i)=>{var s=i(2160),n=i(688),r=i(6148),o=i(4866),a=Object;t.exports=o?function(t){return"symbol"==typeof t}:function(t){var e=s("Symbol");return n(e)&&r(e.prototype,a(t))}},8344:(t,e,i)=>{var s=i(7331);t.exports=function(t){return s(t.length)}},1135:(t,e,i)=>{var s=i(9668),n=i(4694),r=i(688),o=i(4678),a=i(9924),h=i(453).CONFIGURABLE,l=i(1881),c=i(7804),d=c.enforce,u=c.get,p=String,_=Object.defineProperty,g=s("".slice),m=s("".replace),f=s([].join),v=a&&!n((function(){return 8!==_((function(){}),"length",{value:8}).length})),x=String(String).split("String"),y=t.exports=function(t,e,i){"Symbol("===g(p(e),0,7)&&(e="["+m(p(e),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(e="get "+e),i&&i.setter&&(e="set "+e),(!o(t,"name")||h&&t.name!==e)&&(a?_(t,"name",{value:e,configurable:!0}):t.name=e),v&&i&&o(i,"arity")&&t.length!==i.arity&&_(t,"length",{value:i.arity});try{i&&o(i,"constructor")&&i.constructor?a&&_(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var s=d(t);return o(s,"source")||(s.source=f(x,"string"==typeof e?e:"")),t};Function.prototype.toString=y((function(){return r(this)&&u(this).source||l(this)}),"toString")},1787:t=>{var e=Math.ceil,i=Math.floor;t.exports=Math.trunc||function(t){var s=+t;return(s>0?i:e)(s)}},2131:(t,e,i)=>{var s=i(9924),n=i(7913),r=i(2666),o=i(9175),a=i(2358),h=TypeError,l=Object.defineProperty,c=Object.getOwnPropertyDescriptor,d="enumerable",u="configurable",p="writable";e.f=s?r?function(t,e,i){if(o(t),e=a(e),o(i),"function"==typeof t&&"prototype"===e&&"value"in i&&p in i&&!i[p]){var s=c(t,e);s&&s[p]&&(t[e]=i.value,i={configurable:u in i?i[u]:s[u],enumerable:d in i?i[d]:s[d],writable:!1})}return l(t,e,i)}:l:function(t,e,i){if(o(t),e=a(e),o(i),n)try{return l(t,e,i)}catch(t){}if("get"in i||"set"in i)throw new h("Accessors not supported");return"value"in i&&(t[e]=i.value),t}},7537:(t,e,i)=>{var s=i(9924),n=i(8724),r=i(8208),o=i(7781),a=i(6854),h=i(2358),l=i(4678),c=i(7913),d=Object.getOwnPropertyDescriptor;e.f=s?d:function(t,e){if(t=a(t),e=h(e),c)try{return d(t,e)}catch(t){}if(l(t,e))return o(!n(r.f,t,e),t[e])}},6217:(t,e,i)=>{var s=i(1528),n=i(2367).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return s(t,n)}},5168:(t,e)=>{e.f=Object.getOwnPropertySymbols},6148:(t,e,i)=>{var s=i(9668);t.exports=s({}.isPrototypeOf)},1528:(t,e,i)=>{var s=i(9668),n=i(4678),r=i(6854),o=i(1138).indexOf,a=i(7390),h=s([].push);t.exports=function(t,e){var i,s=r(t),l=0,c=[];for(i in s)!n(a,i)&&n(s,i)&&h(c,i);for(;e.length>l;)n(s,i=e[l++])&&(~o(c,i)||h(c,i));return c}},1728:(t,e,i)=>{var s=i(1528),n=i(2367);t.exports=Object.keys||function(t){return s(t,n)}},8208:(t,e)=>{var i={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor,n=s&&!i.call({1:2},1);e.f=n?function(t){var e=s(this,t);return!!e&&e.enumerable}:i},110:(t,e,i)=>{var s=i(8724),n=i(688),r=i(5309),o=TypeError;t.exports=function(t,e){var i,a;if("string"===e&&n(i=t.toString)&&!r(a=s(i,t)))return a;if(n(i=t.valueOf)&&!r(a=s(i,t)))return a;if("string"!==e&&n(i=t.toString)&&!r(a=s(i,t)))return a;throw new o("Can't convert object to primitive value")}},990:(t,e,i)=>{var s=i(2160),n=i(9668),r=i(6217),o=i(5168),a=i(9175),h=n([].concat);t.exports=s("Reflect","ownKeys")||function(t){var e=r.f(a(t)),i=o.f;return i?h(e,i(t)):e}},8588:(t,e,i)=>{var s=i(2150);t.exports=s},1166:(t,e,i)=>{var s=i(5268),n=TypeError;t.exports=function(t){if(s(t))throw new n("Can't call method on "+t);return t}},1962:(t,e,i)=>{var s=i(2645),n=i(5736),r=s("keys");t.exports=function(t){return r[t]||(r[t]=n(t))}},6762:(t,e,i)=>{var s=i(2150),n=i(1604),r="__core-js_shared__",o=s[r]||n(r,{});t.exports=o},2645:(t,e,i)=>{var s=i(6555),n=i(6762);(t.exports=function(t,e){return n[t]||(n[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.33.3",mode:s?"pure":"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.33.3/LICENSE",source:"https://github.com/zloirock/core-js"})},4112:(t,e,i)=>{var s=i(7067),n=i(4694),r=i(2150).String;t.exports=!!Object.getOwnPropertySymbols&&!n((function(){var t=Symbol("symbol detection");return!r(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&s&&s<41}))},7352:(t,e,i)=>{var s=i(1680),n=Math.max,r=Math.min;t.exports=function(t,e){var i=s(t);return i<0?n(i+e,0):r(i,e)}},6854:(t,e,i)=>{var s=i(4347),n=i(1166);t.exports=function(t){return s(n(t))}},1680:(t,e,i)=>{var s=i(1787);t.exports=function(t){var e=+t;return e!=e||0===e?0:s(e)}},7331:(t,e,i)=>{var s=i(1680),n=Math.min;t.exports=function(t){return t>0?n(s(t),9007199254740991):0}},298:(t,e,i)=>{var s=i(1166),n=Object;t.exports=function(t){return n(s(t))}},1272:(t,e,i)=>{var s=i(8724),n=i(5309),r=i(7935),o=i(5383),a=i(110),h=i(2032),l=TypeError,c=h("toPrimitive");t.exports=function(t,e){if(!n(t)||r(t))return t;var i,h=o(t,c);if(h){if(void 0===e&&(e="default"),i=s(h,t,e),!n(i)||r(i))return i;throw new l("Can't convert object to primitive value")}return void 0===e&&(e="number"),a(t,e)}},2358:(t,e,i)=>{var s=i(1272),n=i(7935);t.exports=function(t){var e=s(t,"string");return n(e)?e:e+""}},2522:(t,e,i)=>{var s={};s[i(2032)("toStringTag")]="z",t.exports="[object z]"===String(s)},599:(t,e,i)=>{var s=i(1566),n=String;t.exports=function(t){if("Symbol"===s(t))throw new TypeError("Cannot convert a Symbol value to a string");return n(t)}},3397:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},5736:(t,e,i)=>{var s=i(9668),n=0,r=Math.random(),o=s(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+o(++n+r,36)}},4866:(t,e,i)=>{var s=i(4112);t.exports=s&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},2666:(t,e,i)=>{var s=i(9924),n=i(4694);t.exports=s&&n((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},4724:(t,e,i)=>{var s=i(2150),n=i(688),r=s.WeakMap;t.exports=n(r)&&/native code/.test(String(r))},2032:(t,e,i)=>{var s=i(2150),n=i(2645),r=i(4678),o=i(5736),a=i(4112),h=i(4866),l=s.Symbol,c=n("wks"),d=h?l.for||l:l&&l.withoutSetter||o;t.exports=function(t){return r(c,t)||(c[t]=a&&r(l,t)?l[t]:d("Symbol."+t)),c[t]}},7206:(t,e,i)=>{var s=i(5532),n=i(9668),r=i(1052),o=i(298),a=i(8344),h=i(955),l=i(599),c=i(4694),d=i(3097),u=i(567),p=i(9016),_=i(821),g=i(7067),m=i(4389),f=[],v=n(f.sort),x=n(f.push),y=c((function(){f.sort(void 0)})),w=c((function(){f.sort(null)})),b=u("sort"),C=!c((function(){if(g)return g<70;if(!(p&&p>3)){if(_)return!0;if(m)return m<603;var t,e,i,s,n="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(s=0;s<47;s++)f.push({k:e+s,v:i})}for(f.sort((function(t,e){return e.v-t.v})),s=0;s<f.length;s++)e=f[s].k.charAt(0),n.charAt(n.length-1)!==e&&(n+=e);return"DGBEFHACIJK"!==n}}));s({target:"Array",proto:!0,forced:y||!w||!b||!C},{sort:function(t){void 0!==t&&r(t);var e=o(this);if(C)return void 0===t?v(e):v(e,t);var i,s,n=[],c=a(e);for(s=0;s<c;s++)s in e&&x(n,e[s]);for(d(n,function(t){return function(e,i){return void 0===i?-1:void 0===e?1:void 0!==t?+t(e,i)||0:l(e)>l(i)?1:-1}}(t)),i=a(n),s=0;s<i;)e[s]=n[s++];for(;s<c;)h(e,s++);return e}})},9867:(t,e,i)=>{var s=i(5532),n=i(298),r=i(1728);s({target:"Object",stat:!0,forced:i(4694)((function(){r(1)}))},{keys:function(t){return r(n(t))}})}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var r=e[s]={id:s,exports:{}};return t[s].call(r.exports,r,r.exports,i),r.exports}i.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return i.d(e,{a:e}),e},i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var s={};return(()=>{i.r(s),i.d(s,{ActionContext:()=>ys,ActionQueue:()=>ji,ActionSequence:()=>ur,ActionsComponent:()=>ws,ActionsSystem:()=>En,ActivateEvent:()=>H,Actor:()=>Ts,AddedComponent:()=>Li,AddedEntity:()=>js,AffineMatrix:()=>Ft,Animation:()=>mn,AnimationDirection:()=>pn,AnimationEvents:()=>gn,AnimationStrategy:()=>_n,ArcadeSolver:()=>ln,AudioContextFactory:()=>Ae,Axes:()=>j,Axis:()=>zs,BaseAlign:()=>ns,Blink:()=>_s,BodyComponent:()=>Mi,BoundingBox:()=>At,BroadphaseStrategy:()=>ti,BrowserComponent:()=>Hn,BrowserEvents:()=>Wn,Buttons:()=>Y,Camera:()=>Vs,CameraEvents:()=>Gs,Canvas:()=>Fe,Circle:()=>Ki,CircleCollider:()=>Ti,Clock:()=>Jn,ClosestLine:()=>Ai,ClosestLineJumpTable:()=>Si,Collider:()=>wi,ColliderComponent:()=>Fi,CollisionContact:()=>Ei,CollisionEndEvent:()=>O,CollisionGroup:()=>_i,CollisionGroupManager:()=>pi,CollisionJumpTable:()=>Ii,CollisionPostSolveEvent:()=>z,CollisionPreSolveEvent:()=>L,CollisionResolutionStrategy:()=>Je,CollisionStartEvent:()=>U,CollisionSystem:()=>un,CollisionType:()=>Ke,Color:()=>yt,ColorBlindFlags:()=>zn,ColorBlindnessMode:()=>kn,ColorBlindnessPostProcessor:()=>Ln,Component:()=>hi,CompositeCollider:()=>bi,Configurable:()=>vn,ConsoleAppender:()=>tt,ContactConstraintPoint:()=>cn,ContactEndEvent:()=>M,ContactStartEvent:()=>k,CoordPlane:()=>ii,DeactivateEvent:()=>W,Debug:()=>Un,DebugGraphicsComponent:()=>Bs,DebugSystem:()=>Sn,DebugText:()=>Kt,DegreeOfFreedom:()=>ki,Delay:()=>ms,Detector:()=>Xe,Die:()=>fs,Direction:()=>os,DisplayMode:()=>ye,DynamicTree:()=>vi,DynamicTreeCollisionProcessor:()=>yi,EX_VERSION:()=>Br,EaseBy:()=>ps,EaseTo:()=>us,EasingFunctions:()=>Yi,EdgeCollider:()=>Di,ElasticToActorStrategy:()=>Ns,EmitterType:()=>xn,Engine:()=>ar,EngineEvents:()=>rr,EnterTriggerEvent:()=>q,EnterViewPortEvent:()=>V,Entity:()=>Hi,EntityEvents:()=>Ni,EntityManager:()=>tn,EventDispatcher:()=>hr,EventEmitter:()=>d,EventTypes:()=>a,Events:()=>t,ExResponse:()=>ke,ExcaliburGraphicsContext2DCanvas:()=>xe,ExcaliburGraphicsContextWebGL:()=>me,ExitTriggerEvent:()=>X,ExitViewPortEvent:()=>G,Fade:()=>gs,Flags:()=>l,Follow:()=>vs,Font:()=>As,FontCache:()=>Cs,FontStyle:()=>rs,FontUnit:()=>is,FpsSampler:()=>$n,FrameStats:()=>On,Future:()=>St,GameEvent:()=>u,GameStartEvent:()=>m,GameStopEvent:()=>f,Gamepad:()=>Z,GamepadAxisEvent:()=>I,GamepadButtonEvent:()=>P,GamepadConnectEvent:()=>T,GamepadDisconnectEvent:()=>E,Gamepads:()=>K,Gif:()=>br,GlobalCoordinates:()=>Gn,Graphic:()=>Nt,GraphicsComponent:()=>qi,GraphicsGroup:()=>fn,GraphicsLayer:()=>Gi,GraphicsLayers:()=>Vi,GraphicsSystem:()=>An,HiddenEvent:()=>B,ImageFiltering:()=>Wt,ImageSource:()=>Vt,InitializeEvent:()=>N,Input:()=>r,InputMapper:()=>nr,Integrator:()=>ei,IsometricEntityComponent:()=>Pn,IsometricEntitySystem:()=>In,IsometricMap:()=>dr,IsometricTile:()=>cr,KeyEvent:()=>st,Keyboard:()=>nt,Keys:()=>$,KillEvent:()=>p,Label:()=>lr,LimitCameraBoundsStrategy:()=>Ws,Line:()=>Er,LineSegment:()=>Ci,Loader:()=>Ve,LoaderEvents:()=>Ge,LockCameraToActorAxisStrategy:()=>Os,LockCameraToActorStrategy:()=>Us,LogLevel:()=>Q,Logger:()=>J,Material:()=>ue,Matrix:()=>Rt,MatrixLocations:()=>Ct,MediaEvent:()=>ze,Meet:()=>xs,MotionComponent:()=>ui,MotionSystem:()=>hn,MoveBy:()=>Ji,MoveTo:()=>ts,NativePointerButton:()=>Zn,NativeSoundEvent:()=>Ue,NativeSoundProcessedEvent:()=>Oe,Observable:()=>ci,OffscreenSystem:()=>Dn,Pair:()=>gi,ParallaxComponent:()=>Ds,ParallelActions:()=>pr,ParseGif:()=>Tr,Particle:()=>bn,ParticleEmitter:()=>Cn,ParticleTransform:()=>yn,Physics:()=>ni,PhysicsStats:()=>Nn,PhysicsWorld:()=>Bn,PointerButton:()=>Yn,PointerComponent:()=>Zi,PointerEvent:()=>Vn,PointerEventReceiver:()=>Qn,PointerScope:()=>rt,PointerSystem:()=>Tn,PointerType:()=>jn,Polygon:()=>Pr,PolygonCollider:()=>Bi,Pool:()=>ce,PostCollisionEvent:()=>F,PostDebugDrawEvent:()=>w,PostDrawEvent:()=>x,PostFrameEvent:()=>S,PostKillEvent:()=>g,PostUpdateEvent:()=>C,PreCollisionEvent:()=>R,PreDebugDrawEvent:()=>y,PreDrawEvent:()=>v,PreFrameEvent:()=>A,PreKillEvent:()=>_,PreUpdateEvent:()=>b,Projection:()=>mi,QuadIndexBuffer:()=>oe,QuadTree:()=>Rs,Query:()=>sn,QueryManager:()=>nn,RadiusAroundActorStrategy:()=>Hs,Random:()=>at,Raster:()=>Re,Ray:()=>xi,RealisticSolver:()=>dn,Rectangle:()=>Xi,RemovedComponent:()=>Ui,RemovedEntity:()=>$s,Repeat:()=>Qi,RepeatForever:()=>$i,Resolution:()=>we,Resource:()=>zt,ResourceEvents:()=>Lt,RotateBy:()=>hs,RotateTo:()=>as,RotationType:()=>es,ScaleBy:()=>cs,ScaleTo:()=>ls,Scene:()=>Fn,SceneEvents:()=>Rn,Screen:()=>Ce,ScreenAppender:()=>et,ScreenElement:()=>Ps,ScreenEvents:()=>be,ScreenShader:()=>Mn,ScrollPreventionMode:()=>or,Semaphore:()=>Dr,Shader:()=>Jt,Shape:()=>Ri,Side:()=>bt,Sound:()=>We,SoundEvents:()=>He,Sprite:()=>Ht,SpriteFont:()=>Xt,SpriteSheet:()=>qt,StandardClock:()=>tr,StateMachine:()=>Me,StrategyContainer:()=>Ls,Stream:()=>Sr,System:()=>Ys,SystemManager:()=>rn,SystemType:()=>Zs,TagComponent:()=>li,TestClock:()=>er,Text:()=>Ss,TextAlign:()=>ss,TextureLoader:()=>Gt,Tile:()=>Ms,TileMap:()=>ks,TileMapEvents:()=>Fs,Timer:()=>Is,Toaster:()=>sr,Transform:()=>ai,TransformComponent:()=>di,TreeNode:()=>fi,Trigger:()=>Ks,TriggerEvents:()=>qs,TwoPI:()=>ht,Util:()=>o,Vector:()=>vt,VectorView:()=>ri,VertexBuffer:()=>te,VertexLayout:()=>ee,VisibleEvent:()=>D,WebAudio:()=>Se,WebAudioInstance:()=>Le,WheelDeltaMode:()=>Kn,WheelEvent:()=>qn,World:()=>on,canonicalizeAngle:()=>ut,clamp:()=>dt,createId:()=>c,frac:()=>lt,hasGraphicsTick:()=>Wi,hasOnInitialize:()=>gr,hasOnPostUpdate:()=>xr,hasOnPreUpdate:()=>fr,hasPostDraw:()=>wr,hasPreDraw:()=>yr,has_initialize:()=>_r,has_postupdate:()=>vr,has_preupdate:()=>mr,isAddedComponent:()=>zi,isAddedSystemEntity:()=>Qs,isRemoveSystemEntity:()=>Js,isRemovedComponent:()=>Oi,isScreenElement:()=>Es,maxMessages:()=>Ze,obsolete:()=>$e,pixelSnapEpsilon:()=>_e,randomInRange:()=>mt,randomIntInRange:()=>ft,range:()=>gt,resetObsoleteCounter:()=>je,sign:()=>ct,toDegrees:()=>pt,toRadians:()=>_t,vec:()=>xt,webgl:()=>e});var t={};i.r(t),i.d(t,{ActivateEvent:()=>H,CollisionEndEvent:()=>O,CollisionPostSolveEvent:()=>z,CollisionPreSolveEvent:()=>L,CollisionStartEvent:()=>U,ContactEndEvent:()=>M,ContactStartEvent:()=>k,DeactivateEvent:()=>W,EnterTriggerEvent:()=>q,EnterViewPortEvent:()=>V,EventTypes:()=>a,ExitTriggerEvent:()=>X,ExitViewPortEvent:()=>G,GameEvent:()=>u,GameStartEvent:()=>m,GameStopEvent:()=>f,GamepadAxisEvent:()=>I,GamepadButtonEvent:()=>P,GamepadConnectEvent:()=>T,GamepadDisconnectEvent:()=>E,HiddenEvent:()=>B,InitializeEvent:()=>N,KillEvent:()=>p,PostCollisionEvent:()=>F,PostDebugDrawEvent:()=>w,PostDrawEvent:()=>x,PostFrameEvent:()=>S,PostKillEvent:()=>g,PostUpdateEvent:()=>C,PreCollisionEvent:()=>R,PreDebugDrawEvent:()=>y,PreDrawEvent:()=>v,PreFrameEvent:()=>A,PreKillEvent:()=>_,PreUpdateEvent:()=>b,VisibleEvent:()=>D});var e={};i.r(e),i.d(e,{getAttributeComponentSize:()=>Qt,getAttributePointerType:()=>$t,getGlTypeSizeBytes:()=>jt});var n={};i.r(n),i.d(n,{circle:()=>De,line:()=>Te,point:()=>Ee,roundRect:()=>Ie,vector:()=>Pe});var r={};i.r(r),i.d(r,{Axes:()=>j,Buttons:()=>Y,Gamepad:()=>Z,Gamepads:()=>K,KeyEvent:()=>st,Keyboard:()=>nt,Keys:()=>$,NativePointerButton:()=>Zn,PointerButton:()=>Yn,PointerComponent:()=>Zi,PointerEvent:()=>Vn,PointerEventReceiver:()=>Qn,PointerScope:()=>rt,PointerSystem:()=>Tn,PointerType:()=>jn,WheelDeltaMode:()=>Kn,WheelEvent:()=>qn});var o={};i.r(o),i.d(o,{ConsoleAppender:()=>tt,DrawUtil:()=>n,EasingFunctions:()=>Yi,LogLevel:()=>Q,Logger:()=>J,Observable:()=>ci,ScreenAppender:()=>et,addItemToArray:()=>Et,contains:()=>It,delay:()=>Bt,fail:()=>Dt,getPosition:()=>Tt,removeItemFromArray:()=>Pt});var a;i(1324),i(3571);function h(){if("undefined"==typeof window&&(window={audioContext:function(){}}),"undefined"==typeof window||window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){window.setInterval(t,1e3/60)}),"undefined"==typeof window||window.cancelAnimationFrame||(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),"undefined"!=typeof window&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise(((i,s)=>{t.call(this,e,i,s)}))}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}"undefined"==typeof window||window.devicePixelRatio||(window.devicePixelRatio=window.devicePixelRatio||1)}class l{static useCanvasGraphicsContext(){l.enable("use-canvas-context")}static freeze(){l._FROZEN=!0}static _reset(){l._FROZEN=!1,l._FLAGS={}}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");l._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");l._FLAGS[t]=!1}static isEnabled(t){return!!l._FLAGS[t]}static show(){return Object.keys(l._FLAGS)}}function c(t,e){return{type:t,value:e}}l._FROZEN=!1,l._FLAGS={};class d{constructor(){this._paused=!1,this._listeners={},this._listenersOnce={},this._pipes=[]}clear(){this._listeners={},this._listenersOnce={},this._pipes.length=0}on(t,e){var i;return this._listeners[t]=null!==(i=this._listeners[t])&&void 0!==i?i:[],this._listeners[t].push(e),{close:()=>this.off(t,e)}}once(t,e){var i;return this._listenersOnce[t]=null!==(i=this._listenersOnce[t])&&void 0!==i?i:[],this._listenersOnce[t].push(e),{close:()=>this.off(t,e)}}off(t,e){var i,s;if(e){const n=null===(i=this._listeners[t])||void 0===i?void 0:i.filter((t=>t!==e));this._listeners[t]=n;const r=null===(s=this._listenersOnce[t])||void 0===s?void 0:s.filter((t=>t!==e));this._listenersOnce[t]=r}else delete this._listeners[t]}emit(t,e){var i;if(this._paused)return;null===(i=this._listeners[t])||void 0===i||i.forEach((t=>t(e)));const s=this._listenersOnce[t];this._listenersOnce[t]=[],s&&s.forEach((t=>t(e))),this._pipes.forEach((i=>{i.emit(t,e)}))}pipe(t){if(this===t)throw Error("Cannot pipe to self");return this._pipes.push(t),{close:()=>{const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}}}unpipe(t){const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}pause(){this._paused=!0}unpause(){this._paused=!1}}!function(t){t.Kill="kill",t.PreKill="prekill",t.PostKill="postkill",t.PreDraw="predraw",t.PostDraw="postdraw",t.PreDebugDraw="predebugdraw",t.PostDebugDraw="postdebugdraw",t.PreUpdate="preupdate",t.PostUpdate="postupdate",t.PreFrame="preframe",t.PostFrame="postframe",t.PreCollision="precollision",t.CollisionStart="collisionstart",t.CollisionEnd="collisionend",t.PostCollision="postcollision",t.Initialize="initialize",t.Activate="activate",t.Deactivate="deactivate",t.ExitViewport="exitviewport",t.EnterViewport="enterviewport",t.ExitTrigger="exit",t.EnterTrigger="enter",t.Connect="connect",t.Disconnect="disconnect",t.Button="button",t.Axis="axis",t.Visible="visible",t.Hidden="hidden",t.Start="start",t.Stop="stop",t.PointerUp="pointerup",t.PointerDown="pointerdown",t.PointerMove="pointermove",t.PointerEnter="pointerenter",t.PointerLeave="pointerleave",t.PointerCancel="pointercancel",t.PointerWheel="pointerwheel",t.Up="up",t.Down="down",t.Move="move",t.Enter="enter",t.Leave="leave",t.Cancel="cancel",t.Wheel="wheel",t.Press="press",t.Release="release",t.Hold="hold",t.PointerDragStart="pointerdragstart",t.PointerDragEnd="pointerdragend",t.PointerDragEnter="pointerdragenter",t.PointerDragLeave="pointerdragleave",t.PointerDragMove="pointerdragmove"}(a||(a={}));class u{constructor(){this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class p extends u{constructor(t){super(),this.target=t}}class _ extends u{constructor(t){super(),this.target=t}}class g extends u{constructor(t){super(),this.target=t}}class m extends u{constructor(t){super(),this.target=t}}class f extends u{constructor(t){super(),this.target=t}}class v extends u{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class x extends u{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class y extends u{constructor(t,e){super(),this.ctx=t,this.target=e}}class w extends u{constructor(t,e){super(),this.ctx=t,this.target=e}}class b extends u{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class C extends u{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class A extends u{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class S extends u{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class T extends u{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class E extends u{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class P extends u{constructor(t,e,i){super(),this.button=t,this.value=e,this.target=i}}class I extends u{constructor(t,e,i){super(),this.axis=t,this.value=e,this.target=i}}class D extends u{constructor(t){super(),this.target=t}}class B extends u{constructor(t){super(),this.target=t}}class R extends u{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}}class F extends u{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class k{constructor(t,e,i){this.target=t,this.other=e,this.contact=i}}class M{constructor(t,e){this.target=t,this.other=e}}class L{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class z{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class U extends u{constructor(t,e,i){super(),this.other=e,this.contact=i,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class O extends u{constructor(t,e){super(),this.other=e,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class N extends u{constructor(t,e){super(),this.engine=t,this.target=e}}class H extends u{constructor(t,e){super(),this.context=t,this.target=e}}class W extends u{constructor(t,e){super(),this.context=t,this.target=e}}class G extends u{constructor(t){super(),this.target=t}}class V extends u{constructor(t){super(),this.target=t}}class q extends u{constructor(t,e){super(),this.target=t,this.actor=e}}class X extends u{constructor(t,e){super(),this.target=t,this.actor=e}}class K{constructor(){this.events=new d,this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter((t=>void 0!==typeof t)).length,i=t.buttons.filter((t=>void 0!==typeof t)).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}emit(t,e){this.events.emit(t,e)}on(t,e){return this._enableAndUpdate(),this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this._enableAndUpdate(),this.events.off(t,e)}update(){if(!this.enabled||!this.supported)return;this.init();const t=this._navigator.getGamepads();for(let e=0;e<t.length;e++){if(!t[e]){const t=this.at(e);t.connected&&this.events.emit("disconnect",new E(e,t)),t.connected=!1;continue}if(!this.at(e).connected&&this._isGamepadValid(t[e])&&this.events.emit("connect",new T(e,this.at(e))),this.at(e).connected=!0,this.at(e).update(),t[e].timestamp&&t[e].timestamp===this._gamePadTimeStamps[e])continue;let i,s,n,r,o;for(i in this._gamePadTimeStamps[e]=t[e].timestamp,this.at(e).navigatorGamepad=t[e],Y)s=Y[i],"number"==typeof s&&t[e].buttons[s]&&(o=t[e].buttons[s].value,o!==this._oldPads[e].getButton(s)&&(t[e].buttons[s].pressed?(this.at(e).updateButton(s,o),this.at(e).events.emit("button",new P(s,o,this.at(e)))):this.at(e).updateButton(s,0)));for(n in j)r=j[n],"number"==typeof r&&(o=t[e].axes[r],o!==this._oldPads[e].getAxes(r)&&(this.at(e).updateAxes(r,o),this.at(e).events.emit("axis",new I(r,o,this.at(e)))));this._oldPads[e]=this._clonePad(t[e])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new Z),this._oldPads.push(new Z);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter((t=>t.connected)).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new Z;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}K.MinAxisMoveThreshold=.05;class Z{constructor(){this.events=new d,this.connected=!1,this._axes=new Array(4),this._buttons=new Array(16),this._buttonsUp=new Array(16),this._buttonsDown=new Array(16);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}update(){this._buttonsDown=new Array(16),this._buttonsUp=new Array(16)}isButtonPressed(t,e=1){return this._buttons[t]>=e}isButtonHeld(t,e=1){return this._buttons[t]>=e}wasButtonPressed(t,e=1){return this._buttonsDown[t]>=e}wasButtonReleased(t){return Boolean(this._buttonsUp[t])}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<K.MinAxisMoveThreshold?0:e}updateButton(t,e){0===e&&this._buttons[t]?this._buttonsUp[t]=1:this._buttonsDown[t]=e,this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var Y,j,Q,$;!function(t){t[t.Face1=0]="Face1",t[t.Face2=1]="Face2",t[t.Face3=2]="Face3",t[t.Face4=3]="Face4",t[t.LeftBumper=4]="LeftBumper",t[t.RightBumper=5]="RightBumper",t[t.LeftTrigger=6]="LeftTrigger",t[t.RightTrigger=7]="RightTrigger",t[t.Select=8]="Select",t[t.Start=9]="Start",t[t.LeftStick=10]="LeftStick",t[t.RightStick=11]="RightStick",t[t.DpadUp=12]="DpadUp",t[t.DpadDown=13]="DpadDown",t[t.DpadLeft=14]="DpadLeft",t[t.DpadRight=15]="DpadRight"}(Y||(Y={})),function(t){t[t.LeftStickX=0]="LeftStickX",t[t.LeftStickY=1]="LeftStickY",t[t.RightStickX=2]="RightStickX",t[t.RightStickY=3]="RightStickY"}(j||(j={})),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"}(Q||(Q={}));class J{constructor(){if(this._appenders=[],this.defaultLevel=Q.Info,J._INSTANCE)throw new Error("Logger is a singleton");return J._INSTANCE=this,J._INSTANCE.addAppender(new tt),J._INSTANCE}static getInstance(){return null==J._INSTANCE&&(J._INSTANCE=new J),J._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){null==t&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}debug(...t){this._log(Q.Debug,t)}info(...t){this._log(Q.Info,t)}warn(...t){this._log(Q.Warn,t)}error(...t){this._log(Q.Error,t)}fatal(...t){this._log(Q.Fatal,t)}}J._INSTANCE=null;class tt{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+Q[t]+"] : "),t<Q.Warn?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<Q.Error?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class et{constructor(t,e){this._messages=[],this._canvas=document.createElement("canvas"),this._canvas.width=t||window.innerWidth,this._canvas.height=e||window.innerHeight,this._canvas.style.position="absolute",this._ctx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._messages.unshift("["+Q[t]+"] : "+i);let s=10,n=1;for(let t=0;t<this._messages.length;t++)this._ctx.fillStyle="rgba(255,255,255,"+n.toFixed(2)+")",this._ctx.fillText(this._messages[t],200,s),s+=10,n=n>0?n-.05:0}}function it(){try{const t=()=>{};window.top.addEventListener("blur",t),window.top.removeEventListener("blur",t)}catch(t){return!0}return!1}!function(t){t.Num0="Numpad0",t.Num1="Numpad1",t.Num2="Numpad2",t.Num3="Numpad3",t.Num4="Numpad4",t.Num5="Numpad5",t.Num6="Numpad6",t.Num7="Numpad7",t.Num8="Numpad8",t.Num9="Numpad9",t.NumAdd="NumpadAdd",t.NumSubtract="NumpadSubtract",t.NumMultiply="NumpadMultiply",t.NumDivide="NumpadDivide",t.NumDecimal="NumpadDecimal",t.Numpad0="Numpad0",t.Numpad1="Numpad1",t.Numpad2="Numpad2",t.Numpad3="Numpad3",t.Numpad4="Numpad4",t.Numpad5="Numpad5",t.Numpad6="Numpad6",t.Numpad7="Numpad7",t.Numpad8="Numpad8",t.Numpad9="Numpad9",t.NumpadAdd="NumpadAdd",t.NumpadSubtract="NumpadSubtract",t.NumpadMultiply="NumpadMultiply",t.NumpadDivide="NumpadDivide",t.NumpadDecimal="NumpadDecimal",t.NumLock="NumLock",t.ShiftLeft="ShiftLeft",t.ShiftRight="ShiftRight",t.AltLeft="AltLeft",t.AltRight="AltRight",t.ControlLeft="ControlLeft",t.ControlRight="ControlRight",t.MetaLeft="MetaLeft",t.MetaRight="MetaRight",t.Key0="Digit0",t.Key1="Digit1",t.Key2="Digit2",t.Key3="Digit3",t.Key4="Digit4",t.Key5="Digit5",t.Key6="Digit6",t.Key7="Digit7",t.Key8="Digit8",t.Key9="Digit9",t.Digit0="Digit0",t.Digit1="Digit1",t.Digit2="Digit2",t.Digit3="Digit3",t.Digit4="Digit4",t.Digit5="Digit5",t.Digit6="Digit6",t.Digit7="Digit7",t.Digit8="Digit8",t.Digit9="Digit9",t.F1="F1",t.F2="F2",t.F3="F3",t.F4="F4",t.F5="F5",t.F6="F6",t.F7="F7",t.F8="F8",t.F9="F9",t.F10="F10",t.F11="F11",t.F12="F12",t.A="KeyA",t.B="KeyB",t.C="KeyC",t.D="KeyD",t.E="KeyE",t.F="KeyF",t.G="KeyG",t.H="KeyH",t.I="KeyI",t.J="KeyJ",t.K="KeyK",t.L="KeyL",t.M="KeyM",t.N="KeyN",t.O="KeyO",t.P="KeyP",t.Q="KeyQ",t.R="KeyR",t.S="KeyS",t.T="KeyT",t.U="KeyU",t.V="KeyV",t.W="KeyW",t.X="KeyX",t.Y="KeyY",t.Z="KeyZ",t.KeyA="KeyA",t.KeyB="KeyB",t.KeyC="KeyC",t.KeyD="KeyD",t.KeyE="KeyE",t.KeyF="KeyF",t.KeyG="KeyG",t.KeyH="KeyH",t.KeyI="KeyI",t.KeyJ="KeyJ",t.KeyK="KeyK",t.KeyL="KeyL",t.KeyM="KeyM",t.KeyN="KeyN",t.KeyO="KeyO",t.KeyP="KeyP",t.KeyQ="KeyQ",t.KeyR="KeyR",t.KeyS="KeyS",t.KeyT="KeyT",t.KeyU="KeyU",t.KeyV="KeyV",t.KeyW="KeyW",t.KeyX="KeyX",t.KeyY="KeyY",t.KeyZ="KeyZ",t.Semicolon="Semicolon",t.Quote="Quote",t.Comma="Comma",t.Minus="Minus",t.Period="Period",t.Slash="Slash",t.Equal="Equal",t.BracketLeft="BracketLeft",t.Backslash="Backslash",t.BracketRight="BracketRight",t.Backquote="Backquote",t.Up="ArrowUp",t.Down="ArrowDown",t.Left="ArrowLeft",t.Right="ArrowRight",t.ArrowUp="ArrowUp",t.ArrowDown="ArrowDown",t.ArrowLeft="ArrowLeft",t.ArrowRight="ArrowRight",t.Space="Space",t.Backspace="Backspace",t.Delete="Delete",t.Esc="Escape",t.Escape="Escape",t.Enter="Enter",t.NumpadEnter="NumpadEnter",t.ContextMenu="ContextMenu"}($||($={}));class st extends u{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class nt{constructor(){this.events=new d,this._keys=[],this._keysUp=[],this._keysDown=[],this._releaseAllKeys=t=>{for(const e of this._keys){const i=new st(e,t.key,t);this.events.emit("up",i),this.events.emit("release",i)}this._keysUp=Array.from(new Set(this._keys.concat(this._keysUp))),this._keys.length=0},this._handleKeyDown=t=>{t.metaKey||!this._keys.includes($.MetaLeft)&&!this._keys.includes($.MetaRight)||this._releaseAllKeys(t);const e=t.code;if(-1===this._keys.indexOf(e)){this._keys.push(e),this._keysDown.push(e);const i=new st(e,t.key,t);this.events.emit("down",i),this.events.emit("press",i)}},this._handleKeyUp=t=>{const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new st(e,t.key,t);this.events.emit("up",s),this.events.emit("release",s),"Meta"===t.key&&this._releaseAllKeys(t)}}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}init(t){let{global:e}=t;const{grabWindowFocus:i}=t;e||(it()?(e=window,i&&window.focus(),J.getInstance().warn("Excalibur might be in a cross-origin iframe, in order to receive keyboard events it must be in focus")):e=window.top),e.addEventListener("blur",(()=>{this._keys.length=0})),e.addEventListener("keyup",this._handleKeyUp),e.addEventListener("keydown",this._handleKeyDown)}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.events.emit("hold",new st(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._keysDown.indexOf(t)>-1}isHeld(t){return this._keys.indexOf(t)>-1}wasReleased(t){return this._keysUp.indexOf(t)>-1}triggerEvent(t,e,i){"down"===t&&this._handleKeyDown(new KeyboardEvent("keydown",{code:e,key:null!=i?i:null})),"up"===t&&this._handleKeyUp(new KeyboardEvent("keyup",{code:e,key:null!=i?i:null}))}}var rt;!function(t){t.Canvas="Canvas",t.Document="Document"}(rt||(rt={}));const ot=4294967295;class at{constructor(t){this.seed=t,this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Date.now())>>>0;for(let t=1;t<this._n;t++){const e=this._mt[t-1]^this._mt[t-1]>>>this._w-2;this._mt[t]=(this._f*((4294901760&e)>>>16)<<16)+this._f*(65535&e)+t>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[1&e]&ot;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[1&e]&ot;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[1&e]&ot,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const t=this.integer(0,n.length-1);i[s++]=n[t],n.splice(t,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i=null;for(let t=0;t<e.length-2;t++){const s=this.integer(t,e.length-1);i=e[t],e[t]=e[s],e[s]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}}const ht=2*Math.PI;function lt(t){return t>=0?t-Math.floor(t):t-Math.ceil(t)}function ct(t){return 0===t?0:t<0?-1:1}function dt(t,e,i){return Math.min(Math.max(e,t),i)}function ut(t){let e=t;if(t>ht)for(;e>ht;)e-=ht;if(t<0)for(;e<0;)e+=ht;return e}function pt(t){return 180/Math.PI*t}function _t(t){return t/180*Math.PI}const gt=(t,e)=>Array.from(new Array(e-t+1),((e,i)=>i+t));function mt(t,e,i=new at){return i?i.floating(t,e):t+Math.random()*(e-t)}function ft(t,e,i=new at){return i?i.integer(t,e):Math.round(mt(t,e))}class vt{static get Zero(){return new vt(0,0)}static get One(){return new vt(1,1)}static get Half(){return new vt(.5,.5)}static get Up(){return new vt(0,-1)}static get Down(){return new vt(0,1)}static get Left(){return new vt(-1,0)}static get Right(){return new vt(1,0)}static fromAngle(t){return new vt(Math.cos(t),Math.sin(t))}static isValid(t){return null!=t&&(!isNaN(t.x)&&!isNaN(t.y)&&(t.x!==1/0&&t.y!==1/0&&t.x!==-1/0&&t.y!==-1/0))}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}static min(t,e){return new vt(Math.min(t.x,e.x),Math.min(t.y,e.y))}static max(t,e){return new vt(Math.max(t.x,e.x),Math.max(t.y,e.y))}constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=.001){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){if(!t)return Math.sqrt(this.x*this.x+this.y*this.y);const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}squareDistance(t){t||(t=vt.Zero);const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}clampMagnitude(t){const e=dt(this.size,0,t);return this.size=e,this}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}normalize(){const t=this.distance();return t>0?new vt(this.x/t,this.y/t):new vt(0,1)}average(t){return this.add(t).scale(.5)}scale(t,e){const i=e||new vt(0,0);return t instanceof vt?(i.x=this.x*t.x,i.y=this.y*t.y):(i.x=this.x*t,i.y=this.y*t),i}add(t,e){return e?(e.x=this.x+t.x,e.y=this.y+t.y,e):new vt(this.x+t.x,this.y+t.y)}sub(t){return new vt(this.x-t.x,this.y-t.y)}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return t instanceof vt?this.x*t.y-this.y*t.x:"number"==typeof t?new vt(t*this.y,-t*this.x):void 0}static cross(t,e){return new vt(-t*e.y,t*e.x)}perpendicular(){return new vt(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Math.atan2(this.y,this.x)}rotate(t,e){e||(e=new vt(0,0));const i=Math.sin(t),s=Math.cos(t),n=s*(this.x-e.x)-i*(this.y-e.y)+e.x,r=i*(this.x-e.x)+s*(this.y-e.y)+e.y;return new vt(n,r)}clone(t){const e=null!=t?t:new vt(0,0);return e.x=this.x,e.y=this.y,e}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}}function xt(t,e){return new vt(t,e)}class yt{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=null!=s?s:1}static fromRGB(t,e,i,s){return new yt(t,e,i,s)}static fromRGBString(t){let e=null;if(e=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i)){const t=parseInt(e[1],10),i=parseInt(e[2],10),s=parseInt(e[3],10);let n=1;return e[4]&&(n=parseFloat(e[4])),new yt(t,i,s,n)}throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){let e=null;if(e=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i)){const t=parseInt(e[1],16),i=parseInt(e[2],16),s=parseInt(e[3],16);let n=1;return e[4]&&(n=parseInt(e[4],16)/255),new yt(t,i,s,n)}throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new wt(t,e,i,s).toRGBA()}lighten(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new yt(e,i,s,n)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new yt(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new yt(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=t.toString(16);return 1===e.length?"0"+e:e}toHex(){return"#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b)}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return void 0!==this.a||null!==this.a?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return wt.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(){return new yt(this.r,this.g,this.b,this.a)}static get Black(){return yt.fromHex("#000000")}static get White(){return yt.fromHex("#FFFFFF")}static get Gray(){return yt.fromHex("#808080")}static get LightGray(){return yt.fromHex("#D3D3D3")}static get DarkGray(){return yt.fromHex("#A9A9A9")}static get Yellow(){return yt.fromHex("#FFFF00")}static get Orange(){return yt.fromHex("#FFA500")}static get Red(){return yt.fromHex("#FF0000")}static get Vermilion(){return yt.fromHex("#FF5B31")}static get Rose(){return yt.fromHex("#FF007F")}static get Magenta(){return yt.fromHex("#FF00FF")}static get Violet(){return yt.fromHex("#7F00FF")}static get Blue(){return yt.fromHex("#0000FF")}static get Azure(){return yt.fromHex("#007FFF")}static get Cyan(){return yt.fromHex("#00FFFF")}static get Viridian(){return yt.fromHex("#59978F")}static get Green(){return yt.fromHex("#00FF00")}static get Chartreuse(){return yt.fromHex("#7FFF00")}static get Transparent(){return yt.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return yt.fromHex("#176BAA")}}class wt{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4}o/=6}return new wt(o,a,h,s)}toRGBA(){let t,e,i;if(0===this.s)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=wt.hue2rgb(n,s,this.h+1/3),e=wt.hue2rgb(n,s,this.h),i=wt.hue2rgb(n,s,this.h-1/3)}return new yt(255*t,255*e,255*i,this.a)}toString(){return`hsla(${this.h.toFixed(0)}, ${this.s.toFixed(0)}, ${this.l.toFixed(0)}, ${this.a.toFixed(0)})`}}var bt,Ct;!function(t){t.None="None",t.Top="Top",t.Bottom="Bottom",t.Left="Left",t.Right="Right"}(bt||(bt={})),function(t){t.getOpposite=function(e){return e===t.Top?t.Bottom:e===t.Bottom?t.Top:e===t.Left?t.Right:e===t.Right?t.Left:t.None},t.fromDirection=function(e){const i=[vt.Left,vt.Right,vt.Up,vt.Down],s=[t.Left,t.Right,t.Top,t.Bottom];let n=-Number.MAX_VALUE,r=-1;for(let t=0;t<i.length;t++)i[t].dot(e)>n&&(n=i[t].dot(e),r=t);return s[r]}}(bt||(bt={}));class At{constructor(t=0,e=0,i=0,s=0){"object"==typeof t?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):"number"==typeof t&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}clone(){return new At(this.left,this.top,this.right,this.bottom)}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?bt.Right:bt.Left:t.y<0?bt.Bottom:bt.Top:bt.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let r=0;r<t.length;r++)t[r].x<e&&(e=t[r].x),t[r].x>s&&(s=t[r].x),t[r].y<i&&(i=t[r].y),t[r].y>n&&(n=t[r].y);return new At(e,i,s,n)}static fromDimension(t,e,i=vt.Half,s=vt.Zero){return new At(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return 0===this.width||0===this.height}get center(){return new vt((this.left+this.right)/2,(this.top+this.bottom)/2)}translate(t){return new At(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=vt.Zero){const i=this.getPoints().map((i=>i.rotate(t,e)));return At.fromPoints(i)}scale(t,e=vt.Zero){const i=this.translate(e);return new At(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=t.data[0]*this.left,i=t.data[1]*this.left,s=t.data[0]*this.right,n=t.data[1]*this.right,r=t.data[2]*this.top,o=t.data[3]*this.top,a=t.data[2]*this.bottom,h=t.data[3]*this.bottom,l=t.getPosition(),c=Math.min(e,s)+Math.min(r,a)+l.x,d=Math.min(i,n)+Math.min(o,h)+l.y,u=Math.max(e,s)+Math.max(r,a)+l.x,p=Math.max(i,n)+Math.max(o,h)+l.y;return new At({left:c,top:d,right:u,bottom:p})}getPerimeter(){return 2*(this.width+this.height)}getPoints(){const t=[];return t.push(new vt(this.left,this.top)),t.push(new vt(this.right,this.top)),t.push(new vt(this.right,this.bottom)),t.push(new vt(this.left,this.bottom)),t}rayCast(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e}rayCastTime(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e?i:-1}contains(t){return t instanceof vt?this.left<=t.x&&this.top<=t.y&&this.bottom>=t.y&&this.right>=t.x:t instanceof At&&(this.left<=t.left&&this.top<=t.top&&t.bottom<=this.bottom&&t.right<=this.right)}combine(t){return new At(Math.min(this.left,t.left),Math.min(this.top,t.top),Math.max(this.right,t.right),Math.max(this.bottom,t.bottom))}get dimensions(){return new vt(this.width,this.height)}overlaps(t,e){const i=e||0;if(t.hasZeroDimensions())return this.contains(t);if(this.hasZeroDimensions())return t.contains(this);const s=this.combine(t);return s.width+i<t.width+this.width&&s.height+i<t.height+this.height}intersect(t){const e=this.combine(t);if(e.width<t.width+this.width&&e.height<t.height+this.height&&!e.dimensions.equals(t.dimensions)&&!e.dimensions.equals(this.dimensions)){let e=0;e=this.right>=t.left&&this.right<=t.right?t.left-this.right:t.right-this.left;let i=0;return i=this.top<=t.bottom&&this.top>=t.top?t.bottom-this.top:t.top-this.bottom,Math.abs(e)<Math.abs(i)?new vt(e,0):new vt(0,i)}if(e.dimensions.equals(t.dimensions)||e.dimensions.equals(this.dimensions)){let e=0;e=this.width-t.width>=0?this.right-t.right<=t.left-this.left?t.left-this.right:t.right-this.left:t.right-this.right<=this.left-t.left?this.left-t.right:this.right-t.left;let i=0;return i=this.height-t.height>=0?this.bottom-t.bottom<=t.top-this.top?t.top-this.bottom:t.bottom-this.top:t.bottom-this.bottom<=this.top-t.top?this.top-t.bottom:this.bottom-t.top,Math.abs(e)<Math.abs(i)?new vt(e,0):new vt(0,i)}return null}intersectWithSide(t){const e=this.intersect(t);return At.getSideFromIntersection(e)}draw(t,e=yt.Yellow){t.debug.drawRect(this.left,this.top,this.width,this.height,{color:e})}}class St{constructor(){this._isCompleted=!1,this.promise=new Promise(((t,e)=>{this._resolver=t,this._rejecter=e}))}get isCompleted(){return this._isCompleted}resolve(t){this._isCompleted||(this._isCompleted=!0,this._resolver(t))}reject(t){this._isCompleted||(this._isCompleted=!0,this._rejecter(t))}}function Tt(t){let e=0,i=0;const s=t=>{e+=t.offsetLeft,t.offsetParent&&s(t.offsetParent)},n=t=>{i+=t.offsetTop,t.offsetParent&&n(t.offsetParent)};return s(t),n(t),new vt(e,i)}function Et(t,e){return-1===e.indexOf(t)&&(e.push(t),!0)}function Pt(t,e){let i=-1;return(i=e.indexOf(t))>-1&&(e.splice(i,1),!0)}function It(t,e){for(let i=0;i<t.length;i++)if(t[i]===e)return!0;return!1}function Dt(t){throw new Error(t)}function Bt(t,e){var i;const s=new St;return(null!==(i=null==e?void 0:e.schedule.bind(e))&&void 0!==i?i:setTimeout)((()=>{s.resolve()}),t),s.promise}!function(t){t[t.X=12]="X",t[t.Y=13]="Y"}(Ct||(Ct={}));class Rt{constructor(){this.data=new Float32Array(16),this._scaleX=1,this._scaleSignX=1,this._scaleY=1,this._scaleSignY=1}static ortho(t,e,i,s,n,r){const o=new Rt;return o.data[0]=2/(e-t),o.data[1]=0,o.data[2]=0,o.data[3]=0,o.data[4]=0,o.data[5]=2/(s-i),o.data[6]=0,o.data[7]=0,o.data[8]=0,o.data[9]=0,o.data[10]=-2/(r-n),o.data[11]=0,o.data[12]=-(e+t)/(e-t),o.data[13]=-(s+i)/(s-i),o.data[14]=-(r+n)/(r-n),o.data[15]=1,o}clone(t){const e=t||new Rt;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e.data[6]=this.data[6],e.data[7]=this.data[7],e.data[8]=this.data[8],e.data[9]=this.data[9],e.data[10]=this.data[10],e.data[11]=this.data[11],e.data[12]=this.data[12],e.data[13]=this.data[13],e.data[14]=this.data[14],e.data[15]=this.data[15],e}toDOMMatrix(){return new DOMMatrix([...this.data])}static fromFloat32Array(t){const e=new Rt;return e.data=t,e}static identity(){const t=new Rt;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=Rt.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=Rt.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=Rt.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multiply(t,e){if(t instanceof vt){const i=e||new vt(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[4]+this.data[12],r=s.x*this.data[1]+s.y*this.data[5]+this.data[13];return i.x=n,i.y=r,i}{const i=e||new Rt,s=t,n=this.data[0],r=this.data[1],o=this.data[2],a=this.data[3],h=this.data[4],l=this.data[5],c=this.data[6],d=this.data[7],u=this.data[8],p=this.data[9],_=this.data[10],g=this.data[11],m=this.data[12],f=this.data[13],v=this.data[14],x=this.data[15],y=s.data[0],w=s.data[1],b=s.data[2],C=s.data[3],A=s.data[4],S=s.data[5],T=s.data[6],E=s.data[7],P=s.data[8],I=s.data[9],D=s.data[10],B=s.data[11],R=s.data[12],F=s.data[13],k=s.data[14],M=s.data[15];i.data[0]=n*y+h*w+u*b+m*C,i.data[1]=r*y+l*w+p*b+f*C,i.data[2]=o*y+c*w+_*b+v*C,i.data[3]=a*y+d*w+g*b+x*C,i.data[4]=n*A+h*S+u*T+m*E,i.data[5]=r*A+l*S+p*T+f*E,i.data[6]=o*A+c*S+_*T+v*E,i.data[7]=a*A+d*S+g*T+x*E,i.data[8]=n*P+h*I+u*D+m*B,i.data[9]=r*P+l*I+p*D+f*B,i.data[10]=o*P+c*I+_*D+v*B,i.data[11]=a*P+d*I+g*D+x*B,i.data[12]=n*R+h*F+u*k+m*M,i.data[13]=r*R+l*F+p*k+f*M,i.data[14]=o*R+c*F+_*k+v*M,i.data[15]=a*R+d*F+g*k+x*M;const L=this.getScale();return i._scaleSignX=ct(L.x)*ct(i._scaleSignX),i._scaleSignY=ct(L.y)*ct(i._scaleSignY),i}}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],_=this.data[12],g=this.data[13],m=this.data[14],f=this.data[15];return this.data[12]=i*t+o*e+0*c+1*_,this.data[13]=s*t+a*e+0*d+1*g,this.data[14]=n*t+h*e+0*u+1*m,this.data[15]=r*t+l*e+0*p+1*f,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return xt(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=this.data[4],o=this.data[5],a=this.data[6],h=this.data[7],l=Math.sin(t),c=Math.cos(t);return this.data[0]=c*e+l*r,this.data[1]=c*i+l*o,this.data[2]=c*s+l*a,this.data[3]=c*n+l*h,this.data[4]=c*r-l*e,this.data[5]=c*o-l*i,this.data[6]=c*a-l*s,this.data[7]=c*h-l*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=r*t,this.data[4]=o*e,this.data[5]=a*e,this.data[6]=h*e,this.data[7]=l*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){return ut(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=xt(this.data[0],this.data[4]).size;return this._scaleSignX*t}getScaleY(){const t=xt(this.data[1],this.data[5]).size;return this._scaleSignY*t}getScale(){return xt(this.getScaleX(),this.getScaleY())}setScaleX(t){if(this._scaleX===t)return;this._scaleSignX=ct(t);const e=xt(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t,this._scaleX=t}setScaleY(t){if(this._scaleY===t)return;this._scaleSignY=ct(t);const e=xt(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t,this._scaleY=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(t){const e=1/this.getBasisDeterminant(),i=this.data[0],s=this.data[4],n=this.data[1],r=this.data[5],o=t||Rt.identity();o.data[0]=r*e,o.data[1]=-n*e,o.data[4]=-s*e,o.data[5]=i*e;const a=this.data[12],h=this.data[13];return o.data[12]=-(a*o.data[0]+h*o.data[4]),o.data[13]=-(a*o.data[1]+h*o.data[5]),o}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&0===this.data[3]&&0===this.data[4]&&1===this.data[5]&&0===this.data[6]&&0===this.data[7]&&0===this.data[8]&&0===this.data[9]&&1===this.data[10]&&0===this.data[11]&&0===this.data[12]&&0===this.data[13]&&0===this.data[14]&&1===this.data[15]}toString(){return`\n[${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]\n[${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]\n[${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]\n[${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]\n`}}class Ft{constructor(){this.data=new Float64Array(6),this._scale=new Float64Array([1,1]),this._scaleSignX=1,this._scaleSignY=1}toDOMMatrix(){return new DOMMatrix([...this.data])}static identity(){const t=new Ft;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}static translation(t,e){const i=Ft.identity();return i.data[4]=t,i.data[5]=e,i}static scale(t,e){const i=Ft.identity();return i.data[0]=t,i.data[3]=e,i._scale[0]=t,i._scale[1]=e,i}static rotation(t){const e=Ft.identity();return e.data[0]=Math.cos(t),e.data[1]=Math.sin(t),e.data[2]=-Math.sin(t),e.data[3]=Math.cos(t),e}setPosition(t,e){this.data[4]=t,this.data[5]=e}getPosition(){return xt(this.data[4],this.data[5])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=Math.sin(t),o=Math.cos(t);return this.data[0]=o*e+r*s,this.data[1]=o*i+r*n,this.data[2]=o*s-r*e,this.data[3]=o*n-r*i,this}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5];return this.data[4]=i*t+n*e+o,this.data[5]=s*t+r*e+a,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*e,this.data[3]=r*e,this._scale[0]=t,this._scale[1]=e,this}determinant(){return this.data[0]*this.data[3]-this.data[1]*this.data[2]}inverse(t){const e=1/this.determinant(),i=this.data[0],s=this.data[2],n=this.data[1],r=this.data[3],o=t||Ft.identity();o.data[0]=r*e,o.data[1]=-n*e,o.data[2]=-s*e,o.data[3]=i*e;const a=this.data[4],h=this.data[5];return o.data[4]=-(a*o.data[0]+h*o.data[2]),o.data[5]=-(a*o.data[1]+h*o.data[3]),o}multiply(t,e){if(t instanceof vt){const i=e||new vt(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[2]+this.data[4],r=s.x*this.data[1]+s.y*this.data[3]+this.data[5];return i.x=n,i.y=r,i}{const i=e||new Ft,s=t,n=this.data[0],r=this.data[1],o=this.data[2],a=this.data[3],h=this.data[4],l=this.data[5],c=s.data[0],d=s.data[1],u=s.data[2],p=s.data[3],_=s.data[4],g=s.data[5];i.data[0]=n*c+o*d,i.data[1]=r*c+a*d,i.data[2]=n*u+o*p,i.data[3]=r*u+a*p,i.data[4]=n*_+o*g+h,i.data[5]=r*_+a*g+l;const m=this.getScale();return i._scaleSignX=ct(m.x)*ct(i._scaleSignX),i._scaleSignY=ct(m.y)*ct(i._scaleSignY),i}}to4x4(){const t=new Rt;return t.data[0]=this.data[0],t.data[1]=this.data[1],t.data[2]=0,t.data[3]=0,t.data[4]=this.data[2],t.data[5]=this.data[3],t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=this.data[4],t.data[13]=this.data[5],t.data[14]=0,t.data[15]=1,t}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[2]=-i*e.x,this.data[3]=s*e.y}getRotation(){return ut(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=xt(this.data[0],this.data[2]).distance();return this._scaleSignX*t}getScaleY(){const t=xt(this.data[1],this.data[3]).distance();return this._scaleSignY*t}getScale(){return xt(this.getScaleX(),this.getScaleY())}setScaleX(t){if(t===this._scale[0])return;this._scaleSignX=ct(t);const e=xt(this.data[0]*this._scaleSignX,this.data[2]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[2]=e.y*t,this._scale[0]=t}setScaleY(t){if(t===this._scale[1])return;this._scaleSignY=ct(t);const e=xt(this.data[1]*this._scaleSignY,this.data[3]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[3]=e.y*t,this._scale[1]=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&1===this.data[3]&&0===this.data[4]&&0===this.data[5]}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}clone(t){const e=t||new Ft;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e}toString(){return`\n[${this.data[0]} ${this.data[2]} ${this.data[4]}]\n[${this.data[1]} ${this.data[3]} ${this.data[5]}]\n[0 0 1]\n`}}class kt{constructor(){this._transforms=[],this._currentTransform=Ft.identity()}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone()}restore(){this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class Mt{constructor(){this._states=[],this._currentState=this._getDefaultState()}_getDefaultState(){return{opacity:1,z:0,tint:yt.White,material:null}}_cloneState(){return{opacity:this._currentState.opacity,z:this._currentState.z,tint:this._currentState.tint.clone(),material:this._currentState.material}}save(){this._states.push(this._currentState),this._currentState=this._cloneState()}restore(){this._currentState=this._states.pop()}get current(){return this._currentState}set current(t){this._currentState=t}}const Lt={Complete:"complete",Load:"load",LoadStart:"loadstart",Progress:"progress",Error:"error"};class zt{constructor(t,e,i=!1){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=J.getInstance(),this.events=new d}isLoaded(){return null!==this.data}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise(((t,e)=>{if(null!==this.data)return this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),void t(this.data);const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",(t=>this.events.emit("loadstart",t))),i.addEventListener("progress",(t=>this.events.emit("progress",t))),i.addEventListener("error",(t=>this.events.emit("error",t))),i.addEventListener("load",(t=>this.events.emit("load",t))),i.addEventListener("load",(()=>{if(0!==i.status&&200!==i.status)return this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),void e(new Error(i.statusText));this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)})),i.send()}))}}function Ut(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]!==s&&(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t)),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}function Ot(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}class Nt{isStale(){return this._transformStale}get flipHorizontal(){return this._flipHorizontal}set flipHorizontal(t){this._flipHorizontal=t,this._transformStale=!0}get flipVertical(){return this._flipVertical}set flipVertical(t){this._flipVertical=t,this._transformStale=!0}get rotation(){return this._rotation}set rotation(t){this._rotation=t,this._transformStale=!0}get scale(){return this._scale}set scale(t){this._scale=Ut(t,(()=>{this._transformStale=!0})),this._transformStale=!0}get origin(){return this._origin}set origin(t){this._origin=Ut(t,(()=>{this._transformStale=!0})),this._transformStale=!0}constructor(t){var e,i,s,n,r,o;this.id=Nt._ID++,this.transform=Ft.identity(),this.tint=null,this._transformStale=!0,this.showDebug=!1,this._flipHorizontal=!1,this._flipVertical=!1,this._rotation=0,this.opacity=1,this._scale=vt.One,this._origin=null,this._width=0,this._height=0,t&&(this.origin=null!==(e=t.origin)&&void 0!==e?e:this.origin,this.flipHorizontal=null!==(i=t.flipHorizontal)&&void 0!==i?i:this.flipHorizontal,this.flipVertical=null!==(s=t.flipVertical)&&void 0!==s?s:this.flipVertical,this.rotation=null!==(n=t.rotation)&&void 0!==n?n:this.rotation,this.opacity=null!==(r=t.opacity)&&void 0!==r?r:this.opacity,this.scale=null!==(o=t.scale)&&void 0!==o?o:this.scale)}cloneGraphicOptions(){return{origin:this.origin?this.origin.clone():null,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():null}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t,this._transformStale=!0}set height(t){this._height=t,this._transformStale=!0}get localBounds(){return At.fromDimension(this.width,this.height,vt.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),this._transformStale&&(this.transform.reset(),this.transform.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(this.transform),this._flip(this.transform),this._transformStale=!1),t.multiply(this.transform),t.opacity=t.opacity*this.opacity,this.tint&&(t.tint=this.tint)}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=null!==(e=this.origin)&&void 0!==e?e:xt(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}Nt._ID=0;class Ht extends Nt{static from(t){return new Ht({image:t})}constructor(t){var e,i;super(t),this._logger=J.getInstance(),this._dirty=!0,this._logNotLoadedWarning=!1,this.image=t.image;const{width:s,height:n}=t;this.sourceView=null!==(e=t.sourceView)&&void 0!==e?e:{x:0,y:0,width:null!=s?s:0,height:null!=n?n:0},this.destSize=null!==(i=t.destSize)&&void 0!==i?i:{width:null!=s?s:0,height:null!=n?n:0},this._updateSpriteDimensions(),this.image.ready.then((()=>{this._updateSpriteDimensions()}))}get width(){return Math.abs(this.destSize.width*this.scale.x)}get height(){return Math.abs(this.destSize.height*this.scale.y)}set width(t){t/=Math.abs(this.scale.x),this.destSize.width=t,super.width=Math.ceil(this.destSize.width)}set height(t){t/=Math.abs(this.scale.y),this.destSize.height=t,super.height=Math.ceil(this.destSize.height)}_updateSpriteDimensions(){var t,e,i,s,n,r;const{width:o,height:a}=this.image;this.sourceView.width=(null===(t=this.sourceView)||void 0===t?void 0:t.width)||o,this.sourceView.height=(null===(e=this.sourceView)||void 0===e?void 0:e.height)||a,this.destSize.width=(null===(i=this.destSize)||void 0===i?void 0:i.width)||(null===(s=this.sourceView)||void 0===s?void 0:s.width)||o,this.destSize.height=(null===(n=this.destSize)||void 0===n?void 0:n.height)||(null===(r=this.sourceView)||void 0===r?void 0:r.height)||a,this.width=Math.ceil(this.destSize.width)*this.scale.x,this.height=Math.ceil(this.destSize.height)*this.scale.y}_preDraw(t,e,i){this.image.isLoaded()&&this._dirty&&(this._dirty=!1,this._updateSpriteDimensions()),super._preDraw(t,e,i)}_drawImage(t,e,i){this.image.isLoaded()?t.drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,e,i,this.destSize.width,this.destSize.height):(this._logNotLoadedWarning||this._logger.warn(`ImageSource ${this.image.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.\n\nRead https://excaliburjs.com/docs/imagesource for more information.`),this._logNotLoadedWarning=!0)}clone(){return new Ht({image:this.image,sourceView:{...this.sourceView},destSize:{...this.destSize},...this.cloneGraphicOptions()})}}var Wt;!function(t){t.Pixel="Pixel",t.Blended="Blended"}(Wt||(Wt={}));class Gt{constructor(t){this._textureMap=new Map,this._gl=t,Gt._MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE)}get(t){return this._textureMap.get(t)}has(t){return this._textureMap.has(t)}load(t,e,i=!1){const s=this._gl;if(!s)return null;let n=null;if(this.has(t)&&(n=this.get(t)),n)return i&&(s.bindTexture(s.TEXTURE_2D,n),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t)),n;n=s.createTexture(),Gt.checkImageSizeSupportedAndLog(t),s.bindTexture(s.TEXTURE_2D,n),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);const r=null!=e?e:Gt.filtering;return s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,r===Wt.Pixel?s.NEAREST:s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,r===Wt.Pixel?s.NEAREST:s.LINEAR),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t),this._textureMap.set(t,n),n}delete(t){const e=this._gl;if(!e)return null;let i=null;this.has(t)&&(i=this.get(t),e.deleteTexture(i))}static checkImageSizeSupportedAndLog(t){var e;const i=null!==(e=t.dataset.originalSrc)&&void 0!==e?e:"internal canvas bitmap";return t.width>Gt._MAX_TEXTURE_SIZE||t.height>Gt._MAX_TEXTURE_SIZE?(Gt._LOGGER.error(`The image [${i}] provided to Excalibur is too large for the device's maximum texture size of (${Gt._MAX_TEXTURE_SIZE}x${Gt._MAX_TEXTURE_SIZE}) please resize to an image for excalibur to render properly.\n\nImages will likely render as black rectangles.\n\nRead more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!1):((t.width>4096||t.height>4096)&&Gt._LOGGER.warn(`The image [${i}] provided to excalibur is too large may not work on all mobile devices, it is recommended you resize images to a maximum (4096x4096).\n\nImages will likely render as black rectangles on some mobile platforms.\n\nRead more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!0)}}Gt._LOGGER=J.getInstance(),Gt.filtering=Wt.Blended,Gt._MAX_TEXTURE_SIZE=4096;class Vt{get width(){return this.image.naturalWidth}get height(){return this.image.naturalHeight}isLoaded(){return this._src||(this._src=this.data.src),!!this._src}get image(){return this.data}constructor(t,e=!1,i){this.path=t,this._logger=J.getInstance(),this.data=new Image,this._readyFuture=new St,this.ready=this._readyFuture.promise,this._resource=new zt(t,"blob",e),this.filtering=i,(t.endsWith(".svg")||t.endsWith(".gif"))&&this._logger.warn(`Image type is not fully supported, you may have mixed results ${t}. Fully supported: jpg, bmp, and png`)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){if(this.isLoaded())return this.data;try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=await this._resource.load();t=URL.createObjectURL(e)}const e=new Image,i=new St;e.onload=()=>i.resolve(),e.src=t,e.setAttribute("data-original-src",this.path),await i.promise,this.data=e,Gt.checkImageSizeSupportedAndLog(this.data)}catch(t){throw`Error loading ImageSource from path '${this.path}' with error [${t.message}]`}return this.data.setAttribute("filtering",this.filtering),this._readyFuture.resolve(this.data),this.data}toSprite(){return Ht.from(this)}unload(){this.data=new Image}}class qt{constructor(t){this._logger=J.getInstance(),this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=null!=i?i:1,this.columns=null!=s?s:this.sprites.length}getSprite(t,e){if(t>=this.columns||t<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1}`),null;if(e>=this.rows||e<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1}`),null;const i=t+e*this.columns;return this.sprites[i]}static fromImageSourceWithSourceViews(t){const e=t.sourceViews.map((e=>new Ht({image:t.image,sourceView:e})));return new qt({sprites:e})}static fromImageSource(t){var e;const i=[];t.spacing=null!==(e=t.spacing)&&void 0!==e?e:{};const{image:s,grid:{rows:n,columns:r,spriteWidth:o,spriteHeight:a},spacing:{originOffset:h,margin:l}}=t,c={x:0,y:0,...h},d={x:0,y:0,...l};for(let t=0;t<r;t++)for(let e=0;e<n;e++)i[t+e*r]=new Ht({image:s,sourceView:{x:t*o+d.x*t+c.x,y:e*a+d.y*e+c.y,width:o,height:a},destSize:{height:a,width:o}});return new qt({sprites:i,rows:n,columns:r})}clone(){return new qt({sprites:this.sprites.map((t=>t.clone())),rows:this.rows,columns:this.columns})}}class Xt extends Nt{constructor(t){super(t),this._text="",this.alphabet="",this.shadow=null,this.caseInsensitive=!1,this.spacing=0,this._logger=J.getInstance(),this._alreadyWarnedAlphabet=!1,this._alreadyWarnedSpriteSheet=!1;const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:r}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=null!=s?s:this.caseInsensitive,this.spacing=null!=n?n:this.spacing,this.shadow=null!=r?r:this.shadow}_getCharacterSprites(t){const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let t=0;t<i.length;t++){const n=i[t];let r=s.indexOf(n);-1===r&&(r=0,this._alreadyWarnedAlphabet||(this._logger.warn(`SpriteFont - Cannot find letter '${n}' in configured alphabet '${s}'.`),this._logger.warn("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."),this._alreadyWarnedAlphabet=!0));const o=this.spriteSheet.sprites[r];o?e.push(o):this._alreadyWarnedSpriteSheet||(this._logger.warn(`SpriteFont - Cannot find sprite for '${n}' at index '${r}' in configured SpriteSheet`),this._logger.warn("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."),this._alreadyWarnedSpriteSheet=!0)}return e}measureText(t,e){const i=this._getLinesFromText(t,e),s=i.reduce(((t,e)=>t.length>e.length?t:e)),n=this._getCharacterSprites(s);let r=0,o=0;for(const t of n)r+=t.width+this.spacing,o=Math.max(o,t.height);return At.fromDimension(r,o*i.length,vt.Zero)}_drawImage(t,e,i,s){let n=0,r=0,o=0;const a=this._getLinesFromText(this._text,s);for(const s of a){for(const a of this._getCharacterSprites(s))a.draw(t,e+n,i+r),n+=a.width+this.spacing,o=Math.max(o,a.height);n=0,r+=o}}render(t,e,i,s,n,r){this._text=e;const o=this.measureText(e,r);this.width=o.width,this.height=o.height,this.shadow&&(t.save(),t.translate(this.shadow.offset.x,this.shadow.offset.y),this._preDraw(t,s,n),this._drawImage(t,0,0,r),this._postDraw(t),t.restore()),this._preDraw(t,s,n),this._drawImage(t,0,0,r),this._postDraw(t)}clone(){return new Xt({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}_getLinesFromText(t,e){if(this._cachedText===t&&this._cachedRenderWidth===e)return this._cachedLines;const i=t.split("\n");if(null==e)return i;for(let t=0;t<i.length;t++){let s=i[t],n="";if(this.measureText(s).width>e){for(;this.measureText(s).width>e;)n=s[s.length-1]+n,s=s.slice(0,-1);i[t]=s,i[t+1]=n}}return this._cachedText=t,this._cachedLines=i,this._cachedRenderWidth=e,i}}class Kt{constructor(){this.fontSheet="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABACAYAAAD1Xam+AAAAAXNSR0IArs4c6QAABlFJREFUeJztndmy4yoMRcWt/v9fdr8EWoDAaDD4JntVpeqcxBrMIGQDNhEAAAAAAAAAAAAAAOCrSbMfr+u6yoEpTY+906GV57YtPkjyXj9WZZ+wHWHfo2N3/bU6Tte9Rv6ptruqRyMvKvvIX/zY3I/vjLeqsg6l/CWdp0KHKO/1Y1H2EdsR9j06Ntdfp+N03SvkH2u7i3pu5XkQ+DNTkgNJSok+/183xpcdWZHjgUzpQ2pGD67vaf//KRAGAq3tdhCy2tcMQKPyXyz7iPqrdBjbX5h9g7xbtvWf4ZJvM4D/BKG24Sd+IkQ0TC9aW5NM5FbO2HgrPVzW2vmN50DZNv/QWtl5bfPy85SBtdy9dFmjsf2F2SehTBVE+u+tkE5+lAGcJlFwGuodwRRU2Qe3rx0FhPNflc3HWC7BEh8EDGVR5IMCiLnDONtPp87qhxVH/S/LvzUAuDs/kyGimA5oSONKR1w8vsLpv+v+S9vhmS71JRiX1xB5CWZNw7m6rMrllMag/RJyWb67BEgpDVMWSydc+K47pr35w05kWd7ReEq6116KaG4CsbJ7OmV9PdZLEKkONiC1/7ZONVgDsajLIJPYp2OUAXRpnPcGmnIE6eSK4nv5YQqqSYO52JqnYfYj/PdQXQIY7XszuMofMgZRT/1LdeC5h2I5/0EdWDMY2Yb05WDE1RodVdpSA5r85slArAVnSf+89iP896St0f5bZKVA7Gk/3ja8q+152/+wrLqBWZTem3IBADbRBoDuHgAA4HdAAADgh0EAAOCHQQAA4IdBAADgh0EAAOCHuVsKbJ3P9M7jjuxHzGfv8j9iDt47Dx7hP8cjq5F/o/0T62Aer//ZOgDrajBp6aNlOWTEajKLjgj/Pcs/vfZD/a++3Pc8hNfZ966EVeh5vP75luDRJUAl0KzJfnopaqbaTuzZiulc2BS5lltFXntu3dcQsXadl59Wn1H+dfYNtrt2d6D/LDF9HkCQw6eXFbr8P9X5W/un5Ol8gz1t39p5pWOPn0vLynbgdnfe8maEQw+UIPJdfxdOd/4oTtVD0IYg8wDywGas0I04T5O3P8/qf2UWwPpkn1PbOT1bN2tFe59EM7TvKf+TRFw+erZ2ey4hpS3hp9qBkqq/tjsSU1OYqucBWB1yynt5QxC42Mdk30pAEIio//zRG3feBzLUX+TTjCKwlH83aI/KbpQBVEHgUGF0j/SitcLofHem8q6AyH0wBhFv4WszuOjy0yK2vc/oRWQoP2X9ve78jfaLnpncbBqQSC6s0HnIRT0a2yNZjfxT8+ir8t+yDsDTWaS6X70GP33+d77stp+I5HtBdwEAAPBl8ECApcAA/DBvfSowAGAB7/05ZAAA/DAIAADMMU3fOuS2ggAAwBjrorKoxWiPBxHMAgAg490Ts0VeePdA+ZfJDKcCh7sBqY88mmjklZeOt9iXPrvx2I2QPRnN2/qzyJ84h4gNcbtfasq5mM1rZr+bBWh2A+bIIX13Z9wqL+nQvFno7v3oq4tJItCed7isUT6C/I7BUn9KP95wDicYBYpcjncrO2c/dmW4tBtw4RiRld1IDxDyYsoXMHxF1w3dyz0Nne8033AOFsT6VgRCafl89fenTZUfbm8CGhrgdDcS7anAsvnkkP0IeCfQ+JzYunky6jhNYj5bl7++4fJvN9WDSKS/292A0wyANyKDI91bfkm3kcH7ckaP/SKW/VHKRZAcI14pP3beu0fPyn/DuZQbWMogNnsc16sziE96f7H/iai7uTf0/3N8lwFz/e13T00Djt4OrInCnkeChXT+qOcKOLA21tJpsv/G8/COnGnw97J9QwbTvd6djYSv7fxEVTuV/LzNhj7nOawv6bfbAGCYEpQ6HxFtuxs6sq9tzOYHobQ6Nje+6vo5BwFrPZ4OgMayS4PPt1NlzdLfbRCYBoBc+NaO4JWPwLEf33oN3unY3InKPQBW6Z7nEZzEmrl4iZjC804lqgePPEOguQcwWghUphxm343wyt/pWpWR0OrR+jvyxavHajfb9pTjbt9bH07Z5/expM4TLWfwb7QQqMoC+UDWXZo/4RgA38LOgUvLJAAQ1Td9y9//0ylxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+g79apuVUsS5ZmwAAAABJRU5ErkJggg==",this.size=16,this.load()}load(){return this._imageSource=new Vt(this.fontSheet),this._imageSource.load().then((()=>{this._spriteSheet=qt.fromImageSource({image:this._imageSource,grid:{rows:4,columns:16,spriteWidth:16,spriteHeight:16}}),this._spriteFont=new Xt({alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,!'&.\"?-()+# ",caseInsensitive:!0,spriteSheet:this._spriteSheet,spacing:-6})}))}write(t,e,i){this._imageSource.isLoaded()&&this._spriteFont.render(t,e,null,i.x,i.y)}}class Zt{constructor(t,e){this._gl=t,this._texture=e}use(){const t=this._gl;t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture)}disable(){const t=this._gl;t.bindTexture(t.TEXTURE_2D,null)}}class Yt{constructor(t){this.width=t.width,this.height=t.height,this._gl=t.gl,this._setupFramebuffer()}setResolution(t,e){const i=this._gl;this.width=t,this.height=e,i.bindTexture(i.TEXTURE_2D,this._frameTexture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null)}get frameBuffer(){return this._frameBuffer}get frameTexture(){return this._frameTexture}_setupFramebuffer(){const t=this._gl;this._frameTexture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this._frameTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);const e=t.COLOR_ATTACHMENT0;this._frameBuffer=t.createFramebuffer(),t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,e,t.TEXTURE_2D,this._frameTexture,0),this.disable()}toRenderSource(){return new Zt(this._gl,this._frameTexture)}use(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.viewport(0,0,this.width,this.height)}disable(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null)}}function jt(t,e){switch(e){case t.FLOAT:return 4;case t.SHORT:case t.UNSIGNED_SHORT:return 2;case t.BYTE:case t.UNSIGNED_BYTE:default:return 1}}function Qt(t,e){switch(e){case t.LOW_FLOAT:case t.HIGH_FLOAT:case t.FLOAT:return 1;case t.FLOAT_VEC2:return 2;case t.FLOAT_VEC3:return 3;case t.FLOAT_VEC4:return 4;case t.BYTE:case t.UNSIGNED_BYTE:case t.UNSIGNED_SHORT:case t.SHORT:default:return 1}}function $t(t,e){switch(e){case t.LOW_FLOAT:case t.HIGH_FLOAT:case t.FLOAT:case t.FLOAT_VEC2:case t.FLOAT_VEC3:case t.FLOAT_VEC4:return t.FLOAT;case t.BYTE:return t.BYTE;case t.UNSIGNED_BYTE:return t.UNSIGNED_BYTE;case t.SHORT:return t.SHORT;case t.UNSIGNED_SHORT:return t.UNSIGNED_SHORT;default:return t.FLOAT}}class Jt{get compiled(){return this._compiled}constructor(t){this._logger=J.getInstance(),this.uniforms={},this.attributes={},this._compiled=!1;const{gl:e,vertexSource:i,fragmentSource:s}=t;this._gl=e,this.vertexSource=i,this.fragmentSource=s}use(){this._gl.useProgram(this.program),Jt._ACTIVE_SHADER_INSTANCE=this}isCurrentlyBound(){return Jt._ACTIVE_SHADER_INSTANCE===this}compile(){const t=this._gl,e=this._compileShader(t,this.vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this.fragmentSource,t.FRAGMENT_SHADER);this.program=this._createProgram(t,e,i);const s=this.getAttributes();for(const t of s)this.attributes[t.name]=t;const n=this.getUniforms();for(const t of n)this.uniforms[t.name]=t;return this._compiled=!0,this.program}getUniforms(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS),i=[];for(let s=0;s<e;s++){const e=t.getActiveUniform(this.program,s),n=t.getUniformLocation(this.program,e.name);i.push({name:e.name,glType:e.type,location:n})}return i}getAttributes(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES),i=[];for(let s=0;s<e;s++){const e=t.getActiveAttrib(this.program,s),n=t.getAttribLocation(this.program,e.name);i.push({name:e.name,glType:$t(t,e.type),size:Qt(t,e.type),location:n,normalized:!1})}return i}setTexture(t,e){const i=this._gl;i.activeTexture(i.TEXTURE0+t),i.bindTexture(i.TEXTURE_2D,e)}setUniformInt(t,e){this.setUniform("uniform1i",t,~~e)}trySetUniformInt(t,e){return this.trySetUniform("uniform1i",t,~~e)}setUniformIntArray(t,e){this.setUniform("uniform1iv",t,e)}trySetUniformIntArray(t,e){return this.trySetUniform("uniform1iv",t,e)}setUniformBoolean(t,e){this.setUniform("uniform1i",t,e?1:0)}trySetUniformBoolean(t,e){return this.trySetUniform("uniform1i",t,e?1:0)}setUniformFloat(t,e){this.setUniform("uniform1f",t,e)}trySetUniformFloat(t,e){return this.trySetUniform("uniform1f",t,e)}setUniformFloatArray(t,e){this.setUniform("uniform1fv",t,e)}trySetUniformFloatArray(t,e){return this.trySetUniform("uniform1fv",t,e)}setUniformFloatVector(t,e){this.setUniform("uniform2f",t,e.x,e.y)}trySetUniformFloatVector(t,e){return this.trySetUniform("uniform2f",t,e.x,e.y)}setUniformFloatColor(t,e){this.setUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}trySetUniformFloatColor(t,e){return this.trySetUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}setUniformMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,e.data)}trySetUniformMatrix(t,e){return this.trySetUniform("uniformMatrix4fv",t,!1,e.data)}setUniform(t,e,...i){if(!this._compiled)throw Error(`Must compile shader before setting a uniform ${t}:${e}`);if(!this.isCurrentlyBound())throw Error("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms");const s=this._gl.getUniformLocation(this.program,e);if(!s)throw Error(`Uniform ${t}:${e} doesn't exist or is not used in the shader source code, unused uniforms are optimized away by most browsers`);{const e=[s,...i];this._gl[t].apply(this._gl,e)}}trySetUniform(t,e,...i){if(!this._compiled)return this._logger.warn(`Must compile shader before setting a uniform ${t}:${e}`),!1;if(!this.isCurrentlyBound())return this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1;const s=this._gl.getUniformLocation(this.program,e);if(!s)return!1;{const e=[s,...i];this._gl[t].apply(this._gl,e)}return!0}_createProgram(t,e,i){const s=t.createProgram();if(null===s)throw Error("Could not create graphics shader program");t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s);if(!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.VERTEX_SHADER===i?"vertex":"fragment",n=t.createShader(i);if(null===n)throw Error(`Could not build shader: [${e}]`);t.shaderSource(n,e),t.compileShader(n);if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);throw Error(`Could not compile ${s} shader:\n\n${i}${this._processSourceForError(e,i)}`)}return n}_processSourceForError(t,e){if(!t)return e;const i=t.split("\n"),s=e.search(/\d:\d/),n=e.indexOf(" ",s),[r,o]=e.slice(s,n).split(":").map((t=>Number(t)));for(let t=0;t<i.length;t++)i[t]=`${t+1}: ${i[t]}${o===t+1?" <----- ERROR!":""}`;return"\n\nSource:\n"+i.join("\n")}}Jt._ACTIVE_SHADER_INSTANCE=null;class te{constructor(t){this.type="dynamic";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=this._gl.createBuffer(),!n&&!i)throw Error("Must either provide data or a size to the VertexBuffer");this.bufferData=n||new Float32Array(i),this.type=null!=s?s:this.type,e.bindBuffer(e.ARRAY_BUFFER,this.buffer),e.bufferData(e.ARRAY_BUFFER,this.bufferData,"static"===this.type?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this.buffer)}upload(t){const e=this._gl;e.bindBuffer(e.ARRAY_BUFFER,this.buffer),t?e.bufferSubData(e.ARRAY_BUFFER,0,this.bufferData,0,t):e.bufferData(e.ARRAY_BUFFER,this.bufferData,"static"===this.type?e.STATIC_DRAW:e.DYNAMIC_DRAW)}}class ee{get vertexBuffer(){return this._vertexBuffer}get attributes(){return this._attributes}constructor(t){this._logger=J.getInstance(),this._layout=[],this._attributes=[],this._vertexTotalSizeBytes=0;const{gl:e,shader:i,vertexBuffer:s,attributes:n}=t;this._gl=e,this._vertexBuffer=s,this._attributes=n,this._shader=i,i&&this.initialize()}get totalVertexSizeBytes(){return this._vertexTotalSizeBytes}set shader(t){t&&this._shader!==t&&(this._shader=t,this.initialize())}get shader(){return this._shader}initialize(){if(!this._shader)return;if(!this._shader.compiled)throw Error("Shader not compiled, shader must be compiled before defining a vertex layout");this._vertexTotalSizeBytes=0,this._layout.length=0;const t=this._shader.attributes;for(const e of this._attributes){const i=t[e[0]];if(!i)throw Error(`The attribute named: ${e[0]} size ${e[1]} not found in the shader source code:\n ${this._shader.vertexSource}`);if(i.size!==e[1])throw Error(`VertexLayout size definition for attribute: [${e[0]}, ${e[1]}], doesnt match shader source size ${i.size}:\n ${this._shader.vertexSource}`);this._layout.push(i)}let e=0;for(const t of this._layout){const i=jt(this._gl,t.glType);this._vertexTotalSizeBytes+=i*t.size,e+=t.size}this._vertexBuffer.bufferData.length%e!=0&&this._logger.warn(`The vertex component size (${e}) does divide evenly into the specified vertex buffer (${this._vertexBuffer.bufferData.length})`)}use(t=!1,e){if(!this._shader)throw Error("No shader is associated with this vertex layout, a shader must be set");const i=this._gl;if(!this._shader.isCurrentlyBound())throw Error("Shader associated with this vertex layout is not active! Call shader.use() before layout.use()");this._vertexBuffer.bind(),t&&this._vertexBuffer.upload(e);let s=0;for(const t of this._layout)i.vertexAttribPointer(t.location,t.size,t.glType,t.normalized,this.totalVertexSizeBytes,s),i.enableVertexAttribArray(t.location),s+=jt(i,t.glType)*t.size}}class ie{static clear(){ie.DrawCallCount=0,ie.DrawnImagesCount=0}}ie.DrawCallCount=0,ie.DrawnImagesCount=0;class se{constructor(){this.type="ex.line",this.priority=0,this._maxLines=10922,this._vertexIndex=0,this._lineCount=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Jt({gl:t,vertexSource:"#version 300 es\r\nin vec2 a_position;\r\nin vec4 a_color;\r\n\r\nout lowp vec4 v_color;\r\n\r\nuniform mat4 u_matrix;\r\n\r\nvoid main() {\r\n // Set the vertex position using the ortho transform matrix\r\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\r\n\r\n // Passthrough the color\r\n v_color = a_color;\r\n}",fragmentSource:"#version 300 es\r\nprecision mediump float;\r\n\r\n// Color\r\nin lowp vec4 v_color;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n fragColor = v_color;\r\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._vertexBuffer=new te({gl:t,size:12*this._maxLines,type:"dynamic"}),this._layout=new ee({gl:t,vertexBuffer:this._vertexBuffer,shader:this._shader,attributes:[["a_position",2],["a_color",4]]})}draw(t,e,i){this._isFull()&&this.flush(),this._lineCount++;const s=this._context.getTransform(),n=s.multiply(t),r=s.multiply(e),o=this._vertexBuffer.bufferData;o[this._vertexIndex++]=n.x,o[this._vertexIndex++]=n.y,o[this._vertexIndex++]=i.r/255,o[this._vertexIndex++]=i.g/255,o[this._vertexIndex++]=i.b/255,o[this._vertexIndex++]=i.a,o[this._vertexIndex++]=r.x,o[this._vertexIndex++]=r.y,o[this._vertexIndex++]=i.r/255,o[this._vertexIndex++]=i.g/255,o[this._vertexIndex++]=i.b/255,o[this._vertexIndex++]=i.a}_isFull(){return this._lineCount>=this._maxLines}hasPendingDraws(){return 0!==this._lineCount}flush(){if(0===this._lineCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),t.drawArrays(t.LINES,0,2*this._lineCount),ie.DrawnImagesCount+=this._lineCount,ie.DrawCallCount++,this._vertexIndex=0,this._lineCount=0}}class ne{constructor(){this.type="ex.point",this.priority=0,this._maxPoints=10922,this._pointCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Jt({gl:t,vertexSource:"#version 300 es\r\nin vec2 a_position;\r\nin vec4 a_color;\r\nin float a_size;\r\nout lowp vec4 v_color;\r\nuniform mat4 u_matrix;\r\n\r\nvoid main() {\r\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\r\n gl_PointSize = a_size * 2.0;\r\n v_color = a_color;\r\n}",fragmentSource:'#version 300 es\r\n\r\nprecision mediump float;\r\nin lowp vec4 v_color;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n float r = 0.0, delta = 0.0, alpha = 1.0;\r\n vec2 cxy = 2.0 * gl_PointCoord - 1.0;\r\n r = dot(cxy, cxy);\r\n\r\n delta = fwidth(r);\r\n alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r);\r\n // "premultiply" the color by alpha\r\n vec4 color = v_color;\r\n color.a = color.a * alpha;\r\n color.rgb = color.rgb * color.a;\r\n fragColor = color;\r\n}'}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._buffer=new te({gl:t,size:7*this._maxPoints,type:"dynamic"}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_color",4],["a_size",1]]})}draw(t,e,i){this._isFull()&&this.flush(),this._pointCount++;const s=this._context.getTransform(),n=this._context.opacity,r=this._context.snapToPixel,o=s.multiply(t);r&&(o.x=~~(o.x+_e),o.y=~~(o.y+_e));const a=this._buffer.bufferData;a[this._vertexIndex++]=o.x,a[this._vertexIndex++]=o.y,a[this._vertexIndex++]=e.r/255,a[this._vertexIndex++]=e.g/255,a[this._vertexIndex++]=e.b/255,a[this._vertexIndex++]=e.a*n,a[this._vertexIndex++]=i*Math.max(s.getScaleX(),s.getScaleY())}_isFull(){return this._pointCount>=this._maxPoints}hasPendingDraws(){return 0!==this._pointCount}flush(){if(0===this._pointCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),t.drawArrays(t.POINTS,0,this._pointCount),ie.DrawnImagesCount+=this._pointCount,ie.DrawCallCount++,this._pointCount=0,this._vertexIndex=0}}class re{constructor(t){this._gl=t,this._shader=new Jt({gl:t,vertexSource:"#version 300 es\r\nin vec2 a_position;\r\n\r\nin vec2 a_texcoord;\r\nout vec2 v_texcoord;\r\n\r\nvoid main() {\r\n gl_Position = vec4(a_position, 0.0, 1.0);\r\n\r\n // Pass the texcoord to the fragment shader.\r\n v_texcoord = a_texcoord;\r\n}",fragmentSource:"#version 300 es\r\nprecision mediump float;\r\n\r\n// Passed in from the vertex shader.\r\nin vec2 v_texcoord;\r\n\r\n// The texture.\r\nuniform sampler2D u_texture;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n fragColor = texture(u_texture, v_texcoord);\r\n}"}),this._shader.compile(),this._buffer=new te({gl:t,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}renderWithPostProcessor(t){const e=this._gl;t.getShader().use(),t.getLayout().use(),e.drawArrays(e.TRIANGLES,0,6)}renderToScreen(){const t=this._gl;this._shader.use(),this._layout.use(),t.drawArrays(t.TRIANGLES,0,6)}}class oe{constructor(t,e,i){this._logger=J.getInstance(),this._gl=t,this.buffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer);const s=6*e;if(i){const i=65535,n=Math.floor((i-1)/4);this.bufferGlType=t.UNSIGNED_SHORT,this.bufferData=new Uint16Array(s),e>n&&this._logger.warn(`Total quads exceeds hardware index buffer limit (uint16), max(${n}) requested quads(${e})`)}else this.bufferData=new Uint32Array(s);let n=0;for(let t=0;t<s;t+=6)this.bufferData[t+0]=n+0,this.bufferData[t+1]=n+1,this.bufferData[t+2]=n+2,this.bufferData[t+3]=n+2,this.bufferData[t+4]=n+1,this.bufferData[t+5]=n+3,n+=4;t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}get size(){return this.bufferData.length}upload(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer)}}class ae{constructor(){this.type="ex.image",this.priority=0,this._maxImages=10922,this._maxTextures=0,this._imageCount=0,this._textures=[],this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._maxTextures=Math.min(t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),125);const i=this._transformFragmentSource("#version 300 es\r\nprecision mediump float;\r\n\r\n// UV coord\r\nin vec2 v_texcoord;\r\n\r\n// Texture index\r\nin lowp float v_textureIndex;\r\n\r\n// Textures in the current draw\r\nuniform sampler2D u_textures[%%count%%];\r\n\r\n// Opacity\r\nin float v_opacity;\r\n\r\nin vec4 v_tint;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n // In order to support the most efficient sprite batching, we have multiple\r\n // textures loaded into the gpu (usually 8) this picker logic skips over textures\r\n // that do not apply to a particular sprite.\r\n\r\n vec4 color = vec4(1.0, 0, 0, 1.0);\r\n\r\n // GLSL is templated out to pick the right texture and set the vec4 color\r\n %%texture_picker%%\r\n\r\n color.rgb = color.rgb * v_opacity;\r\n color.a = color.a * v_opacity;\r\n fragColor = color * v_tint;\r\n}",this._maxTextures);this._shader=new Jt({gl:t,fragmentSource:i,vertexSource:"#version 300 es\r\nin vec2 a_position;\r\n\r\n// Opacity \r\nin float a_opacity;\r\nout float v_opacity;\r\n\r\n// UV coordinate\r\nin vec2 a_texcoord;\r\nout vec2 v_texcoord;\r\n\r\n// Texture number\r\nin lowp float a_textureIndex;\r\nout lowp float v_textureIndex;\r\n\r\nin vec4 a_tint;\r\nout vec4 v_tint;\r\n\r\nuniform mat4 u_matrix;\r\n\r\nvoid main() {\r\n // Set the vertex position using the ortho transform matrix\r\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\r\n\r\n // Pass through the Opacity to the fragment shader\r\n v_opacity = a_opacity;\r\n // Pass through the UV coord to the fragment shader\r\n v_texcoord = a_texcoord;\r\n // Pass through the texture number to the fragment shader\r\n v_textureIndex = a_textureIndex;\r\n // Pass through the tint\r\n v_tint = a_tint;\r\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map(((t,e)=>e))),this._buffer=new te({gl:t,size:40*this._maxImages,type:"dynamic"}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_opacity",1],["a_texcoord",2],["a_textureIndex",1],["a_tint",4]]}),this._quads=new oe(t,this._maxImages,!0)}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let t=0;t<e;t++)s+=0===t?`if (v_textureIndex <= ${t}.5) {\n`:` else if (v_textureIndex <= ${t}.5) {\n`,s+=` color = texture(u_textures[${t}], v_texcoord);\n`,s+=" }\n";return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){const e=t.getAttribute("filtering");let i=null;e!==Wt.Blended&&e!==Wt.Pixel||(i=e);const s="true"===t.getAttribute("forceUpload"),n=this._context.textureLoader.load(t,i,s);t.removeAttribute("forceUpload"),-1===this._textures.indexOf(n)&&this._textures.push(n)}_bindTextures(t){for(let e=0;e<this._maxTextures;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this._textures[e]||this._textures[0])}_getTextureIdForImage(t){if(t){const e=this._context.textureLoader.get(t);return this._textures.indexOf(e)}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}draw(t,e,i,s,n,r,o,a,h){var l,c,d,u;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);let p=(null==t?void 0:t.width)||s||0,_=(null==t?void 0:t.height)||n||0,g=[0,0,null!==(l=null!=s?s:null==t?void 0:t.width)&&void 0!==l?l:0,null!==(c=null!=n?n:null==t?void 0:t.height)&&void 0!==c?c:0],m=[null!=e?e:1,null!=i?i:1];void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(g=[null!=e?e:1,null!=i?i:1,null!==(d=null!=s?s:null==t?void 0:t.width)&&void 0!==d?d:0,null!==(u=null!=n?n:null==t?void 0:t.height)&&void 0!==u?u:0],m=[r,o],p=a,_=h),e=g[0],i=g[1];const f=g[2],v=g[3],x=this._context.getTransform(),y=this._context.opacity,w=this._context.snapToPixel;let b=xt(m[0],m[1]),C=xt(m[0]+p,m[1]),A=xt(m[0],m[1]+_),S=xt(m[0]+p,m[1]+_);b=x.multiply(b),C=x.multiply(C),A=x.multiply(A),S=x.multiply(S),w&&(b.x=~~(b.x+_e),b.y=~~(b.y+_e),C.x=~~(C.x+_e),C.y=~~(C.y+_e),A.x=~~(A.x+_e),A.y=~~(A.y+_e),S.x=~~(S.x+_e),S.y=~~(S.y+_e));const T=this._context.tint,E=this._getTextureIdForImage(t),P=t.width||p,I=t.height||_,D=e/P,B=i/I,R=(e+f-.01)/P,F=(i+v-.01)/I,k=this._layout.vertexBuffer.bufferData;k[this._vertexIndex++]=b.x,k[this._vertexIndex++]=b.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=D,k[this._vertexIndex++]=B,k[this._vertexIndex++]=E,k[this._vertexIndex++]=T.r/255,k[this._vertexIndex++]=T.g/255,k[this._vertexIndex++]=T.b/255,k[this._vertexIndex++]=T.a,k[this._vertexIndex++]=A.x,k[this._vertexIndex++]=A.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=D,k[this._vertexIndex++]=F,k[this._vertexIndex++]=E,k[this._vertexIndex++]=T.r/255,k[this._vertexIndex++]=T.g/255,k[this._vertexIndex++]=T.b/255,k[this._vertexIndex++]=T.a,k[this._vertexIndex++]=C.x,k[this._vertexIndex++]=C.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=R,k[this._vertexIndex++]=B,k[this._vertexIndex++]=E,k[this._vertexIndex++]=T.r/255,k[this._vertexIndex++]=T.g/255,k[this._vertexIndex++]=T.b/255,k[this._vertexIndex++]=T.a,k[this._vertexIndex++]=S.x,k[this._vertexIndex++]=S.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=R,k[this._vertexIndex++]=F,k[this._vertexIndex++]=E,k[this._vertexIndex++]=T.r/255,k[this._vertexIndex++]=T.g/255,k[this._vertexIndex++]=T.b/255,k[this._vertexIndex++]=T.a}hasPendingDraws(){return 0!==this._imageCount}flush(){if(0===this._imageCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0,40*this._imageCount),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._bindTextures(t),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._imageCount,this._quads.bufferGlType,0),ie.DrawnImagesCount+=this._imageCount,ie.DrawCallCount++,this._imageCount=0,this._vertexIndex=0,this._textures.length=0}}class he{constructor(){this.type="ex.rectangle",this.priority=0,this._maxRectangles=10922,this._rectangleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Jt({gl:t,fragmentSource:"#version 300 es\r\n\r\nprecision mediump float;\r\n\r\n// UV coord\r\nin vec2 v_uv;\r\n\r\nin vec2 v_size; // in pixels\r\n\r\n// Color coord to blend with image\r\nin lowp vec4 v_color;\r\n\r\n// Stroke color if used\r\nin lowp vec4 v_strokeColor;\r\n\r\n// Stroke thickness if used\r\nin lowp float v_strokeThickness; // in pixels\r\n\r\n// Opacity\r\nin float v_opacity;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n // modified from https://stackoverflow.com/questions/59197671/glsl-rounded-rectangle-with-variable-border\r\n vec2 uv = v_uv;\r\n vec2 fragCoord = uv * v_size;\r\n float maxX = v_size.x - v_strokeThickness;\r\n float minX = v_strokeThickness;\r\n float maxY = v_size.y - v_strokeThickness;\r\n float minY = v_strokeThickness;\r\n\r\n if (fragCoord.x < maxX && fragCoord.x > minX &&\r\n fragCoord.y < maxY && fragCoord.y > minY) {\r\n fragColor = v_color;\r\n } else {\r\n fragColor = v_strokeColor;\r\n }\r\n fragColor.a *= v_opacity;\r\n fragColor.rgb *= fragColor.a;\r\n\r\n // vec2 v2CenteredPos = abs(fragCoord - v_size.xy / 2.0);\r\n // vec2 v2HalfShapeSizePx = v_size.xy/2.0 - v_strokeThickness/2.0;\r\n\r\n // float fHalfBorderDist = 0.0;\r\n // float fHalfBorderThickness = 0.0;\r\n\r\n // if (fragCoord.x > max(v_radius, v_strokeThickness) && \r\n // fragCoord.x < v_size.x - max(v_radius, v_strokeThickness))\r\n // {\r\n // fHalfBorderDist = v2CenteredPos.y - v2HalfShapeSizePx.y;\r\n // fHalfBorderThickness = v_strokeThickness / 2.0;\r\n // }\r\n // else if (fragCoord.y > max(v_radius, v_strokeThickness) && \r\n // fragCoord.y < v_size.y - max(v_radius, v_strokeThickness))\r\n // {\r\n // fHalfBorderDist = v2CenteredPos.x - v2HalfShapeSizePx.x;\r\n // fHalfBorderThickness = v_strokeThickness / 2.0;\r\n // }\r\n // else\r\n // {\r\n // vec2 edgeVec = max(vec2(0.0), v_radius - vec2(\r\n // uv.x > 0.5 ? v_size.x - fragCoord.x : fragCoord.x,\r\n // uv.y > 0.5 ? v_size.y - fragCoord.y : fragCoord.y));\r\n \r\n // float ellipse_ab = v_radius-v_strokeThickness;\r\n // vec2 ellipse_isect = (v_strokeThickness > v_radius || v_strokeThickness > v_radius) ? vec2(0.0) :\r\n // edgeVec.xy * ellipse_ab*ellipse_ab / length(ellipse_ab*edgeVec.yx); \r\n \r\n // fHalfBorderThickness = (v_radius - length(ellipse_isect)) / 2.0;\r\n // fHalfBorderDist = length(edgeVec) - (v_radius - fHalfBorderThickness);\r\n // }\r\n\r\n // vec4 v4FromColor = v_strokeColor;\r\n // v4FromColor.rgb *= v4FromColor.a;\r\n // vec4 v4ToColor = vec4(0.0); // background color is transparent\r\n // if (fHalfBorderDist < 0.0) {\r\n // v4ToColor = v_color;\r\n // v4ToColor.rgb *= v4ToColor.a;\r\n // }\r\n\r\n // float mixPct = abs(fHalfBorderDist) - fHalfBorderThickness;\r\n\r\n // vec4 finalColor = mix(v4FromColor, v4ToColor, mixPct);\r\n // gl_FragColor = finalColor;\r\n}",vertexSource:"#version 300 es\r\nin vec2 a_position;\r\n\r\n// UV coordinate\r\nin vec2 a_uv;\r\nout vec2 v_uv;\r\n\r\nin vec2 a_size;\r\nout vec2 v_size;\r\n\r\n// Opacity \r\nin float a_opacity;\r\nout float v_opacity;\r\n\r\nin vec4 a_color;\r\nout vec4 v_color;\r\n\r\nin vec4 a_strokeColor;\r\nout vec4 v_strokeColor;\r\n\r\nin float a_strokeThickness;\r\nout float v_strokeThickness;\r\n\r\nuniform mat4 u_matrix;\r\n\r\n\r\nvoid main() {\r\n // Set the vertex position using the ortho transform matrix\r\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\r\n\r\n // Pass through UV coords\r\n v_uv = a_uv;\r\n // Pass through size\r\n v_size = a_size;\r\n // Pass through the Opacity to the fragment shader\r\n v_opacity = a_opacity;\r\n // Pass through the color to the fragment shader\r\n v_color = a_color;\r\n // Pass through the stroke color to the fragment shader\r\n v_strokeColor = a_strokeColor;\r\n // Pass through the stroke thickenss to the fragment shader\r\n v_strokeThickness = a_strokeThickness;\r\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new te({gl:t,size:64*this._maxRectangles,type:"dynamic"}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_size",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new oe(t,this._maxRectangles,!0)}_isFull(){return this._rectangleCount>=this._maxRectangles}draw(...t){t[0]instanceof vt&&t[1]instanceof vt?this.drawLine.apply(this,t):this.drawRectangle.apply(this,t)}drawLine(t,e,i,s=1){this._isFull()&&this.flush(),this._rectangleCount++;const n=this._context.getTransform(),r=this._context.opacity,o=this._context.snapToPixel,a=e.sub(t),h=a.size,l=a.normalize().perpendicular(),c=s/2,d=n.multiply(l.scale(c).add(t)),u=n.multiply(l.scale(-c).add(t)),p=n.multiply(l.scale(c).add(e)),_=n.multiply(l.scale(-c).add(e));o&&(d.x=~~(d.x+_e),d.y=~~(d.y+_e),p.x=~~(p.x+_e),p.y=~~(p.y+_e),u.x=~~(u.x+_e),u.y=~~(u.y+_e),_.x=~~(_.x+_e),_.y=~~(_.y+_e));const g=yt.Transparent,m=this._layout.vertexBuffer.bufferData;m[this._vertexIndex++]=d.x,m[this._vertexIndex++]=d.y,m[this._vertexIndex++]=0,m[this._vertexIndex++]=0,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=u.x,m[this._vertexIndex++]=u.y,m[this._vertexIndex++]=0,m[this._vertexIndex++]=1,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=p.x,m[this._vertexIndex++]=p.y,m[this._vertexIndex++]=1,m[this._vertexIndex++]=0,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=_.x,m[this._vertexIndex++]=_.y,m[this._vertexIndex++]=1,m[this._vertexIndex++]=1,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0}drawRectangle(t,e,i,s,n=yt.Transparent,r=0){this._isFull()&&this.flush(),this._rectangleCount++;const o=this._context.getTransform(),a=this._context.opacity,h=this._context.snapToPixel,l=o.multiply(t.add(xt(0,0))),c=o.multiply(t.add(xt(e,0))),d=o.multiply(t.add(xt(e,i))),u=o.multiply(t.add(xt(0,i)));h&&(l.x=~~(l.x+_e),l.y=~~(l.y+_e),c.x=~~(c.x+_e),c.y=~~(c.y+_e),u.x=~~(u.x+_e),u.y=~~(u.y+_e),d.x=~~(d.x+_e),d.y=~~(d.y+_e));const p=this._layout.vertexBuffer.bufferData;p[this._vertexIndex++]=l.x,p[this._vertexIndex++]=l.y,p[this._vertexIndex++]=0,p[this._vertexIndex++]=0,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=u.x,p[this._vertexIndex++]=u.y,p[this._vertexIndex++]=0,p[this._vertexIndex++]=1,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=c.x,p[this._vertexIndex++]=c.y,p[this._vertexIndex++]=1,p[this._vertexIndex++]=0,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=d.x,p[this._vertexIndex++]=d.y,p[this._vertexIndex++]=1,p[this._vertexIndex++]=1,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r}hasPendingDraws(){return 0!==this._rectangleCount}flush(){if(0===this._rectangleCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._rectangleCount,this._quads.bufferGlType,0),ie.DrawnImagesCount+=this._rectangleCount,ie.DrawCallCount++,this._rectangleCount=0,this._vertexIndex=0}}class le{constructor(){this.type="ex.circle",this.priority=0,this._maxCircles=10922,this._circleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Jt({gl:t,fragmentSource:"#version 300 es\r\nprecision highp float;\r\n\r\n// UV coord\r\nin vec2 v_uv;\r\n\r\n// Color coord to blend with image\r\nin lowp vec4 v_color;\r\n\r\n// Stroke color if used\r\nin lowp vec4 v_strokeColor;\r\n\r\n// Stroke thickness if used\r\nin lowp float v_strokeThickness;\r\n\r\n// Opacity\r\nin float v_opacity;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n // make (0, 0) the center the uv \r\n vec2 uv = v_uv * 2.0 - 1.0;\r\n\r\n vec4 color = v_color;\r\n vec4 strokeColor = v_strokeColor;\r\n\r\n // circle border is at radius 1.0 \r\n // dist is > 0 when inside the circle \r\n float d = length(uv);\r\n float dist = 1.0 - length(uv);\r\n\r\n // Fade based on fwidth\r\n float fade = fwidth(dot(uv, uv));\r\n\r\n // if dist is greater than 0 step to 1;\r\n // when we cross this 0 threshold add a smooth fade\r\n float fill = smoothstep(-fade/2.0, fade/2.0, dist);\r\n\r\n // if dist is greater than the stroke thickness step to 1\r\n float stroke = 1.0 - smoothstep(v_strokeThickness, v_strokeThickness + fade, dist);\r\n\r\n strokeColor.a *= fill * stroke;\r\n strokeColor.rgb *= strokeColor.a;\r\n\r\n color.a *= fill * (1.0 - stroke);\r\n color.rgb *= color.a;\r\n\r\n vec4 finalColor = mix(vec4(0.0), (color + strokeColor), fill);\r\n finalColor.rgb = finalColor.rgb * v_opacity;\r\n finalColor.a = finalColor.a * v_opacity;\r\n fragColor = finalColor;\r\n}",vertexSource:"#version 300 es\r\nin vec2 a_position;\r\n\r\n// UV coordinate\r\nin vec2 a_uv;\r\nout vec2 v_uv;\r\n\r\n// Opacity \r\nin float a_opacity;\r\nout float v_opacity;\r\n\r\nin vec4 a_color;\r\nout vec4 v_color;\r\n\r\nin vec4 a_strokeColor;\r\nout vec4 v_strokeColor;\r\n\r\nin float a_strokeThickness;\r\nout float v_strokeThickness;\r\n\r\nuniform mat4 u_matrix;\r\n\r\n\r\nvoid main() {\r\n // Set the vertex position using the ortho transform matrix\r\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\r\n\r\n // Pass through UV coords\r\n v_uv = a_uv;\r\n // Pass through the Opacity to the fragment shader\r\n v_opacity = a_opacity;\r\n // Pass through the color to the fragment shader\r\n v_color = a_color;\r\n // Pass through the stroke color to the fragment shader\r\n v_strokeColor = a_strokeColor;\r\n // Pass through the stroke thickenss to the fragment shader\r\n v_strokeThickness = a_strokeThickness;\r\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new te({gl:t,size:56*this._maxCircles,type:"dynamic"}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new oe(t,this._maxCircles,!0)}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=yt.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const r=this._context.getTransform(),o=this._context.opacity,a=this._context.snapToPixel,h=r.multiply(t.add(xt(-e,-e))),l=r.multiply(t.add(xt(e,-e))),c=r.multiply(t.add(xt(e,e))),d=r.multiply(t.add(xt(-e,e)));a&&(h.x=~~(h.x+_e),h.y=~~(h.y+_e),l.x=~~(l.x+_e),l.y=~~(l.y+_e),d.x=~~(d.x+_e),d.y=~~(d.y+_e),c.x=~~(c.x+_e),c.y=~~(c.y+_e));const u=this._layout.vertexBuffer.bufferData;u[this._vertexIndex++]=h.x,u[this._vertexIndex++]=h.y,u[this._vertexIndex++]=0,u[this._vertexIndex++]=0,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=d.x,u[this._vertexIndex++]=d.y,u[this._vertexIndex++]=0,u[this._vertexIndex++]=1,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=l.x,u[this._vertexIndex++]=l.y,u[this._vertexIndex++]=1,u[this._vertexIndex++]=0,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=c.x,u[this._vertexIndex++]=c.y,u[this._vertexIndex++]=1,u[this._vertexIndex++]=1,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e}hasPendingDraws(){return 0!==this._circleCount}flush(){if(0===this._circleCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._circleCount,this._quads.bufferGlType,0),ie.DrawnImagesCount+=this._circleCount,ie.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}class ce{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this.disableWarnings=!1,this._logger=J.getInstance()}preallocate(){for(let t=0;t<this.maxObjects;t++)this.objects[t]=this.builder()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){t(this.get()),this.index--}get(...t){if(this.index===this.maxObjects&&(this.disableWarnings||this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=2*this.maxObjects),this.objects[this.index])return this.recycler(this.objects[this.index++],...t);this.totalAllocations++;return this.objects[this.index++]=this.builder(...t)}done(...t){this.index=0;for(const e of t){const t=this.objects.indexOf(e);this.objects[t]=this.builder(),this.totalAllocations++}return t}}class de{constructor(){this.z=0,this.priority=0,this.transform=Ft.identity(),this.state={z:0,opacity:1,tint:yt.White,material:null}}}class ue{constructor(t){this._color=yt.Transparent,this._initialized=!1;const{color:e,name:i,vertexSource:s,fragmentSource:n}=t;this._name=i,this._vertexSource=null!=s?s:"#version 300 es\nin vec2 a_position;\n\nin vec2 a_uv;\nout vec2 v_uv;\n\nuniform mat4 u_matrix;\nuniform mat4 u_transform;\n\nvoid main() {\n // Set the vertex position using the ortho & transform matrix\n gl_Position = u_matrix * u_transform * vec4(a_position, 0.0, 1.0);\n\n // Pass through the UV coord to the fragment shader\n v_uv = a_uv;\n}\n",this._fragmentSource=n,this._color=null!=e?e:this._color}initialize(t,e){this._initialized||(this._shader=e.createShader({vertexSource:this._vertexSource,fragmentSource:this._fragmentSource}),this._shader.compile(),this._initialized=!0)}get name(){var t;return null!==(t=this._name)&&void 0!==t?t:"anonymous material"}getShader(){return this._shader}use(){if(!this._initialized)throw Error(`Material ${this.name} not yet initialized, use the ExcaliburGraphicsContext.createMaterial() to work around this.`);this._shader.use(),this._shader.trySetUniformFloatColor("u_color",this._color)}}class pe{constructor(){this.type="ex.material",this.priority=0,this._textures=[]}initialize(t,e){this._gl=t,this._context=e,this._buffer=new te({gl:t,size:16,type:"dynamic"}),this._layout=new ee({gl:t,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2]]}),this._quads=new oe(t,1,!0)}draw(t,e,i,s,n,r,o,a,h){var l,c,d,u;const p=this._gl,_=this._context.material;_.initialize(p,this._context);const g=this._context.getTransform(),m=this._context.opacity,f=_.getShader(),v=this._layout.vertexBuffer.bufferData;let x=0,y=(null==t?void 0:t.width)||s||0,w=(null==t?void 0:t.height)||n||0,b=[0,0,null!==(l=null!=s?s:null==t?void 0:t.width)&&void 0!==l?l:0,null!==(c=null!=n?n:null==t?void 0:t.height)&&void 0!==c?c:0],C=[null!=e?e:1,null!=i?i:1];void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(b=[null!=e?e:1,null!=i?i:1,null!==(d=null!=s?s:null==t?void 0:t.width)&&void 0!==d?d:0,null!==(u=null!=n?n:null==t?void 0:t.height)&&void 0!==u?u:0],C=[r,o],y=a,w=h),e=b[0],i=b[1];const A=b[2],S=b[3],T=xt(C[0],C[1]),E=xt(C[0]+y,C[1]),P=xt(C[0],C[1]+w),I=xt(C[0]+y,C[1]+w),D=t.width||y,B=t.height||w,R=e/D,F=i/B,k=(e+A-.01)/D,M=(i+S-.01)/B;v[x++]=T.x,v[x++]=T.y,v[x++]=R,v[x++]=F,v[x++]=P.x,v[x++]=P.y,v[x++]=R,v[x++]=M,v[x++]=E.x,v[x++]=E.y,v[x++]=k,v[x++]=F,v[x++]=I.x,v[x++]=I.y,v[x++]=k,v[x++]=M;const L=this._addImageAsTexture(t);_.use(),this._layout.shader=f,this._layout.use(!0),f.trySetUniformFloat("u_opacity",m),f.trySetUniformFloatVector("u_resolution",xt(this._context.width,this._context.height)),f.trySetUniformFloatVector("u_graphic_resolution",xt(D,B)),f.trySetUniformFloatVector("u_size",xt(A,S)),f.trySetUniformMatrix("u_matrix",this._context.ortho),f.trySetUniformMatrix("u_transform",g.to4x4()),p.activeTexture(p.TEXTURE0+0),p.bindTexture(p.TEXTURE_2D,L),f.trySetUniformInt("u_graphic",0),this._quads.bind(),p.drawElements(p.TRIANGLES,6,this._quads.bufferGlType,0),ie.DrawnImagesCount++,ie.DrawCallCount++}_addImageAsTexture(t){const e=t.getAttribute("filtering");let i=null;e!==Wt.Blended&&e!==Wt.Pixel||(i=e);const s="true"===t.getAttribute("forceUpload"),n=this._context.textureLoader.load(t,i,s);return t.removeAttribute("forceUpload"),-1===this._textures.indexOf(n)&&this._textures.push(n),n}hasPendingDraws(){return!1}flush(){}}const _e=1e-4;class ge{constructor(t){this._webglCtx=t,this._debugText=new Kt}drawRect(t,e,i,s,n={color:yt.Black}){this.drawLine(xt(t,e),xt(t+i,e),{...n}),this.drawLine(xt(t+i,e),xt(t+i,e+s),{...n}),this.drawLine(xt(t+i,e+s),xt(t,e+s),{...n}),this.drawLine(xt(t,e+s),xt(t,e),{...n})}drawLine(t,e,i={color:yt.Black}){this._webglCtx.draw("ex.line",t,e,i.color)}drawPoint(t,e={color:yt.Black,size:5}){this._webglCtx.draw("ex.point",t,e.color,e.size)}drawText(t,e){this._debugText.write(this._webglCtx,t,e)}}class me{get z(){return this._state.current.z}set z(t){this._state.current.z=t}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}get ortho(){return this._ortho}checkIfResolutionSupported(t){let e=!0;return(t.width>4096||t.height>4096)&&(e=!1),e}constructor(t){this._logger=J.getInstance(),this._renderers=new Map,this._isDrawLifecycle=!1,this.useDrawSorting=!0,this._drawCallPool=new ce((()=>new de),(t=>(t.priority=0,t.z=0,t.renderer=void 0,t.args=void 0,t)),4e3),this._drawCalls=[],this._postProcessTargets=[],this._postprocessors=[],this._transform=new kt,this._state=new Mt,this.snapToPixel=!1,this.smoothing=!1,this.backgroundColor=yt.ExcaliburBlue,this._alreadyWarnedDrawLifecycle=!1,this.debug=new ge(this),this._totalPostProcessorTime=0;const{canvasElement:e,enableTransparency:i,smoothing:s,snapToPixel:n,backgroundColor:r,useDrawSorting:o}=t;if(this.__gl=e.getContext("webgl2",{antialias:null!=s?s:this.smoothing,premultipliedAlpha:!1,alpha:null==i||i,depth:!0,powerPreference:"high-performance"}),!this.__gl)throw Error("Failed to retrieve webgl context from browser");this.textureLoader=new Gt(this.__gl),this.snapToPixel=null!=n?n:this.snapToPixel,this.smoothing=null!=s?s:this.smoothing,this.backgroundColor=null!=r?r:this.backgroundColor,this.useDrawSorting=null!=o?o:this.useDrawSorting,this._drawCallPool.disableWarnings=!0,this._drawCallPool.preallocate(),this._init()}_init(){const t=this.__gl;this._ortho=Rt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA),this.register(new ae),this.register(new pe),this.register(new he),this.register(new le),this.register(new ne),this.register(new se),this._screenRenderer=new re(t),this._renderTarget=new Yt({gl:t,width:t.canvas.width,height:t.canvas.height}),this._postProcessTargets=[new Yt({gl:t,width:t.canvas.width,height:t.canvas.height}),new Yt({gl:t,width:t.canvas.width,height:t.canvas.height})]}register(t){this._renderers.set(t.type,t),t.initialize(this.__gl,this)}get(t){return this._renderers.get(t)}_isCurrentRenderer(t){return!this._currentRenderer||this._currentRenderer===t}beginDrawLifecycle(){this._isDrawLifecycle=!0}endDrawLifecycle(){this._isDrawLifecycle=!1}draw(t,...e){this._isDrawLifecycle||this._alreadyWarnedDrawLifecycle||(this._logger.warn("Attempting to draw outside the the drawing lifecycle (preDraw/postDraw) is not supported and is a source of bugs/errors.\nIf you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPostDraw handler."),this._alreadyWarnedDrawLifecycle=!0);const i=this._renderers.get(t);if(!i)throw Error(`No renderer with name ${t} has been registered`);if(this.useDrawSorting){const s=this._drawCallPool.get();s.z=this._state.current.z,s.priority=i.priority,s.renderer=t,this.getTransform().clone(s.transform),s.state.z=this._state.current.z,s.state.opacity=this._state.current.opacity,s.state.tint=this._state.current.tint,s.state.material=this._state.current.material,s.args=e,this._drawCalls.push(s)}else this._currentRenderer||(this._currentRenderer=i),this._isCurrentRenderer(i)||this._currentRenderer.flush(),i.draw(...e),this._currentRenderer=i}resetTransform(){this._transform.current=Ft.identity()}updateViewport(t){const e=this.__gl;this._ortho=this._ortho=Rt.ortho(0,t.width,t.height,0,400,-400),this._renderTarget.setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[0].setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[1].setResolution(e.canvas.width,e.canvas.height)}drawImage(t,e,i,s,n,r,o,a,h){if(0!==s&&0!==n&&0!==a&&0!==h&&0!==t.width&&0!==t.height)return t?void(this._state.current.material?this.draw("ex.material",t,e,i,s,n,r,o,a,h):this.draw("ex.image",t,e,i,s,n,r,o,a,h)):(J.getInstance().warn("Cannot draw a null or undefined image"),void(console.trace&&console.trace()))}drawLine(t,e,i,s=1){this.draw("ex.rectangle",t,e,i,s)}drawRectangle(t,e,i,s,n,r){this.draw("ex.rectangle",t,e,i,s,n,r)}drawCircle(t,e,i,s,n){this.draw("ex.circle",t,e,i,s,n)}save(){this._transform.save(),this._state.save()}restore(){this._transform.restore(),this._state.restore()}translate(t,e){this._transform.translate(this.snapToPixel?~~(t+_e):t,this.snapToPixel?~~(e+_e):e)}rotate(t){this._transform.rotate(t)}scale(t,e){this._transform.scale(t,e)}transform(t){this._transform.current=t}getTransform(){return this._transform.current}multiply(t){this._transform.current.multiply(t,this._transform.current)}addPostProcessor(t){this._postprocessors.push(t),t.initialize(this.__gl)}removePostProcessor(t){const e=this._postprocessors.indexOf(t);-1!==e&&this._postprocessors.splice(e,1)}clearPostProcessors(){this._postprocessors.length=0}updatePostProcessors(t){for(const e of this._postprocessors){const i=e.getShader();i.use();const s=i.getUniforms();this._totalPostProcessorTime+=t,s.find((t=>"u_time_ms"===t.name))&&i.setUniformFloat("u_time_ms",this._totalPostProcessorTime),s.find((t=>"u_elapsed_ms"===t.name))&&i.setUniformFloat("u_elapsed_ms",t),s.find((t=>"u_resolution"===t.name))&&i.setUniformFloatVector("u_resolution",xt(this.width,this.height)),e.onUpdate&&e.onUpdate(t)}}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){const e=new ue(t);return e.initialize(this.__gl,this),e}createShader(t){const e=this.__gl,{vertexSource:i,fragmentSource:s}=t,n=new Jt({gl:e,vertexSource:i,fragmentSource:s});return n.compile(),n}clear(){const t=this.__gl;this._renderTarget.use(),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT)}flush(){const t=this.__gl;if(this._renderTarget.use(),this.useDrawSorting){const t=new Map;for(const[e]of this._renderers){const i=this._drawCalls.findIndex((t=>t.renderer===e));t.set(e,i)}this._drawCalls.sort(((e,i)=>{const s=e.z-i.z,n=t.get(e.renderer)-t.get(i.renderer),r=e.priority-i.priority;return 0===s?0===r?n:r:s}));const e=this._transform.current,i=this._state.current;if(this._drawCalls.length){let t=this._drawCalls[0].renderer,e=this._renderers.get(t);for(let i=0;i<this._drawCalls.length;i++)this._transform.current=this._drawCalls[i].transform,this._state.current=this._drawCalls[i].state,this._drawCalls[i].renderer!==t&&(e.flush(),t=this._drawCalls[i].renderer,e=this._renderers.get(t)),e.draw(...this._drawCalls[i].args);e.hasPendingDraws()&&e.flush()}this._transform.current=e,this._state.current=i,this._drawCallPool.done(),this._drawCalls.length=0}else for(const t of this._renderers.values())t.hasPendingDraws()&&t.flush();this._renderTarget.disable();this._renderTarget.toRenderSource().use();for(let t=0;t<this._postprocessors.length;t++)this._postProcessTargets[t%2].use(),this._screenRenderer.renderWithPostProcessor(this._postprocessors[t]),this._postProcessTargets[t%2].toRenderSource().use();t.bindFramebuffer(t.FRAMEBUFFER,null),this._screenRenderer.renderToScreen()}}const fe=1e-4;class ve{constructor(t){this._ex=t,this._debugText=new Kt}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~(t+fe):t,this._ex.snapToPixel?~~(e+fe):e,this._ex.snapToPixel?~~(i+fe):i,this._ex.snapToPixel?~~(s+fe):s),this._ex.__ctx.restore()}drawLine(t,e,i={color:yt.Black}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=i.color.toString(),this._ex.__ctx.moveTo(this._ex.snapToPixel?~~(t.x+fe):t.x,this._ex.snapToPixel?~~(t.y+fe):t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~(e.x+fe):e.x,this._ex.snapToPixel?~~(e.y+fe):e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:yt.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+fe):t.x,this._ex.snapToPixel?~~(t.y+fe):t.y,e.size,0,2*Math.PI),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class xe{get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}constructor(t){this.useDrawSorting=!1,this.z=0,this.backgroundColor=yt.ExcaliburBlue,this._state=new Mt,this.snapToPixel=!1,this.debug=new ve(this);const{canvasElement:e,enableTransparency:i,snapToPixel:s,smoothing:n,backgroundColor:r}=t;this.__ctx=e.getContext("2d",{alpha:null==i||i}),this.backgroundColor=null!=r?r:this.backgroundColor,this.snapToPixel=null!=s?s:this.snapToPixel,this.smoothing=null!=n?n:this.smoothing}resetTransform(){this.__ctx.resetTransform()}updateViewport(t){}drawImage(t,e,i,s,n,r,o,a,h){if(0===s||0===n)return;if(0===a||0===h)return;if(0===t.width||0===t.height)return;this.__ctx.globalAlpha=this.opacity;const l=[t,e,i,s,n,r,o,a,h].filter((t=>void 0!==t)).map((t=>"number"==typeof t&&this.snapToPixel?~~t:t));this.__ctx.drawImage.apply(this.__ctx,l),ie.DrawCallCount++,ie.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~(t.x+fe):t.x,this.snapToPixel?~~(t.y+fe):t.y),this.__ctx.lineTo(this.snapToPixel?~~(e.x+fe):e.x,this.snapToPixel?~~(e.y+fe):e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~(t.x+fe):t.x,this.snapToPixel?~~(t.y+fe):t.y,this.snapToPixel?~~(e+fe):e,this.snapToPixel?~~(i+fe):i),this.__ctx.restore()}drawCircle(t,e,i,s,n){this.__ctx.save(),this.__ctx.beginPath(),s&&(this.__ctx.strokeStyle=s.toString()),n&&(this.__ctx.lineWidth=n),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~(t.x+fe):t.x,this.snapToPixel?~~(t.y+fe):t.y,e,0,2*Math.PI),this.__ctx.fill(),s&&this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save(),this._state.save()}restore(){this.__ctx.restore(),this._state.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~(t+fe):t,this.snapToPixel?~~(e+fe):e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}getTransform(){throw new Error("Not implemented")}multiply(t){this.__ctx.setTransform(this.__ctx.getTransform().multiply(t.toDOMMatrix()))}addPostProcessor(t){}removePostProcessor(t){}clearPostProcessors(){}updatePostProcessors(t){}beginDrawLifecycle(){}endDrawLifecycle(){}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){return null}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),ie.clear()}flush(){}}var ye;!function(t){t.Fixed="Fixed",t.FitContainerAndFill="FitContainerAndFill",t.FitScreenAndFill="FitScreenAndFill",t.FitContainerAndZoom="FitContainerAndZoom",t.FitScreenAndZoom="FitScreenAndZoom",t.FitScreen="FitScreen",t.FillScreen="FillScreen",t.FitContainer="FitContainer",t.FillContainer="FillContainer"}(ye||(ye={}));class we{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}const be={ScreenResize:"resize",PixelRatioChange:"pixelratio",FullScreenChange:"fullscreen"};class Ce{constructor(t){var e,i,s;this.events=new d,this._antialiasing=!0,this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullScreen=!1,this._isDisposed=!1,this._logger=J.getInstance(),this._fullscreenChangeHandler=()=>{this._isFullScreen=!this._isFullScreen,this._logger.debug("Fullscreen Change",this._isFullScreen),this.events.emit("fullscreen",{fullscreen:this.isFullScreen})},this._pixelRatioChangeHandler=()=>{this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._listenForPixelRatio(),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport(),this.events.emit("pixelratio",{pixelRatio:this.pixelRatio})},this._resizeHandler=()=>{const t=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(t),this.applyResolutionAndViewport(),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._alreadyWarned=!1,this._contentArea=new At,this.viewport=t.viewport,this.resolution=null!==(e=t.resolution)&&void 0!==e?e:{...this.viewport},this._contentResolution=this.resolution,this._displayMode=null!==(i=t.displayMode)&&void 0!==i?i:ye.Fixed,this._canvas=t.canvas,this.graphicsContext=t.context,this._antialiasing=null!==(s=t.antialiasing)&&void 0!==s?s:this._antialiasing,this._browser=t.browser,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._listenForPixelRatio(),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}_listenForPixelRatio(){this._mediaQueryList&&!this._mediaQueryList.addEventListener&&this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler,{once:!0}):this._mediaQueryList.addListener(this._pixelRatioChangeHandler)}dispose(){this._isDisposed||(this._isDisposed=!0,this._browser.window.off("resize",this._resizeHandler),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler))}_calculateDevicePixelRatio(){if(window.devicePixelRatio<1)return 1;return window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get isHiDpi(){return 1!==this.pixelRatio}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){switch(this.displayMode){case ye.FillContainer:case ye.FitContainer:case ye.FitContainerAndFill:case ye.FitContainerAndZoom:return this.canvas.parentElement||document.body;default:return window}}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution={...this.resolution},this.viewport={...this.viewport}}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop()}applyResolutionAndViewport(){if(this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this.graphicsContext instanceof me){this.graphicsContext.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})||this._alreadyWarned||(this._alreadyWarned=!0,this._logger.warn(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) and pixel ratio (${this.pixelRatio}) are too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`))}this._antialiasing?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",""===this._canvas.style.imageRendering&&(this._canvas.style.imageRendering="crisp-edges")),this._canvas.style.width=this.viewport.width+"px",this._canvas.style.height=this.viewport.height+"px",this.graphicsContext.updateViewport(this.resolution),this.graphicsContext.resetTransform(),this.graphicsContext.smoothing=this._antialiasing,this.graphicsContext instanceof xe&&this.graphicsContext.scale(this.pixelRatio,this.pixelRatio)}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this.graphicsContext.smoothing=this._antialiasing}get isFullScreen(){return this._isFullScreen}goFullScreen(t){if(t){const e=document.getElementById(t);if(e){e.getAttribute("ex-fullscreen-listener")||(e.setAttribute("ex-fullscreen-listener","true"),e.addEventListener("fullscreenchange",this._fullscreenChangeHandler));return e.requestFullscreen()}}return this._canvas.requestFullscreen()}exitFullScreen(){return document.exitFullscreen()}pageToScreenCoordinates(t){let e=t.x,i=t.y;if(this._isFullScreen||(e-=Tt(this._canvas).x,i-=Tt(this._canvas).y),this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio;i=(i-(window.innerHeight-t)/2)/t*this.viewport.height,e=e/window.innerWidth*this.viewport.width}else{const t=window.innerHeight*this.aspectRatio;e=(e-(window.innerWidth-t)/2)/t*this.viewport.width,i=i/window.innerHeight*this.viewport.height}return e=e/this.viewport.width*this.resolution.width,i=i/this.viewport.height*this.resolution.height,new vt(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;if(e=e/this.resolution.width*this.viewport.width,i=i/this.resolution.height*this.viewport.height,this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio,s=(window.innerHeight-t)/2;i=i/this.viewport.height*t+s,e=e/this.viewport.width*window.innerWidth}else{const t=window.innerHeight*this.aspectRatio,s=(window.innerWidth-t)/2;e=e/this.viewport.width*t+s,i=i/this.viewport.height*window.innerHeight}return this._isFullScreen||(e+=Tt(this._canvas).x,i+=Tt(this._canvas).y),new vt(e,i)}screenToWorldCoordinates(t){return this._camera?this._camera.inverse.multiply(t):t.sub(xt(this.resolution.width/2,this.resolution.height/2))}worldToScreenCoordinates(t){return this._camera?this._camera.transform.multiply(t):t.add(xt(this.resolution.width/2,this.resolution.height/2))}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){return At.fromDimension(this.resolution.width,this.resolution.height,vt.Half).scale(xt(1/this._camera.zoom,1/this._camera.zoom)).rotate(this._camera.rotation).translate(this._camera.pos)}getScreenBounds(){return At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero,vt.Zero)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return xt(this.halfDrawWidth,this.halfDrawHeight)}get contentArea(){return this._contentArea}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i},this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero)}_computeFitScreenAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndFill(t,e)}_computeFitContainerAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.canvas.parentElement,e=t.clientWidth,i=t.clientHeight;this._computeFitAndFill(e,i)}_computeFitAndFill(t,e){if(this.viewport={width:t,height:e},t/e<=this._contentResolution.width/this._contentResolution.height){this.resolution={width:t*this._contentResolution.width/t,height:t*this._contentResolution.width/t*e/t};const i=(this.resolution.height-this._contentResolution.height)/2;this._contentArea=new At({top:i,left:0,right:this._contentResolution.width,bottom:this.resolution.height-i})}else{this.resolution={width:e*this._contentResolution.height/e*t/e,height:e*this._contentResolution.height/e};const i=(this.resolution.width-this._contentResolution.width)/2;this._contentArea=new At({top:0,left:i,right:this.resolution.width-i,bottom:this._contentResolution.height})}}_computeFitScreenAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndZoom(t,e)}_computeFitContainerAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=this.canvas.parentElement;t.style.position="relative",t.style.overflow="hidden";const e=t.clientWidth,i=t.clientHeight;this._computeFitAndZoom(e,i)}_computeFitAndZoom(t,e){const i=this.aspectRatio;let s=0,n=0;t/i<e?(s=t,n=t/i):(s=e*i,n=e);const r=t/s,o=e/n,a=Math.max(r,o),h=s*a,l=n*a;this.canvas.style.left=h>t?-(h-t)/2+"px":"",this.canvas.style.top=l>e?-(l-e)/2+"px":"",this.viewport={width:h,height:l};const c=At.fromDimension(this.viewport.width,this.viewport.height,vt.Zero);if(this.viewport.width>t){const e=(this.viewport.width-t)/this.viewport.width*this.resolution.width;c.top=0,c.left=e/2,c.right=this.resolution.width-e/2,c.bottom=this.resolution.height}if(this.viewport.height>e){const t=(this.viewport.height-e)/this.viewport.height*this.resolution.height;c.top=t/2,c.left=0,c.bottom=this.resolution.height-t/2,c.right=this.resolution.width}this._contentArea=c}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0;const s=this.canvas.parentElement;s.clientWidth/t<s.clientHeight?(e=s.clientWidth,i=s.clientWidth/t):(e=s.clientHeight*t,i=s.clientHeight),this.viewport={width:e,height:i},this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero)}_applyDisplayMode(){this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver((()=>{this._resizeHandler()})),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler)}_setResolutionAndViewportByDisplayMode(t){this.displayMode===ye.FillContainer&&(this.resolution={width:t.clientWidth,height:t.clientHeight},this.viewport=this.resolution),this.displayMode===ye.FillScreen&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero),this.displayMode===ye.FitScreen&&this._computeFit(),this.displayMode===ye.FitContainer&&this._computeFitContainer(),this.displayMode===ye.FitScreenAndFill&&this._computeFitScreenAndFill(),this.displayMode===ye.FitContainerAndFill&&this._computeFitContainerAndFill(),this.displayMode===ye.FitScreenAndZoom&&this._computeFitScreenAndZoom(),this.displayMode===ye.FitContainerAndZoom&&this._computeFitContainerAndZoom()}}class Ae{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}Ae._INSTANCE=null;class Se{static unlock(){return new Promise(((t,e)=>{if(Se._UNLOCKED||!Ae.create())return t(!0);const i=setTimeout((()=>{J.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),t(!1)}),200),s=Ae.create();s.resume().then((()=>{const e=s.createBuffer(1,1,22050),n=s.createBufferSource();let r=!1;n.buffer=e,n.connect(s.destination),n.onended=()=>r=!0,n.start(0),setTimeout((()=>{!function(t){return!!t.playbackState}(n)?(s.currentTime>0||r)&&(Se._UNLOCKED=!0):n.playbackState!==n.PLAYING_STATE&&n.playbackState!==n.FINISHED_STATE||(Se._UNLOCKED=!0)}),0),clearTimeout(i),t(!0)}),(()=>{e()}))}))}static isUnlocked(){return this._UNLOCKED}}function Te(t,e=yt.Red,i,s,n,r,o=1,a="butt"){t.save(),t.beginPath(),t.lineWidth=o,t.lineCap=a,t.strokeStyle=e.toString(),t.moveTo(i,s),t.lineTo(n,r),t.closePath(),t.stroke(),t.restore()}function Ee(t,e=yt.Red,i){t.beginPath(),t.strokeStyle=e.toString(),t.arc(i.x,i.y,5,0,2*Math.PI),t.closePath(),t.stroke()}function Pe(t,e,i,s,n=1){const r=e?e.toString():"blue",o=s.scale(n);t.beginPath(),t.strokeStyle=r,t.moveTo(i.x,i.y),t.lineTo(i.x+o.x,i.y+o.y),t.closePath(),t.stroke()}function Ie(t,e,i,s,n,r=5,o=yt.White,a=null){let h;if("number"==typeof r)h={tl:r,tr:r,br:r,bl:r};else{const t={tl:0,tr:0,br:0,bl:0};for(const e in t)if(t.hasOwnProperty(e)){const i=e;h[i]=r[i]||t[i]}}t.beginPath(),t.moveTo(e+h.tl,i),t.lineTo(e+s-h.tr,i),t.quadraticCurveTo(e+s,i,e+s,i+h.tr),t.lineTo(e+s,i+n-h.br),t.quadraticCurveTo(e+s,i+n,e+s-h.br,i+n),t.lineTo(e+h.bl,i+n),t.quadraticCurveTo(e,i+n,e,i+n-h.bl),t.lineTo(e,i+h.tl),t.quadraticCurveTo(e,i,e+h.tl,i),t.closePath(),a&&(t.fillStyle=a.toString(),t.fill()),o&&(t.strokeStyle=o.toString(),t.stroke())}function De(t,e,i,s,n=yt.White,r=null){t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),r&&(t.fillStyle=r.toString(),t.fill()),n&&(t.strokeStyle=n.toString(),t.stroke())}Se._UNLOCKED=!1;var Be=i(1388);class Re extends Nt{constructor(t){var e,i,s,n,r,o,a,h,l,c;super(t),this.filtering=null,this.lineCap="butt",this.quality=1,this._dirty=!0,this._smoothing=!1,this._color=Ut(yt.Black,(()=>this.flagDirty())),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.quality=null!==(e=t.quality)&&void 0!==e?e:this.quality,this.color=null!==(i=t.color)&&void 0!==i?i:yt.Black,this.strokeColor=null==t?void 0:t.strokeColor,this.smoothing=null!==(s=t.smoothing)&&void 0!==s?s:this.smoothing,this.lineWidth=null!==(n=t.lineWidth)&&void 0!==n?n:this.lineWidth,this.lineDash=null!==(r=t.lineDash)&&void 0!==r?r:this.lineDash,this.lineCap=null!==(o=t.lineCap)&&void 0!==o?o:this.lineCap,this.padding=null!==(a=t.padding)&&void 0!==a?a:this.padding,this.filtering=null!==(h=t.filtering)&&void 0!==h?h:this.filtering),this._bitmap=document.createElement("canvas");const d=null!==(l=null==t?void 0:t.width)&&void 0!==l?l:this._bitmap.width,u=null!==(c=null==t?void 0:t.height)&&void 0!==c?c:this._bitmap.height;this.width=d,this.height=u;const p=this._bitmap.getContext("2d");if(!p)throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic");this._ctx=p}cloneRasterOptions(){return{color:this.color?this.color.clone():null,strokeColor:this.strokeColor?this.strokeColor.clone():null,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,lineCap:this.lineCap,quality:this.quality,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return Math.abs(this._getTotalWidth()*this.scale.x)}set width(t){t/=Math.abs(this.scale.x),this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return Math.abs(this._getTotalHeight()*this.scale.y)}set height(t){t/=Math.abs(this.scale.y),this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return 1*((null!==(t=this._originalWidth)&&void 0!==t?t:this._bitmap.width)+2*this.padding)}_getTotalHeight(){var t;return 1*((null!==(t=this._originalHeight)&&void 0!==t?t:this._bitmap.height)+2*this.padding)}get localBounds(){return At.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,vt.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){this.flagDirty(),this._color=Ut(t,(()=>this.flagDirty()))}get strokeColor(){return this._strokeColor}set strokeColor(t){this.flagDirty(),this._strokeColor=Ut(t,(()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperties(this._ctx),this.execute(this._ctx),this._ctx.restore()}_applyRasterProperties(t){var e,i,s;this._bitmap.width=this._getTotalWidth()*this.quality,this._bitmap.height=this._getTotalHeight()*this.quality,this._bitmap.setAttribute("filtering",this.filtering),this._bitmap.setAttribute("forceUpload","true"),t.scale(this.quality,this.quality),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash(null!==(e=this.lineDash)&&void 0!==e?e:t.getLineDash()),t.lineCap=this.lineCap,t.strokeStyle=null===(i=this.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=null===(s=this.color)||void 0===s?void 0:s.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.scale(1/this.quality,1/this.quality),t.drawImage(this._bitmap,e,i)}}class Fe extends Re{get ctx(){return this._ctx}constructor(t){super(t),this._options=t}clone(){return new Fe({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(null===(e=this._options)||void 0===e?void 0:e.draw)&&(null===(i=this._options)||void 0===i||i.draw(t)),this._options.cache||this.flagDirty()}}class ke{}ke.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Me{constructor(){this.states=new Map}get currentState(){return this._currentState}set currentState(t){this._currentState=t}static create(t,e){const i=new Me;i.data=e;for(const e in t.states)i.states.set(e,{name:e,...t.states[e]});for(const t of i.states.values())for(const e of t.transitions)if("*"!==e&&!i.states.has(e))throw Error(`Invalid state machine, state [${t.name}] has a transition to another state that doesn't exist [${e}]`);return i.currentState=i.startState=i.states.get(t.start),i}in(t){return this.currentState.name===t}go(t,e){var i,s;if(this.currentState.transitions.includes(t)||this.currentState.transitions.includes("*")){const n=this.states.get(t);if(this.currentState.onExit){if(!1===(null===(i=this.currentState)||void 0===i?void 0:i.onExit({to:n.name,data:this.data})))return!1}if(null==n?void 0:n.onEnter){if(!1===(null==n?void 0:n.onEnter({from:this.currentState.name,eventData:e,data:this.data})))return!1}return this.currentState=n,(null===(s=this.currentState)||void 0===s?void 0:s.onState)&&this.currentState.onState(),!0}return!1}update(t){this.currentState.onUpdate&&this.currentState.onUpdate(this.data,t)}save(t){localStorage.setItem(t,JSON.stringify({currentState:this.currentState.name,data:this.data}))}restore(t){const e=JSON.parse(localStorage.getItem(t));this.currentState=this.states.get(e.currentState),this.data=e.data}}class Le{_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.value=this._playbackRate,this._instance.connect(this._volumeNode),this._volumeNode.connect(this._audioContext.destination)}_handleEnd(){this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)})}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)}))}get loop(){return this._loop}set volume(t){t=dt(t,0,1),this._volume=t,this._stateMachine.in("PLAYING")&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}get duration(){var t;return null!==(t=this._duration)&&void 0!==t?t:this.getTotalPlaybackDuration()}set duration(t){this._duration=t}constructor(t){this._src=t,this._audioContext=Ae.create(),this._volumeNode=this._audioContext.createGain(),this._playingFuture=new St,this._stateMachine=Me.create({start:"STOPPED",states:{PLAYING:{onEnter:({data:t})=>{this._createNewBufferSource(),this._handleEnd(),this.loop?this._instance.start(0,t.pausedAt*this._playbackRate):this._instance.start(0,t.pausedAt*this._playbackRate,this.duration),t.startedAt=this._audioContext.currentTime-t.pausedAt,t.pausedAt=0},onState:()=>this._playStarted(),onExit:({to:t})=>{"STOPPED"===t&&this._playingFuture.resolve(!0),this._instance.onended=null,this._instance.disconnect(),this._instance.stop(0),this._instance=null},transitions:["STOPPED","PAUSED","SEEK"]},SEEK:{onEnter:({eventData:t,data:e})=>{e.pausedAt=(null!=t?t:0)/this._playbackRate,e.startedAt=0},transitions:["*"]},STOPPED:{onEnter:({data:t})=>{t.pausedAt=0,t.startedAt=0,this._playingFuture.resolve(!0)},transitions:["PLAYING","PAUSED","SEEK"]},PAUSED:{onEnter:({data:t})=>{t.pausedAt=this._audioContext.currentTime-t.startedAt},transitions:["PLAYING","STOPPED","SEEK"]}}},{startedAt:0,pausedAt:0}),this._volume=1,this._loop=!1,this._playStarted=()=>{},this._playbackRate=1,this._createNewBufferSource()}isPlaying(){return this._stateMachine.in("PLAYING")}isPaused(){return this._stateMachine.in("PAUSED")||this._stateMachine.in("SEEK")}isStopped(){return this._stateMachine.in("STOPPED")}play(t=(()=>{})){return this._playStarted=t,this._stateMachine.go("PLAYING"),this._playingFuture.promise}pause(){this._stateMachine.go("PAUSED")}stop(){this._stateMachine.go("STOPPED")}seek(t){this._stateMachine.go("PAUSED"),this._stateMachine.go("SEEK",t)}getTotalPlaybackDuration(){return this._src.duration}getPlaybackPosition(){const{pausedAt:t,startedAt:e}=this._stateMachine.data;return t?t*this._playbackRate:e?(this._audioContext.currentTime-e)*this._playbackRate:0}set playbackRate(t){this._instance.playbackRate.value=this._playbackRate=t}get playbackRate(){return this._instance.playbackRate.value}}class ze extends u{set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}stopPropagation(){}action(){}propagate(){}layPath(t){}}class Ue extends ze{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class Oe extends ze{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}function Ne(t){try{const e=new Audio,i=/.*\.([A-Za-z0-9]+)(?:(?:\?|\#).*)*$/,s=t.match(i)[1];return!!e.canPlayType("audio/"+s)}catch(t){return J.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}const He={VolumeChange:"volumechange",Processed:"processed",Pause:"pause",Stop:"stop",PlaybackEnd:"playbackend",Resume:"resume",PlaybackStart:"playbackstart"};class We{set loop(t){this._loop=t;for(const t of this._tracks)t.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const t of this._tracks)t.volume=this._volume;this.events.emit("volumechange",new Ue(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}set duration(t){this._duration=t}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}constructor(...t){this.events=new d,this.logger=J.getInstance(),this._loop=!1,this._volume=1,this._isStopped=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._playbackRate=1,this._audioContext=Ae.create(),this._resource=new zt("",ke.type.arraybuffer);for(const e of t)if(Ne(e)){this.path=e;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",t.join(", ")),this.logger.warn("Attempting to use",t[0]),this.path=t[0])}isLoaded(){return!!this.data}async load(){var t,e;if(this.data)return this.data;const i=await this._resource.load(),s=await this.decodeAudio(i.slice(0));return this._duration=null!==(e=null!==(t=this._duration)&&void 0!==t?t:null==s?void 0:s.duration)&&void 0!==e?e:void 0,this.events.emit("processed",new Oe(this,s)),this.data=s}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(t){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),await Promise.reject()}}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",(()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())})),this._engine.on("visible",(()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)})),this._engine.on("start",(()=>{this._isStopped=!1})),this._engine.on("stop",(()=>{this.stop(),this._isStopped=!0})))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some((t=>t.isPlaying()))}isPaused(){return this._tracks.some((t=>t.isPaused()))}isStopped(){return this._tracks.some((t=>t.isStopped()))}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t||this.volume,this.isPaused()?this._resumePlayback():this._startPlayback()):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this.events.emit("pause",new Ue(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.events.emit("stop",new Ue(this)),this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._tracks.forEach((t=>{t.playbackRate=this._playbackRate}))}seek(t,e=0){0===this._tracks.length&&this._getTrackInstance(this.data),this._tracks[e].seek(t)}getTotalPlaybackDuration(){return this.data.duration}getPlaybackPosition(t=0){return this._tracks.length?this._tracks[t].getPlaybackPosition():0}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(){if(this.isPaused){const t=[];for(const e of this._tracks)t.push(e.play().then((()=>(this.events.emit("playbackend",new Ue(this,e)),this._tracks.splice(this.getTrackId(e),1),!0))));this.events.emit("resume",new Ue(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(t)}return!0}async _startPlayback(){const t=this._getTrackInstance(this.data),e=await t.play((()=>{this.events.emit("playbackstart",new Ue(this,t)),this.logger.debug("Playing new instance for sound",this.path)}));this.events.emit("playbackend",new Ue(this,t));const i=this.getTrackId(t);return-1!==i&&this._tracks.splice(i,1),e}_getTrackInstance(t){const e=new Le(t);return e.loop=this.loop,e.volume=this.volume,e.duration=this.duration,e.playbackRate=this._playbackRate,this._tracks.push(e),e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Ge={};class Ve{get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.src=this.logo),this._imageElement}_getScreenParent(){return this._engine?this._engine.screen.canvas.parentElement:document.body}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");if(t&&(this._playButtonRootElement=t),!this._playButtonRootElement){this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute";this._getScreenParent().appendChild(this._playButtonRootElement)}return this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}constructor(t){this.events=new d,this.canvas=new Fe({filtering:Wt.Blended,smoothing:!0,cache:!0,draw:this.draw.bind(this)}),this._resourceList=[],this._index=0,this._playButtonShown=!1,this._resourceCount=0,this._numLoaded=0,this._progressCounts={},this._totalCounts={},this.logo="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=yt.White,this.backgroundColor="#176BAA",this.suppressPlayButton=!1,this._playButtonStyles=Be.Z.toString(),this.playButtonText="Play game",this.startButtonFactory=()=>{let t=document.getElementById("excalibur-play");return t||(t=document.createElement("button")),t.id="excalibur-play",t.textContent=this.playButtonText,t.style.display="none",t},this._loaderResizeHandler=t=>{this._engine.screen.resolution=this._engine.screen.viewport,this._engine.screen.applyResolutionAndViewport(),this.canvas.width=t.viewport.width,this.canvas.height=t.viewport.height,this.canvas.flagDirty()},this._loadingFuture=new St,t&&this.addResources(t)}wireEngine(t){this._engine||(this._engine=t,this.canvas.width=this._engine.canvas.width,this.canvas.height=this._engine.canvas.height)}addResource(t){const e=this._index++;this._resourceList.push(t),this._progressCounts[e]=0,this._totalCounts[e]=1,this._resourceCount++}addResources(t){let e=0;const i=t.length;for(;e<i;e++)this.addResource(t[e])}isLoaded(){return this._numLoaded===this._resourceCount}async showPlayButton(){var t,e;if(!this.suppressPlayButton){const t=()=>{this._positionPlayButton()};(null===(e=this._engine)||void 0===e?void 0:e.browser)&&this._engine.browser.window.on("resize",t),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",(t=>{"Enter"===t.key&&this._playButton.click()})),this._positionPlayButton();const i=new Promise((e=>{const i=i=>{var s;i.stopPropagation(),this.hidePlayButton(),(null===(s=this._engine)||void 0===s?void 0:s.browser)&&this._engine.browser.window.off("resize",t),e()};this._playButton.addEventListener("click",i),this._playButton.addEventListener("touchend",i),this._playButton.addEventListener("pointerup",i)}));return await i}this.hidePlayButton(),await Bt(500,null===(t=this._engine)||void 0===t?void 0:t.clock)}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}update(t,e){}areResourcesLoaded(){return this._loadingFuture.promise}async load(){var t,e;this._engine.screen.events.on("resize",this._loaderResizeHandler),await(null===(t=this._image)||void 0===t?void 0:t.decode()),this.canvas.flagDirty(),await Promise.all(this._resourceList.map((async t=>{await t.load().finally((()=>{this._numLoaded++,this.canvas.flagDirty()}))})));for(const t of this._resourceList)t instanceof We&&t.wireEngine(this._engine);return this._loadingFuture.resolve(),await Bt(200,null===(e=this._engine)||void 0===e?void 0:e.clock),this.canvas.flagDirty(),await this.showPlayButton(),await Se.unlock(),this._engine.screen.events.off("resize",this._loaderResizeHandler),this.data=this._resourceList}markResourceComplete(){this._numLoaded++}get progress(){return this._resourceCount>0?dt(this._numLoaded,0,this._resourceCount)/this._resourceCount:1}_positionPlayButton(){if(this._engine){const t=this._engine.screen.viewport.height,e=this._engine.screen.viewport.width;if(this._playButtonRootElement){const i=this._engine.canvas.offsetLeft,s=this._engine.canvas.offsetTop,n=this._playButton.clientWidth,r=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=i+e/2-n/2+"px",this._playButtonRootElement.style.top=s+t/2-r/2+100+"px")}}}draw(t){const e=this._engine.canvasHeight/this._engine.pixelRatio,i=this._engine.canvasWidth/this._engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,.75*i);let r=i/2-n/2;this.logoPosition&&(r=this.logoPosition.x,s=this.logoPosition.y);const o=Math.floor(n*(this.logoHeight/this.logoWidth)),a=this._engine.getAntialiasing();if(this._engine.setAntialiasing(!0),this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s,n,o):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s-o-20,n,o),!this.suppressPlayButton&&this._playButtonShown)return void this._engine.setAntialiasing(a);let h=r,l=s;this.loadingBarPosition&&(h=this.loadingBarPosition.x,l=this.loadingBarPosition.y),t.lineWidth=2,Ie(t,h,l,n,20,10,this.loadingBarColor);const c=n*this.progress-10;Ie(t,h+5,l+5,c>10?c:10,10,5,null,this.loadingBarColor),this._engine.setAntialiasing(a)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const qe={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class Xe{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(t){return!1}return"arraybuffer"===t.responseType},dataUrlSupport:function(){return 0===document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return null===this._features&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t="%cSUPPORTED BROWSER FEATURES\n==========================%c\n";const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(qe))i[s]?(t+="(%c✓%c)",e.push("font-weight: bold; color: green"),e.push("font-weight: normal; color: inherit")):(t+="(%c✗%c)",e.push("font-weight: bold; color: red"),e.push("font-weight: normal; color: inherit")),t+=" "+qe[s]+"\n";e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:(()=>this._criticalTests.canvasSupport())(),arraybuffer:(()=>this._criticalTests.arrayBufferSupport())(),dataurl:(()=>this._criticalTests.dataUrlSupport())(),objecturl:(()=>this._criticalTests.objectUrlSupport())(),rgba:(()=>this._criticalTests.rgbaSupport())(),webaudio:(()=>this._warningTest.webAudioSupport())(),webgl:(()=>this._warningTest.webglSupport())(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),J.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const t in this._warningTest)this._warningTest[t]()||J.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",t);return!0}}var Ke;!function(t){t.PreventCollision="PreventCollision",t.Passive="Passive",t.Active="Active",t.Fixed="Fixed"}(Ke||(Ke={}));const Ze=5,Ye={},je=()=>{for(const t in Ye)Ye[t]=0},Qe=(t,e)=>{const i=l.isEnabled("suppress-obsolete-message");Ye[t]<Ze&&!i&&(J.getInstance().warn(t),console.trace&&e.showStackTrace&&console.trace()),Ye[t]++};function $e(t){return t={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...t},function(e,i,s){if(s&&"function"!=typeof s.value&&"function"!=typeof s.get&&"function"!=typeof s.set)throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${e.name||""}${e.name&&i?".":""}${i||""}`} is marked obsolete: ${t.message}`+(t.alternateMethod?` Use ${t.alternateMethod} instead`:"");Ye[n]||(Ye[n]=0);const r=s?{...s}:e;if(!s){class e extends r{constructor(...e){Qe(n,t),super(...e)}}return e}return s&&s.value?(r.value=function(){return Qe(n,t),s.value.apply(this,arguments)},r):(s&&s.get&&(r.get=function(){return Qe(n,t),s.get.apply(this,arguments)}),s&&s.set&&(r.set=function(){return Qe(n,t),s.set.apply(this,arguments)}),r)}}var Je,ti,ei,ii,si=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t.Arcade="arcade",t.Realistic="realistic"}(Je||(Je={})),function(t){t[t.DynamicAABBTree=0]="DynamicAABBTree"}(ti||(ti={})),function(t){t[t.Euler=0]="Euler"}(ei||(ei={}));class ni{static get gravity(){return ni.acc}static set gravity(t){ni.acc=t}static useArcadePhysics(){ni.collisionResolutionStrategy=Je.Arcade}static useRealisticPhysics(){ni.collisionResolutionStrategy=Je.Realistic}static get dynamicTreeVelocityMultiplyer(){return ni.dynamicTreeVelocityMultiplier}static set dynamicTreeVelocityMultiplyer(t){ni.dynamicTreeVelocityMultiplier=t}}ni.acc=new vt(0,0),ni.enabled=!0,ni.broadphaseStrategy=ti.DynamicAABBTree,ni.collisionResolutionStrategy=Je.Arcade,ni.defaultMass=10,ni.integrator=ei.Euler,ni.dynamicTreeVelocityMultiplier=2,ni.boundsPadding=5,ni.positionIterations=3,ni.velocityIterations=8,ni.slop=1,ni.steeringFactor=.2,ni.warmStart=!0,ni.bodiesCanSleepByDefault=!1,ni.surfaceEpsilon=.1,ni.sleepEpsilon=.07,ni.wakeThreshold=3*ni.sleepEpsilon,ni.sleepBias=.9,ni.checkForFastBodies=!0,ni.disableMinimumSpeedForFastBody=!1,si([$e({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"dynamicTreeVelocityMultiplier"})],ni,"dynamicTreeVelocityMultiplyer",null),function(t){t.World="world",t.Screen="screen"}(ii||(ii={}));class ri extends vt{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}class oi extends vt{constructor(t,e){super(t.x,t.y),this.original=t,this.change=e}get x(){return this._x=this.original.x}set x(t){this.change(t,this._y),this._x=this.original.x=t}get y(){return this._y=this.original.y}set y(t){this.change(this._x,t),this._y=this.original.y=t}}class ai{constructor(){this._parent=null,this._children=[],this._pos=xt(0,0),this._rotation=0,this._scale=xt(1,1),this._isDirty=!1,this._isInverseDirty=!1,this._matrix=Ft.identity(),this._inverse=Ft.identity()}get parent(){return this._parent}set parent(t){if(this._parent){const t=this._parent._children.indexOf(this);t>-1&&this._parent._children.splice(t,1)}this._parent=t,this._parent&&this._parent._children.push(this),this.flagDirty()}get children(){return this._children}set pos(t){t.equals(this._pos)||(this._pos.x=t.x,this._pos.y=t.y,this.flagDirty())}get pos(){return new oi(this._pos,((t,e)=>{t===this._pos.x&&e===this._pos.y||this.flagDirty()}))}set globalPos(t){let e=t.clone();this.parent&&(e=this.parent.inverse.multiply(t)),e.equals(this._pos)||(this._pos=e,this.flagDirty())}get globalPos(){return new ri({getX:()=>this.matrix.data[4],getY:()=>this.matrix.data[5],setX:t=>{if(this.parent){const{x:e}=this.parent.inverse.multiply(xt(t,this.pos.y));this.pos.x=e}else this.pos.x=t;t!==this.matrix.data[4]&&this.flagDirty()},setY:t=>{if(this.parent){const{y:e}=this.parent.inverse.multiply(xt(this.pos.x,t));this.pos.y=e}else this.pos.y=t;t!==this.matrix.data[5]&&this.flagDirty()}})}set rotation(t){const e=ut(t);e!==this._rotation&&this.flagDirty(),this._rotation=e}get rotation(){return this._rotation}set globalRotation(t){let e=0;this.parent&&(e=this.parent.globalRotation);const i=ut(t+e);i!==this._rotation&&this.flagDirty(),this._rotation=i}get globalRotation(){return this.parent?this.matrix.getRotation():this.rotation}set scale(t){t.equals(this._scale)||(this._scale.x=t.x,this._scale.y=t.y,this.flagDirty())}get scale(){return new oi(this._scale,((t,e)=>{t===this._scale.x&&e===this._scale.y||this.flagDirty()}))}set globalScale(t){let e=xt(1,1);this.parent&&(e=this.parent.globalScale),this.scale=t.scale(xt(1/e.x,1/e.y))}get globalScale(){return new ri({getX:()=>this.parent?this.matrix.getScaleX():this.scale.x,getY:()=>this.parent?this.matrix.getScaleY():this.scale.y,setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.scale.x=t/e}else this.scale.x=t},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.scale.y=t/e}else this.scale.y=t}})}get matrix(){return this._isDirty&&(null===this.parent?this._matrix=this._calculateMatrix():this._matrix=this.parent.matrix.multiply(this._calculateMatrix()),this._isDirty=!1),this._matrix}get inverse(){return this._isInverseDirty&&(this._inverse=this.matrix.inverse(),this._isInverseDirty=!1),this._inverse}_calculateMatrix(){return Ft.identity().translate(this.pos.x,this.pos.y).rotate(this.rotation).scale(this.scale.x,this.scale.y)}flagDirty(){this._isDirty=!0,this._isInverseDirty=!0;for(let t=0;t<this._children.length;t++)this._children[t].flagDirty()}apply(t){return this.matrix.multiply(t)}applyInverse(t){return this.inverse.multiply(t)}setTransform(t,e,i){this._pos.x=t.x,this._pos.y=t.y,this._rotation=ut(e),this._scale.x=i.x,this._scale.y=i.y,this.flagDirty()}clone(t){const e=null!=t?t:new ai;return this._pos.clone(e._pos),e._rotation=this._rotation,this._scale.clone(e._scale),e.flagDirty(),e}}class hi{constructor(){this.owner=null}clone(){const t=new this.constructor;for(const i in this)if(this.hasOwnProperty(i)){const s=this[i];(null==(e=s)?void 0:e.clone)&&"owner"!==i&&"clone"!==i?t[i]=s.clone():t[i]=s}var e;return t}}class li extends hi{constructor(t,e){super(),this.type=t,this.value=e}}class ci{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);-1!==e&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);-1!==e&&this.subscriptions.splice(e,1)}notifyAll(t){const e=this.observers.length;for(let i=0;i<e;i++)this.observers[i].notify(t);const i=this.subscriptions.length;for(let e=0;e<i;e++)this.subscriptions[e](t)}clear(){this.observers.length=0,this.subscriptions.length=0}}class di extends hi{constructor(){super(...arguments),this.type="ex.transform",this._transform=new ai,this._addChildTransform=t=>{const e=t.get(di);e&&(e._transform.parent=this._transform)},this.zIndexChanged$=new ci,this._z=0,this.coordPlane=ii.World}get(){return this._transform}onAdd(t){for(const e of t.children)this._addChildTransform(e);t.childrenAdded$.subscribe((t=>this._addChildTransform(t))),t.childrenRemoved$.subscribe((t=>{const e=t.get(di);e&&(e._transform.parent=null)}))}onRemove(t){this._transform.parent=null}get z(){return this._z}set z(t){const e=this._z;this._z=t,e!==t&&this.zIndexChanged$.notifyAll(t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get globalPos(){return this._transform.globalPos}set globalPos(t){this._transform.globalPos=t}get rotation(){return this._transform.rotation}set rotation(t){this._transform.rotation=t}get globalRotation(){return this._transform.globalRotation}set globalRotation(t){this._transform.globalRotation=t}get scale(){return this._transform.scale}set scale(t){this._transform.scale=t}get globalScale(){return this._transform.globalScale}set globalScale(t){this._transform.globalScale=t}applyInverse(t){return this._transform.applyInverse(t)}apply(t){return this._transform.apply(t)}clone(){const t=new di;return t._transform=this._transform.clone(),t._z=this._z,t}}class ui extends hi{constructor(){super(...arguments),this.type="ex.motion",this.vel=vt.Zero,this.acc=vt.Zero,this.scaleFactor=vt.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1}}class pi{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t)){const i=this._GROUPS.get(t);if(i.mask===e)return i;throw new Error(`Collision group ${t} already exists with a different mask!`)}const i=new _i(t,this._CURRENT_BIT,void 0!==e?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}}pi._STARTING_BIT=1,pi._MAX_GROUPS=32,pi._CURRENT_GROUP=1,pi._CURRENT_BIT=pi._STARTING_BIT,pi._GROUPS=new Map;class _i{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){const e=this.category&t.mask,i=this.mask&t.category;return 0!==e&&0!==i}invert(){const t=pi.create("~("+this.name+")",0|~this.mask);return t._category=~this.category,t}static combine(t){const e=t.map((t=>t.name)).join("+"),i=~t.reduce(((t,e)=>e.category|t),0);return pi.create(e,i)}static collidesWith(t){const e=`collidesWith(${t.map((t=>t.name)).join("+")})`,i=t.reduce(((t,e)=>e.category|t),0);return pi.create(e,i)}toString(){return`\ncategory: ${this.category.toString(2).padStart(32,"0")}\nmask: ${(this.mask>>>0).toString(2).padStart(32,"0")}\n `}}_i.All=new _i("Collide with all groups",-1,-1);class gi{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=gi.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;const n=null===(i=null==t?void 0:t.owner)||void 0===i?void 0:i.get(Mi),r=null===(s=null==e?void 0:e.owner)||void 0===s?void 0:s.get(Mi);return t.id!==e.id&&((!t.owner||!e.owner||t.owner.id!==e.owner.id)&&(!t.localBounds.hasZeroDimensions()&&!e.localBounds.hasZeroDimensions()&&(!(!n||!r)&&(!!n.group.canCollide(r.group)&&((n.collisionType!==Ke.Fixed||r.collisionType!==Ke.Fixed)&&(r.collisionType!==Ke.PreventCollision&&n.collisionType!==Ke.PreventCollision&&!(!n.active||!r.active)))))))}get canCollide(){const t=this.colliderA,e=this.colliderB;return gi.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class mi{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class fi{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new At,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class vi{constructor(t=new At(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this.worldBounds=t,this.root=null,this.nodes={}}_insert(t){if(null===this.root)return this.root=t,void(this.root.parent=null);const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const t=i.left,s=i.right,n=i.bounds.getPerimeter(),r=i.bounds.combine(e).getPerimeter(),o=2*r,a=2*(r-n);let h=0;const l=e.combine(t.bounds);let c,d;t.isLeaf()?h=l.getPerimeter()+a:(d=t.bounds.getPerimeter(),c=l.getPerimeter(),h=c-d+a);let u=0;const p=e.combine(s.bounds);if(s.isLeaf()?u=p.getPerimeter()+a:(d=s.bounds.getPerimeter(),c=p.getPerimeter(),u=c-d+a),o<h&&o<u)break;i=h<u?t:s}const s=i.parent,n=new fi(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,null!==s?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let r=t.parent;for(;r;){if(r=this._balance(r),!r.left)throw new Error("Parent of current leaf cannot have a null left child"+r);if(!r.right)throw new Error("Parent of current leaf cannot have a null right child"+r);r.height=1+Math.max(r.left.height,r.right.height),r.bounds=r.left.bounds.combine(r.right.bounds),r=r.parent}}_remove(t){if(t===this.root)return void(this.root=null);const e=t.parent,i=e.parent;let s;if(s=e.left===t?e.right:e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let t=i;for(;t;)t=this._balance(t),t.bounds=t.left.bounds.combine(t.right.bounds),t.height=1+Math.max(t.left.height,t.right.height),t=t.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new fi;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return J.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=ni.boundsPadding,s.top-=ni.boundsPadding,s.right+=ni.boundsPadding,s.bottom+=ni.boundsPadding,t.owner){const i=null===(e=t.owner)||void 0===e?void 0:e.get(Mi);if(i){const t=32*i.vel.x/1e3*ni.dynamicTreeVelocityMultiplier,e=32*i.vel.y/1e3*ni.dynamicTreeVelocityMultiplier;t<0?s.left+=t:s.right+=t,e<0?s.top+=e:s.bottom+=e}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(null===t)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,r=i,o=e.left,a=e.right,h=i.left,l=i.right,c=r.height-n.height;if(c>1)return r.left=s,r.parent=s.parent,s.parent=r,r.parent?r.parent.left===s?r.parent.left=r:r.parent.right=r:this.root=r,h.height>l.height?(r.right=h,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),r.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(n.height,l.height),r.height=1+Math.max(s.height,h.height)):(r.right=l,s.right=h,h.parent=s,s.bounds=n.bounds.combine(h.bounds),r.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,h.height),r.height=1+Math.max(s.height,l.height)),r;if(c<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return o.height>a.height?(n.right=o,s.left=a,a.parent=s,s.bounds=r.bounds.combine(a.bounds),n.bounds=s.bounds.combine(o.bounds),s.height=1+Math.max(r.height,a.height),n.height=1+Math.max(s.height,o.height)):(n.right=a,s.left=o,o.parent=s,s.bounds=r.bounds.combine(o.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(r.height,o.height),n.height=1+Math.max(s.height,a.height)),n}return t}getHeight(){return null===this.root?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.overlaps(i)){if(!n.isLeaf()||n.data===t)return s(n.left)||s(n.right);if(e.call(t,n.data))return!0}return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e)){if(!n.isLeaf())return s(n.left)||s(n.right);if(i.call(t,n.data))return!0}return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.draw(t,yt.Green):i.bounds.draw(t,yt.White),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class xi{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(0===this.dir.cross(t.getSlope())&&0!==e.cross(this.dir))return-1;const i=this.dir.cross(t.getSlope());if(0===i)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}class yi{constructor(){this._dynamicCollisionTree=new vi,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[]}getColliders(){return this._colliders}rayCast(t,e){var i,s,n;const r=[],o=null!==(i=null==e?void 0:e.maxDistance)&&void 0!==i?i:1/0,a=null==e?void 0:e.collisionGroup,h=a?a.category:null!==(s=null==e?void 0:e.collisionMask)&&void 0!==s?s:_i.All.category,l=null!==(n=null==e?void 0:e.searchAllColliders)&&void 0!==n&&n;return this._dynamicCollisionTree.rayCastQuery(t,o,(e=>{const i=e.owner.get(Mi),s=0!=(h&i.group.category);if((null==i?void 0:i.group)&&!s)return!1;const n=e.rayCast(t,o);return!(!n||(r.push({distance:n.sub(t.pos).distance(),point:n,collider:e,body:i}),l))})),r}track(t){if(t)if(t instanceof bi){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t);else J.getInstance().warn("Cannot track null collider")}untrack(t){if(t)if(t instanceof bi){const e=t.getColliders();for(const t of e){const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}else{const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}else J.getInstance().warn("Cannot untrack a null collider")}_pairExists(t,e){const i=gi.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter((t=>{var e,i;const s=null===(e=t.owner)||void 0===e?void 0:e.get(Mi);return(null===(i=t.owner)||void 0===i?void 0:i.active)&&s.collisionType!==Ke.PreventCollision}));let r;this._collisionPairCache=[],this._pairs.clear();for(let t=0,e=n.length;t<e;t++)r=n[t],this._dynamicCollisionTree.query(r,(t=>{if(!this._pairExists(r,t)&&gi.canCollide(r,t)){const e=new gi(r,t);this._pairs.add(e.id),this._collisionPairCache.push(e)}return!1}));if(i&&(i.physics.pairs=this._collisionPairCache.length),ni.checkForFastBodies)for(const t of n){const e=t.owner.get(Mi);if(e.collisionType!==Ke.Active)continue;const n=e.vel.size*s+.5*e.acc.size*s*s,r=Math.min(t.bounds.height,t.bounds.width);if(ni.disableMinimumSpeedForFastBody||n>r/2){i&&i.physics.fastBodies++;const s=e.globalPos.sub(e.oldPos),r=t.center,o=t.getFurthestPoint(e.vel),a=o.sub(s),h=new xi(a,e.vel);let l;h.pos=h.pos.add(h.dir.scale(-2*ni.surfaceEpsilon));let c=new vt(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(h,n+2*ni.surfaceEpsilon,(e=>{if(!this._pairExists(t,e)&&gi.canCollide(t,e)){const t=e.rayCast(h,n+10*ni.surfaceEpsilon);if(t){const i=t.sub(a);i.size<c.size&&(c=i,l=e)}}return!1})),l&&vt.isValid(c)){const s=new gi(t,l);this._pairs.has(s.id)||(this._pairs.add(s.id),this._collisionPairCache.push(s));const n=r.sub(o);e.globalPos=a.add(n).add(c).add(h.dir.scale(10*ni.surfaceEpsilon)),t.update(e.transform.get()),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const t of n)e.physics.contacts.set(t.id,t)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}class wi{constructor(){this.id=c("collider",wi._ID++),this.__compositeColliderId=null,this.events=new d}touching(t){return!!this.collide(t)}}wi._ID=0;class bi extends wi{constructor(t){super(),this._collisionProcessor=new yi,this._dynamicAABBTree=new vi,this._colliders=[];for(const e of t)this.addCollider(e)}clearColliders(){this._colliders=[]}addCollider(t){t.events.pipe(this.events),t.__compositeColliderId=this.id,this._colliders.push(t),this._collisionProcessor.track(t),this._dynamicAABBTree.trackCollider(t)}removeCollider(t){t.events.pipe(this.events),t.__compositeColliderId=null,Pt(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:vt.Zero}get center(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:vt.Zero}get bounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.bounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.bounds)&&void 0!==e?e:(new At).translate(this.worldPos))}get localBounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.localBounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new At)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const s of e)i.push(s.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const e of i){const i=e.dot(t);i>n&&(s=e,n=i)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof bi&&(e=t.getColliders());const i=[];for(const t of e)this._dynamicAABBTree.query(t,(e=>(i.push(new gi(t,e)),!1)));let s=[];for(const t of i)s=s.concat(t.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof bi){const s=t.getColliders();for(const t of e)for(const e of s){const s=t.getClosestLineBetween(e);s&&i.push(s)}}else for(const s of e){const e=t.getClosestLineBetween(s);e&&i.push(e)}if(i.length){let t=i[0].getLength(),e=i[0];for(const s of i){const i=s.getLength();i<t&&(t=i,e=s)}return e}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const i=n.rayCast(t,e);i&&s.push(i)}if(s.length){let e=s[0],i=e.dot(t.dir);for(const n of s){const s=t.dir.dot(n);s<i&&(e=n,i=s)}return e}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const e=s.project(t);e&&i.push(e)}if(i.length){const t=new mi(i[0].min,i[0].max);for(const e of i)t.min=Math.min(e.min,t.min),t.max=Math.max(e.max,t.max);return t}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}debug(t,e){const i=this.getColliders();for(const s of i)s.debug(t,e)}clone(){return new bi(this._colliders.map((t=>t.clone())))}}class Ci{constructor(t,e){this.begin=t,this.end=e}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this._normal?this._normal:this._normal=this.end.sub(this.begin).normal()}dir(){return this._dir?this._dir:this._dir=this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){if(this._slope)return this._slope;const t=this.begin,e=this.end,i=t.distance(e);return this._slope=e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){if(this._length)return this._length;const t=this.begin,e=this.end,i=t.distance(e);return this._length=i}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new Ci(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e){let i=t;i=i.normalize();const s=i.dot(this.begin)-e,n=i.dot(this.end)-e,r=[];if(s<=0&&r.push(this.begin),n<=0&&r.push(this.end),s*n<0){const t=s/(s-n);r.push(this.begin.add(this.end.sub(this.begin).scale(t)))}return 2!==r.length?null:new Ci(r[0],r[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),r=((this.end.y-this.begin.y)*i-(this.end.x-this.begin.x)*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?r:Math.abs(r)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(null!==t)return new vt(t,i*t+s);if(null!==e)return new vt((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if("number"==typeof arguments[0]&&"number"==typeof arguments[1])t=new vt(arguments[0],arguments[1]),e=arguments[2]||0;else{if(!(arguments[0]instanceof vt))throw"Could not determine the arguments for Vector.hasPoint";t=arguments[0],e=arguments[1]||0}const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,r=this.end.y-this.begin.y,o=i*r-s*n;return!(Math.abs(o)>e)&&(Math.abs(n)>=Math.abs(r)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:r>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y)}}function Ai(t,e,i,s){const n=t.sub(i),r=e.dot(e),o=e.dot(s),a=s.dot(s),h=e.dot(n),l=s.dot(n),c=r*a-o*o;let d=c,u=c;if(0===c||c<=.01){const e=h/o;return new Ci(t,i.add(s.scale(e)))}let p=o*l-a*h,_=r*l-o*h;return p<0?(p=0,_=l,u=a):p>d&&(p=d,_=l+o,u=a),_<0?(_=0,-h<0?p=0:-h>r?p=d:(p=-h,d=r)):_>u&&(_=u,-h+o<0?p=0:-h+o>r?p=d:(p=-h+o,d=r)),p=Math.abs(p)<.001?0:p/d,_=Math.abs(_)<.001?0:_/u,new Ci(t.add(e.scale(p)),i.add(s.scale(_)))}const Si={PolygonPolygonClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=s.negate(),r=new xi(t.worldPos,s),o=new xi(i,n),a=t.rayCast(r).add(r.dir.scale(.1)),h=e.rayCast(o).add(o.dir.scale(.1)),l=t.getClosestFace(a),c=e.getClosestFace(h);return Ai(l.face.begin,l.face.getEdge(),c.face.begin,c.face.getEdge())},PolygonEdgeClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=new xi(t.worldPos,i),n=t.rayCast(s).add(s.dir.scale(.1)),r=t.getClosestFace(n),o=r.face.begin,a=r.face.getEdge(),h=e.asLine();return Ai(o,a,h.begin,h.getEdge())},PolygonCircleClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=new xi(t.worldPos,s.normalize()),r=t.rayCast(n).add(n.dir.scale(.1)),o=t.getClosestFace(r),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(i.x-a.x)+h.y*(i.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-i.x,2)+Math.pow(a.y+h.y*l-i.y,2))-e.radius,d=(a.x+h.x*l-i.x)*e.radius/(e.radius+c),u=(a.y+h.y*l-i.y)*e.radius/(e.radius+c);return new Ci(h.scale(l).add(a),new vt(i.x+d,i.y+u))},CircleCircleClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=t.worldPos.sub(e.worldPos),n=new xi(t.worldPos,i),r=new xi(e.worldPos,s),o=t.rayCast(n),a=e.rayCast(r);return new Ci(o,a)},CircleEdgeClosestLine(t,e){const i=t.worldPos,s=e.asLine(),n=s.begin,r=s.getEdge();let o=(r.x*(i.x-n.x)+r.y*(i.y-n.y))/(r.x*r.x+r.y*r.y);o>1?o=1:o<0&&(o=0);const a=Math.sqrt(Math.pow(n.x+r.x*o-i.x,2)+Math.pow(n.y+r.y*o-i.y,2))-t.radius,h=(n.x+r.x*o-i.x)*t.radius/(t.radius+a),l=(n.y+r.y*o-i.y)*t.radius/(t.radius+a);return new Ci(r.scale(o).add(n),new vt(i.x+h,i.y+l))},EdgeEdgeClosestLine(t,e){const i=t.asLine(),s=i.begin,n=i.getEdge(),r=e.asLine();return Ai(s,n,r.begin,r.getEdge())}};class Ti extends wi{get worldPos(){return this._globalMatrix.getPosition()}get radius(){var t;const e=this._transform,i=null!==(t=null==e?void 0:e.globalScale)&&void 0!==t?t:vt.One;return this._naturalRadius*Math.min(i.x,i.y)}set radius(t){var e;const i=this._transform,s=null!==(e=null==i?void 0:i.globalScale)&&void 0!==e?e:vt.One;this._naturalRadius=t/Math.min(s.x,s.y)}constructor(t){super(),this.offset=vt.Zero,this._globalMatrix=Ft.identity(),this.offset=t.offset||vt.Zero,this.radius=t.radius||0,this._globalMatrix.translate(this.offset.x,this.offset.y)}clone(){return new Ti({offset:this.offset.clone(),radius:this.radius})}get center(){return this._globalMatrix.getPosition()}contains(t){var e,i;return(null!==(i=null===(e=this._transform)||void 0===e?void 0:e.pos)&&void 0!==i?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){const i=this.center,s=t.dir,n=t.pos,r=Math.sqrt(Math.pow(s.dot(n.sub(i)),2)-Math.pow(n.sub(i).distance(),2)+Math.pow(this.radius,2));if(r<0)return null;{let o=0;if(0===r)return o=-s.dot(n.sub(i)),o>0&&o<e?t.getPoint(o):null;{const o=-s.dot(n.sub(i))+r,a=-s.dot(n.sub(i))-r,h=[];o>=0&&h.push(o),a>=0&&h.push(a);const l=Math.min(...h);return l<=e?t.getPoint(l):null}}}getClosestLineBetween(t){if(t instanceof Ti)return Si.CircleCircleClosestLine(this,t);if(t instanceof Bi)return Si.PolygonCircleClosestLine(t,this).flip();if(t instanceof Di)return Si.CircleEdgeClosestLine(this,t).flip();throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ti)return Ii.CollideCircleCircle(this,t);if(t instanceof Bi)return Ii.CollideCirclePolygon(this,t);if(t instanceof Di)return Ii.CollideCircleEdge(this,t);throw new Error("Circle could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){var t,e,i;const s=this._transform,n=null!==(t=null==s?void 0:s.globalScale)&&void 0!==t?t:vt.One,r=null!==(e=null==s?void 0:s.globalRotation)&&void 0!==e?e:0,o=null!==(i=null==s?void 0:s.globalPos)&&void 0!==i?i:vt.Zero;return new At(this.offset.x-this._naturalRadius,this.offset.y-this._naturalRadius,this.offset.x+this._naturalRadius,this.offset.y+this._naturalRadius).rotate(r).scale(n).translate(o)}get localBounds(){return new At(this.offset.x-this._naturalRadius,this.offset.y-this._naturalRadius,this.offset.x+this._naturalRadius,this.offset.y+this._naturalRadius)}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){var e;this._transform=t;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=this.center.dot(t);return e.push(i),e.push(i+this.radius),e.push(i-this.radius),new mi(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){var i,s,n,r;const o=this._transform,a=null!==(i=null==o?void 0:o.globalScale)&&void 0!==i?i:vt.One,h=null!==(s=null==o?void 0:o.globalRotation)&&void 0!==s?s:0,l=null!==(n=null==o?void 0:o.globalPos)&&void 0!==n?n:vt.Zero;t.save(),t.translate(l.x,l.y),t.rotate(h),t.scale(a.x,a.y),t.drawCircle(null!==(r=this.offset)&&void 0!==r?r:vt.Zero,this._naturalRadius,yt.Transparent,e,2),t.restore()}}class Ei{constructor(t,e,i,s,n,r,o,a){var h,l;this._canceled=!1,this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=r,this.localPoints=o,this.info=a,this.id=gi.calculatePairHash(t.id,e.id),(t.__compositeColliderId||e.__compositeColliderId)&&(this.id+="|"+gi.calculatePairHash(null!==(h=t.__compositeColliderId)&&void 0!==h?h:t.id,null!==(l=e.__compositeColliderId)&&void 0!==l?l:e.id))}matchAwake(){const t=this.colliderA.owner.get(Mi),e=this.colliderB.owner.get(Mi);t&&e&&t.sleeping!==e.sleeping&&(t.sleeping&&t.collisionType!==Ke.Fixed&&e.sleepMotion>=ni.wakeThreshold&&t.setSleeping(!1),e.sleeping&&e.collisionType!==Ke.Fixed&&t.sleepMotion>=ni.wakeThreshold&&e.setSleeping(!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}}class Pi{static findPolygonPolygonSeparation(t,e){let i=-Number.MAX_VALUE,s=null,n=null,r=-1,o=null;const a=t.getSides(),h=t.getLocalSides();for(let t=0;t<a.length;t++){const h=a[t],l=h.normal(),c=e.getFurthestPoint(l.negate()),d=h.distanceToPoint(c,!0);d>i&&(i=d,s=h,n=l,r=t,o=c)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:h[r],sideId:r,point:o,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}static findCirclePolygonSeparation(t,e){const i=e.axes,s=e.center.sub(t.worldPos),n=e.getFurthestPoint(s.negate());i.push(n.sub(t.worldPos).normalize());let r=Number.MAX_VALUE,o=null,a=-1;for(let s=0;s<i.length;s++){const n=e.project(i[s]),h=t.project(i[s]),l=n.getOverlap(h);if(l<=0)return null;l<r&&(r=l,o=i[s],a=s)}return a<0?null:o.normalize().scale(r)}}const Ii={CollideCircleCircle(t,e){const i=t.worldPos,s=e.worldPos,n=t.radius+e.radius,r=i.distance(s);if(r>n)return[];const o=n-r,a=s.sub(i).normalize(),h=a.perpendicular(),l=a.scale(o),c=t.getFurthestPoint(a),d=t.getFurthestLocalPoint(a);return[new Ei(t,e,l,a,h,[c],[d],{collider:t,separation:o,axis:a,point:c})]},CollideCirclePolygon(t,e){var i,s;let n=Pi.findCirclePolygonSeparation(t,e);if(!n)return[];const r=n.dot(e.center.sub(t.center));n=r<0?n.negate():n;const o=t.getFurthestPoint(n),a=(null!==(s=null===(i=t.owner)||void 0===i?void 0:i.get(di))&&void 0!==s?s:new di).applyInverse(o),h=n.normalize(),l={collider:t,separation:-n.size,axis:h,point:o,localPoint:a,side:e.findSide(h.negate()),localSide:e.findLocalSide(h.negate())};return[new Ei(t,e,n,h,h.perpendicular(),[o],[a],l)]},CollideCircleEdge(t,e){const i=t.center,s=e.asLine(),n=s.end.sub(s.begin),r=n.dot(s.end.sub(i)),o=n.dot(i.sub(s.begin)),a=e.asLine(),h=e.asLocalLine();if(o<=0){const n=s.begin.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.begin,side:a,localSide:h};return[new Ei(t,e,o.scale(l),o,o.perpendicular(),[a.begin],[h.begin],c)]}if(r<=0){const n=s.end.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.end,side:a,localSide:h};return[new Ei(t,e,o.scale(l),o,o.perpendicular(),[a.end],[h.end],c)]}const l=n.dot(n),c=s.begin.scale(r).add(s.end.scale(o)).scale(1/l),d=i.sub(c),u=d.dot(d);if(u>t.radius*t.radius)return[];let p=n.perpendicular();p.dot(i.sub(s.begin))<0&&(p.x=-p.x,p.y=-p.y),p=p.normalize();const _=t.radius-Math.sqrt(u),g=p.scale(_),m={collider:t,separation:_,axis:p,point:c,side:a,localSide:h};return[new Ei(t,e,g,p.negate(),p.negate().perpendicular(),[c],[c.sub(e.worldPos)],m)]},CollideEdgeEdge:()=>[],CollidePolygonEdge(t,e){var i;const s=t.center,n=e.center.sub(s).normalize(),r=new Bi({points:[e.begin,e.end,e.end.add(n.scale(100)),e.begin.add(n.scale(100))],offset:e.offset});r.owner=e.owner;(null===(i=e.owner)||void 0===i?void 0:i.get(di))&&r.update(e.owner.get(di).get());const o=this.CollidePolygonPolygon(t,r);return o.length&&(o[0].colliderB=e,o[0].id=gi.calculatePairHash(t.id,e.id)),o},CollidePolygonPolygon(t,e){var i,s,n,r;const o=Pi.findPolygonPolygonSeparation(t,e);if(o.separation>0)return[];const a=Pi.findPolygonPolygonSeparation(e,t);if(a.separation>0)return[];const h=o.separation>a.separation?o:a,l=(h.collider===t?e:t).findSide(h.axis.negate()),c=h.side,d=c.dir().normalize(),u=l.clip(d.negate(),-d.dot(c.begin));let p=null;if(u&&(p=u.clip(d,d.dot(c.end))),p){const o=p.getPoints().filter((t=>c.below(t)));let a=h.axis,l=a.perpendicular();e.center.sub(t.center).dot(a)<0&&(a=a.negate(),l=a.perpendicular());let d=[];if(h.collider===t){const t=null!==(s=null===(i=e.owner)||void 0===i?void 0:i.get(di))&&void 0!==s?s:new di;d=o.map((e=>t.applyInverse(e)))}else{const e=null!==(r=null===(n=t.owner)||void 0===n?void 0:n.get(di))&&void 0!==r?r:new di;d=o.map((t=>e.applyInverse(t)))}return[new Ei(t,e,a.scale(-h.separation),a,l,o,d,h)]}return[]},FindContactSeparation(t,e){var i,s,n,r;const o=t.colliderA,a=null!==(s=null===(i=t.colliderA.owner)||void 0===i?void 0:i.get(di))&&void 0!==s?s:new di,h=t.colliderB,l=null!==(r=null===(n=t.colliderB.owner)||void 0===n?void 0:n.get(di))&&void 0!==r?r:new di;if(o instanceof Ti&&h instanceof Ti){return-(o.radius+h.radius-a.pos.distance(l.pos))}if(o instanceof Bi&&h instanceof Bi&&t.info.localSide){let i,s;return t.info.collider===o?(i=new Ci(a.apply(t.info.localSide.begin),a.apply(t.info.localSide.end)),s=l.apply(e)):(i=new Ci(l.apply(t.info.localSide.begin),l.apply(t.info.localSide.end)),s=a.apply(e)),i.distanceToPoint(s,!0)}if(o instanceof Bi&&h instanceof Ti||h instanceof Bi&&o instanceof Ti){const i=a.apply(e);if(t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Di&&h instanceof Bi||h instanceof Di&&o instanceof Bi){let i;if(i=t.info.collider===o?l.apply(e):a.apply(e),t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Ti&&h instanceof Di||h instanceof Ti&&o instanceof Di){const i=l.apply(e);let s;o instanceof Ti&&(s=o.getFurthestPoint(t.normal));const n=i.distance(s);if(t.info.side)return n>0?-n:0}return 0}};class Di extends wi{constructor(t){var e;super(),this._globalMatrix=Ft.identity(),this.begin=t.begin||vt.Zero,this.end=t.end||vt.Zero,this.offset=null!==(e=t.offset)&&void 0!==e?e:vt.Zero}clone(){return new Di({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos.add(this.offset))&&void 0!==t?t:this.offset}get center(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.average(e)}_getTransformedBegin(){return this._globalMatrix.multiply(this.begin)}_getTransformedEnd(){return this._globalMatrix.multiply(this.end)}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){const i=this._getTransformedBegin().sub(t.pos);if(0===t.dir.cross(this.getSlope())&&0!==i.cross(t.dir))return null;const s=t.dir.cross(this.getSlope());if(0===s)return null;const n=i.cross(this.getSlope())/s;if(n>=0&&n<=e){const e=i.cross(t.dir)/s/this.getLength();if(e>=0&&e<=1)return t.getPoint(n)}return null}getClosestLineBetween(t){if(t instanceof Ti)return Si.CircleEdgeClosestLine(t,this);if(t instanceof Bi)return Si.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Di)return Si.EdgeEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ti)return Ii.CollideCircleEdge(t,this);if(t instanceof Bi)return Ii.CollidePolygonEdge(t,this);if(t instanceof Di)return Ii.CollideEdgeEdge();throw new Error("Edge could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new At(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new Ci(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new Ci(this.begin,this.end)}get axes(){const t=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),e=[];return e.push(t),e.push(t.negate()),e.push(t.normal()),e.push(t.normal().negate()),e}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){var e;this._transform=t;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new mi(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.drawLine(i,s,e,2),t.drawCircle(i,2,e),t.drawCircle(s,2,e)}}class Bi extends wi{set points(t){this._localBoundsDirty=!0,this._localSidesDirty=!0,this._sidesDirty=!0,this._points=t}get points(){return this._points}constructor(t){var e,i;super(),this._logger=J.getInstance(),this._transformedPoints=[],this._sides=[],this._localSides=[],this._globalMatrix=Ft.identity(),this._transformedPointsDirty=!0,this._sidesDirty=!0,this._localSidesDirty=!0,this._localBoundsDirty=!0,this.offset=null!==(e=t.offset)&&void 0!==e?e:vt.Zero,this._globalMatrix.translate(this.offset.x,this.offset.y),this.points=null!==(i=t.points)&&void 0!==i?i:[];this._isCounterClockwiseWinding(this.points)||this.points.reverse(),this.isConvex()||this._logger.warn("Excalibur only supports convex polygon colliders and will not behave properly.Call PolygonCollider.triangulate() to build a new collider composed of smaller convex triangles"),this._calculateTransformation()}_isCounterClockwiseWinding(t){let e=0;for(let i=0;i<t.length;i++)e+=(t[(i+1)%t.length].x-t[i].x)*(t[(i+1)%t.length].y+t[i].y);return e<0}isConvex(){if(this.points.length<3)return!1;let t=this.points[this.points.length-2],e=this.points[this.points.length-1],i=Math.atan2(e.y-t.y,e.x-t.x),s=0,n=0,r=0;for(const[o,a]of this.points.entries()){if(t=e,s=i,e=a,i=Math.atan2(e.y-t.y,e.x-t.x),t.equals(e))return!1;let h=i-s;if(h<=-Math.PI?h+=2*Math.PI:h>Math.PI&&(h-=2*Math.PI),0===o){if(0===h)return!1;n=h>0?1:-1}else if(n*h<=0)return!1;r+=h}return 1===Math.abs(Math.round(r/(2*Math.PI)))}tessellate(){const t=[];for(let e=1;e<this.points.length-2;e++)t.push([this.points[0],this.points[e+1],this.points[e+2]]);return t.push([this.points[0],this.points[1],this.points[2]]),new bi(t.map((t=>Ri.Polygon(t))))}triangulate(){if(this.points.length<3)throw Error("Invalid polygon");function t(t,e){return t>=e.length?e[t%e.length]:t<0?e[t%e.length+e.length]:e[t]}function e(t,e,i,s){const n=i.sub(e),r=s.sub(i),o=e.sub(s),a=t.sub(e),h=t.sub(i),l=t.sub(s),c=n.cross(a),d=r.cross(h),u=o.cross(l);return!(c>0||d>0||u>0)}const i=[],s=[...this.points],n=gt(0,this.points.length-1);for(;n.length>3;)for(let r=0;r<n.length;r++){const o=n[r],a=t(r-1,n),h=t(r+1,n),l=s[o],c=s[a],d=s[h],u=c.sub(l);if(!(d.sub(l).cross(u)>0))continue;let p=!0;for(let t=0;t<n.length;t++){const i=n[t];if(i===o||i===a||i===h)continue;if(e(s[i],c,l,d)){p=!1;break}}if(p){i.push([c,l,d]),n.splice(r,1);break}}return i.push([s[n[0]],s[n[1]],s[n[2]]]),new bi(i.map((t=>Ri.Polygon(t))))}clone(){return new Bi({offset:this.offset.clone(),points:this.points.map((t=>t.clone()))})}get worldPos(){return this._transform?this._transform.pos.add(this.offset):this.offset}get center(){return this.bounds.center}_calculateTransformation(){const t=this.points,e=t.length;this._transformedPoints.length=0;for(let i=0;i<e;i++)this._transformedPoints[i]=this._globalMatrix.multiply(t[i].clone())}getTransformedPoints(){return this._transformedPointsDirty&&(this._calculateTransformation(),this._transformedPointsDirty=!1),this._transformedPoints}getSides(){if(this._sidesDirty){const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new Ci(e[s],e[(s+1)%i]));this._sides=t,this._sidesDirty=!1}return this._sides}getLocalSides(){if(this._localSidesDirty){const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new Ci(e[s],e[(s+1)%i]));this._localSides=t,this._localSidesDirty=!1}return this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}get axes(){const t=[],e=this.getSides();for(let i=0;i<e.length;i++)t.push(e[i].normal());return t}update(t){var e;if(t){this._transform=t,this._transformedPointsDirty=!0,this._sidesDirty=!0;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}}contains(t){const e=new xi(t,new vt(1,0));return this.getSides().reduce((function(t,i){return e.intersect(i)>=0?t+1:t}),0)%2!=0}getClosestLineBetween(t){if(t instanceof Ti)return Si.PolygonCircleClosestLine(this,t);if(t instanceof Bi)return Si.PolygonPolygonClosestLine(this,t);if(t instanceof Di)return Si.PolygonEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ti)return Ii.CollideCirclePolygon(t,this);if(t instanceof Bi)return Ii.CollidePolygonPolygon(this,t);if(t instanceof Di)return Ii.CollidePolygonEdge(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let r=0;r<e.length;r++){const o=e[r].distanceToPoint(t);o<i&&(i=o,s=r,n=o)}return-1!==s?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){return this.localBounds.transform(this._globalMatrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=At.fromPoints(this.points),this._localBoundsDirty=!1),this._localBounds}getInertia(t){if(this._cachedMass===t&&this._cachedInertia)return this._cachedInertia;let e=0,i=0;const s=this.points;for(let t=0;t<s.length;t++){const n=(t+1)%s.length,r=s[n].cross(s[t]);e+=r*(s[t].dot(s[t])+s[t].dot(s[n])+s[n].dot(s[n])),i+=r}return this._cachedMass=t,this._cachedInertia=t/6*(e/i)}rayCast(t,e=1/0){const i=this.getSides(),s=i.length;let n=Number.MAX_VALUE,r=-1;for(let o=0;o<s;o++){const s=t.intersect(i[o]);s>=0&&s<n&&s<=e&&(n=s,r=o)}return r>=0?t.getPoint(n):null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;r<i;r++){const i=e[r].dot(t);s=Math.min(s,i),n=Math.max(n,i)}return new mi(s,n)}debug(t,e){const i=this.getTransformedPoints()[0],s=[i,...this.getTransformedPoints(),i];for(let i=0;i<s.length-1;i++)t.drawLine(s[i],s[i+1],e,2),t.drawCircle(s[i],2,e),t.drawCircle(s[i+1],2,e)}}class Ri{static Box(t,e,i=vt.Half,s=vt.Zero){return new Bi({points:new At(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints(),offset:s})}static Polygon(t,e=vt.Zero){return new Bi({points:t,offset:e})}static Circle(t,e=vt.Zero){return new Ti({radius:t,offset:e})}static Edge(t,e){return new Di({begin:t,end:e})}static Capsule(t,e,i=vt.Zero){const s=J.getInstance();t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider");if(e>=t){return new bi([Ri.Circle(t/2,xt(0,-e/2+t/2).add(i)),Ri.Box(t,e-t,vt.Half,i),Ri.Circle(t/2,xt(0,e/2-t/2).add(i))])}return new bi([Ri.Circle(e/2,xt(-t/2+e/2,0).add(i)),Ri.Box(t-e,e,vt.Half,i),Ri.Circle(e/2,xt(t/2-e/2,0).add(i))])}}class Fi extends hi{constructor(t){super(),this.type="ex.collider",this.events=new d,this.$colliderAdded=new ci,this.$colliderRemoved=new ci,this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,t.events.pipe(this.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this._collider.events.unpipe(this.events),this.$colliderRemoved.notifyAll(this._collider),this._collider.owner=null,this._collider=null)}clone(){return new Fi(this._collider.clone())}get bounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.bounds)&&void 0!==e?e:new At}get localBounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new At}update(){var t;const e=null===(t=this.owner)||void 0===t?void 0:t.get(di);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e.get()))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof bi&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach((e=>{e.mtv=e.mtv.negate(),e.normal=e.normal.negate(),e.tangent=e.normal.perpendicular(),e.colliderA=this._collider,e.colliderB=t._collider})),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",(e=>{const i=e;t.events.emit("precollision",new R(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("postcollision",(e=>{const i=e;t.events.emit("postcollision",new F(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("collisionstart",(e=>{const i=e;t.events.emit("collisionstart",new U(i.target.owner,i.other.owner,i.contact))})),this.events.on("collisionend",(e=>{const i=e;t.events.emit("collisionend",new O(i.target.owner,i.other.owner))}))}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=vt.Half,s=vt.Zero){const n=Ri.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=vt.Zero){const i=Ri.Polygon(t,e);return this.set(i)}useCircleCollider(t,e=vt.Zero){const i=Ri.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=Ri.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new bi(t))}}var ki;!function(t){t.Rotation="rotation",t.X="x",t.Y="y"}(ki||(ki={}));class Mi extends hi{constructor(t){var e,i,s;super(),this.type="ex.body",this.dependencies=[di,ui],this.id=c("body",Mi._ID++),this.events=new d,this._oldTransform=new ai,this.__oldTransformCaptured=!1,this.enableFixedUpdateInterpolate=!0,this.collisionType=Ke.PreventCollision,this.group=_i.All,this._mass=ni.defaultMass,this.sleepMotion=5*ni.sleepEpsilon,this.canSleep=ni.bodiesCanSleepByDefault,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this.oldVel=new vt(0,0),this.oldAcc=vt.Zero,t&&(this.collisionType=null!==(e=t.type)&&void 0!==e?e:this.collisionType,this.group=null!==(i=t.group)&&void 0!==i?i:this.group,this.useGravity=null!==(s=t.useGravity)&&void 0!==s?s:this.useGravity)}get matrix(){return this.transform.get().matrix}get mass(){return this._mass}set mass(t){this._mass=t,this._cachedInertia=void 0,this._cachedInverseInertia=void 0}get inverseMass(){return this.collisionType===Ke.Fixed?0:1/this.mass}get sleeping(){return this._sleeping}setSleeping(t){this._sleeping=t,t?(this.vel=vt.Zero,this.acc=vt.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=5*ni.sleepEpsilon}updateMotion(){this._sleeping&&this.setSleeping(!0);const t=this.vel.size*this.vel.size+Math.abs(this.angularVelocity*this.angularVelocity),e=ni.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=dt(this.sleepMotion,0,10*ni.sleepEpsilon),this.canSleep&&this.sleepMotion<ni.sleepEpsilon&&this.setSleeping(!0)}get inertia(){if(this._cachedInertia)return this._cachedInertia;const t=this.owner.get(Fi);if(t){t.$colliderAdded.subscribe((()=>{this._cachedInertia=null})),t.$colliderRemoved.subscribe((()=>{this._cachedInertia=null}));const e=t.get();if(e)return this._cachedInertia=e.getInertia(this.mass)}return 0}get inverseInertia(){return this._cachedInverseInertia?this._cachedInverseInertia:this._cachedInverseInertia=this.collisionType===Ke.Fixed?0:1/this.inertia}get active(){var t;return!!(null===(t=this.owner)||void 0===t?void 0:t.active)}get center(){return this.globalPos}get transform(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(di)}get motion(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(ui)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get globalPos(){return this.transform.globalPos}set globalPos(t){this.transform.globalPos=t}get oldPos(){return this._oldTransform.pos}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get oldRotation(){return this._oldTransform.rotation}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get oldScale(){return this._oldTransform.scale}get scaleFactor(){return this.motion.scaleFactor}set scaleFactor(t){this.motion.scaleFactor=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==Ke.Active)return;const i=e.scale(this.inverseMass);if(this.limitDegreeOfFreedom.includes(ki.X)&&(i.x=0),this.limitDegreeOfFreedom.includes(ki.Y)&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes(ki.Rotation)){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==Ke.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes(ki.X)&&(e.x=0),this.limitDegreeOfFreedom.includes(ki.Y)&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===Ke.Active&&!this.limitDegreeOfFreedom.includes(ki.Rotation)){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.__oldTransformCaptured=!0,this.transform.get().clone(this._oldTransform),this.oldVel.setTo(this.vel.x,this.vel.y),this.oldAcc.setTo(this.acc.x,this.acc.y)}clone(){return super.clone()}}Mi._ID=0;class Li{constructor(t){this.data=t,this.type="Component Added"}}function zi(t){return!!t&&"Component Added"===t.type}class Ui{constructor(t){this.data=t,this.type="Component Removed"}}function Oi(t){return!!t&&"Component Removed"===t.type}const Ni={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class Hi{constructor(t,e){if(this.events=new d,this.id=Hi._ID++,this.scene=null,this._name="anonymous",this.active=!0,this._componentsToRemove=[],this._componentTypeToInstance=new Map,this._componentStringToInstance=new Map,this._tagsMemo=[],this._typesMemo=[],this.componentAdded$=new ci,this.componentRemoved$=new ci,this._parent=null,this.childrenAdded$=new ci,this.childrenRemoved$=new ci,this._children=[],this._isInitialized=!1,this._setName(e),t)for(const e of t)this.addComponent(e)}_setName(t){this._name=t||`Entity#${this.id}`}get name(){return this._name}set name(t){this._setName(t)}kill(){this.active&&(this.active=!1,this.unparent())}isKilled(){return!this.active}get tags(){return this._tagsMemo}hasTag(t){return this.tags.includes(t)}addTag(t){return this.addComponent(new li(t))}removeTag(t,e=!1){return this.removeComponent(t,e)}get types(){return this._typesMemo}_rebuildMemos(){this._tagsMemo=Array.from(this._componentStringToInstance.values()).filter((t=>t instanceof li)).map((t=>t.type)),this._typesMemo=Array.from(this._componentStringToInstance.keys())}getComponents(){return Array.from(this._componentStringToInstance.values())}_notifyAddComponent(t){this._rebuildMemos();const e=new Li({component:t,entity:this});this.componentAdded$.notifyAll(e)}_notifyRemoveComponent(t){const e=new Ui({component:t,entity:this});this.componentRemoved$.notifyAll(e),this._rebuildMemos()}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}addChild(t){if(null!==t.parent)throw new Error("Entity already has a parent, cannot add without unparenting");if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");return this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t),this}removeChild(t){return t.parent===this&&(Pt(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){for(let t=this.children.length-1;t>=0;t--)this.removeChild(this.children[t]);return this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();e=e.concat(i.children),t=t.concat(i.children)}return t}clone(){const t=new Hi;for(const e of this.types)t.addComponent(this.get(e).clone());for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const e of t.children)this.addChild(e.clone().addTemplate(e));return this}addComponent(t,e=!1){if(this.has(t.type)){if(!e)return this;this.removeComponent(t,!0)}if(t.dependencies&&t.dependencies.length)for(const e of t.dependencies)this.addComponent(new e);t.owner=this;const i=t.constructor;return this._componentTypeToInstance.set(i,t),this._componentStringToInstance.set(t.type,t),t.onAdd&&t.onAdd(this),this._notifyAddComponent(t),this}removeComponent(t,e=!1){return e?"string"==typeof t?this._removeComponentByType(t):t instanceof hi&&this._removeComponentByType(t.type):this._componentsToRemove.push(t),this}clearComponents(){const t=this.getComponents();for(const e of t)this.removeComponent(e)}_removeComponentByType(t){if(this.has(t)){const e=this.get(t);e.owner=null,e.onRemove&&e.onRemove(this);const i=e.constructor;this._componentTypeToInstance.delete(i),this._componentStringToInstance.delete(e.type),this._notifyRemoveComponent(e)}}processComponentRemoval(){for(const t of this._componentsToRemove){const e="string"==typeof t?t:t.type;this._removeComponentByType(e)}this._componentsToRemove.length=0}has(t){return"string"==typeof t?this._componentStringToInstance.has(t):this._componentTypeToInstance.has(t)}get(t){return"string"==typeof t?this._componentStringToInstance.get(t):this._componentTypeToInstance.get(t)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0)}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}function Wi(t){return!!t.tick}Hi._ID=0;class Gi{constructor(t,e){this._options=t,this._graphics=e,this.graphics=[]}get name(){return this._options.name}hide(t){if(t){let e=null;e=t instanceof Nt?t:this._graphics.getGraphic(t),this.graphics=this.graphics.filter((t=>t.graphic!==e)),this._graphics.recalculateBounds()}else this.graphics.length=0}show(t,e){let i;return e={...e},t instanceof Nt?i=this._graphics.copyGraphics?t.clone():t:(i=this._graphics.getGraphic(t),i||J.getInstance().error(`No such graphic added to component named ${t}. These named graphics are available: `,this._graphics.getNames())),i?(this.graphics.push({graphic:i,options:e}),this._graphics.recalculateBounds(),i):null}use(t,e){return e={...e},this.hide(),this.show(t,e)}get order(){return this._options.order}set order(t){this._options.order=t}get offset(){var t;return null!==(t=this._options.offset)&&void 0!==t?t:vt.Zero}set offset(t){this._options.offset=t}get currentKeys(){var t;return null!==(t=this.name)&&void 0!==t?t:"anonymous"}clone(t){const e=new Gi({...this._options},t);return e.graphics=[...this.graphics.map((t=>({graphic:t.graphic.clone(),options:{...t.options}})))],e}}class Vi{constructor(t){this._component=t,this._layers=[],this._layerMap={},this.default=new Gi({name:"default",order:0},t),this._maybeAddLayer(this.default)}create(t){const e=new Gi(t,this._component);return this._maybeAddLayer(e)}get(t){return t?this._getLayer(t):this._layers}currentKeys(){const t=[];for(const e of this._layers)t.push(e.currentKeys);return t}has(t){return t in this._layerMap}_maybeAddLayer(t){return this._layerMap[t.name]?this._layerMap[t.name]:(this._layerMap[t.name]=t,this._layers.push(t),this._layers.sort(((t,e)=>t.order-e.order)),t)}_getLayer(t){return this._layerMap[t]}clone(t){const e=new Vi(t);e._layerMap={},e._layers=[],e.default=this.default.clone(t),e._maybeAddLayer(e.default);return this._layers.filter((t=>"default"!==t.name)).map((e=>e.clone(t))).forEach((t=>e._maybeAddLayer(t))),e}}class qi extends hi{getGraphic(t){return this._graphics[t]}getNames(){return Object.keys(this._graphics)}constructor(t){super(),this.type="ex.graphics",this._graphics={},this.visible=!0,this.opacity=1,this.offset=vt.Zero,this.anchor=vt.Half,this.flipHorizontal=!1,this.flipVertical=!1,this.copyGraphics=!1,this._localBounds=null,t={visible:this.visible,...t};const{current:e,anchor:i,opacity:s,visible:n,graphics:r,offset:o,copyGraphics:a,onPreDraw:h,onPostDraw:l}=t;this._graphics=r||{},this.offset=null!=o?o:this.offset,this.opacity=null!=s?s:this.opacity,this.anchor=null!=i?i:this.anchor,this.copyGraphics=null!=a?a:this.copyGraphics,this.onPreDraw=null!=h?h:this.onPreDraw,this.onPostDraw=null!=l?l:this.onPostDraw,this.visible=!!n,this.layers=new Vi(this),e&&this._graphics[e]&&this.show(this._graphics[e])}get current(){return this.layers.default.graphics}get graphics(){return this._graphics}add(t,e){let i="default",s=null;return"string"==typeof t?(i=t,s=e):s=t,this._graphics[i]=this.copyGraphics?s.clone():s,"default"===i&&this.show("default"),s}show(t,e){const i=this.layers.default.show(t,e);return this.recalculateBounds(),i}use(t,e){const i=this.layers.default.use(t,e);return this.recalculateBounds(),i}hide(t){this.layers.default.hide(t)}set localBounds(t){this._localBounds=t}recalculateBounds(){let t=new At;for(const e of this.layers.get())for(const{graphic:i,options:s}of e.graphics){let n=this.anchor,r=this.offset;(null==s?void 0:s.anchor)&&(n=s.anchor),(null==s?void 0:s.offset)&&(r=s.offset);const o=i.localBounds,a=-o.width*n.x+r.x,h=-o.height*n.y+r.y;t=null==i?void 0:i.localBounds.translate(xt(a+e.offset.x,h+e.offset.y)).combine(t)}this._localBounds=t}get localBounds(){return this._localBounds&&!this._localBounds.hasZeroDimensions()||this.recalculateBounds(),this._localBounds}update(t,e=0){for(const i of this.layers.get())for(const{graphic:s}of i.graphics)Wi(s)&&(null==s||s.tick(t,e))}clone(){const t=new qi;return t._graphics={...this._graphics},t.offset=this.offset.clone(),t.opacity=this.opacity,t.anchor=this.anchor.clone(),t.copyGraphics=this.copyGraphics,t.onPreDraw=this.onPreDraw,t.onPostDraw=this.onPostDraw,t.visible=this.visible,t.layers=this.layers.clone(t),t}}class Xi extends Re{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new Xi({width:this.width,height:this.height,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class Ki extends Re{get radius(){return this._radius}set radius(t){this._radius=t,this.width=2*this._radius,this.height=2*this._radius,this.flagDirty()}constructor(t){var e,i,s;super(t),this._radius=0;const n=null!==(e=t.lineWidth)&&void 0!==e?e:t.strokeColor?1:0;this.padding=null!==(i=t.padding)&&void 0!==i?i:2+n/2,this.radius=t.radius,this.filtering=null!==(s=t.filtering)&&void 0!==s?s:Wt.Blended,this.rasterize()}clone(){return new Ki({radius:this.radius,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,2*Math.PI),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class Zi extends hi{constructor(){super(...arguments),this.type="ex.pointer",this.useColliderShape=!0,this.useGraphicsBounds=!1}}class Yi{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new vt(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}}Yi.Linear=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*t/s+e)),Yi.EaseInQuad=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t+e)),Yi.EaseOutQuad=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>-(i-=e)*(t/=s)*(t-2)+e)),Yi.EaseInOutQuad=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e))),Yi.EaseInCubic=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t*t+e)),Yi.EaseOutCubic=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(t/=s,(i-=e)*(--t*t*t+1)+e))),Yi.EaseInOutCubic=Yi.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e)));class ji{constructor(t){this._actions=[],this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}hasNext(){return this._actions.length>0}isComplete(){return 0===this._actions.length}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){this._actions.length>0&&(this._currentAction=this._actions[0],this._currentAction.update(t),this._currentAction.isComplete(this._entity)&&this._completedActions.push(this._actions.shift()))}}class Qi{constructor(t,e,i){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new ys(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class $i{constructor(t,e){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new ys(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}class Ji{constructor(t,e,i,s){if(this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(di),this._motion=t.get(ui),this._speed=s,this._offset=new vt(e,i),s<=0)throw J.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new vt(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.size,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(di);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class ts{constructor(t,e,i,s){this.entity=t,this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._end=new vt(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new vt(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=xt(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}isComplete(t){const e=t.get(di);return this._stopped||new vt(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}var es,is,ss,ns,rs,os;!function(t){t[t.ShortestPath=0]="ShortestPath",t[t.LongestPath=1]="LongestPath",t[t.Clockwise=2]="Clockwise",t[t.CounterClockwise=3]="CounterClockwise"}(es||(es={}));class as{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._end=e,this._speed=i,this._rotationType=s||es.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const t=Math.abs(this._end-this._start),e=ht-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+ht)%ht>=Math.PI,this._rotationType){case es.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case es.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case es.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case es.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class hs{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._speed=i,this._offset=e,this._rotationType=s||es.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const t=Math.abs(this._end-this._start),e=ht-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+ht)%ht>=Math.PI,this._rotationType){case es.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case es.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case es.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case es.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._start=void 0,this._currentNonCannonAngle=void 0,this._distance=void 0}}class ls{constructor(t,e,i,s,n){this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*t}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*t}this.isComplete()&&(this._tx.scale=xt(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startX)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class cs{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._offset=new vt(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class ds{constructor(t){this._method=null,this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class us{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new vt(0,0),this._lerpEnd=new vt(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._lerpDuration=s,this._lerpEnd=new vt(e,i)}_initialize(){this._lerpStart=new vt(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=xt((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=xt(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=vt.Zero)}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=xt(0,0),this._stopped=!0}}class ps{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new vt(0,0),this._lerpEnd=new vt(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._lerpDuration=s,this._offset=new vt(e,i)}_initialize(){this._lerpStart=new vt(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._lerpEnd=this._lerpStart.add(this._offset)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=xt((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=xt(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=vt.Zero)}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=xt(0,0),this._stopped=!0}}class _s{constructor(t,e,i,s=1){this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(qi),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0,this._elapsedTime=0,this._totalTime=0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.visible&&this._elapsedTime>=this._timeVisible&&(this._graphics.visible=!1,this._elapsedTime=0),!this._graphics.visible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.visible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.visible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.visible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._elapsedTime=0,this._totalTime=0}}class gs{constructor(t,e,i){this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(qi),this._endOpacity=e,this._speed=this._ogspeed=i}update(t){this._graphics&&(this._started||(this._started=!0,this._speed=this._ogspeed,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._speed>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._speed),this._speed-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),J.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||Math.abs(this._graphics.opacity-this._endOpacity)<.05}stop(){this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class ms{constructor(t){this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1,this._stopped=!1}}class fs{constructor(t){this._stopped=!1,this._entity=t}update(t){this._entity.get(ws).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class vs{constructor(t,e,i){this._started=!1,this._stopped=!1,this._tx=t.get(di),this._motion=t.get(ui),this._followTx=e.get(di),this._followMotion=e.get(ui),this._current=new vt(this._tx.pos.x,this._tx.pos.y),this._end=new vt(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=void 0!==i?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(0!==e&&(this._speed=e),this._current=xt(this._tx.pos.x,this._tx.pos.y),this._end=xt(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const t=this._dir.scale(this._speed);this._motion.vel=xt(t.x,t.y)}else this._motion.vel=xt(0,0);this.isComplete()&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}stop(){this._motion.vel=xt(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1,this._stopped=!1}}class xs{constructor(t,e,i){this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tx=t.get(di),this._motion=t.get(ui),this._meetTx=e.get(di),this._meetMotion=e.get(ui),this._current=new vt(this._tx.pos.x,this._tx.pos.y),this._end=new vt(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,void 0!==i&&(this._speedWasSpecified=!0)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));0===e||this._speedWasSpecified||(this._speed=e),this._current=xt(this._tx.pos.x,this._tx.pos.y),this._end=xt(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=xt(i.x,i.y),this.isComplete()&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}isComplete(){return this._stopped||this._distanceBetween<=1}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._distanceBetween=void 0}}class ys{constructor(t){this._entity=t,this._queue=new ji(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}runAction(t){return t.reset(),this._queue.add(t),this}easeTo(...t){var e,i;let s=0,n=0,r=0,o=Yi.Linear;return t[0]instanceof vt?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new us(this._entity,s,n,r,o)),this}easeBy(...t){var e,i;let s=0,n=0,r=0,o=Yi.Linear;return t[0]instanceof vt?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new ps(this._entity,s,n,r,o)),this}moveTo(t,e,i){let s=0,n=0,r=0;return t instanceof vt?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new ts(this._entity,s,n,r)),this}moveBy(t,e,i){let s=0,n=0,r=0;return t instanceof vt?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new Ji(this._entity,s,n,r)),this}rotateTo(t,e,i){return this._queue.add(new as(this._entity,t,e,i)),this}rotateBy(t,e,i){return this._queue.add(new hs(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,r=1,o=0,a=0;return t instanceof vt&&e instanceof vt&&(n=t.x,r=t.y,o=e.x,a=e.y),"number"==typeof t&&"number"==typeof e&&(n=t,r=e,o=i,a=s),this._queue.add(new ls(this._entity,n,r,o,a)),this}scaleBy(t,e,i){let s=1,n=1;return t instanceof vt&&(s=t.x,n=t.y,i=e),"number"==typeof t&&"number"==typeof e&&(s=t,n=e),this._queue.add(new cs(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new _s(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new gs(this._entity,t,e)),this}delay(t){return this._queue.add(new ms(t)),this}die(){return this._queue.add(new fs(this._entity)),this}callMethod(t){return this._queue.add(new ds(t)),this}repeat(t,e){return e?(this._queue.add(new Qi(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new $i(this._entity,t)),this}follow(t,e){return void 0===e?this._queue.add(new vs(this._entity,t)):this._queue.add(new vs(this._entity,t,e)),this}meet(t,e){return void 0===e?this._queue.add(new xs(this._entity,t)):this._queue.add(new xs(this._entity,t,e)),this}toPromise(){return new Promise((t=>{this._queue.add(new ds((()=>{t()})))}))}}class ws extends hi{constructor(){super(...arguments),this.type="ex.actions",this.dependencies=[di,ui]}onAdd(t){this._ctx=new ys(t)}onRemove(){this._ctx=null}getQueue(){var t;return null===(t=this._ctx)||void 0===t?void 0:t.getQueue()}runAction(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.runAction(t)}update(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.update(t)}clearActions(){var t;null===(t=this._ctx)||void 0===t||t.clearActions()}easeTo(...t){return this._ctx.easeTo.apply(this._ctx,t)}easeBy(...t){return this._ctx.easeBy.apply(this._ctx,t)}moveTo(t,e,i){return this._ctx.moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._ctx.moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._ctx.rotateTo(t,e,i)}rotateBy(t,e,i){return this._ctx.rotateBy(t,e,i)}scaleTo(t,e,i,s){return this._ctx.scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._ctx.scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._ctx.blink(t,e,i)}fade(t,e){return this._ctx.fade(t,e)}delay(t){return this._ctx.delay(t)}die(){return this._ctx.die()}callMethod(t){return this._ctx.callMethod(t)}repeat(t,e){return this._ctx.repeat(t,e)}repeatForever(t){return this._ctx.repeatForever(t)}follow(t,e){return this._ctx.follow(t,e)}meet(t,e){return this._ctx.meet(t,e)}toPromise(){return this._ctx.toPromise()}}!function(t){t.Em="em",t.Rem="rem",t.Px="px",t.Pt="pt",t.Percent="%"}(is||(is={})),function(t){t.Left="left",t.Right="right",t.Center="center",t.Start="start",t.End="end"}(ss||(ss={})),function(t){t.Top="top",t.Hanging="hanging",t.Middle="middle",t.Alphabetic="alphabetic",t.Ideographic="ideographic",t.Bottom="bottom"}(ns||(ns={})),function(t){t.Normal="normal",t.Italic="italic",t.Oblique="oblique"}(rs||(rs={})),function(t){t.LeftToRight="ltr",t.RightToLeft="rtl"}(os||(os={}));class bs{constructor(t,e,i,s){this.font=t,this.text=e,this.color=i,this.maxWidth=s,this._textFragments=[],this.disposed=!1,this._dirty=!0,this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.dimensions=this.measureText(e),this._setDimension(this.dimensions,this.ctx),this._lastHashCode=this.getHashCode()}measureText(t,e){if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);let i=null;i=null!=e?this._getLinesFromText(t,e):t.split("\n");const s=i.reduce(((t,e)=>t.length>e.length?t:e));this._applyFont(this.ctx);const n=this.ctx.measureText(s);let r=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);const o=r*i.length;r=o;const a=o-Math.abs(n.actualBoundingBoxAscent);return new At({left:0-Math.abs(n.actualBoundingBoxLeft)-this.font.padding,top:0-Math.abs(n.actualBoundingBoxAscent)-this.font.padding,bottom:0+a+this.font.padding,right:0+Math.abs(n.actualBoundingBoxRight)+this.font.padding})}_setDimension(t,e){e.canvas.width=2*(t.width+2*this.font.padding)*this.font.quality,e.canvas.height=2*(t.height+2*this.font.padding)*this.font.quality}static getHashCode(t,e,i){var s;return e+"__hashcode__"+t.fontString+t.showDebug+t.textAlign+t.baseAlign+t.direction+JSON.stringify(t.shadow)+(t.padding.toString()+t.smoothing.toString()+t.lineWidth.toString()+t.lineDash.toString()+(null===(s=t.strokeColor)||void 0===s?void 0:s.toString())+(i?i.toString():t.color.toString()))}getHashCode(t=!0){return bs.getHashCode(this.font,this.text,t?this.color:void 0)}_applyRasterProperties(t){var e,i;t.translate(this.font.padding,this.font.padding),t.imageSmoothingEnabled=this.font.smoothing,t.lineWidth=this.font.lineWidth,t.setLineDash(null!==(e=this.font.lineDash)&&void 0!==e?e:t.getLineDash()),t.strokeStyle=null===(i=this.font.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=this.color.toString()}_applyFont(t){t.resetTransform(),t.translate(this.font.padding+t.canvas.width/2,this.font.padding+t.canvas.height/2),t.scale(this.font.quality,this.font.quality),t.textAlign=this.font.textAlign,t.textBaseline=this.font.baseAlign,t.font=this.font.fontString,t.direction=this.font.direction,this.font.shadow&&(t.shadowColor=this.font.shadow.color.toString(),t.shadowBlur=this.font.shadow.blur,t.shadowOffsetX=this.font.shadow.offset.x,t.shadowOffsetY=this.font.shadow.offset.y)}_drawText(t,e,i){this._applyRasterProperties(t),this._applyFont(t);for(let s=0;s<e.length;s++){const n=e[s];this.color&&t.fillText(n,0,s*i),this.font.strokeColor&&t.strokeText(n,0,s*i)}this.font.showDebug&&(Te(t,yt.Green,-t.canvas.width/2,0,t.canvas.width/2,0,2),Te(t,yt.Red,0,-t.canvas.height/2,0,t.canvas.height/2,2))}_splitTextBitmap(t){const e=[];let i=0,s=0;const n=Math.min(4096,t.canvas.width),r=Math.min(4096,t.canvas.height);for(;i<t.canvas.width;){for(;s<t.canvas.height;){const o=document.createElement("canvas");o.width=n,o.height=r;o.getContext("2d").drawImage(t.canvas,i,s,n,r,0,0,n,r),e.push({x:i,y:s,canvas:o}),s+=r}i+=n,s=0}return e}flagDirty(){this._dirty=!0}render(t,e,i,s){if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);this._ex=t;const n=this.getHashCode();if(this._lastHashCode!==n&&(this._dirty=!0),this._dirty){this.dimensions=this.measureText(this.text,s),this._setDimension(this.dimensions,this.ctx);const e=this._getLinesFromText(this.text,s),i=this.dimensions.height/e.length;if(this._drawText(this.ctx,e,i),t instanceof me)for(const e of this._textFragments)t.textureLoader.delete(e.canvas);if(this._textFragments=this._splitTextBitmap(this.ctx),t instanceof me)for(const e of this._textFragments)t.textureLoader.load(e.canvas,this.font.filtering,!0);this._lastHashCode=n,this._dirty=!1}for(const s of this._textFragments)t.drawImage(s.canvas,0,0,s.canvas.width,s.canvas.height,s.x/this.font.quality+e-this.ctx.canvas.width/this.font.quality/2,s.y/this.font.quality+i-this.ctx.canvas.height/this.font.quality/2,s.canvas.width/this.font.quality,s.canvas.height/this.font.quality)}dispose(){if(this.disposed=!0,this.dimensions=void 0,this.canvas=void 0,this.ctx=void 0,this._ex instanceof me)for(const t of this._textFragments)this._ex.textureLoader.delete(t.canvas);this._textFragments.length=0}_getLinesFromText(t,e){if(this._chachedText===t&&this._cachedRenderWidth===e)return this._chachedLines;const i=t.split("\n");if(null==e)return i;for(let t=0;t<i.length;t++){let s=i[t],n="";if(this.measureText(s).width>e){for(;this.measureText(s).width>e;)n=s[s.length-1]+n,s=s.slice(0,-1);i[t]=s,i[t+1]=n}}return this._chachedText=t,this._chachedLines=i,this._cachedRenderWidth=e,i}}class Cs{static measureText(t,e,i){const s=bs.getHashCode(e,t);if(Cs._MEASURE_CACHE.has(s))return Cs._MEASURE_CACHE.get(s);Cs._LOGGER.debug("Font text measurement cache miss");const n=e.measureTextWithoutCache(t,i);return Cs._MEASURE_CACHE.set(s,n),n}static getTextInstance(t,e,i){const s=bs.getHashCode(e,t,i);let n=Cs._TEXT_CACHE.get(s);return n||(n=new bs(e,t,i),Cs._TEXT_CACHE.set(s,n),Cs._LOGGER.debug("Font text instance cache miss")),Cs._TEXT_USAGE.set(n,performance.now()),n}static checkAndClearCache(){const t=[],e=new Set;for(const[i,s]of Cs._TEXT_USAGE.entries())if(s+100<performance.now())Cs._LOGGER.debug(`Text cache entry timed out ${i.text}`),t.push(i),i.dispose();else{const t=i.getHashCode(!1);e.add(t)}t.forEach((t=>{Cs._TEXT_USAGE.delete(t)})),this._TEXT_CACHE.clear();for(const[t]of this._TEXT_USAGE.entries())this._TEXT_CACHE.set(t.getHashCode(),t);const i=new Map;for(const t of e)Cs._MEASURE_CACHE.has(t)&&i.set(t,Cs._MEASURE_CACHE.get(t));this._MEASURE_CACHE.clear(),this._MEASURE_CACHE=i}static get cacheSize(){return Cs._TEXT_USAGE.size}static clearCache(){for(const[t]of Cs._TEXT_USAGE.entries())t.dispose();Cs._TEXT_USAGE.clear(),Cs._TEXT_CACHE.clear(),Cs._MEASURE_CACHE.clear()}}Cs._LOGGER=J.getInstance(),Cs._TEXT_USAGE=new Map,Cs._TEXT_CACHE=new Map,Cs._MEASURE_CACHE=new Map;class As extends Nt{constructor(t={}){var e,i,s,n,r,o,a,h,l,c,d,u,p,_,g,m,f,v,x;super(t),this.filtering=Wt.Blended,this.quality=2,this.padding=2,this.smoothing=!1,this.lineWidth=1,this.lineDash=[],this.color=yt.Black,this.family="sans-serif",this.style=rs.Normal,this.bold=!1,this.unit=is.Px,this.textAlign=ss.Left,this.baseAlign=ns.Alphabetic,this.direction=os.LeftToRight,this.size=10,this.shadow=null,this._textBounds=new At,this._textMeasurement=new bs(this,"",yt.Black),this.smoothing=null!==(e=null==t?void 0:t.smoothing)&&void 0!==e?e:this.smoothing,this.padding=null!==(i=null==t?void 0:t.padding)&&void 0!==i?i:this.padding,this.color=null!==(s=null==t?void 0:t.color)&&void 0!==s?s:this.color,this.strokeColor=null!==(n=null==t?void 0:t.strokeColor)&&void 0!==n?n:this.strokeColor,this.lineDash=null!==(r=null==t?void 0:t.lineDash)&&void 0!==r?r:this.lineDash,this.lineWidth=null!==(o=null==t?void 0:t.lineWidth)&&void 0!==o?o:this.lineWidth,this.filtering=null!==(a=null==t?void 0:t.filtering)&&void 0!==a?a:this.filtering,this.family=null!==(h=null==t?void 0:t.family)&&void 0!==h?h:this.family,this.style=null!==(l=null==t?void 0:t.style)&&void 0!==l?l:this.style,this.bold=null!==(c=null==t?void 0:t.bold)&&void 0!==c?c:this.bold,this.size=null!==(d=null==t?void 0:t.size)&&void 0!==d?d:this.size,this.unit=null!==(u=null==t?void 0:t.unit)&&void 0!==u?u:this.unit,this.textAlign=null!==(p=null==t?void 0:t.textAlign)&&void 0!==p?p:this.textAlign,this.baseAlign=null!==(_=null==t?void 0:t.baseAlign)&&void 0!==_?_:this.baseAlign,this.direction=null!==(g=null==t?void 0:t.direction)&&void 0!==g?g:this.direction,this.quality=null!==(m=null==t?void 0:t.quality)&&void 0!==m?m:this.quality,(null==t?void 0:t.shadow)&&(this.shadow={},this.shadow.blur=null!==(f=t.shadow.blur)&&void 0!==f?f:this.shadow.blur,this.shadow.offset=null!==(v=t.shadow.offset)&&void 0!==v?v:this.shadow.offset,this.shadow.color=null!==(x=t.shadow.color)&&void 0!==x?x:this.shadow.color)}clone(){return new As({...this.cloneGraphicOptions(),size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:null})}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get localBounds(){return this._textBounds}_drawImage(t,e,i){}_rotate(t){var e;const i=null!==(e=this.origin)&&void 0!==e?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}measureTextWithoutCache(t,e){return this._textMeasurement.measureText(t,e)}measureText(t,e){return Cs.measureText(t,this,e)}_postDraw(t){t.restore()}render(t,e,i,s,n,r){const o=Cs.getTextInstance(e,this,i);this._textBounds=o.dimensions,this._preDraw(t,s,n),o.render(t,s,n,r),this._postDraw(t)}}class Ss extends Nt{constructor(t){var e,i;super(t),this._text="",this._textWidth=0,this._textHeight=0,this.font=null!==(e=t.font)&&void 0!==e?e:new As,this.color=null!==(i=t.color)&&void 0!==i?i:this.color,this.text=t.text,this.maxWidth=t.maxWidth}clone(){var t,e;return new Ss({text:this.text.slice(),color:null!==(e=null===(t=this.color)||void 0===t?void 0:t.clone())&&void 0!==e?e:yt.Black,font:this.font.clone(),maxWidth:this.maxWidth})}get text(){return this._text}set text(t){this._text=t,this._calculateDimension()}get font(){return this._font}set font(t){this._font=t}get width(){return 0===this._textWidth&&this._calculateDimension(),this._textWidth*this.scale.x}get height(){return 0===this._textHeight&&this._calculateDimension(),this._textHeight*this.scale.y}_calculateDimension(){const{width:t,height:e}=this.font.measureText(this._text,this.maxWidth);this._textWidth=t,this._textHeight=e}get localBounds(){return this.font.measureText(this._text,this.maxWidth).scale(this.scale)}_rotate(t){}_flip(t){}_preDraw(t,e,i){(this.isStale()||this.font.isStale())&&(this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity),this.font.tint=this.tint,super._preDraw(t,e,i)}_drawImage(t,e,i){var s;let n=yt.Black;this.font instanceof As&&(n=null!==(s=this.color)&&void 0!==s?s:this.font.color);const{width:r,height:o}=this.font.measureText(this._text,this.maxWidth);this._textWidth=r,this._textHeight=o,this.font.render(t,this._text,n,e,i,this.maxWidth),this.font.showDebug&&(t.debug.drawRect(e-r,i-o,2*r,2*o),null!=this.maxWidth&&t.debug.drawRect(e,i,this.maxWidth,this.height,{color:yt.Yellow}))}}class Ts extends Hi{get body(){return this.get(Mi)}get transform(){return this.get(di)}get motion(){return this.get(ui)}get graphics(){return this.get(qi)}get collider(){return this.get(Fi)}get pointer(){return this.get(Zi)}get actions(){return this.get(ws)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(di).scale}set scale(t){this.get(di).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=Ut(t,(t=>this._handleAnchorChange(t))),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get isOffScreen(){return this.hasTag("ex.offscreen")}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.events.on("pointerdragstart",this._pointerDragStartHandler),this.events.on("pointerdragend",this._pointerDragEndHandler),this.events.on("pointerdragmove",this._pointerDragMoveHandler),this.events.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.events.off("pointerdragstart",this._pointerDragStartHandler),this.events.off("pointerdragend",this._pointerDragEndHandler),this.events.off("pointerdragmove",this._pointerDragMoveHandler),this.events.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this._color}set color(t){var e;this._color=t.clone();const i=null===(e=this.graphics.layers.default.graphics[0])||void 0===e?void 0:e.graphic;(i instanceof Re||i instanceof Ss)&&(i.color=this._color)}constructor(t){super(),this.events=new d,this._anchor=Ut(vt.Half,(t=>this._handleAnchorChange(t))),this.logger=J.getInstance(),this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this._pointerDragLeaveHandler=t=>{this._dragging&&(this.pos=t.worldPos)};const{name:e,x:i,y:s,pos:n,coordPlane:r,scale:o,width:a,height:h,radius:l,collider:c,vel:u,acc:p,rotation:_,angularVelocity:g,z:m,color:f,visible:v,anchor:x,collisionType:y,collisionGroup:w}={...t};this._setName(e),this.anchor=null!=x?x:Ts.defaults.anchor.clone();const b=new di;this.addComponent(b),this.pos=null!=n?n:xt(null!=i?i:0,null!=s?s:0),this.rotation=null!=_?_:0,this.scale=null!=o?o:xt(1,1),this.z=null!=m?m:0,b.coordPlane=null!=r?r:ii.World,this.addComponent(new Zi),this.addComponent(new qi({anchor:this.anchor})),this.addComponent(new ui),this.vel=null!=u?u:vt.Zero,this.acc=null!=p?p:vt.Zero,this.angularVelocity=null!=g?g:0,this.addComponent(new ws),this.addComponent(new Mi),this.body.collisionType=null!=y?y:Ke.Passive,w&&(this.body.group=w),c?this.addComponent(new Fi(c)):l?this.addComponent(new Fi(Ri.Circle(l))):a>0&&h>0?this.addComponent(new Fi(Ri.Box(a,h,this.anchor))):this.addComponent(new Fi),this.graphics.visible=null==v||v,f&&(this.color=f,a&&h?this.graphics.add(new Xi({color:f,width:a,height:h})):l&&this.graphics.add(new Ki({color:f,radius:l})))}clone(){const t=new Ts({color:this.color.clone(),anchor:this.anchor.clone()});t.clearComponents(),t.processComponentRemoval();const e=this.getComponents();for(const i of e)t.addComponent(i.clone(),!0);return t}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_prekill(t){this.events.emit("prekill",new _(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){this.events.emit("postkill",new g(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.events.emit("kill",new p(this)),super.kill(),this._postkill(this.scene)):this.logger.warn(`Cannot kill actor named "${this.name}", it was never added to the Scene`)}unkill(){this.active=!0}isKilled(){return!this.active}get z(){return this.get(di).z}set z(t){this.get(di).z=t}get center(){const t=this.getGlobalPos();return new vt(t.x+this.width/2-this.anchor.x*this.width,t.y+this.height/2-this.anchor.y*this.height)}get localCenter(){return new vt(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(di).globalRotation}getGlobalPos(){return this.get(di).globalPos}getGlobalScale(){return this.get(di).globalScale}contains(t,e,i=!1){const s=xt(t,e),n=this.get(Fi);n.update();const r=n.get();if(!r)return!1;const o=r.contains(s);return i?o||this.children.some((i=>i.contains(t,e,!0))):o}within(t,e){const i=this.get(Fi),s=t.get(Fi),n=i.get(),r=s.get();return!(!n||!r)&&n.getClosestLineBetween(r).getLength()<=e}update(t,e){this._initialize(t),this._preupdate(t,e),this._postupdate(t,e)}onPreUpdate(t,e){}onPostUpdate(t,e){}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}}function Es(t){return t instanceof Ps}Ts.defaults={anchor:vt.Half};class Ps extends Ts{constructor(t){var e,i;super({...t}),this.get(di).coordPlane=ii.Screen,this.anchor=null!==(e=null==t?void 0:t.anchor)&&void 0!==e?e:xt(0,0),this.body.collisionType=null!==(i=null==t?void 0:t.collisionType)&&void 0!==i?i:Ke.PreventCollision,this.pointer.useGraphicsBounds=!0,this.pointer.useColliderShape=!1,!(null==t?void 0:t.collider)&&(null==t?void 0:t.width)>0&&(null==t?void 0:t.height)>0&&this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new vt(t,e));return super.contains(s.x,s.y)}}class Is{get complete(){return this._complete}constructor(t,e,i,s,n,r){if(this._logger=J.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this.randomRange=[0,0],this._baseInterval=10,this._generateRandomInterval=()=>this._baseInterval+this.random.integer(this.randomRange[0],this.randomRange[1]),this._complete=!1,this.scene=null,"function"!=typeof t){const o=t;t=o.fcn,e=o.interval,i=o.repeats,s=o.numberOfRepeats,n=o.randomRange,r=o.random}if(s&&s>=0&&(this.maxNumberOfRepeats=s,!i))throw new Error("repeats must be set to true if numberOfRepeats is set");if(this.id=Is._MAX_ID++,this._callbacks=[],this._baseInterval=this.interval=e,n){if(n[0]>n[1])throw new Error("min value must be lower than max value for range");this.random=null!=r?r:new at,this.randomRange=n,this.interval=this._generateRandomInterval(),this.on((()=>{this.interval=this._generateRandomInterval()}))}this.repeats=i||this.repeats,t&&this.on(t)}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach((t=>{t.call(this)})),this._numberOfTicks++,this.repeats||(this._complete=!0,this._running=!1),this._elapsedTime=0))}reset(t,e){if(t&&t>=0&&(this._baseInterval=this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}}Is._MAX_ID=0;class Ds extends hi{constructor(t){super(),this.type="ex.parallax",this.parallaxFactor=xt(1,1),this.parallaxFactor=null!=t?t:this.parallaxFactor}}class Bs extends hi{constructor(t,e=!0){super(),this.draw=t,this.useTransform=e,this.type="ex.debuggraphics"}}class Rs{constructor(t,e){this.bounds=t,this.options=e,this._defaultOptions={maxDepth:10,capacity:10,level:0},this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null,this.options={...this._defaultOptions,...e},this.halfWidth=t.width/2,this.halfHeight=t.height/2}_split(){this._isDivided=!0;const t={maxDepth:this.options.maxDepth,capacity:this.options.capacity,level:this.options.level+1};this.topLeft=new Rs(new At({left:this.bounds.left,top:this.bounds.top,right:this.bounds.left+this.halfWidth,bottom:this.bounds.top+this.halfHeight}),t),this.topRight=new Rs(new At({left:this.bounds.left+this.halfWidth,top:this.bounds.top,right:this.bounds.right,bottom:this.bounds.top+this.halfHeight}),t),this.bottomLeft=new Rs(new At({left:this.bounds.left,top:this.bounds.top+this.halfHeight,right:this.bounds.left+this.halfWidth,bottom:this.bounds.bottom}),t),this.bottomRight=new Rs(new At({left:this.bounds.left+this.halfWidth,top:this.bounds.top+this.halfHeight,right:this.bounds.right,bottom:this.bounds.bottom}),t)}_insertIntoSubNodes(t){var e,i,s,n;(null===(e=this.topLeft)||void 0===e?void 0:e.bounds.overlaps(t.bounds))&&this.topLeft.insert(t),(null===(i=this.topRight)||void 0===i?void 0:i.bounds.overlaps(t.bounds))&&this.topRight.insert(t),(null===(s=this.bottomLeft)||void 0===s?void 0:s.bounds.overlaps(t.bounds))&&this.bottomLeft.insert(t),(null===(n=this.bottomRight)||void 0===n?void 0:n.bounds.overlaps(t.bounds))&&this.bottomRight.insert(t)}insert(t){if(this._isDivided)this._insertIntoSubNodes(t);else if(this.items.push(t),this.items.length>this.options.capacity&&this.options.level<this.options.maxDepth){this._isDivided||this._split();for(const t of this.items)this._insertIntoSubNodes(t);this.items.length=0}}remove(t){var e,i,s,n;if(this.bounds.overlaps(t.bounds))if(this._isDivided)(null===(e=this.topLeft)||void 0===e?void 0:e.bounds.overlaps(t.bounds))&&this.topLeft.remove(t),(null===(i=this.topRight)||void 0===i?void 0:i.bounds.overlaps(t.bounds))&&this.topRight.remove(t),(null===(s=this.bottomLeft)||void 0===s?void 0:s.bounds.overlaps(t.bounds))&&this.bottomLeft.remove(t),(null===(n=this.bottomRight)||void 0===n?void 0:n.bounds.overlaps(t.bounds))&&this.bottomRight.remove(t);else{const e=this.items.indexOf(t);e>-1&&this.items.splice(e,1)}}query(t){let e=this.items;return this._isDivided&&(this.topLeft.bounds.overlaps(t)&&(e=e.concat(this.topLeft.query(t))),this.topRight.bounds.overlaps(t)&&(e=e.concat(this.topRight.query(t))),this.bottomLeft.bounds.overlaps(t)&&(e=e.concat(this.bottomLeft.query(t))),this.bottomRight.bounds.overlaps(t)&&(e=e.concat(this.bottomRight.query(t)))),e=e.filter(((t,i)=>e.indexOf(t)>=i)),e}clear(){this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null}getAllItems(){let t=this.items;return this._isDivided&&(t=t.concat(this.topLeft.getAllItems()),t=t.concat(this.topRight.getAllItems()),t=t.concat(this.bottomLeft.getAllItems()),t=t.concat(this.bottomRight.getAllItems())),t=t.filter(((e,i)=>t.indexOf(e)>=i)),t}getTreeDepth(){return this._isDivided?1+Math.max(this.topLeft.getTreeDepth(),this.topRight.getTreeDepth(),this.bottomLeft.getTreeDepth(),this.bottomRight.getTreeDepth()):0}debug(t){this.bounds.draw(t,yt.Yellow),this._isDivided&&(this.topLeft.bounds.draw(t,yt.Yellow),this.topRight.bounds.draw(t,yt.Yellow),this.bottomLeft.bounds.draw(t,yt.Yellow),this.bottomRight.bounds.draw(t,yt.Yellow))}}const Fs={PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw"};class ks extends Hi{flagCollidersDirty(){this._collidersDirty=!0}flagTilesDirty(){for(let t=0;t<this.tiles.length;t++)this.tiles[t]&&this.tiles[t].flagDirty()}get x(){var t;return null!==(t=this._transform.pos.x)&&void 0!==t?t:0}set x(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this.get(di).pos=xt(t,this.y))}get y(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos.y)&&void 0!==e?e:0}set y(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this._transform.pos=xt(this.x,t))}get z(){var t;return null!==(t=this._transform.z)&&void 0!==t?t:0}set z(t){this._transform&&(this._transform.z=t)}get rotation(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.rotation)&&void 0!==e?e:0}set rotation(t){this._transform&&(this._transform.rotation=t)}get scale(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.scale)&&void 0!==e?e:vt.One}set scale(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.scale)&&(this._transform.scale=t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}constructor(t){var e,i;super(null,t.name),this.events=new d,this._token=0,this.logger=J.getInstance(),this.tiles=[],this._rows=[],this._cols=[],this.renderFromTopOfGraphic=!1,this._collidersDirty=!0,this._originalOffsets=new WeakMap,this.addComponent(new di),this.addComponent(new ui),this.addComponent(new Mi({type:Ke.Fixed})),this.addComponent(new qi({onPostDraw:(t,e)=>this.draw(t,e)})),this.addComponent(new Bs((t=>this.debug(t)),!1)),this.addComponent(new Fi),this._graphics=this.get(qi),this._transform=this.get(di),this._motion=this.get(ui),this._collider=this.get(Fi),this._composite=this._collider.useCompositeCollider([]),this._transform.pos=null!==(e=t.pos)&&void 0!==e?e:vt.Zero,this._oldPos=this._transform.pos.clone(),this._oldScale=this._transform.scale.clone(),this.renderFromTopOfGraphic=null!==(i=t.renderFromTopOfGraphic)&&void 0!==i?i:this.renderFromTopOfGraphic,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.rows=t.rows,this.columns=t.columns,this._quadTree=new Rs(At.fromDimension(this.columns*this.tileWidth,this.rows*this.tileHeight,vt.Zero,this.pos)),this.tiles=new Array(this.rows*this.columns),this._rows=new Array(this.rows),this._cols=new Array(this.columns);let s=[];for(let t=0;t<this.columns;t++){for(let e=0;e<this.rows;e++){const i=new Ms({x:t,y:e,map:this});i.map=this,this._quadTree.insert(i),this.tiles[t+e*this.columns]=i,s.push(i),this._rows[e]||(this._rows[e]=[]),this._rows[e].push(i)}this._cols[t]=s,s=[]}this._graphics.localBounds=new At({left:0,top:0,right:this.columns*this.tileWidth*this.scale.x,bottom:this.rows*this.tileHeight*this.scale.y})}_initialize(t){super._initialize(t),this._engine=t}_getOrSetColliderOriginalOffset(t){if(this._originalOffsets.has(t))return this._originalOffsets.get(t);{const e=t.offset;return this._originalOffsets.set(t,e),e}}_updateQuadTree(){this._quadTree=new Rs(At.fromDimension(this.columns*this.tileWidth,this.rows*this.tileHeight,vt.Zero,vt.Zero).scale(this.scale).translate(this.pos).rotate(this.rotation,this.pos));for(let t=0;t<this.tiles.length;t++)this._quadTree.insert(this.tiles[t])}_updateColliders(){this._collider.$colliderRemoved.notifyAll(this._composite),this._composite.clearColliders();const t=[];let e;this._composite=this._collider.useCompositeCollider([]);for(let i=0;i<this.columns;i++){for(let s=0;s<this.rows;s++){0===s&&(e=null);const n=this.tiles[i+s*this.columns];if(n.solid)if(n.getColliders().length>0){for(const t of n.getColliders()){const e=this._getOrSetColliderOriginalOffset(t);t.offset=xt(n.x*this.tileWidth*this.scale.x,n.y*this.tileHeight*this.scale.y).add(e),t.owner=this,this._composite.addCollider(t)}e&&t.push(e),e=null}else e=e?e.combine(n.defaultGeometry):n.defaultGeometry;else e&&t.push(e),e=null}if(e){const i=t[t.length-1];i&&i.top===e.top&&i.bottom===e.bottom?t[t.length-1]=i.combine(e):t.push(e)}}for(const e of t){const t=Ri.Box(e.width,e.height,vt.Zero,xt(e.left-this.pos.x,e.top-this.pos.y));t.owner=this,this._composite.addCollider(t)}this._collider.update(),this._collider.$colliderAdded.notifyAll(this._composite)}getTileByIndex(t){return this.tiles[t]}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=Math.floor((t.x-this.pos.x)/(this.tileWidth*this.scale.x)),i=Math.floor((t.y-this.pos.y)/(this.tileHeight*this.scale.y)),s=this.getTile(e,i);return e>=0&&i>=0&&e<this.columns&&i<this.rows&&s?s:null}getRows(){return this._rows}getColumns(){return this._cols}update(t,e){this.onPreUpdate(t,e),this.emit("preupdate",new b(t,e,this)),this._oldPos.equals(this.pos)&&this._oldRotation===this.rotation&&this._oldScale.equals(this.scale)||(this.flagCollidersDirty(),this.flagTilesDirty()),this._collidersDirty&&(this._collidersDirty=!1,this._updateColliders(),this._updateQuadTree()),this._token++,this.pos.clone(this._oldPos),this._oldRotation=this.rotation,this.scale.clone(this._oldScale),this._transform.pos=this.pos,this.onPostUpdate(t,e),this.emit("postupdate",new C(t,e,this))}draw(t,e){this.emit("predraw",new v(t,e,this));let i=this._engine.screen.getWorldBounds();const s=this._engine.screen.getScreenBounds();let n,r,o;const a=this._transform.coordPlane===ii.Screen,h=this.get(Ds);if(h){let t=this.pos;const e=vt.One.sub(h.parallaxFactor),s=this._engine.currentScene.camera.pos.scale(e);t=t.sub(s),i=i.translate(t)}const l=this._quadTree.query(a?s:i);for(let i=0;i<l.length;i++){const s=l[i];for(n=s.getGraphics(),r=0,o=n.length;r<o;r++){const i=n[r];if(i){Wi(i)&&(null==i||i.tick(e,this._token));const n=this.renderFromTopOfGraphic?0:i.height-this.tileHeight;i.draw(t,s.x*this.tileWidth,s.y*this.tileHeight-n)}}}this.emit("postdraw",new x(t,e,this))}debug(t){const e=this.tileWidth*this.columns*this.scale.x,i=this.tileHeight*this.rows*this.scale.y,s=this.pos;for(let i=0;i<this.rows+1;i++){const n=xt(0,i*this.tileHeight*this.scale.y);t.drawLine(s.add(n),s.add(xt(e,n.y)),yt.Red,2)}for(let e=0;e<this.columns+1;e++){const n=xt(e*this.tileWidth*this.scale.x,0);t.drawLine(s.add(n),s.add(xt(n.x,i)),yt.Red,2)}const n=this._composite.getColliders();t.save(),t.translate(this.pos.x,this.pos.y),t.scale(this.scale.x,this.scale.y);for(const e of n){const i=yt.Gray;i.a=.5;const s=e.localBounds,n=e.worldPos.sub(this.pos);t.drawRectangle(n,s.width,s.height,i)}t.restore(),t.save(),t.z=999,this._quadTree.debug(t);for(let e=0;e<this.tiles.length;e++)this.tiles[e].bounds.draw(t);t.restore()}}class Ms extends Hi{get pos(){return this._posDirty&&(this._recalculate(),this._posDirty=!1),this._pos}get width(){return this._width}get height(){return this._height}get solid(){return this._solid}set solid(t){var e;null===(e=this.map)||void 0===e||e.flagCollidersDirty(),this._solid=t}getGraphics(){return this._graphics}addGraphic(t){this._graphics.push(t)}removeGraphic(t){Pt(t,this._graphics)}clearGraphics(){this._graphics.length=0}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}constructor(t){var e,i;super(),this._posDirty=!1,this._solid=!1,this._graphics=[],this._colliders=[],this.data=new Map,this.x=t.x,this.y=t.y,this.map=t.map,this._width=t.map.tileWidth*this.map.scale.x,this._height=t.map.tileHeight*this.map.scale.y,this.solid=null!==(e=t.solid)&&void 0!==e?e:this.solid,this._graphics=null!==(i=t.graphics)&&void 0!==i?i:[],this._recalculate()}flagDirty(){return this._posDirty=!0}_recalculate(){const t=this.map.pos.add(xt(this.x*this.map.tileWidth,this.y*this.map.tileHeight));this._geometry=new At(t.x,t.y,t.x+this.map.tileWidth,t.y+this.map.tileHeight),this._width=this.map.tileWidth*this.map.scale.x,this._height=this.map.tileHeight*this.map.scale.y,this._pos=this.map.pos.add(xt(this.x*this._width,this.y*this._height)),this._bounds=new At(this._pos.x,this._pos.y,this._pos.x+this._width,this._pos.y+this._height),this.map.rotation&&(this._bounds=this._bounds.rotate(this.map.rotation,this.map.pos)),this._posDirty=!1}get bounds(){return this._posDirty&&this._recalculate(),this._bounds}get defaultGeometry(){return this._geometry}get center(){return this._posDirty&&this._recalculate(),new vt(this._pos.x+this._width/2,this._pos.y+this._height/2)}}class Ls{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new Us(t))}lockToActorAxis(t,e){this.camera.addStrategy(new Os(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new Ns(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new Hs(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Ws(t))}}var zs;!function(t){t[t.X=0]="X",t[t.Y=1]="Y"}(zs||(zs={}));class Us{constructor(t){this.target=t,this.action=(t,e,i,s)=>t.center}}class Os{constructor(t,e){this.target=t,this.axis=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus();return this.axis===zs.X?new vt(n.x,r.y):new vt(r.x,n.y)}}}class Ns{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(t,e,i,s)=>{const n=t.center;let r=e.getFocus(),o=e.vel.clone();const a=n.sub(r).scale(this.cameraElasticity);o=o.add(a);const h=o.scale(-1).scale(this.cameraFriction);return o=o.add(h),r=r.add(o),r}}}class Hs{constructor(t,e){this.target=t,this.radius=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus(),o=n.sub(r),a=o.size;if(a>=this.radius){const t=a-this.radius;return r.add(o.normalize().scale(t))}return r}}}class Ws{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(t,e,i,s)=>{const n=e.getFocus();this.boundSizeChecked||((t.bottom-t.top<i.drawHeight||t.right-t.left<i.drawWidth)&&J.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let r=n.x,o=n.y;return n.x<t.left+i.halfDrawWidth?r=t.left+i.halfDrawWidth:n.x>t.right-i.halfDrawWidth&&(r=t.right-i.halfDrawWidth),n.y<t.top+i.halfDrawHeight?o=t.top+i.halfDrawHeight:n.y>t.bottom-i.halfDrawHeight&&(o=t.bottom-i.halfDrawHeight),xt(r,o)}}}const Gs={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class Vs{constructor(){this.events=new d,this.transform=Ft.identity(),this.inverse=Ft.identity(),this._cameraStrategies=[],this.strategy=new Ls(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this._angularVelocity=0,this._posChanged=!1,this._pos=Ot(vt.Zero,(()=>this._posChanged=!0)),this.vel=vt.Zero,this.acc=vt.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._zoomEasing=Yi.EaseInOutCubic,this._easing=Yi.EaseInOutCubic,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this._angularVelocity}set angularVelocity(t){this._angularVelocity=t}get pos(){return this._pos}set pos(t){this._pos=Ot(t,(()=>this._posChanged=!0)),this._posChanged=!0}get x(){return this.pos.x}set x(t){this._follow||this._cameraMoving||(this.pos=xt(t,this.pos.y))}get y(){return this.pos.y}set y(t){this._follow||this._cameraMoving||(this.pos=xt(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=xt(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=xt(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=xt(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=xt(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=Yi.EaseInOutCubic){if("function"!=typeof i)throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise((t=>{this._lerpResolve=t})),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=Yi.EaseInOutCubic){return this._zoomPromise=new Promise((t=>{this._zoomResolve=t})),e?(this._isZooming=!0,this._zoomEasing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t,this._zoomPromise):(this._isZooming=!1,this.zoom=t,Promise.resolve(!0))}get viewport(){return this._viewport?this._viewport:new At(0,0,0,0)}addStrategy(t){this._cameraStrategies.push(t)}removeStrategy(t){Pt(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t,this._screen=t.screen;const e=this._screen.contentArea;let i=xt(e.width/2,e.height/2);if(!this._engine.loadingComplete){const t=this._screen.peekResolution();t&&(i=xt(t.width/2,t.height/2))}this._halfWidth=i.x,this._halfHeight=i.y,this._posChanged||(this.pos=i),this.updateTransform(),this.runStrategies(t,t.clock.elapsed()),this.updateViewport(),this.updateTransform(),this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0}}onInitialize(t){}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}runStrategies(t,e){for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e)}updateViewport(){this._viewport=new At(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){const t=(0,this._zoomEasing)(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration);this.zoom=t,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){const t=Yi.CreateVectorEasingFunction(this._easing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration);this.pos=t,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const t=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(t)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=1+(Math.random()*this._shakeMagnitudeX|0),this._yShake=1+(Math.random()*this._shakeMagnitudeY|0)),this.runStrategies(t,e),this.updateViewport(),this.updateTransform(),this._postupdate(t,e)}draw(t){t.multiply(this.transform)}updateTransform(){const t=this._screen.resolution.width/this.zoom,e=this._screen.resolution.height/this.zoom,i=xt(-this.x+t/2+this._xShake,-this.y+e/2+this._yShake);this.transform.reset(),this.transform.scale(this.zoom,this.zoom),this.transform.translate(t/2,e/2),this.transform.rotate(this.rotation),this.transform.translate(-t/2,-e/2),this.transform.translate(i.x,i.y),this.transform.inverse(this.inverse)}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}const qs={ExitTrigger:"exit",EnterTrigger:"enter"},Xs={pos:vt.Zero,width:10,height:10,visible:!1,action:()=>{},filter:()=>!0,repeat:-1};class Ks extends Ts{constructor(t){super({x:t.pos.x,y:t.pos.y,width:t.width,height:t.height}),this.events=new d,this.action=()=>{},this.filter=()=>!0,this.repeat=-1,t={...Xs,...t},this.filter=t.filter||this.filter,this.repeat=t.repeat||this.repeat,this.action=t.action||this.action,t.target&&(this.target=t.target),this.graphics.visible=t.visible,this.body.collisionType=Ke.Passive,this.events.on("collisionstart",(t=>{this.filter(t.other)&&(this.events.emit("enter",new q(this,t.other)),this._dispatchAction(),0===this.repeat&&this.kill())})),this.events.on("collisionend",(t=>{this.filter(t.other)&&this.events.emit("exit",new X(this,t.other))}))}set target(t){this._target=t,this.filter=e=>e===t}get target(){return this._target}_initialize(t){super._initialize(t)}_dispatchAction(){0!==this.repeat&&(this.action.call(this),this.repeat--)}}var Zs;!function(t){t.Update="update",t.Draw="draw"}(Zs||(Zs={}));class Ys{constructor(){this.priority=0}notify(t){}}class js{constructor(t){this.data=t,this.type="Entity Added"}}function Qs(t){return!!t&&"Entity Added"===t.type}class $s{constructor(t){this.data=t,this.type="Entity Removed"}}function Js(t){return!!t&&"Entity Removed"===t.type}class tn{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._entitiesToRemove=[]}updateEntities(t,e){for(const i of this.entities)i.update(t.engine,e),i.active||this.removeEntity(i)}findEntitiesForRemoval(){for(const t of this.entities)t.active||this.removeEntity(t)}notify(t){zi(t)&&this._world.queryManager.addEntity(t.data.entity),Oi(t)&&this._world.queryManager.removeComponent(t.data.entity,t.data.component)}addEntity(t){t.active=!0,t.scene=this._world.context,t&&!this._entityIndex[t.id]&&(this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.componentAdded$.register(this),t.componentRemoved$.register(this),t.children.forEach((e=>{e.scene=t.scene,this.addEntity(e)})),t.childrenAdded$.register({notify:t=>{this.addEntity(t)}}),t.childrenRemoved$.register({notify:t=>{this.removeEntity(t,!1)}}))}removeEntity(t,e=!0){var i;let s=0;s=t instanceof Hi?t.id:t;const n=this._entityIndex[s];n&&n.active&&(n.active=!1),n&&e?this._entitiesToRemove.push(n):(delete this._entityIndex[s],n&&(n.scene=null,Pt(n,this.entities),this._world.queryManager.removeEntity(n),n.componentAdded$.unregister(this),n.componentRemoved$.unregister(this),n.children.forEach((t=>{t.scene=null,this.removeEntity(t,e)})),n.childrenAdded$.clear(),n.childrenRemoved$.clear(),(null===(i=this._world.context)||void 0===i?void 0:i.engine)&&this._world.context.engine.stats.currFrame.actors.killed++))}processEntityRemovals(){for(const t of this._entitiesToRemove)t.active||this.removeEntity(t,!1);this._entitiesToRemove.length=0}processComponentRemovals(){for(const t of this.entities)t.processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter((e=>e.name===t))}clear(){for(let t=this.entities.length-1;t>=0;t--)this.removeEntity(this.entities[t])}}const en=t=>[...t].sort(((t,e)=>t.localeCompare(e))).join("+");class sn extends ci{get key(){return this._key?this._key:this._key=en(this.types)}constructor(t){super(),this._entities=[],t[0]instanceof Function?this.types=t.map((t=>(new t).type)):this.types=t}getEntities(t){return t&&this._entities.sort(t),this._entities}addEntity(t){!It(this._entities,t)&&this.matches(t)&&(this._entities.push(t),this.notifyAll(new js(t)))}removeEntity(t){Pt(t,this._entities)&&this.notifyAll(new $s(t))}clear(){this._entities.length=0;for(let t=this.observers.length-1;t>=0;t--)this.unregister(this.observers[t])}matches(t){let e=[];e=t instanceof Hi?t.types:t;let i=!0;for(const t of this.types)if(i=i&&e.indexOf(t)>-1,!i)return!1;return i}contain(t){return this.types.indexOf(t)>-1}}class nn{constructor(t){this._world=t,this._queries={}}_addQuery(t){this._queries[en(t.types)]=t;for(const e of this._world.entityManager.entities)t.addEntity(e)}maybeRemoveQuery(t){0===t.observers.length&&(t.clear(),delete this._queries[en(t.types)])}addEntity(t){for(const e in this._queries)this._queries[e]&&this._queries[e].addEntity(t)}removeComponent(t,e){for(const i in this._queries)this._queries[i].contain(e.type)&&this._queries[i].removeEntity(t)}removeEntity(t){for(const e in this._queries)this._queries[e].removeEntity(t)}createQuery(t){const e=this.getQuery(t);if(e)return e;const i=new sn(t);return this._addQuery(i),i}getQuery(t){const e=en(t);return this._queries[e]?this._queries[e]:null}}class rn{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find((e=>e instanceof t))}addSystem(t){if(!t.types||0===t.types.length)throw new Error("Attempted to add a System without any types");const e=this._world.queryManager.createQuery(t.types);this.systems.push(t),this.systems.sort(((t,e)=>t.priority-e.priority)),e.register(t),this.initialized&&t.initialize&&t.initialize(this._world.context)}removeSystem(t){Pt(t,this.systems);const e=this._world.queryManager.getQuery(t.types);e&&(e.unregister(t),this._world.queryManager.maybeRemoveQuery(e))}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world.context)}}updateSystems(t,e,i){const s=this.systems.filter((e=>e.systemType===t));for(const t of s)t.preupdate&&t.preupdate(e,i);for(const t of s){const s=this._world.queryManager.getQuery(t.types).getEntities(t.sort);if(e instanceof Fn)for(const t of s)t._initialize(null==e?void 0:e.engine);t.update(s,i)}for(const t of s)t.postupdate&&t.postupdate(e,i)}clear(){for(let t=this.systems.length-1;t>=0;t--)this.removeSystem(this.systems[t])}}class on{constructor(t){this.context=t,this.queryManager=new nn(this),this.entityManager=new tn(this),this.systemManager=new rn(this)}update(t,e){t===Zs.Update&&this.entityManager.updateEntities(this.context,e),this.systemManager.updateSystems(t,this.context,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){t instanceof Hi&&this.entityManager.addEntity(t),t instanceof Ys&&this.systemManager.addSystem(t)}remove(t,e=!0){t instanceof Hi&&this.entityManager.removeEntity(t,e),t instanceof Ys&&this.systemManager.removeSystem(t)}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}class an{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n,an._ACC)),t.pos.add(e.vel.scale(n,an._VEL),an._POS).addEqual(i.scale(.5*n*n,an._VEL_ACC)),e.angularVelocity+=e.torque*(1/e.inertia)*n;const r=t.rotation+e.angularVelocity*n;t.scale.add(e.scaleFactor.scale(n,this._SCALE_FACTOR),an._SCALE);t.get().setTransform(an._POS,r,an._SCALE)}}an._POS=new vt(0,0),an._SCALE=new vt(1,1),an._ACC=new vt(0,0),an._VEL=new vt(0,0),an._VEL_ACC=new vt(0,0),an._SCALE_FACTOR=new vt(0,0);class hn extends Ys{constructor(){super(...arguments),this.types=["ex.transform","ex.motion"],this.systemType=Zs.Update,this.priority=-1}update(t,e){let i,s;for(let n=0;n<t.length;n++){i=t[n].get(di),s=t[n].get(ui);const r=t[n].get(Mi);if(null==r?void 0:r.sleeping)continue;const o=s.acc.clone();(null==r?void 0:r.collisionType)===Ke.Active&&(null==r?void 0:r.useGravity)&&o.addEqual(ni.gravity),null==r||r.captureOldTransform(),an.integrate(i,s,o,e)}}}class ln{constructor(){this.directionMap=new Map,this.distanceMap=new Map}solve(t){this.preSolve(t),(t=t.filter((t=>!t.isCanceled()))).sort(((t,e)=>this.distanceMap.get(t.id)-this.distanceMap.get(e.id)));for(const e of t)this.solvePosition(e),this.solveVelocity(e);return this.postSolve(t),t}preSolve(t){const e=1e-4;for(const i of t){if(Math.abs(i.mtv.x)<e&&Math.abs(i.mtv.y)<e){i.cancel();continue}const t=bt.fromDirection(i.mtv),s=i.mtv.negate(),n=i.colliderA.worldPos.squareDistance(i.colliderB.worldPos);this.distanceMap.set(i.id,n),i.colliderA.events.emit("precollision",new R(i.colliderA,i.colliderB,t,s)),i.colliderB.events.emit("precollision",new R(i.colliderB,i.colliderA,bt.getOpposite(t),s.negate()))}}postSolve(t){var e,i;for(const s of t){if(s.isCanceled())continue;const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Mi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Mi);if(r&&o&&(r.collisionType===Ke.Passive||o.collisionType===Ke.Passive))continue;const a=bt.fromDirection(s.mtv),h=s.mtv.negate();s.colliderA.events.emit("postcollision",new F(s.colliderA,s.colliderB,a,h)),s.colliderB.events.emit("postcollision",new F(s.colliderB,s.colliderA,bt.getOpposite(a),h.negate()))}}solvePosition(t){var e,i;const s=1e-4;if(!t.colliderA.bounds.overlaps(t.colliderB.bounds,s))return void t.cancel();if(Math.abs(t.mtv.x)<s&&Math.abs(t.mtv.y)<s)return void t.cancel();let n=t.mtv;const r=t.colliderA,o=t.colliderB,a=null===(e=r.owner)||void 0===e?void 0:e.get(Mi),h=null===(i=o.owner)||void 0===i?void 0:i.get(Mi);if(a&&h){if(a.collisionType===Ke.Passive||h.collisionType===Ke.Passive)return;a.collisionType===Ke.Active&&h.collisionType===Ke.Active&&(n=n.scale(.5)),a.collisionType===Ke.Active&&(a.globalPos.x-=n.x,a.globalPos.y-=n.y,r.update(a.transform.get())),h.collisionType===Ke.Active&&(h.globalPos.x+=n.x,h.globalPos.y+=n.y,o.update(h.transform.get()))}}solveVelocity(t){var e,i;if(t.isCanceled())return;const s=t.colliderA,n=t.colliderB,r=null===(e=s.owner)||void 0===e?void 0:e.get(Mi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Mi);if(r&&o){if(r.collisionType===Ke.Passive||o.collisionType===Ke.Passive)return;const e=t.normal,i=e.negate();if(r.collisionType===Ke.Active&&r.vel.normalize().dot(i)<0){const t=e.scale(e.dot(r.vel.negate()));r.vel=r.vel.add(t)}if(o.collisionType===Ke.Active&&o.vel.normalize().dot(e)<0){const t=i.scale(i.dot(o.vel.negate()));o.vel=o.vel.add(t)}}}}class cn{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new vt(0,0),this.bToContact=new vt(0,0),this.originalVelocityAndRestitution=0,this.update()}update(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Mi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Mi);if(i&&s){const t=this.contact.normal,e=this.contact.tangent;this.aToContact=this.point.sub(i.globalPos),this.bToContact=this.point.sub(s.globalPos);const n=this.aToContact.cross(t),r=this.bToContact.cross(t);this.normalMass=i.inverseMass+s.inverseMass+i.inverseInertia*n*n+s.inverseInertia*r*r;const o=this.aToContact.cross(e),a=this.bToContact.cross(e);this.tangentMass=i.inverseMass+s.inverseMass+i.inverseInertia*o*o+s.inverseInertia*a*a}return this}getRelativeVelocity(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Mi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Mi);if(i&&s){const t=i.vel.add(vt.cross(i.angularVelocity,this.aToContact));return s.vel.add(vt.cross(s.angularVelocity,this.bToContact)).sub(t)}return vt.Zero}}class dn{constructor(){this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return null!==(e=this.idToContactConstraint.get(t))&&void 0!==e?e:[]}solve(t){return this.preSolve(t),t=t.filter((t=>!t.isCanceled())),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}preSolve(t){var e,i,s;const n=1e-4;for(const e of t){if(Math.abs(e.mtv.x)<n&&Math.abs(e.mtv.y)<n){e.cancel();continue}const t=bt.fromDirection(e.mtv);e.colliderA.events.emit("precollision",new R(e.colliderA,e.colliderB,t,e.mtv)),e.colliderA.events.emit("beforecollisionresolve",new L(e.colliderA,e.colliderB,t,e.mtv,e)),e.colliderB.events.emit("precollision",new R(e.colliderB,e.colliderA,bt.getOpposite(t),e.mtv.negate())),e.colliderB.events.emit("beforecollisionresolve",new L(e.colliderB,e.colliderA,bt.getOpposite(t),e.mtv.negate(),e)),e.matchAwake()}const r=Array.from(this.idToContactConstraint.keys());for(const n of t){const t=r.indexOf(n.id);t>-1&&r.splice(t,1);const o=null!==(e=this.idToContactConstraint.get(n.id))&&void 0!==e?e:[];let a=0;const h=n.colliderA.owner.get(Mi),l=n.colliderB.owner.get(Mi);if(h&&l)for(const t of n.points){const e=n.normal,r=n.tangent,c=t.sub(h.globalPos),d=t.sub(l.globalPos),u=c.cross(e),p=d.cross(e),_=h.inverseMass+l.inverseMass+h.inverseInertia*u*u+l.inverseInertia*p*p,g=c.cross(r),m=d.cross(r),f=h.inverseMass+l.inverseMass+h.inverseInertia*g*g+l.inverseInertia*m*m;o[a]&&(null===(s=null===(i=o[a])||void 0===i?void 0:i.point)||void 0===s?void 0:s.squareDistance(t))<4?(o[a].point=t,o[a].local=n.localPoints[a]):o[a]=new cn(t,n.localPoints[a],n),o[a].aToContact=c,o[a].bToContact=d,o[a].normalMass=1/_,o[a].tangentMass=1/f;const v=h.bounciness>l.bounciness?h.bounciness:l.bounciness,x=n.normal.dot(o[a].getRelativeVelocity());o[a].originalVelocityAndRestitution=0,x<-.1&&(o[a].originalVelocityAndRestitution=-v*x),a++}this.idToContactConstraint.set(n.id,o)}for(const t of r)this.idToContactConstraint.delete(t);if(ni.warmStart)this.warmStart(t);else for(const e of t){const t=this.getContactConstraints(e.id);for(const e of t)e.normalImpulse=0,e.tangentImpulse=0}}postSolve(t){for(const e of t){const t=e.colliderA.owner.get(Mi),i=e.colliderB.owner.get(Mi);if(t&&i){if(t.collisionType===Ke.Passive||i.collisionType===Ke.Passive)continue;t.updateMotion(),i.updateMotion()}const s=bt.fromDirection(e.mtv);e.colliderA.events.emit("postcollision",new F(e.colliderA,e.colliderB,s,e.mtv)),e.colliderA.events.emit("aftercollisionresolve",new z(e.colliderA,e.colliderB,s,e.mtv,e)),e.colliderB.events.emit("postcollision",new F(e.colliderB,e.colliderA,bt.getOpposite(s),e.mtv.negate())),e.colliderB.events.emit("aftercollisionresolve",new z(e.colliderB,e.colliderA,bt.getOpposite(s),e.mtv.negate(),e))}this.lastFrameContacts.clear();for(const e of t)this.lastFrameContacts.set(e.id,e)}warmStart(t){var e,i,s;for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Mi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Mi);if(t&&r){const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e)if(ni.warmStart){const e=n.normal.scale(i.normalImpulse),s=n.tangent.scale(i.tangentImpulse),o=e.add(s);t.applyImpulse(i.point,o.negate()),r.applyImpulse(i.point,o)}else i.normalImpulse=0,i.tangentImpulse=0}}}solvePosition(t){var e,i,s;for(let n=0;n<ni.positionIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Mi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Mi);if(t&&r){if(t.collisionType===Ke.Passive||r.collisionType===Ke.Passive)continue;const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e){const e=n.normal,s=Ii.FindContactSeparation(n,i.local),o=-5,a=dt(ni.steeringFactor*(s+ni.slop),o,0),h=e.scale(-a*i.normalMass);if(t.collisionType===Ke.Active){const e=h.negate().scale(t.inverseMass);t.limitDegreeOfFreedom.includes(ki.X)&&(e.x=0),t.limitDegreeOfFreedom.includes(ki.Y)&&(e.y=0),t.globalPos=t.globalPos.add(e),t.limitDegreeOfFreedom.includes(ki.Rotation)||(t.rotation-=i.aToContact.cross(h)*t.inverseInertia)}if(r.collisionType===Ke.Active){const t=h.scale(r.inverseMass);r.limitDegreeOfFreedom.includes(ki.X)&&(t.x=0),r.limitDegreeOfFreedom.includes(ki.Y)&&(t.y=0),r.globalPos=r.globalPos.add(t),r.limitDegreeOfFreedom.includes(ki.Rotation)||(r.rotation+=i.bToContact.cross(h)*r.inverseInertia)}}}}}solveVelocity(t){var e,i,s;for(let n=0;n<ni.velocityIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Mi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Mi);if(t&&r){if(t.collisionType===Ke.Passive||r.collisionType===Ke.Passive)continue;const e=Math.min(t.friction,r.friction),i=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const s of i){let i=-s.getRelativeVelocity().dot(n.tangent)*s.tangentMass;const o=e*s.normalImpulse,a=dt(s.tangentImpulse+i,-o,o);i=a-s.tangentImpulse,s.tangentImpulse=a;const h=n.tangent.scale(i);t.applyImpulse(s.point,h.negate()),r.applyImpulse(s.point,h)}for(const e of i){const i=e.getRelativeVelocity().dot(n.normal);let s=-e.normalMass*(i-e.originalVelocityAndRestitution);const o=Math.max(e.normalImpulse+s,0);s=o-e.normalImpulse,e.normalImpulse=o;const a=n.normal.scale(s);t.applyImpulse(e.point,a.negate()),r.applyImpulse(e.point,a)}}}}}class un extends Ys{constructor(t){super(),this.types=["ex.transform","ex.motion","ex.collider"],this.systemType=Zs.Update,this.priority=-1,this._realisticSolver=new dn,this._arcadeSolver=new ln,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._processor=t.collisionProcessor,this._trackCollider=t=>this._processor.track(t),this._untrackCollider=t=>this._processor.untrack(t)}notify(t){if(Qs(t)){const e=t.data.get(Fi);e.$colliderAdded.subscribe(this._trackCollider),e.$colliderRemoved.subscribe(this._untrackCollider);const i=e.get();i&&this._processor.track(i)}else{const e=t.data.get(Fi),i=e.get();e&&i&&this._processor.untrack(i)}}initialize(t){this._engine=t.engine}update(t,e){var i,s,n,r;if(!ni.enabled)return;let o=[];for(const e of t){const t=e.get(Fi),s=null==t?void 0:t.get();if(t&&(null===(i=t.owner)||void 0===i?void 0:i.active)&&s)if(t.update(),s instanceof bi){const t=s.getColliders();o=o.concat(t)}else o.push(s)}this._processor.update(o);const a=this._processor.broadphase(o,e);this._currentFrameContacts.clear();let h=this._processor.narrowphase(a,null===(r=null===(n=null===(s=this._engine)||void 0===s?void 0:s.debug)||void 0===n?void 0:n.stats)||void 0===r?void 0:r.currFrame);h=this.getSolver().solve(h);for(const t of h){const e=t.id.indexOf("|");if(e>0){const i=t.id.substring(e+1);this._currentFrameContacts.set(i,t)}else this._currentFrameContacts.set(t.id,t)}this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts)}getSolver(){return ni.collisionResolutionStrategy===Je.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionstart",new U(t,i,e)),t.events.emit("contactstart",new k(t,i,e)),i.events.emit("collisionstart",new U(i,t,e)),i.events.emit("contactstart",new k(i,t,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionend",new O(t,i)),t.events.emit("contactend",new M(t,i)),i.events.emit("collisionend",new O(i,t)),i.events.emit("contactend",new M(i,t))}}}var pn,_n;!function(t){t.Forward="forward",t.Backward="backward"}(pn||(pn={})),function(t){t.End="end",t.Loop="loop",t.PingPong="pingpong",t.Freeze="freeze"}(_n||(_n={}));const gn={Frame:"frame",Loop:"loop",End:"end"};class mn extends Nt{constructor(t){var e,i;super(t),this.events=new d,this.frames=[],this.strategy=_n.Loop,this.frameDuration=100,this.timeScale=1,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._pingPongDirection=1,this._done=!1,this._playing=!0,this._reversed=!1,this.frames=t.frames,this.strategy=null!==(e=t.strategy)&&void 0!==e?e:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:null!==(i=t.frameDuration)&&void 0!==i?i:this.frameDuration,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){return new mn({frames:this.frames.map((t=>({...t}))),frameDuration:this.frameDuration,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}get width(){const t=this.currentFrame;return t?Math.abs(t.graphic.width*this.scale.x):0}get height(){const t=this.currentFrame;return t?Math.abs(t.graphic.height*this.scale.y):0}static fromSpriteSheet(t,e,i,s=_n.Loop){const n=t.sprites.length-1,r=e.filter((t=>t<0||t>n));return r.length&&mn._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${r.join(",")} no frame will be shown`),new mn({frames:t.sprites.filter(((t,i)=>e.indexOf(i)>-1)).map((t=>({graphic:t,duration:i}))),strategy:s})}static fromSpriteSheetCoordinates(t){const{spriteSheet:e,frameCoordinates:i,durationPerFrameMs:s,strategy:n,reverse:r}=t,o=null!=s?s:100,a=[];for(const t of i){const{x:i,y:s,duration:n}=t,r=e.getSprite(i,s);r?a.push({graphic:r,duration:null!=n?n:o}):mn._LOGGER.warn(`Skipping frame! SpriteSheet does not have coordinate (${i}, ${s}), please check your SpriteSheet to confirm that sprite exists`)}return new mn({frames:a,strategy:n,reverse:r})}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get isPlaying(){return this._playing}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!(!this._reversed||1!==this._pingPongDirection)?pn.Backward:pn.Forward}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._done=!1,this._firstTick=!0,this._currentFrame=0}get canFinish(){switch(this.strategy){case _n.End:case _n.Freeze:return!0;default:return!1}}get done(){return this._done}goToFrame(t){this._currentFrame=t,this._timeLeftInFrame=this.frameDuration;const e=this.frames[this._currentFrame];e&&!this._done&&(this._timeLeftInFrame=(null==e?void 0:e.duration)||this.frameDuration,this.events.emit("frame",{...e,frameIndex:this.currentFrameIndex}))}_nextFrame(){const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case _n.Loop:e=(t+1)%this.frames.length,0===e&&this.events.emit("loop",this);break;case _n.End:e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break;case _n.Freeze:e=dt(t+1,0,this.frames.length-1),e>=this.frames.length-1&&(this._done=!0,this.events.emit("end",this));break;case _n.PingPong:t+this._pingPongDirection>=this.frames.length&&(this._pingPongDirection=-1,this.events.emit("loop",this)),t+this._pingPongDirection<0&&(this._pingPongDirection=1,this.events.emit("loop",this)),e=t+this._pingPongDirection%this.frames.length}return e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",{...this.currentFrame,frameIndex:this.currentFrameIndex})),this._timeLeftInFrame-=t*this.timeScale,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame())))}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic.draw(t,e,i)}}mn._LOGGER=J.getInstance();class fn extends Nt{constructor(t){super(t),this.members=[],this.members=t.members,this._updateDimensions()}clone(){return new fn({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){let t=new At;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return this.width=t.width,this.height=t.height,t}get localBounds(){let t=new At;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return t}_isAnimationOrGroup(t){return t instanceof mn||t instanceof fn}tick(t,e){for(const i of this.members){const s=i.graphic;this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){const e=t.graphic;this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){for(const s of this.members)t.save(),t.translate(e,i),s.graphic.draw(t,s.pos.x,s.pos.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}function vn(t){return class extends t{assign(t){for(const e in t)"function"!=typeof this[e]&&(this[e]=t[e])}constructor(...t){super(...t);1!==t.filter((function(t){return void 0!==t})).length||!t[0]||"object"!=typeof t[0]||t[0]instanceof Array||this.assign(t[0])}}}var xn,yn;!function(t){t[t.Circle=0]="Circle",t[t.Rectangle=1]="Rectangle"}(xn||(xn={}));class wn extends Hi{constructor(t,e,i,s,n,r,o,a,h,l){super(),this.position=new vt(0,0),this.velocity=new vt(0,0),this.acceleration=new vt(0,0),this.particleRotationalVelocity=0,this.currentRotation=0,this.focus=null,this.focusAccel=0,this.opacity=1,this.beginColor=yt.White,this.endColor=yt.White,this.life=300,this.fadeFlag=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=yt.White,this.emitter=null,this.particleSize=5,this.particleSprite=null,this.sizeRate=0,this.elapsedMultiplier=0,this.visible=!0,this.isOffscreen=!1;let c=t;if(c&&!(t instanceof Cn)){const d=t;c=d.emitter,e=d.life,i=d.opacity,n=d.endColor,s=d.beginColor,r=d.position,o=d.velocity,a=d.acceleration,h=d.startSize,l=d.endSize}if(this.emitter=c,this.life=e||this.life,this.opacity=i||this.opacity,this.endColor=n||this.endColor.clone(),this.beginColor=s||this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.emitter.particleTransform===yn.Global){const t=this.emitter.transform.globalPos;this.position=(r||this.position).add(t),this.velocity=(o||this.velocity).rotate(this.emitter.transform.globalRotation)}else this.velocity=o||this.velocity,this.position=r||this.position;this.acceleration=a||this.acceleration,this._rRate=(this.endColor.r-this.beginColor.r)/this.life,this._gRate=(this.endColor.g-this.beginColor.g)/this.life,this._bRate=(this.endColor.b-this.beginColor.b)/this.life,this._aRate=this.opacity/this.life,this.startSize=h||0,this.endSize=l||0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.particleSize=this.startSize),this.addComponent(this.transform=new di),this.addComponent(this.graphics=new qi),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=xt(1,1),this.particleSprite?(this.graphics.opacity=this.opacity,this.graphics.use(this.particleSprite)):(this.graphics.localBounds=At.fromDimension(this.particleSize,this.particleSize,vt.Half),this.graphics.onPostDraw=t=>{t.save(),this.graphics.opacity=this.opacity;const e=this._currentColor.clone();e.a=1,t.debug.drawPoint(xt(0,0),{color:e,size:this.particleSize}),t.restore()})}kill(){this.emitter.removeParticle(this)}update(t,e){if(this.life=this.life-e,this.elapsedMultiplier=this.elapsedMultiplier+e,this.life<0&&this.kill(),this.fadeFlag&&(this.opacity=dt(this._aRate*this.life,1e-4,1)),this.startSize>0&&this.endSize>0&&(this.particleSize=dt(this.sizeRate*e+this.particleSize,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=dt(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=dt(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=dt(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=dt(this.opacity,1e-4,1),this.focus){const t=this.focus.sub(this.position).normalize().scale(this.focusAccel).scale(e/1e3);this.velocity=this.velocity.add(t)}else this.velocity=this.velocity.add(this.acceleration.scale(e/1e3));this.position=this.position.add(this.velocity.scale(e/1e3)),this.particleRotationalVelocity&&(this.currentRotation=(this.currentRotation+this.particleRotationalVelocity*e/1e3)%(2*Math.PI)),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=xt(1,1),this.graphics.opacity=this.opacity}}class bn extends(vn(wn)){constructor(t,e,i,s,n,r,o,a,h,l){super(t,e,i,s,n,r,o,a,h,l)}}!function(t){t.Global="global",t.Local="local"}(yn||(yn={}));class Cn extends Ts{get opacity(){return super.graphics.opacity}set opacity(t){super.graphics.opacity=t}get particleSprite(){return this._sprite}set particleSprite(t){t&&(this._sprite=t)}constructor(t){var e,i;super({width:null!==(e=t.width)&&void 0!==e?e:0,height:null!==(i=t.height)&&void 0!==i?i:0}),this._particlesToEmit=0,this.numParticles=0,this.isEmitting=!0,this.particles=[],this.deadParticles=[],this.minVel=0,this.maxVel=0,this.acceleration=new vt(0,0),this.minAngle=0,this.maxAngle=0,this.emitRate=1,this.particleLife=2e3,this.fadeFlag=!1,this.focus=null,this.focusAccel=null,this.startSize=null,this.endSize=null,this.minSize=5,this.maxSize=5,this.beginColor=yt.White,this.endColor=yt.White,this._sprite=null,this.emitterType=xn.Rectangle,this.radius=0,this.particleRotationalVelocity=0,this.randomRotation=!1,this.particleTransform=yn.Global;const{x:s,y:n,pos:r,isEmitting:o,minVel:a,maxVel:h,acceleration:l,minAngle:c,maxAngle:d,emitRate:u,particleLife:p,opacity:_,fadeFlag:g,focus:m,focusAccel:f,startSize:v,endSize:x,minSize:y,maxSize:w,beginColor:b,endColor:C,particleSprite:A,emitterType:S,radius:T,particleRotationalVelocity:E,particleTransform:P,randomRotation:I,random:D}={...t};this.pos=null!=r?r:xt(null!=s?s:0,null!=n?n:0),this.isEmitting=null!=o?o:this.isEmitting,this.minVel=null!=a?a:this.minVel,this.maxVel=null!=h?h:this.maxVel,this.acceleration=null!=l?l:this.acceleration,this.minAngle=null!=c?c:this.minAngle,this.maxAngle=null!=d?d:this.maxAngle,this.emitRate=null!=u?u:this.emitRate,this.particleLife=null!=p?p:this.particleLife,this.opacity=null!=_?_:this.opacity,this.fadeFlag=null!=g?g:this.fadeFlag,this.focus=null!=m?m:this.focus,this.focusAccel=null!=f?f:this.focusAccel,this.startSize=null!=v?v:this.startSize,this.endSize=null!=x?x:this.endSize,this.minSize=null!=y?y:this.minSize,this.maxSize=null!=w?w:this.maxSize,this.beginColor=null!=b?b:this.beginColor,this.endColor=null!=C?C:this.endColor,this.particleSprite=null!=A?A:this.particleSprite,this.emitterType=null!=S?S:this.emitterType,this.radius=null!=T?T:this.radius,this.particleRotationalVelocity=null!=E?E:this.particleRotationalVelocity,this.randomRotation=null!=I?I:this.randomRotation,this.particleTransform=null!=P?P:this.particleTransform,this.body.collisionType=Ke.PreventCollision,this.random=null!=D?D:new at}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;for(let i=0;i<t;i++){const t=this._createParticle();this.particles.push(t),(null===(e=null==this?void 0:this.scene)||void 0===e?void 0:e.world)&&(this.particleTransform===yn.Global?this.scene.world.add(t):this.addChild(t))}}clearParticles(){this.particles.length=0}_createParticle(){let t=0,e=0;const i=mt(this.minAngle,this.maxAngle,this.random),s=mt(this.minVel,this.maxVel,this.random),n=this.startSize||mt(this.minSize,this.maxSize,this.random),r=s*Math.cos(i),o=s*Math.sin(i);if(this.emitterType===xn.Rectangle)t=mt(0,this.width,this.random),e=mt(0,this.height,this.random);else if(this.emitterType===xn.Circle){const s=mt(0,this.radius,this.random);t=s*Math.cos(i),e=s*Math.sin(i)}const a=new bn(this,this.particleLife,this.opacity,this.beginColor,this.endColor,new vt(t,e),new vt(r,o),this.acceleration,this.startSize,this.endSize);return a.fadeFlag=this.fadeFlag,a.particleSize=n,this.particleSprite&&(a.particleSprite=this.particleSprite,a.graphics.opacity=this.opacity,a.graphics.use(this._sprite)),a.particleRotationalVelocity=this.particleRotationalVelocity,this.randomRotation&&(a.currentRotation=mt(0,2*Math.PI,this.random)),this.focus&&(a.focus=this.focus.add(new vt(this.pos.x,this.pos.y)),a.focusAccel=this.focusAccel),a}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let t=0;t<this.deadParticles.length;t++)Pt(this.deadParticles[t],this.particles),(null===(i=null==this?void 0:this.scene)||void 0===i?void 0:i.world)&&this.scene.world.remove(this.deadParticles[t],!1);this.deadParticles.length=0}}class An extends Ys{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=Zs.Draw,this.priority=0,this._token=0,this._sortedTransforms=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0}}get sortedTransforms(){return this._sortedTransforms}initialize(t){this._camera=t.camera,this._engine=t.engine}preupdate(){this._graphicsContext=this._engine.graphicsContext,this._zHasChanged&&(this._sortedTransforms.sort(((t,e)=>t.z-e.z)),this._zHasChanged=!1)}notify(t){if(Qs(t)){const e=t.data.get(di);this._sortedTransforms.push(e),e.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}else{const e=t.data.get(di);e.zIndexChanged$.unsubscribe(this._zIndexUpdate);const i=this._sortedTransforms.indexOf(e);i>-1&&this._sortedTransforms.splice(i,1)}}update(t,e){let i;this._token++,Cs.checkAndClearCache(),this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext);for(const t of this._sortedTransforms){const s=t.owner;if(s.hasTag("ex.offscreen"))continue;if(i=s.get(qi),!i.visible)continue;t.coordPlane===ii.Screen&&this._graphicsContext.restore(),this._graphicsContext.save(),t.coordPlane===ii.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),i.update(e,this._token);const n=s.get(Ds);if(n){const t=vt.One.sub(n.parallaxFactor),e=this._camera.pos.scale(t);this._graphicsContext.translate(e.x,e.y)}this._applyTransform(s),i.material&&(this._graphicsContext.material=i.material),i.onPreDraw&&i.onPreDraw(this._graphicsContext,e);const r=s instanceof bn?s.opacity:1;this._graphicsContext.opacity*=i.opacity*r,this._drawGraphicsComponent(i),i.onPostDraw&&i.onPostDraw(this._graphicsContext,e),this._graphicsContext.restore(),t.coordPlane===ii.Screen&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}this._graphicsContext.restore()}_drawGraphicsComponent(t){var e,i;if(t.visible){const s=t.flipHorizontal,n=t.flipVertical;for(const r of t.layers.get())for(const{graphic:o,options:a}of r.graphics){let h=t.anchor,l=t.offset;(null==a?void 0:a.anchor)&&(h=a.anchor),(null==a?void 0:a.offset)&&(l=a.offset);const c=-o.width*h.x+l.x,d=-o.height*h.y+l.y,u=o.flipHorizontal,p=o.flipVertical;if((s||n)&&(o.flipHorizontal=s?!u:u,o.flipVertical=n?!p:p),null==o||o.draw(this._graphicsContext,c+r.offset.x,d+r.offset.y),(s||n)&&(o.flipHorizontal=u,o.flipVertical=p),(null===(e=this._engine)||void 0===e?void 0:e.isDebug)&&this._engine.debug.graphics.showBounds){const t=xt(c+r.offset.x,d+r.offset.y);if(o instanceof fn)for(const e of o.members)null===(i=e.graphic)||void 0===i||i.localBounds.translate(t.add(e.pos)).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor);else null==o||o.localBounds.translate(t).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}}}}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(di),i=null==t?void 0:t.get(Mi);let s=e.pos,n=e.scale,r=e.rotation;if(i&&this._engine.fixedUpdateFps&&i.__oldTransformCaptured&&i.enableFixedUpdateInterpolate){const t=this._engine.currentFrameLagMs/(1e3/this._engine.fixedUpdateFps);s=e.pos.scale(t).add(i.oldPos.scale(1-t)),n=e.scale.scale(t).add(i.oldScale.scale(1-t));const o=(1-t)*Math.cos(i.oldRotation)+t*Math.cos(e.rotation),a=(1-t)*Math.sin(i.oldRotation)+t*Math.sin(e.rotation);r=Math.atan2(a,o)}e&&(this._graphicsContext.z=e.z,this._graphicsContext.translate(s.x,s.y),this._graphicsContext.scale(n.x,n.y),this._graphicsContext.rotate(r))}}}class Sn extends Ys{constructor(){super(...arguments),this.types=["ex.transform"],this.systemType=Zs.Draw,this.priority=999}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine,this._collisionSystem=t.world.systemManager.get(un)}update(t,e){var i;if(!this._engine.isDebug)return;const s=this._engine.debug.filter;let n,r;const o=this._engine.debug.entity;let a;const h=this._engine.debug.transform;let l;const c=this._engine.debug.motion;let d;const u=this._engine.debug.collider,p=this._engine.debug.physics;let _;const g=this._engine.debug.graphics;let m,f;const v=this._engine.debug.body,x=this._engine.debug.camera;for(const e of t){if(e.hasTag("offscreen"))continue;if(e instanceof bn)continue;if(s.useFilter){if(!(0===s.ids.length||s.ids.includes(e.id)))continue;if(!(""===s.nameQuery||e.name.includes(s.nameQuery)))continue}let t=vt.Zero;const p=xt(0,16);if(n=e.id,r=e.name,a=e.get(di),this._pushCameraTransform(a),this._graphicsContext.save(),this._applyTransform(e),a&&((h.showAll||h.showPosition)&&this._graphicsContext.debug.drawPoint(vt.Zero,{size:4,color:h.positionColor}),(h.showAll||h.showPositionLabel)&&(this._graphicsContext.debug.drawText(`pos${a.pos.toString(2)}`,t),t=t.add(p)),(h.showAll||h.showZIndex)&&(this._graphicsContext.debug.drawText(`z(${a.z.toFixed(1)})`,t),t=t.add(p)),(o.showAll||o.showId)&&(this._graphicsContext.debug.drawText(`id(${n}) ${e.parent?"child of id("+(null===(i=e.parent)||void 0===i?void 0:i.id)+")":""}`,t),t=t.add(p)),(o.showAll||o.showName)&&(this._graphicsContext.debug.drawText(`name(${r})`,t),t=t.add(p)),(h.showAll||h.showRotation)&&(this._graphicsContext.drawLine(vt.Zero,vt.fromAngle(a.rotation).scale(50).add(vt.Zero),h.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${pt(a.rotation).toFixed(2)})`,t),t=t.add(p)),(h.showAll||h.showScale)&&this._graphicsContext.drawLine(vt.Zero,a.scale.add(vt.Zero),h.scaleColor,2)),_=e.get(qi),_&&(g.showAll||g.showBounds)){_.localBounds.draw(this._graphicsContext,g.boundsColor)}if(m=e.get(Bs),m&&(m.useTransform||this._graphicsContext.restore(),m.draw(this._graphicsContext),m.useTransform||(this._graphicsContext.save(),this._applyTransform(e))),f=e.get(Mi),f&&((v.showAll||v.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${f.group.name})`,t),t=t.add(p)),(v.showAll||v.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${f.collisionType})`,t),t=t.add(p)),(v.showAll||v.showMass)&&(this._graphicsContext.debug.drawText(`mass(${f.mass})`,t),t=t.add(p)),(v.showAll||v.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${f.sleepMotion})`,t),t=t.add(p)),(v.showAll||v.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${f.canSleep?f.sleeping:"cant sleep"})`,t),t=t.add(p))),this._graphicsContext.restore(),l=e.get(ui),l&&((c.showAll||c.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${l.vel.toString(2)}`,t.add(a.globalPos)),this._graphicsContext.drawLine(a.globalPos,a.globalPos.add(l.vel),c.velocityColor,2),t=t.add(p)),(c.showAll||c.showAcceleration)&&this._graphicsContext.drawLine(a.globalPos,a.globalPos.add(l.acc),c.accelerationColor,2)),d=e.get(Fi),d){const t=d.get();if((u.showAll||u.showGeometry)&&t&&t.debug(this._graphicsContext,u.geometryColor),u.showAll||u.showBounds)if(t instanceof bi){const e=t.getColliders();for(const t of e){const e=t.bounds,i=xt(e.left,e.top);this._graphicsContext.debug.drawRect(i.x,i.y,e.width,e.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${t.owner.id})`,i)}d.bounds.draw(this._graphicsContext,u.boundsColor)}else if(t){const t=d.bounds,e=xt(t.left,t.top);this._graphicsContext.debug.drawRect(e.x,e.y,t.width,t.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${d.owner.id})`,e)}}this._popCameraTransform(a)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(p.showAll||p.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),p.showAll||p.showCollisionContacts||p.showCollisionNormals)for(const[t,e]of this._engine.debug.stats.currFrame.physics.contacts){if(p.showAll||p.showCollisionContacts)for(const t of e.points)this._graphicsContext.debug.drawPoint(t,{size:5,color:p.collisionContactColor});if(p.showAll||p.showCollisionNormals)for(const t of e.points)this._graphicsContext.debug.drawLine(t,e.normal.scale(30).add(t),{color:p.collisionNormalColor})}this._graphicsContext.restore(),x&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(x.showAll||x.showFocus)&&this._graphicsContext.drawCircle(this._camera.pos,4,x.focusColor),(x.showAll||x.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore()),this._graphicsContext.flush()}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(di);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===ii.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===ii.World&&this._graphicsContext.restore()}}class Tn extends Ys{constructor(){super(...arguments),this.types=["ex.transform","ex.pointer"],this.systemType=Zs.Update,this.priority=-1,this.overrideUseColliderShape=!1,this.overrideUseGraphicsBounds=!1,this.lastFrameEntityToPointers=new Map,this.currentFrameEntityToPointers=new Map,this._sortedTransforms=[],this._sortedEntities=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0}}initialize(t){this._engine=t.engine}preupdate(){this._receiver=this._engine.input.pointers,this._zHasChanged&&(this._sortedTransforms.sort(((t,e)=>e.z-t.z)),this._sortedEntities=this._sortedTransforms.map((t=>t.owner)),this._zHasChanged=!1)}notify(t){if(Qs(t)){const e=t.data.get(di);this._sortedTransforms.push(e),this._sortedEntities.push(e.owner),e.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}else{const e=t.data.get(di);e.zIndexChanged$.unsubscribe(this._zIndexUpdate);const i=this._sortedTransforms.indexOf(e);i>-1&&(this._sortedTransforms.splice(i,1),this._sortedEntities.splice(i,1))}}entityCurrentlyUnderPointer(t,e){return this.currentFrameEntityToPointers.has(t.id)&&this.currentFrameEntityToPointers.get(t.id).includes(e)}entityWasUnderPointer(t,e){return this.lastFrameEntityToPointers.has(t.id)&&this.lastFrameEntityToPointers.get(t.id).includes(e)}entered(t,e){return this.entityCurrentlyUnderPointer(t,e)&&!this.lastFrameEntityToPointers.has(t.id)}left(t,e){return!this.currentFrameEntityToPointers.has(t.id)&&this.entityWasUnderPointer(t,e)}addPointerToEntity(t,e){if(!this.currentFrameEntityToPointers.has(t.id))return void this.currentFrameEntityToPointers.set(t.id,[e]);const i=this.currentFrameEntityToPointers.get(t.id);this.currentFrameEntityToPointers.set(t.id,i.concat(e))}update(t){this._processPointerToEntity(this._sortedEntities),this._dispatchEvents(this._sortedEntities),this._receiver.update(),this.lastFrameEntityToPointers.clear(),this.lastFrameEntityToPointers=new Map(this.currentFrameEntityToPointers),this.currentFrameEntityToPointers.clear(),this._receiver.clear()}_processPointerToEntity(t){var e;let i,s,n,r;for(const o of t){if(i=o.get(di),r=null!==(e=o.get(Zi))&&void 0!==e?e:new Zi,s=o.get(Fi),s&&(r.useColliderShape||this.overrideUseColliderShape)){s.update();const t=s.get();if(t)for(const[e,s]of this._receiver.currentFramePointerCoords.entries())t.contains(i.coordPlane===ii.World?s.worldPos:s.screenPos)&&this.addPointerToEntity(o,e)}if(n=o.get(qi),n&&(r.useGraphicsBounds||this.overrideUseGraphicsBounds)){const t=n.localBounds.transform(i.get().matrix);for(const[e,s]of this._receiver.currentFramePointerCoords.entries())t.contains(i.coordPlane===ii.World?s.worldPos:s.screenPos)&&this.addPointerToEntity(o,e)}}}_processDownAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameDown)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerdown",i),this._receiver.isDragStart(i.pointerId)&&t.events.emit("pointerdragstart",i)),e.set(i.pointerId,i);return e}_processUpAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameUp)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerup",i),this._receiver.isDragEnd(i.pointerId)&&t.events.emit("pointerdragend",i)),e.set(i.pointerId,i);return e}_processMoveAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameMove)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointermove",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragmove",i)),e.set(i.pointerId,i);return e}_processEnterLeaveAndEmit(t,e){for(const i of e){if(i.active&&t.active&&this.entered(t,i.pointerId)){t.events.emit("pointerenter",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragenter",i);break}if(i.active&&t.active&&(this.left(t,i.pointerId)||this.entityCurrentlyUnderPointer(t,i.pointerId)&&"up"===i.type)){t.events.emit("pointerleave",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragleave",i);break}}}_processCancelAndEmit(t){for(const e of this._receiver.currentFrameCancel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,e.pointerId)&&t.events.emit("pointercancel",e)}_processWheelAndEmit(t){for(const e of this._receiver.currentFrameWheel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,0)&&t.events.emit("pointerwheel",e)}_dispatchEvents(t){const e=new Set(this.lastFrameEntityToPointers.keys()),i=new Set(this.currentFrameEntityToPointers.keys()),s=t.filter((t=>e.has(t.id)||i.has(t.id)));let n,r,o;for(const t of s){o=this._processDownAndEmit(t),r=this._processUpAndEmit(t),n=this._processMoveAndEmit(t);const e=[...n.values(),...o.values(),...r.values()];this._processEnterLeaveAndEmit(t,e),this._processCancelAndEmit(t),this._processWheelAndEmit(t)}}}class En extends Ys{constructor(){super(...arguments),this.types=["ex.actions"],this.systemType=Zs.Update,this.priority=-1,this._actions=[]}notify(t){if(Qs(t)){const e=t.data.get(ws);this._actions.push(e)}else{const e=t.data.get(ws),i=this._actions.indexOf(e);i>-1&&this._actions.splice(i,1)}}update(t,e){for(const t of this._actions)t.update(e)}}class Pn extends hi{constructor(t){super(),this.type="ex.isometricentity",this.elevation=0,this.map=t}}class In extends Ys{constructor(){super(...arguments),this.types=["ex.transform","ex.isometricentity"],this.systemType=Zs.Update,this.priority=99}update(t,e){let i,s;for(const e of t){i=e.get(di),s=e.get(Pn);const t=Math.max(s.map.columns*s.map.tileWidth,s.map.rows*s.map.tileHeight)*s.elevation+i.pos.y;i.z=t}}}class Dn extends Ys{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=Zs.Draw,this.priority=-1}initialize(t){this._camera=t.camera,this._screen=t.engine.screen}update(t){let e,i,s;this._worldBounds=this._screen.getWorldBounds();for(const n of t){let t;if(i=n.get(qi),e=n.get(di),s=n.get(Ds),s){const e=vt.One.sub(s.parallaxFactor);t=this._camera.pos.scale(e)}const r=this._isOffscreen(e,i,t);r&&!n.hasTag("ex.offscreen")&&(n.events.emit("exitviewport",new G(n)),n.addTag("ex.offscreen")),!r&&n.hasTag("ex.offscreen")&&(n.events.emit("enterviewport",new V(n)),n.removeTag("ex.offscreen"))}}_isOffscreen(t,e,i){if(t.coordPlane===ii.World){let s=e.localBounds;i&&(s=s.translate(i));const n=s.transform(t.get().matrix);return!this._worldBounds.overlaps(n)}return!1}}class Bn{constructor(){this.collisionProcessor=new yi}rayCast(t,e){return this.collisionProcessor.rayCast(t,e)}}const Rn={Initialize:"initialize",Activate:"activate",Deactivate:"deactivate",PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw"};class Fn{get actors(){return this.world.entityManager.entities.filter((t=>t instanceof Ts))}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter((t=>t instanceof Ks))}get tileMaps(){return this.world.entityManager.entities.filter((t=>t instanceof ks))}get timers(){return this._timers}constructor(){this._logger=J.getInstance(),this.events=new d,this.camera=new Vs,this.world=new on(this),this.physics=new Bn,this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(new En),this.world.add(new hn),this.world.add(new un(this.physics)),this.world.add(new Tn),this.world.add(new In),this.world.add(new Dn),this.world.add(new An),this.world.add(new Sn)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}onInitialize(t){}onActivate(t){}onDeactivate(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.engine=t,this.camera._initialize(t),this.world.systemManager.initialize(),this.onInitialize.call(this,t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0)}_activate(t){this._logger.debug("Scene.onActivate",this),this.onActivate(t)}_deactivate(t){this._logger.debug("Scene.onDeactivate",this),this.onDeactivate(t)}_preupdate(t,e){this.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new v(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new x(t,e,this)),this.onPostDraw(t,e)}update(t,e){let i,s;for(this._preupdate(t,e),i=0,s=this._cancelQueue.length;i<s;i++)this.removeTimer(this._cancelQueue[i]);this._cancelQueue.length=0;for(const t of this._timers)t.update(e);this.world.update(Zs.Update,e),this.camera&&this.camera.update(t,e),this._collectActorStats(t),this._postupdate(t,e)}draw(t,e){var i;this._predraw(t,e),this.world.update(Zs.Draw,e),(null===(i=this.engine)||void 0===i?void 0:i.isDebug)&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new y(t,this)),this.emit("postdebugdraw",new w(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){this.emit("entityadded",{target:t}),this.world.add(t),t.scene=this,t instanceof Is&&(It(this._timers,t)||this.addTimer(t))}transfer(t){let e;t instanceof Hi&&t.scene&&t.scene!==this&&(e=t.scene,t.scene.world.remove(t,!1)),t instanceof Is&&t.scene&&(e=t.scene,t.scene.removeTimer(t)),null==e||e.emit("entityremoved",{target:t}),this.add(t)}remove(t){t instanceof Hi&&(this.emit("entityremoved",{target:t}),t.active&&t.kill(),this.world.remove(t)),t instanceof Is&&this.removeTimer(t)}clear(t=!0){for(let e=this.entities.length-1;e>=0;e--)this.world.remove(this.entities[e],t);for(let t=this.timers.length-1;t>=0;t--)this.removeTimer(this.timers[t])}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return-1!==e&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return!!this.engine&&this.engine.currentScene===this}_collectActorStats(t){const e=this.actors.filter((t=>t instanceof Ps));for(const i of e)t.stats.currFrame.actors.ui++;for(const e of this.actors){t.stats.currFrame.actors.alive++;for(const i of e.children)Es(i)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}var kn;!function(t){t.Protanope="Protanope",t.Deuteranope="Deuteranope",t.Tritanope="Tritanope"}(kn||(kn={}));class Mn{constructor(t,e){this._shader=new Jt({gl:t,vertexSource:"#version 300 es\n in vec2 a_position;\n in vec2 a_texcoord;\n out vec2 v_texcoord;\n\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n // Pass the texcoord to the fragment shader.\n v_texcoord = a_texcoord;\n }",fragmentSource:e}),this._shader.compile(),this._buffer=new te({gl:t,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new ee({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}getShader(){return this._shader}getLayout(){return this._layout}}class Ln{constructor(t,e=!1){this._colorBlindnessMode=t,this._simulate=!1,this._simulate=e}initialize(t){this._shader=new Mn(t,"#version 300 es\r\nprecision mediump float;\r\n// our texture\r\nuniform sampler2D u_image;\r\n// the texCoords passed in from the vertex shader.\r\nin vec2 v_texcoord;\r\n\r\n// color blind type\r\nuniform int u_type;\r\n\r\n// simulation?\r\nuniform bool u_simulate;\r\n\r\nout vec4 fragColor;\r\n\r\nvoid main() {\r\n vec4 o = texture(u_image, v_texcoord);\r\n // RGB to LMS matrix conversion\r\n float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);\r\n float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);\r\n float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);\r\n // Simulate color blindness\r\n float l;\r\n float m;\r\n float s;\r\n //MODE CODE//\r\n if (u_type == 0) {\r\n // Protanope\r\n l = 0.0 * L + 2.02344 * M + -2.52581 * S;\r\n m = 0.0 * L + 1.0 * M + 0.0 * S;\r\n s = 0.0 * L + 0.0 * M + 1.0 * S;;\r\n } else if (u_type == 1) {\r\n // Deuteranope\r\n l = 1.0 * L + 0.0 * M + 0.0 * S;\r\n m = 0.494207 * L + 0.0 * M + 1.24827 * S;\r\n s = 0.0 * L + 0.0 * M + 1.0 * S;\r\n } else if (u_type == 2) {\r\n // Tritanope\r\n l = 1.0 * L + 0.0 * M + 0.0 * S;\r\n m = 0.0 * L + 1.0 * M + 0.0 * S;\r\n s = -0.395913 * L + 0.801109 * M + 0.0 * S;\r\n }\r\n\r\n // LMS to RGB matrix conversion\r\n vec4 error; // simulate the colors\r\n error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);\r\n error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);\r\n error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);\r\n error.a = 1.0;\r\n vec4 diff = o - error;\r\n vec4 correction; // correct the colors\r\n correction.r = 0.0;\r\n correction.g = (diff.r * 0.7) + (diff.g * 1.0);\r\n correction.b = (diff.r * 0.7) + (diff.b * 1.0);\r\n correction = o + correction;\r\n correction.a = o.a;\r\n //SIMULATE//\r\n\r\n // sim \r\n if (u_simulate) {\r\n fragColor = error.rgba;\r\n } else {\r\n fragColor = correction.rgba;\r\n }\r\n}"),this.simulate=this._simulate,this.colorBlindnessMode=this._colorBlindnessMode}getShader(){return this._shader.getShader()}getLayout(){return this._shader.getLayout()}set colorBlindnessMode(t){if(this._colorBlindnessMode=t,this._shader){const t=this._shader.getShader();t.use(),this._colorBlindnessMode===kn.Protanope?t.setUniformInt("u_type",0):this._colorBlindnessMode===kn.Deuteranope?t.setUniformInt("u_type",1):this._colorBlindnessMode===kn.Tritanope&&t.setUniformInt("u_type",2)}}get colorBlindnessMode(){return this._colorBlindnessMode}set simulate(t){if(this._simulate=t,this._shader){const e=this._shader.getShader();e.use(),e.setUniformBoolean("u_simulate",t)}}get simulate(){return this._simulate}}class zn{constructor(t){this._engine=t,this._colorBlindPostProcessor=new Ln(kn.Protanope)}correct(t){this._engine.graphicsContext instanceof me&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!1,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}simulate(t){this._engine.graphicsContext instanceof me&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!0,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}clear(){this._engine.graphicsContext.removePostProcessor(this._colorBlindPostProcessor)}}class Un{constructor(t){this.stats={currFrame:new On,prevFrame:new On},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!0,showName:!1},this.transform={showAll:!1,showPosition:!1,showPositionLabel:!1,positionColor:yt.Yellow,showZIndex:!1,showScale:!1,scaleColor:yt.Green,showRotation:!1,rotationColor:yt.Blue},this.graphics={showAll:!1,showBounds:!0,boundsColor:yt.Yellow},this.collider={showAll:!1,showBounds:!0,boundsColor:yt.Blue,showOwner:!1,showGeometry:!0,geometryColor:yt.Green},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:yt.Cyan,showCollisionContacts:!0,collisionContactColor:yt.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:yt.Yellow,showAcceleration:!1,accelerationColor:yt.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:yt.Red,showZoom:!1},this._engine=t,this.colorBlindMode=new zn(this._engine)}useTestClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toTestClock();return e&&i.start(),this._engine.clock=i,i}useStandardClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toStandardClock();return e&&i.start(),this._engine.clock=i,i}}class On{constructor(){this._id=0,this._delta=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new Nn,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.delta=t.delta,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.delta=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new On;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get delta(){return this._delta}set delta(t){this._delta=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class Nn{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new Nn;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}class Hn{on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}}class Wn{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new Hn(this._windowGlobal),this._documentComponent=new Hn(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class Gn{static fromPagePosition(t,e,i){let s,n,r,o;3===arguments.length?(s=t,n=e,r=new vt(s,n),o=i):(r=t,s=r.x,n=r.y,o=e);const a=o.screen.pageToScreenCoordinates(r),h=o.screen.screenToWorldCoordinates(a);return new Gn(h,r,a)}constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}}class Vn{cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}constructor(t,e,i,s,n,r){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=r,this.active=!0}}class qn{cancel(){this.active=!1}constructor(t,e,i,s,n,r,o,a,h,l,c,d){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=r,this.index=o,this.deltaX=a,this.deltaY=h,this.deltaZ=l,this.deltaMode=c,this.ev=d,this.active=!0}}class Xn{constructor(){this.events=new d,this.lastPagePos=vt.Zero,this.lastScreenPos=vt.Zero,this.lastWorldPos=vt.Zero,this._onPointerMove=t=>{this.lastPagePos=new vt(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new vt(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new vt(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new vt(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new vt(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new vt(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var Kn,Zn,Yn,jn;!function(t){t.Pixel="Pixel",t.Line="Line",t.Page="Page"}(Kn||(Kn={})),function(t){t[t.NoButton=-1]="NoButton",t[t.Left=0]="Left",t[t.Middle=1]="Middle",t[t.Right=2]="Right",t[t.Unknown=3]="Unknown"}(Zn||(Zn={})),function(t){t.Left="Left",t.Middle="Middle",t.Right="Right",t.Unknown="Unknown",t.NoButton="NoButton"}(Yn||(Yn={})),function(t){t.Touch="Touch",t.Mouse="Mouse",t.Pen="Pen",t.Unknown="Unknown"}(jn||(jn={}));class Qn{constructor(t,e){this.target=t,this.engine=e,this.events=new d,this.primary=new Xn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerCoords=new Map,this.currentFramePointerCoords=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}recreate(t,e){const i=new Qn(t,e);return i.primary=this.primary,i._pointers=this._pointers,i}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Xn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return null!==(e=this.currentFramePointerDown.get(t))&&void 0!==e&&e}wasDown(t){var e;return null!==(e=this.lastFramePointerDown.get(t))&&void 0!==e&&e}isDragging(t){return this.isDown(t)}isDragStart(t){return this.isDown(t)&&!this.wasDown(t)}isDragEnd(t){return!this.isDown(t)&&this.wasDown(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerCoords=new Map(this.currentFramePointerCoords);for(const t of this.currentFrameDown){this.emit("down",t);this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){this.emit("up",t);this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){this.emit("move",t);this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){this.emit("cancel",t);this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)this.emit("wheel",t),this.primary.emit("pointerwheel",t),this.primary.emit("wheel",t)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerCoords.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(t){var e;this.target===this.engine.canvas?this.engine.canvas.style.touchAction="none":document.body.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const i={passive:!(this.engine.pageScrollPreventionMode===or.All||this.engine.pageScrollPreventionMode===or.Canvas)};"onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,i):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel,i):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,i);if((null===(e=null==t?void 0:t.grabWindowFocus)||void 0===e||e)&&it()){const t=()=>{window.focus()};window.PointerEvent?this.target.addEventListener("pointerdown",t):(this.target.addEventListener("touchstart",t),this.target.addEventListener("mousedown",t))}}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const e=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort(((t,e)=>t-e)).findIndex((e=>e===t));return this._activeNativePointerIdsToNormalized.set(t,e),e}_handle(t){t.preventDefault();const e=new Map;let i,s;if(n=t,globalThis.TouchEvent&&n instanceof globalThis.TouchEvent){i=Yn.Unknown,s=jn.Touch;for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],n=Gn.fromPagePosition(s.pageX,s.pageY,this.engine),r=i+1,o=this._normalizePointerId(r);this.currentFramePointerCoords.set(o,n),e.set(o,n)}}else{i=this._nativeButtonToPointerButton(t.button),s=jn.Mouse;const n=Gn.fromPagePosition(t.pageX,t.pageY,this.engine);let r=1;(function(t){return globalThis.PointerEvent&&t instanceof globalThis.PointerEvent})(t)&&(r=t.pointerId,s=this._stringToPointerType(t.pointerType));const o=this._normalizePointerId(r);this.currentFramePointerCoords.set(o,n),e.set(o,n)}var n;for(const[n,r]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new Vn("down",n,i,s,r,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new Vn("up",n,i,s,r,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new Vn("move",n,i,s,r,t));break;case"touchcancel":case"pointercancel":this.currentFrameCancel.push(new Vn("cancel",n,i,s,r,t))}}_handleWheel(t){(this.engine.pageScrollPreventionMode===or.All||this.engine.pageScrollPreventionMode===or.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(xt(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,r=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,o=t.deltaZ||0;let a=Kn.Pixel;t.deltaMode&&(1===t.deltaMode?a=Kn.Line:2===t.deltaMode&&(a=Kn.Page));const h=new qn(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,r,o,a,t);this.currentFrameWheel.push(h)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.systemManager.get(Tn),n=this.engine.currentScene.world.queryManager.createQuery(s.types);s.preupdate(),s.update(n.getEntities())}_nativeButtonToPointerButton(t){switch(t){case Zn.NoButton:return Yn.NoButton;case Zn.Left:return Yn.Left;case Zn.Middle:return Yn.Middle;case Zn.Right:return Yn.Right;case Zn.Unknown:return Yn.Unknown;default:return Dt(t)}}_stringToPointerType(t){switch(t){case"touch":return jn.Touch;case"mouse":return jn.Mouse;case"pen":return jn.Pen;default:return jn.Unknown}}}class $n{constructor(t){var e;this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0,this._fps=t.initialFps,this._samplePeriod=null!==(e=t.samplePeriod)&&void 0!==e?e:this._samplePeriod,this._currentFrameTime=1e3/t.initialFps,this._nowFn=t.nowFn,this._previousSampleTime=this._nowFn()}start(){this._beginFrameTime=this._nowFn()}end(){this._frames++;const t=this._nowFn();this._currentFrameTime=t-this._beginFrameTime,t>=this._previousSampleTime+this._samplePeriod&&(this._fps=1e3*this._frames/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class Jn{constructor(t){var e,i,s;this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._options=t,this.tick=t.tick,this._lastTime=null!==(e=this.now())&&void 0!==e?e:0,this._maxFps=null!==(i=t.maxFps)&&void 0!==i?i:this._maxFps,this._onFatalException=null!==(s=t.onFatalException)&&void 0!==s?s:this._onFatalException,this.fpsSampler=new $n({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new er({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new tr({...this._options})}setFatalExceptionHandler(t){this._onFatalException=t}schedule(t,e=0){const i=this._totalElapsed+e;this._scheduledCbs.push([t,i])}_runScheduledCbs(){for(let t=this._scheduledCbs.length-1;t>-1;t--)this._scheduledCbs[t][1]<=this._totalElapsed&&(this._scheduledCbs[t][0](),this._scheduledCbs.splice(t,1))}update(t){try{this.fpsSampler.start();const e=this.now();let i=e-this._lastTime||1;const s=1e3/this._maxFps;if(i>=s){let n=0;0!==s&&(n=i%s,i-=n),i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this._runScheduledCbs(),this.tick(t||i),this._lastTime=0!==s?e-n:e,this.fpsSampler.end()}}catch(t){this._onFatalException(t),this.stop()}}}class tr extends Jn{constructor(t){super(t),this._running=!1}isRunning(){return this._running}start(){if(this._running)return;this._running=!0;const t=()=>{if(this._running)try{this._requestId=window.requestAnimationFrame(t),this.update()}catch(t){throw window.cancelAnimationFrame(this._requestId),t}};t()}stop(){this._running=!1}}class er extends Jn{constructor(t){super({...t}),this._logger=J.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return null!==(t=this._currentTime)&&void 0!==t?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=null!=t?t:this._updateMs;this._running?(this.update(e),this._currentTime+=e):this._logger.warn("The clock is not running, no step will be performed")}run(t,e){for(let i=0;i<t;i++)this.step(null!=e?e:this._updateMs)}}var ir=i(7379);class sr{constructor(){this._toasterCss=ir.Z.toString(),this._isInitialized=!1}_initialize(){this._isInitialized||(this._container=document.createElement("div"),this._container.id="ex-toast-container",document.body.appendChild(this._container),this._isInitialized=!0,this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._toasterCss,document.head.appendChild(this._styleBlock))}dispose(){this._container.parentElement.removeChild(this._container),this._styleBlock.parentElement.removeChild(this._styleBlock),this._isInitialized=!1}_createFragment(t){const e=document.createElement("span");return e.innerText=t,e}toast(t,e,i){this._initialize();const s=document.createElement("div");s.className="ex-toast-message";const n=t.split("[LINK]").map((t=>this._createFragment(t)));if(e){const t=document.createElement("a");t.href=e,t.innerText=i||e,n.splice(1,0,t)}const r=document.createElement("div");n.forEach((t=>{r.appendChild(t)})),s.appendChild(r);const o=document.createElement("button");o.innerText="x",o.addEventListener("click",(()=>{this._container.removeChild(s)})),s.appendChild(o);const a=t=>{if("Escape"===t.key)try{this._container.removeChild(s)}catch(t){}document.removeEventListener("keydown",a)};document.addEventListener("keydown",a);const h=this._container.firstChild;this._container.insertBefore(s,h)}}class nr{constructor(t){this.inputs=t,this._handlers=new Map}execute(){for(const[t,e]of this._handlers.entries()){const i=t(this.inputs);i&&e(i)}}on(t,e){this._handlers.set(t,e)}}h();const rr={FallbackGraphicsContext:"fallbackgraphicscontext",Initialize:"initialize",Visible:"visible",Hidden:"hidden",Start:"start",Stop:"stop",PreUpdate:"preupdate",PostUpdate:"postupdate",PreFrame:"preframe",PostFrame:"postframe",PreDraw:"predraw",PostDraw:"postdraw"};var or;!function(t){t[t.None=0]="None",t[t.Canvas=1]="Canvas",t[t.All=2]="All"}(or||(or={}));class ar{get canvasWidth(){return this.screen.canvasWidth}get halfCanvasWidth(){return this.screen.halfCanvasWidth}get canvasHeight(){return this.screen.canvasHeight}get halfCanvasHeight(){return this.screen.halfCanvasHeight}get drawWidth(){return this.screen.drawWidth}get halfDrawWidth(){return this.screen.halfDrawWidth}get drawHeight(){return this.screen.drawHeight}get halfDrawHeight(){return this.screen.halfDrawHeight}get isHiDpi(){return this.screen.isHiDpi}get stats(){return this.debug.stats}get isFullscreen(){return this.screen.isFullScreen}get displayMode(){return this.screen.displayMode}get pixelRatio(){return this.screen.pixelRatio}get isDebug(){return this._isDebug}get snapToPixel(){return this.graphicsContext.snapToPixel}set snapToPixel(t){this.graphicsContext.snapToPixel=t}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}constructor(t){var e,i,s,n,r,o;this.version=Br,this.events=new d,this.maxFps=Number.POSITIVE_INFINITY,this.scenes={},this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.enableCanvasTransparency=!0,this.onFatalException=t=>{J.getInstance().fatal(t)},this._toaster=new sr,this._timescale=1,this._isInitialized=!1,this._deferredGoTo=null,this._originalOptions={},this._performanceThresholdTriggered=!1,this._fpsSamples=[],this._loadingComplete=!1,this._isReady=!1,this._isReadyPromise=new Promise((t=>{this._isReadyResolve=t})),this.currentFrameElapsedMs=0,this.currentFrameLagMs=0,this._lagMs=0,this._screenShotRequests=[],t={...ar._DEFAULT_ENGINE_OPTIONS,...t},this._originalOptions=t,l.freeze(),this.browser=new Wn(window,document);const a=new Xe;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=a.test())){const e=document.createElement("div");if(e.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(e),a.failedTests.forEach((function(t){const e=document.createElement("div");e.innerText="Browser feature missing "+t,document.body.appendChild(e)})),t.canvasElementId){const e=document.getElementById(t.canvasElementId);e&&e.parentElement.removeChild(e)}return}this._compatible=!0,console.log&&!t.suppressConsoleBootMessage&&(console.log(`%cPowered by Excalibur.js (v${Br})`,"background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;"),console.log("\n /| ________________\nO|===|* >________________>\n \\|"),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=J.getInstance(),this._logger.defaultLevel===Q.Debug&&a.logBrowserFeatures(),this._logger.debug("Building engine..."),this.canvasElementId=t.canvasElementId,t.canvasElementId?(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),this.canvas=document.getElementById(t.canvasElementId)):t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"));let h=null!==(e=t.displayMode)&&void 0!==e?e:ye.Fixed;t.width&&t.height||t.viewport?(void 0===t.displayMode&&(h=ye.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),h=ye.FitScreen),this._originalDisplayMode=h;let c=l.isEnabled("use-canvas-context");if(!c)try{this.graphicsContext=new me({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})}catch(t){this._logger.warn(`Excalibur could not load webgl for some reason (${t.message}) and loaded a Canvas 2D fallback. Some features of Excalibur will not work in this mode. \n\nRead more about this issue at https://excaliburjs.com/docs/webgl`),c=!0}c&&(this.graphicsContext=new xe({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})),this.screen=new Ce({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(i=t.antialiasing)||void 0===i||i,browser:this.browser,viewport:null!==(s=t.viewport)&&void 0!==s?s:t.width&&t.height?{width:t.width,height:t.height}:we.SVGA,resolution:t.resolution,displayMode:h,pixelRatio:t.suppressHiDPIScaling?1:null!==(n=t.pixelRatio)&&void 0!==n?n:null}),Gt.filtering=t.antialiasing?Wt.Blended:Wt.Pixel,t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.maxFps=null!==(r=t.maxFps)&&void 0!==r?r:this.maxFps,this.fixedUpdateFps=null!==(o=t.fixedUpdateFps)&&void 0!==o?o:this.fixedUpdateFps,this.clock=new tr({maxFps:this.maxFps,tick:this._mainloop.bind(this),onFatalException:t=>this.onFatalException(t)}),this.enableCanvasTransparency=t.enableCanvasTransparency,this._loader=new Ve,this._loader.wireEngine(this),this.debug=new Un(this),this._initialize(t),this.rootScene=this.currentScene=new Fn,this.addScene("root",this.rootScene),window.___EXCALIBUR_DEVTOOL=this}_monitorPerformanceThresholdAndTriggerFallback(){const{allow:t}=this._originalOptions.configurePerformanceCanvas2DFallback;let{threshold:e,showPlayerMessage:i}=this._originalOptions.configurePerformanceCanvas2DFallback;if(void 0===e&&(e=ar._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.threshold),void 0===i&&(i=ar._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.showPlayerMessage),!l.isEnabled("use-canvas-context")&&t&&this.ready&&!this._performanceThresholdTriggered){this._fpsSamples.length===e.numberOfFrames&&this._fpsSamples.splice(0,1),this._fpsSamples.push(this.clock.fpsSampler.fps);let t=0;for(let e=0;e<this._fpsSamples.length;e++)t+=this._fpsSamples[e];const s=t/this._fpsSamples.length;this._fpsSamples.length===e.numberOfFrames&&s<=e.fps&&(this._performanceThresholdTriggered=!0,this._logger.warn('Switching to browser 2D Canvas fallback due to performance. Some features of Excalibur will not work in this mode.\nthis might mean your browser doesn\'t have webgl enabled or hardware acceleration is unavailable.\n\nIf in Chrome:\n * Visit Settings > Advanced > System, and ensure "Use Hardware Acceleration" is checked.\n * Visit chrome://flags/#ignore-gpu-blocklist and ensure "Override software rendering list" is "enabled"\nIf in Firefox, visit about:config\n * Ensure webgl.disabled = false\n * Ensure webgl.force-enabled = true\n * Ensure layers.acceleration.force-enabled = true\n\nRead more about this issue at https://excaliburjs.com/docs/performance'),i&&this._toaster.toast("Excalibur is encountering performance issues. It's possible that your browser doesn't have hardware acceleration enabled. Visit [LINK] for more information and potential solutions.","https://excaliburjs.com/docs/performance"),this.useCanvas2DFallback(),this.emit("fallbackgraphicscontext",this.graphicsContext))}}useCanvas2DFallback(){var t,e,i;const s=this.canvas.cloneNode(!1);this.canvas.parentNode.replaceChild(s,this.canvas),this.canvas=s;const n={...this._originalOptions,antialiasing:this.getAntialiasing()},r=this._originalDisplayMode;this.graphicsContext=new xe({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:n.antialiasing,backgroundColor:n.backgroundColor,snapToPixel:n.snapToPixel,useDrawSorting:n.useDrawSorting}),this.screen&&this.screen.dispose(),this.screen=new Ce({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(t=n.antialiasing)||void 0===t||t,browser:this.browser,viewport:null!==(e=n.viewport)&&void 0!==e?e:n.width&&n.height?{width:n.width,height:n.height}:we.SVGA,resolution:n.resolution,displayMode:r,pixelRatio:n.suppressHiDPIScaling?1:null!==(i=n.pixelRatio)&&void 0!==i?i:null}),this.screen.setCurrentCamera(this.currentScene.camera),this.input.pointers.detach();const o=n&&n.pointerScope===rt.Document?document:this.canvas;this.input.pointers=this.input.pointers.recreate(o,this),this.input.pointers.init()}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){t<=0?J.getInstance().error("Cannot set engine.timescale to a value of 0 or less than 0."):this._timescale=t}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e}removeScene(t){if(t instanceof Fn)for(const e in this.scenes)this.scenes.hasOwnProperty(e)&&this.scenes[e]===t&&delete this.scenes[e];"string"==typeof t&&delete this.scenes[t]}add(t){2!==arguments.length?this._deferredGoTo&&this.scenes[this._deferredGoTo]?this.scenes[this._deferredGoTo].add(t):this.currentScene.add(t):this.addScene(arguments[0],arguments[1])}remove(t){t instanceof Hi&&this.currentScene.remove(t),t instanceof Fn&&this.removeScene(t),"string"==typeof t&&this.removeScene(t)}goToScene(t,e){if(this.isInitialized)if(this.scenes[t]){const i=this.currentScene,s=this.scenes[t];if(this._logger.debug("Going to scene:",t),this.currentScene.isInitialized){const t={engine:this,previousScene:i,nextScene:s};this.currentScene._deactivate.apply(this.currentScene,[t,s]),this.currentScene.events.emit("deactivate",new W(t,this.currentScene))}this.currentScene=s,this.screen.setCurrentCamera(s.camera),this.currentScene._initialize(this);const n={engine:this,previousScene:i,nextScene:s,data:e};this.currentScene._activate.apply(this.currentScene,[n,s]),this.currentScene.events.emit("activate",new H(n,this.currentScene))}else this._logger.error("Scene",t,"does not exist!");else this._deferredGoTo=t}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){var e,i,s,n;this.pageScrollPreventionMode=t.scrollPreventionMode;const r=t&&t.pointerScope===rt.Document?document:this.canvas;this.input={keyboard:new nt,pointers:new Qn(r,this),gamepads:new K},this.input.keyboard.init({grabWindowFocus:null===(i=null===(e=this._originalOptions)||void 0===e?void 0:e.grabWindowFocus)||void 0===i||i}),this.input.pointers.init({grabWindowFocus:null===(n=null===(s=this._originalOptions)||void 0===s?void 0:s.grabWindowFocus)||void 0===n||n}),this.input.gamepads.init(),this.inputMapper=new nr(this.input),this.browser.document.on("visibilitychange",(()=>{"hidden"===document.visibilityState?(this.events.emit("hidden",new B(this)),this._logger.debug("Window hidden")):"visible"===document.visibilityState&&(this.events.emit("visible",new D(this)),this._logger.debug("Window visible"))})),this.canvasElementId||t.canvasElement||document.body.appendChild(this.canvas)}onInitialize(t){}setAntialiasing(t){this.screen.antialiasing=t}getAntialiasing(){return this.screen.antialiasing}get isInitialized(){return this._isInitialized}_overrideInitialize(t){if(!this.isInitialized)if(this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0,this._deferredGoTo){const t=this._deferredGoTo;this._deferredGoTo=null,this.goToScene(t)}else this.goToScene("root")}_update(t){if(!this.ready)return this._loader.update(this,t),this.inputMapper.execute(),this.input.keyboard.update(),void this.input.gamepads.update();this._preupdate(t),this.currentScene.update(this,t),this.graphicsContext.updatePostProcessors(t),this._postupdate(t),this.inputMapper.execute(),this.input.keyboard.update(),this.input.gamepads.update()}_preupdate(t){this.emit("preupdate",new b(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new C(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){if(this.graphicsContext.beginDrawLifecycle(),this.graphicsContext.clear(),this._predraw(this.graphicsContext,t),!this._isReady)return this._loader.canvas.draw(this.graphicsContext,0,0),void this.graphicsContext.flush();this.graphicsContext.backgroundColor=this.backgroundColor,this.currentScene.draw(this.graphicsContext,t),this._postdraw(this.graphicsContext,t),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle(),this._checkForScreenShots()}_predraw(t,e){this.emit("predraw",new v(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new x(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return this._loadingComplete}get ready(){return this._isReady}isReady(){return this._isReadyPromise}async start(t){if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");return t&&(this.screen.pushResolutionAndViewport(),this.screen.resolution=this.screen.viewport,this.screen.applyResolutionAndViewport(),this._loader=t,this._loader.suppressPlayButton=this._suppressPlayButton||this._loader.suppressPlayButton,this._loader.wireEngine(this)),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this._logger.debug("Game clock started"),t&&(await this.load(this._loader),this._loadingComplete=!0,this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport()),this._loadingComplete=!0,this._overrideInitialize(this),this._isReady=!0,this._isReadyResolve(),this.emit("start",new m(this)),this._isReadyPromise}_mainloop(t){this.emit("preframe",new A(this,this.stats.prevFrame));const e=t*this.timescale;this.currentFrameElapsedMs=e;const i=this.stats.prevFrame.id+1;this.stats.currFrame.reset(),this.stats.currFrame.id=i,this.stats.currFrame.delta=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps,ie.clear();const s=this.clock.now(),n=1e3/this.fixedUpdateFps;if(this.fixedUpdateFps)for(this._lagMs+=e;this._lagMs>=n;)this._update(n),this._lagMs-=n;else this._update(e);const r=this.clock.now();this.currentFrameLagMs=this._lagMs,this._draw(e);const o=this.clock.now();this.stats.currFrame.duration.update=r-s,this.stats.currFrame.duration.draw=o-r,this.stats.currFrame.graphics.drawnImages=ie.DrawnImagesCount,this.stats.currFrame.graphics.drawCalls=ie.DrawCallCount,this.emit("postframe",new S(this,this.stats.currFrame)),this.stats.prevFrame.reset(this.stats.currFrame),this._monitorPerformanceThresholdAndTriggerFallback()}stop(){this.clock.isRunning()&&(this.emit("stop",new f(this)),this.browser.pause(),this.clock.stop(),this._logger.debug("Game stopped"))}isRunning(){return this.clock.isRunning()}screenshot(t=!1){return new Promise((e=>{this._screenShotRequests.push({preserveHiDPIResolution:t,resolve:e})}))}_checkForScreenShots(){for(const t of this._screenShotRequests){const e=t.preserveHiDPIResolution?this.canvas.width:this.screen.resolution.width,i=t.preserveHiDPIResolution?this.canvas.height:this.screen.resolution.height,s=document.createElement("canvas");s.width=e,s.height=i;const n=s.getContext("2d");n.imageSmoothingEnabled=this.screen.antialiasing,n.drawImage(this.canvas,0,0,e,i);const r=new Image,o=s.toDataURL("image/png");r.src=o,t.resolve(r)}this._screenShotRequests.length=0}async load(t){try{await t.load()}catch(t){this._logger.error("Error loading resources, things may not behave properly",t),await Promise.resolve()}}}ar._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,useDrawSorting:!0,configurePerformanceCanvas2DFallback:{allow:!1,showPlayerMessage:!1,threshold:{fps:20,numberOfFrames:100}},canvasElementId:"",canvasElement:void 0,snapToPixel:!1,pointerScope:rt.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,grabWindowFocus:!0,scrollPreventionMode:or.Canvas,backgroundColor:yt.fromHex("#2185d0")};class hr{constructor(){this._handlers={},this._wiredEventDispatchers=[],this._deferedHandlerRemovals=[]}clear(){this._handlers={},this._wiredEventDispatchers=[]}_processDeferredHandlerRemovals(){for(const t of this._deferedHandlerRemovals)this._removeHandler(t.name,t.handler);this._deferedHandlerRemovals.length=0}emit(t,e){if(this._processDeferredHandlerRemovals(),!t)return;let i,s;if(t=t.toLowerCase(),null==e&&(e=new u),this._handlers[t])for(i=0,s=this._handlers[t].length;i<s;i++)this._handlers[t][i](e);for(i=0,s=this._wiredEventDispatchers.length;i<s;i++)this._wiredEventDispatchers[i].emit(t,e)}on(t,e){this._processDeferredHandlerRemovals(),t=t.toLowerCase(),this._handlers[t]||(this._handlers[t]=[]),this._handlers[t].push(e)}off(t,e){this._deferedHandlerRemovals.push({name:t,handler:e})}_removeHandler(t,e){t=t.toLowerCase();const i=this._handlers[t];if(i)if(e){const s=i.indexOf(e);s>-1&&this._handlers[t].splice(s,1)}else this._handlers[t].length=0}once(t,e){this._processDeferredHandlerRemovals();const i=s=>{const n=s||new u;this.off(t,i),e(n)};this.on(t,i)}wire(t){t._wiredEventDispatchers.push(this)}unwire(t){const e=t._wiredEventDispatchers.indexOf(this);e>-1&&t._wiredEventDispatchers.splice(e,1)}}class lr extends Ts{get font(){return this._font}set font(t){this._font=t,this._text.font=t}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text&&(this._text.color=t)}get opacity(){return this._text.opacity}set opacity(t){this._text.opacity=t}get spriteFont(){return this._spriteFont}set spriteFont(t){t&&(this._spriteFont=t,this._text.font=this._spriteFont)}constructor(t){super(t),this._font=new As,this._text=new Ss({text:"",font:this._font});const{text:e,pos:i,x:s,y:n,spriteFont:r,font:o,color:a}=t;this.pos=null!=i?i:s&&n?xt(s,n):this.pos,this.text=null!=e?e:this.text,this.font=null!=o?o:this.font,this.spriteFont=null!=r?r:this.spriteFont,this._text.color=null!=a?a:this.color;const h=this.get(qi);h.anchor=vt.Zero,h.use(this._text)}_initialize(t){super._initialize(t)}getTextWidth(){return this._text.width}}class cr extends Hi{getGraphics(){return this._graphics}addGraphic(t){this._graphics.push(t),this._gfx.visible=!0,this._gfx.localBounds=this._recalculateBounds()}_recalculateBounds(){let t=this._tileBounds.clone();for(const e of this._graphics){const i=xt(this.map.graphicsOffset.x-this.map.tileWidth/2,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t=t.combine(e.localBounds.translate(i))}return t}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&this._graphics.splice(e,1),this._gfx.localBounds=this._recalculateBounds()}clearGraphics(){this._graphics.length=0,this._gfx.visible=!1,this._gfx.localBounds=this._recalculateBounds()}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}get pos(){return this.map.tileToWorld(xt(this.x,this.y))}get center(){return this.pos.add(xt(0,this.map.tileHeight/2))}constructor(t,e,i,s){super([new di,new qi({offset:null!=i?i:vt.Zero,onPostDraw:(t,e)=>this.draw(t,e)}),new Pn(s)]),this.solid=!1,this._tileBounds=new At,this._graphics=[],this._colliders=[],this.x=t,this.y=e,this.map=s,this._transform=this.get(di),this._isometricEntityComponent=this.get(Pn);const n=this.map.tileWidth/2,r=this.map.tileHeight/2,o=(this.x-this.y)*n,a=(this.x+this.y)*r;this._transform.pos=xt(o,a),this._isometricEntityComponent.elevation=0,this._gfx=this.get(qi),this._gfx.visible=!1;const h=this.map.tileWidth,l=this.map.tileHeight,c=xt(0,this.map.renderFromTopOfGraphic?l:0);this._gfx.localBounds=this._tileBounds=new At({left:-h/2,top:-l,right:h/2,bottom:l}).translate(c)}draw(t,e){const i=this.map.tileWidth/2;t.save(),t.translate(-i,0);for(const e of this._graphics)e.draw(t,this.map.graphicsOffset.x,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t.restore()}}class dr extends Hi{constructor(t){super([new di,new Mi({type:Ke.Fixed}),new Fi,new Bs((t=>this.debug(t)),!1)],t.name),this.renderFromTopOfGraphic=!1,this.graphicsOffset=xt(0,0),this._collidersDirty=!1,this._originalOffsets=new WeakMap;const{pos:e,tileWidth:i,tileHeight:s,columns:n,rows:r,renderFromTopOfGraphic:o,graphicsOffset:a}=t;this.transform=this.get(di),e&&(this.transform.pos=e),this.collider=this.get(Fi),this.collider&&this.collider.set(this._composite=new bi([])),this.renderFromTopOfGraphic=null!=o?o:this.renderFromTopOfGraphic,this.graphicsOffset=null!=a?a:this.graphicsOffset,this.tileWidth=i,this.tileHeight=s,this.columns=n,this.rows=r,this.tiles=new Array(n*r);for(let t=0;t<r;t++)for(let e=0;e<n;e++){const i=new cr(e,t,this.graphicsOffset,this);this.tiles[e+t*n]=i,this.addChild(i)}}update(){this._collidersDirty&&(this.updateColliders(),this._collidersDirty=!1)}flagCollidersDirty(){this._collidersDirty=!0}_getOrSetColliderOriginalOffset(t){if(this._originalOffsets.has(t))return this._originalOffsets.get(t);{const e=t.offset;return this._originalOffsets.set(t,e),e}}updateColliders(){this._composite.clearColliders();const t=this.get(di).pos;for(const e of this.tiles)if(e.solid)for(const i of e.getColliders()){const s=this._getOrSetColliderOriginalOffset(i);i.offset=this.tileToWorld(xt(e.x,e.y)).sub(t).add(s).sub(xt(this.tileWidth/2,this.tileHeight)),i.owner=this,this._composite.addCollider(i)}this.collider.update()}worldToTile(t){t=t.sub(this.transform.globalPos);const e=this.tileWidth/2,i=this.tileHeight/2;return xt(~~((t.x/e+t.y/i)/2),~~((t.y/i-t.x/e)/2))}tileToWorld(t){const e=this.tileWidth/2,i=this.tileHeight/2;return xt((t.x-t.y)*e,(t.x+t.y)*i).add(this.transform.pos)}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=this.worldToTile(t);return this.getTile(e.x,e.y)}_getMaxZIndex(){let t=Number.NEGATIVE_INFINITY;for(const e of this.tiles){const i=e.get(di).z;i>t&&(t=i)}return t}debug(t){t.save(),t.z=this._getMaxZIndex()+.5;for(let e=0;e<this.rows+1;e++){const i=this.tileToWorld(xt(0,e)),s=this.tileToWorld(xt(this.columns,e));t.drawLine(i,s,yt.Red,2)}for(let e=0;e<this.columns+1;e++){const i=this.tileToWorld(xt(e,0)),s=this.tileToWorld(xt(e,this.rows));t.drawLine(i,s,yt.Red,2)}for(const e of this.tiles)t.drawCircle(this.tileToWorld(xt(e.x,e.y)),3,yt.Yellow);t.restore()}}class ur{constructor(t,e){this._stopped=!1,this._sequenceBuilder=e,this._sequenceContext=new ys(t),this._actionQueue=this._sequenceContext.getQueue(),this._sequenceBuilder(this._sequenceContext)}update(t){this._actionQueue.update(t)}isComplete(){return this._stopped||this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._stopped=!1,this._actionQueue.reset()}clone(t){return new ur(t,this._sequenceBuilder)}}class pr{constructor(t){this._actions=t}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}isComplete(t){return this._actions.every((e=>e.isComplete(t)))}reset(){this._actions.forEach((t=>t.reset()))}stop(){this._actions.forEach((t=>t.stop()))}}function _r(t){return!!t._initialize}function gr(t){return!!t.onInitialize}function mr(t){return!!t._preupdate}function fr(t){return!!t.onPreUpdate}function vr(t){return!!t.onPostUpdate}function xr(t){return!!t.onPostUpdate}function yr(t){return!!t.onPreDraw}function wr(t){return!!t.onPostDraw}class br{constructor(t,e=yt.Magenta,i=!1){this.path=t,this.color=e,this._stream=null,this._gif=null,this._textures=[],this._animation=null,this._transparentColor=null,this._resource=new zt(t,"arraybuffer",i),this._transparentColor=e}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){const t=await this._resource.load();this._stream=new Sr(t),this._gif=new Tr(this._stream,this._transparentColor);const e=this._gif.images.map((t=>new Vt(t.src,!1)));return await Promise.all(e.map((t=>t.load()))),this.data=this._textures=e}isLoaded(){return!!this.data}toSprite(t=0){return this._textures[t].toSprite()}toSpriteSheet(){const t=this._textures.map((t=>t.toSprite()));return new qt({sprites:t})}toAnimation(t){const e=this.toSpriteSheet(),i=e.sprites.length;return this._animation=mn.fromSpriteSheet(e,gt(0,i),t),this._animation}get readCheckBytes(){return this._gif.checkBytes}}const Cr=t=>t.reduce((function(t,e){return 2*t+e}),0),Ar=t=>{const e=[];for(let i=7;i>=0;i--)e.push(!!(t&1<<i));return e};class Sr{constructor(t){if(this.data=null,this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=t=>{const e=[];for(let i=0;i<t;i++)e.push(this.readByte());return e},this.read=t=>{let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.readByte());return e},this.readUnsigned=()=>{const t=this.readBytes(2);return(t[1]<<8)+t[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,0===this.len)throw new Error("No data loaded from file")}}class Tr{constructor(t,e=yt.Magenta){this._st=null,this._handler={},this._transparentColor=null,this.frames=[],this.images=[],this.globalColorTable=[],this.checkBytes=[],this.parseColorTable=t=>{const e=[];for(let i=0;i<t;i++){const t="#"+this._st.readBytes(3).map((t=>{const e=t.toString(16);return 1===e.length?"0"+e:e})).join("");e.push(t)}return e},this.readSubBlocks=()=>{let t,e;e="";do{t=this._st.readByte(),e+=this._st.read(t)}while(0!==t);return e},this.parseHeader=()=>{const t={sig:null,ver:null,width:null,height:null,colorRes:null,globalColorTableSize:null,gctFlag:null,sorted:null,globalColorTable:[],bgColor:null,pixelAspectRatio:null};if(t.sig=this._st.read(3),t.ver=this._st.read(3),"GIF"!==t.sig)throw new Error("Not a GIF file.");t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Ar(this._st.readByte());t.gctFlag=e.shift(),t.colorRes=Cr(e.splice(0,3)),t.sorted=e.shift(),t.globalColorTableSize=Cr(e.splice(0,3)),t.bgColor=this._st.readByte(),t.pixelAspectRatio=this._st.readByte(),t.gctFlag&&(t.globalColorTable=this.parseColorTable(1<<t.globalColorTableSize+1),this.globalColorTable=t.globalColorTable),this._handler.hdr&&this._handler.hdr(t)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=t=>{const e=t=>{this.checkBytes.push(this._st.readByte());const e=Ar(this._st.readByte());t.reserved=e.splice(0,3),t.disposalMethod=Cr(e.splice(0,3)),t.userInput=e.shift(),t.transparencyGiven=e.shift(),t.delayTime=this._st.readUnsigned(),t.transparencyIndex=this._st.readByte(),t.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(t)&&this.checkBytes.push(this._handler.gce)},i=t=>{t.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(t)&&this.checkBytes.push(this._handler.com)},s=t=>{this.checkBytes.push(this._st.readByte()),t.ptHeader=this._st.readBytes(12),t.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(t)&&this.checkBytes.push(this._handler.pte)},n=t=>{const e=t=>{this.checkBytes.push(this._st.readByte()),t.unknown=this._st.readByte(),t.iterations=this._st.readUnsigned(),t.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(t)&&this.checkBytes.push(this._handler.app)},i=t=>{t.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[t.identifier]&&this._handler.app[t.identifier](t)&&this.checkBytes.push(this._handler.app[t.identifier])};if(this.checkBytes.push(this._st.readByte()),t.identifier=this._st.read(8),t.authCode=this._st.read(3),"NETSCAPE"===t.identifier)e(t);else i(t)},r=t=>{t.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(t)&&this.checkBytes.push(this._handler.unknown)};switch(t.label=this._st.readByte(),t.label){case 249:t.extType="gce",e(t);break;case 254:t.extType="com",i(t);break;case 1:t.extType="pte",s(t);break;case 255:t.extType="app",n(t);break;default:t.extType="unknown",r(t)}},this.parseImg=t=>{t.leftPos=this._st.readUnsigned(),t.topPos=this._st.readUnsigned(),t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Ar(this._st.readByte());t.lctFlag=e.shift(),t.interlaced=e.shift(),t.sorted=e.shift(),t.reserved=e.splice(0,2),t.lctSize=Cr(e.splice(0,3)),t.lctFlag&&(t.lct=this.parseColorTable(1<<t.lctSize+1)),t.lzwMinCodeSize=this._st.readByte();const i=this.readSubBlocks();t.pixels=function(t,e){let i=0;const s=function(t){let s=0;for(let n=0;n<t;n++)e.charCodeAt(i>>3)&1<<(7&i)&&(s|=1<<n),i++;return s},n=[],r=1<<t,o=r+1;let a=t+1,h=[];const l=function(){h=[],a=t+1;for(let t=0;t<r;t++)h[t]=[t];h[r]=[],h[o]=null};let c,d;for(;;)if(d=c,c=s(a),c!==r){if(c===o)break;if(c<h.length)d!==r&&h.push(h[d].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[d].concat(h[d][0]))}n.push.apply(n,h[c]),h.length===1<<a&&a<12&&a++}else l();return n}(t.lzwMinCodeSize,i),t.interlaced&&(t.pixels=((t,e)=>{const i=new Array(t.length),s=t.length/e,n=(s,n)=>{const r=t.slice(n*e,(n+1)*e);i.splice.apply(i,[s*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2];let a=0;for(let t=0;t<4;t++)for(let e=r[t];e<s;e+=o[t])n(e,a),a++;return i})(t.pixels,t.width)),this.frames.push(t),this.arrayToImage(t),this._handler.img&&this._handler.img(t)&&this.checkBytes.push(this._handler)},this.parseBlock=()=>{const t={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this._handler.eof&&this._handler.eof(t)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&this.parseBlock()},this.arrayToImage=t=>{let e=0;const i=document.createElement("canvas");i.id=e.toString(),i.width=t.width,i.height=t.height,e++;const s=i.getContext("2d");let n=0,r=0;for(let e=0;e<t.pixels.length;e++)r%t.width==0&&(n++,r=0),this.globalColorTable[t.pixels[e]]===this._transparentColor.toHex()?s.fillStyle="rgba(0, 0, 0, 0)":s.fillStyle=this.globalColorTable[t.pixels[e]],s.fillRect(r,n,1,1),r++;const o=new Image;o.src=i.toDataURL(),this.images.push(o)},this._st=t,this._handler={},this._transparentColor=e,this.parseHeader(),this.parseBlock()}}class Er extends Nt{constructor(t){super(),this.color=yt.Black,this.thickness=1;const{start:e,end:i,color:s,thickness:n}=t;this.start=e,this.end=i,this.color=null!=s?s:this.color,this.thickness=null!=n?n:this.thickness,this._localBounds=this._calculateBounds();const{width:r,height:o}=this._localBounds;this.width=r,this.height=o}get localBounds(){return this._localBounds}_calculateBounds(){const t=this.end.sub(this.start).normal(),e=this.thickness/2,i=[this.start.add(t.scale(e)),this.end.add(t.scale(e)),this.end.add(t.scale(-e)),this.start.add(t.scale(-e))];return At.fromPoints(i)}_drawImage(t,e,i){t.drawLine(this.start,this.end,this.color,this.thickness)}clone(){return new Er({start:this.start,end:this.end,color:this.color,thickness:this.thickness})}}class Pr extends Re{get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce(((t,e)=>Math.max(e.x,t)),0)-e.x,this.height=this._points.reduce(((t,e)=>Math.max(e.y,t)),0)-e.y,this.flagDirty()}get minPoint(){return xt(this._points.reduce(((t,e)=>Math.min(e.x,t)),1/0),this._points.reduce(((t,e)=>Math.min(e.y,t)),1/0))}constructor(t){super(t),this.points=t.points,this.filtering=Wt.Blended,this.rasterize()}clone(){return new Pr({points:this.points.map((t=>t.clone())),...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach((i=>{t.lineTo(i.x+e.x,i.y+e.y)})),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}class Ir{constructor(){this._queue=[]}get length(){return this._queue.length}enqueue(){const t=new St;return this._queue.push(t),t.promise}dequeue(t){this._queue.shift().resolve(t)}}class Dr{constructor(t){this._count=t,this._waitQueue=new Ir}get count(){return this._count}get waiting(){return this._waitQueue.length}async enter(){return 0!==this._count?(this._count--,Promise.resolve()):this._waitQueue.enqueue()}exit(t=1){if(0!==t){for(;0!==t&&0!==this._waitQueue.length;)this._waitQueue.dequeue(null),t--;this._count+=t}}}const Br="0.28.3";h()})(),s})()));
2
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ex=e():t.ex=e()}(self,(()=>(()=>{"use strict";var t={1388:(t,e,i)=>{i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n","",{version:3,sources:["webpack://./Loader.css"],names:[],mappings:"AAAA,yBAAyB;;AAEzB;EACE,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,kBAAkB;EAClB,YAAY;EACZ;;+BAE6B;EAC7B,8BAA8B;EAC9B,SAAS;EACT,qBAAqB;EACrB,mBAAmB;EACnB,cAAc;EACd,uBAAuB;EACvB,eAAe;EACf,mBAAmB;EACnB,cAAc;EACd,eAAe;EACf,kBAAkB;EAClB,8DAA8D;EAC9D,wBAAwB;EACxB,qBAAqB;;EAErB,gDAAgD,EAAE,oCAAoC;EACtF,6CAA6C,EAAE,iBAAiB;EAChE,4CAA4C,EAAE,sBAAsB;EACpE,2CAA2C,EAAE,iBAAiB;EAC9D,wCAAwC;AAC1C;;AAEA;;;EAGE;;AAEF;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,uDAAuD;EACvD,UAAU;EACV,SAAS;EACT,QAAQ;EACR,SAAS;AACX;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,WAAW;EACX,YAAY;AACd;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA;EACE,uBAAuB;EACvB,oBAAoB;AACtB;;AAEA;EACE,sBAAsB;AACxB;;AAEA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,oCAAoC;AACpC;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,sBAAsB;AACtB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF",sourcesContent:["/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n"],sourceRoot:""}]);const a=o},7379:(t,e,i)=>{i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"\n#ex-toast-container {\n position: absolute;\n height: 0;\n min-width: 50%;\n left: 50%;\n top: 0;\n}\n\n.ex-toast-message {\n left: -50%;\n position: relative;\n display: flex;\n justify-content: space-between;\n\n\n padding: 10px;\n margin-top: 5px;\n font-size: 18px;\n font-family: sans-serif;\n border-radius: 6px;\n border: 3px solid #b7b779;\n background-color: rgb(253, 253, 192);\n}\n\n\n.ex-toast-message button {\n align-self: flex-start;\n}","",{version:3,sources:["webpack://./Util/Toaster.css"],names:[],mappings:";AACA;EACE,kBAAkB;EAClB,SAAS;EACT,cAAc;EACd,SAAS;EACT,MAAM;AACR;;AAEA;EACE,UAAU;EACV,kBAAkB;EAClB,aAAa;EACb,8BAA8B;;;EAG9B,aAAa;EACb,eAAe;EACf,eAAe;EACf,uBAAuB;EACvB,kBAAkB;EAClB,yBAAyB;EACzB,oCAAoC;AACtC;;;AAGA;EACE,sBAAsB;AACxB",sourcesContent:["\n#ex-toast-container {\n position: absolute;\n height: 0;\n min-width: 50%;\n left: 50%;\n top: 0;\n}\n\n.ex-toast-message {\n left: -50%;\n position: relative;\n display: flex;\n justify-content: space-between;\n\n\n padding: 10px;\n margin-top: 5px;\n font-size: 18px;\n font-family: sans-serif;\n border-radius: 6px;\n border: 3px solid #b7b779;\n background-color: rgb(253, 253, 192);\n}\n\n\n.ex-toast-message button {\n align-self: flex-start;\n}"],sourceRoot:""}]);const a=o},2609:t=>{t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var i="",s=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),s&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),s&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i})).join("")},e.i=function(t,i,s,n,r){"string"==typeof t&&(t=[[null,t,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var h=this[a][0];null!=h&&(o[h]=!0)}for(var l=0;l<t.length;l++){var c=[].concat(t[l]);s&&o[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),n&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=n):c[4]="".concat(n)),e.push(c))}},e}},272:t=>{t.exports=function(t){var e=t[1],i=t[3];if(!i)return e;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),n="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),r="/*# ".concat(n," */");return[e].concat([r]).join("\n")}return[e].join("\n")}},1324:(t,e,i)=>{i(7206);var s=i(8193);t.exports=s("Array","sort")},3571:(t,e,i)=>{i(9867);var s=i(8588);t.exports=s.Object.keys},1052:(t,e,i)=>{var s=i(688),n=i(3397),r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not a function")}},9175:(t,e,i)=>{var s=i(5309),n=String,r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not an object")}},1138:(t,e,i)=>{var s=i(6854),n=i(7352),r=i(8344),o=function(t){return function(e,i,o){var a,h=s(e),l=r(h),c=n(o,l);if(t&&i!=i){for(;l>c;)if((a=h[c++])!=a)return!0}else for(;l>c;c++)if((t||c in h)&&h[c]===i)return t||c||0;return!t&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},567:(t,e,i)=>{var s=i(4694);t.exports=function(t,e){var i=[][t];return!!i&&s((function(){i.call(null,e||function(){return 1},1)}))}},6403:(t,e,i)=>{var s=i(7352),n=i(8344),r=i(3182),o=Array,a=Math.max;t.exports=function(t,e,i){for(var h=n(t),l=s(e,h),c=s(void 0===i?h:i,h),d=o(a(c-l,0)),u=0;l<c;l++,u++)r(d,u,t[l]);return d.length=u,d}},3097:(t,e,i)=>{var s=i(6403),n=Math.floor,r=function(t,e){var i=t.length,h=n(i/2);return i<8?o(t,e):a(t,r(s(t,0,h),e),r(s(t,h),e),e)},o=function(t,e){for(var i,s,n=t.length,r=1;r<n;){for(s=r,i=t[r];s&&e(t[s-1],i)>0;)t[s]=t[--s];s!==r++&&(t[s]=i)}return t},a=function(t,e,i,s){for(var n=e.length,r=i.length,o=0,a=0;o<n||a<r;)t[o+a]=o<n&&a<r?s(e[o],i[a])<=0?e[o++]:i[a++]:o<n?e[o++]:i[a++];return t};t.exports=r},2177:(t,e,i)=>{var s=i(9668),n=s({}.toString),r=s("".slice);t.exports=function(t){return r(n(t),8,-1)}},1566:(t,e,i)=>{var s=i(2522),n=i(688),r=i(2177),o=i(2032)("toStringTag"),a=Object,h="Arguments"===r(function(){return arguments}());t.exports=s?r:function(t){var e,i,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=a(t),o))?i:h?r(e):"Object"===(s=r(e))&&n(e.callee)?"Arguments":s}},3891:(t,e,i)=>{var s=i(4678),n=i(990),r=i(7537),o=i(2131);t.exports=function(t,e,i){for(var a=n(e),h=o.f,l=r.f,c=0;c<a.length;c++){var d=a[c];s(t,d)||i&&s(i,d)||h(t,d,l(e,d))}}},2385:(t,e,i)=>{var s=i(9924),n=i(2131),r=i(7781);t.exports=s?function(t,e,i){return n.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}},7781:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},3182:(t,e,i)=>{var s=i(2358),n=i(2131),r=i(7781);t.exports=function(t,e,i){var o=s(e);o in t?n.f(t,o,r(0,i)):t[o]=i}},2470:(t,e,i)=>{var s=i(688),n=i(2131),r=i(1135),o=i(1604);t.exports=function(t,e,i,a){a||(a={});var h=a.enumerable,l=void 0!==a.name?a.name:e;if(s(i)&&r(i,l,a),a.global)h?t[e]=i:o(e,i);else{try{a.unsafe?t[e]&&(h=!0):delete t[e]}catch(t){}h?t[e]=i:n.f(t,e,{value:i,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return t}},1604:(t,e,i)=>{var s=i(2150),n=Object.defineProperty;t.exports=function(t,e){try{n(s,t,{value:e,configurable:!0,writable:!0})}catch(i){s[t]=e}return e}},955:(t,e,i)=>{var s=i(3397),n=TypeError;t.exports=function(t,e){if(!delete t[e])throw new n("Cannot delete property "+s(e)+" of "+s(t))}},9924:(t,e,i)=>{var s=i(4694);t.exports=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}))},1811:t=>{var e="object"==typeof document&&document.all,i=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:i}},1442:(t,e,i)=>{var s=i(2150),n=i(5309),r=s.document,o=n(r)&&n(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},9016:(t,e,i)=>{var s=i(1370).match(/firefox\/(\d+)/i);t.exports=!!s&&+s[1]},821:(t,e,i)=>{var s=i(1370);t.exports=/MSIE|Trident/.test(s)},1370:t=>{t.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},7067:(t,e,i)=>{var s,n,r=i(2150),o=i(1370),a=r.process,h=r.Deno,l=a&&a.versions||h&&h.version,c=l&&l.v8;c&&(n=(s=c.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1])),!n&&o&&(!(s=o.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=o.match(/Chrome\/(\d+)/))&&(n=+s[1]),t.exports=n},4389:(t,e,i)=>{var s=i(1370).match(/AppleWebKit\/(\d+)\./);t.exports=!!s&&+s[1]},8193:(t,e,i)=>{var s=i(2150),n=i(9668);t.exports=function(t,e){return n(s[t].prototype[e])}},2367:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},5532:(t,e,i)=>{var s=i(2150),n=i(7537).f,r=i(2385),o=i(2470),a=i(1604),h=i(3891),l=i(1633);t.exports=function(t,e){var i,c,d,u,p,_=t.target,g=t.global,m=t.stat;if(i=g?s:m?s[_]||a(_,{}):(s[_]||{}).prototype)for(c in e){if(u=e[c],d=t.dontCallGetSet?(p=n(i,c))&&p.value:i[c],!l(g?c:_+(m?".":"#")+c,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;h(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0),o(i,c,u,t)}}},4694:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},6398:(t,e,i)=>{var s=i(4694);t.exports=!s((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},8724:(t,e,i)=>{var s=i(6398),n=Function.prototype.call;t.exports=s?n.bind(n):function(){return n.apply(n,arguments)}},453:(t,e,i)=>{var s=i(9924),n=i(4678),r=Function.prototype,o=s&&Object.getOwnPropertyDescriptor,a=n(r,"name"),h=a&&"something"===function(){}.name,l=a&&(!s||s&&o(r,"name").configurable);t.exports={EXISTS:a,PROPER:h,CONFIGURABLE:l}},9668:(t,e,i)=>{var s=i(6398),n=Function.prototype,r=n.call,o=s&&n.bind.bind(r,r);t.exports=s?o:function(t){return function(){return r.apply(t,arguments)}}},2160:(t,e,i)=>{var s=i(2150),n=i(688);t.exports=function(t,e){return arguments.length<2?(i=s[t],n(i)?i:void 0):s[t]&&s[t][e];var i}},5383:(t,e,i)=>{var s=i(1052),n=i(5268);t.exports=function(t,e){var i=t[e];return n(i)?void 0:s(i)}},2150:function(t,e,i){var s=function(t){return t&&t.Math===Math&&t};t.exports=s("object"==typeof globalThis&&globalThis)||s("object"==typeof window&&window)||s("object"==typeof self&&self)||s("object"==typeof i.g&&i.g)||s("object"==typeof this&&this)||function(){return this}()||Function("return this")()},4678:(t,e,i)=>{var s=i(9668),n=i(298),r=s({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return r(n(t),e)}},7390:t=>{t.exports={}},7913:(t,e,i)=>{var s=i(9924),n=i(4694),r=i(1442);t.exports=!s&&!n((function(){return 7!==Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},4347:(t,e,i)=>{var s=i(9668),n=i(4694),r=i(2177),o=Object,a=s("".split);t.exports=n((function(){return!o("z").propertyIsEnumerable(0)}))?function(t){return"String"===r(t)?a(t,""):o(t)}:o},1881:(t,e,i)=>{var s=i(9668),n=i(688),r=i(6762),o=s(Function.toString);n(r.inspectSource)||(r.inspectSource=function(t){return o(t)}),t.exports=r.inspectSource},7804:(t,e,i)=>{var s,n,r,o=i(4724),a=i(2150),h=i(5309),l=i(2385),c=i(4678),d=i(6762),u=i(1962),p=i(7390),_="Object already initialized",g=a.TypeError,m=a.WeakMap;if(o||d.state){var f=d.state||(d.state=new m);f.get=f.get,f.has=f.has,f.set=f.set,s=function(t,e){if(f.has(t))throw new g(_);return e.facade=t,f.set(t,e),e},n=function(t){return f.get(t)||{}},r=function(t){return f.has(t)}}else{var v=u("state");p[v]=!0,s=function(t,e){if(c(t,v))throw new g(_);return e.facade=t,l(t,v,e),e},n=function(t){return c(t,v)?t[v]:{}},r=function(t){return c(t,v)}}t.exports={set:s,get:n,has:r,enforce:function(t){return r(t)?n(t):s(t,{})},getterFor:function(t){return function(e){var i;if(!h(e)||(i=n(e)).type!==t)throw new g("Incompatible receiver, "+t+" required");return i}}}},688:(t,e,i)=>{var s=i(1811),n=s.all;t.exports=s.IS_HTMLDDA?function(t){return"function"==typeof t||t===n}:function(t){return"function"==typeof t}},1633:(t,e,i)=>{var s=i(4694),n=i(688),r=/#|\.prototype\./,o=function(t,e){var i=h[a(t)];return i===c||i!==l&&(n(e)?s(e):!!e)},a=o.normalize=function(t){return String(t).replace(r,".").toLowerCase()},h=o.data={},l=o.NATIVE="N",c=o.POLYFILL="P";t.exports=o},5268:t=>{t.exports=function(t){return null==t}},5309:(t,e,i)=>{var s=i(688),n=i(1811),r=n.all;t.exports=n.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:s(t)||t===r}:function(t){return"object"==typeof t?null!==t:s(t)}},6555:t=>{t.exports=!1},7935:(t,e,i)=>{var s=i(2160),n=i(688),r=i(6148),o=i(4866),a=Object;t.exports=o?function(t){return"symbol"==typeof t}:function(t){var e=s("Symbol");return n(e)&&r(e.prototype,a(t))}},8344:(t,e,i)=>{var s=i(7331);t.exports=function(t){return s(t.length)}},1135:(t,e,i)=>{var s=i(9668),n=i(4694),r=i(688),o=i(4678),a=i(9924),h=i(453).CONFIGURABLE,l=i(1881),c=i(7804),d=c.enforce,u=c.get,p=String,_=Object.defineProperty,g=s("".slice),m=s("".replace),f=s([].join),v=a&&!n((function(){return 8!==_((function(){}),"length",{value:8}).length})),x=String(String).split("String"),y=t.exports=function(t,e,i){"Symbol("===g(p(e),0,7)&&(e="["+m(p(e),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(e="get "+e),i&&i.setter&&(e="set "+e),(!o(t,"name")||h&&t.name!==e)&&(a?_(t,"name",{value:e,configurable:!0}):t.name=e),v&&i&&o(i,"arity")&&t.length!==i.arity&&_(t,"length",{value:i.arity});try{i&&o(i,"constructor")&&i.constructor?a&&_(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var s=d(t);return o(s,"source")||(s.source=f(x,"string"==typeof e?e:"")),t};Function.prototype.toString=y((function(){return r(this)&&u(this).source||l(this)}),"toString")},1787:t=>{var e=Math.ceil,i=Math.floor;t.exports=Math.trunc||function(t){var s=+t;return(s>0?i:e)(s)}},2131:(t,e,i)=>{var s=i(9924),n=i(7913),r=i(2666),o=i(9175),a=i(2358),h=TypeError,l=Object.defineProperty,c=Object.getOwnPropertyDescriptor,d="enumerable",u="configurable",p="writable";e.f=s?r?function(t,e,i){if(o(t),e=a(e),o(i),"function"==typeof t&&"prototype"===e&&"value"in i&&p in i&&!i[p]){var s=c(t,e);s&&s[p]&&(t[e]=i.value,i={configurable:u in i?i[u]:s[u],enumerable:d in i?i[d]:s[d],writable:!1})}return l(t,e,i)}:l:function(t,e,i){if(o(t),e=a(e),o(i),n)try{return l(t,e,i)}catch(t){}if("get"in i||"set"in i)throw new h("Accessors not supported");return"value"in i&&(t[e]=i.value),t}},7537:(t,e,i)=>{var s=i(9924),n=i(8724),r=i(8208),o=i(7781),a=i(6854),h=i(2358),l=i(4678),c=i(7913),d=Object.getOwnPropertyDescriptor;e.f=s?d:function(t,e){if(t=a(t),e=h(e),c)try{return d(t,e)}catch(t){}if(l(t,e))return o(!n(r.f,t,e),t[e])}},6217:(t,e,i)=>{var s=i(1528),n=i(2367).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return s(t,n)}},5168:(t,e)=>{e.f=Object.getOwnPropertySymbols},6148:(t,e,i)=>{var s=i(9668);t.exports=s({}.isPrototypeOf)},1528:(t,e,i)=>{var s=i(9668),n=i(4678),r=i(6854),o=i(1138).indexOf,a=i(7390),h=s([].push);t.exports=function(t,e){var i,s=r(t),l=0,c=[];for(i in s)!n(a,i)&&n(s,i)&&h(c,i);for(;e.length>l;)n(s,i=e[l++])&&(~o(c,i)||h(c,i));return c}},1728:(t,e,i)=>{var s=i(1528),n=i(2367);t.exports=Object.keys||function(t){return s(t,n)}},8208:(t,e)=>{var i={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor,n=s&&!i.call({1:2},1);e.f=n?function(t){var e=s(this,t);return!!e&&e.enumerable}:i},110:(t,e,i)=>{var s=i(8724),n=i(688),r=i(5309),o=TypeError;t.exports=function(t,e){var i,a;if("string"===e&&n(i=t.toString)&&!r(a=s(i,t)))return a;if(n(i=t.valueOf)&&!r(a=s(i,t)))return a;if("string"!==e&&n(i=t.toString)&&!r(a=s(i,t)))return a;throw new o("Can't convert object to primitive value")}},990:(t,e,i)=>{var s=i(2160),n=i(9668),r=i(6217),o=i(5168),a=i(9175),h=n([].concat);t.exports=s("Reflect","ownKeys")||function(t){var e=r.f(a(t)),i=o.f;return i?h(e,i(t)):e}},8588:(t,e,i)=>{var s=i(2150);t.exports=s},1166:(t,e,i)=>{var s=i(5268),n=TypeError;t.exports=function(t){if(s(t))throw new n("Can't call method on "+t);return t}},1962:(t,e,i)=>{var s=i(2645),n=i(5736),r=s("keys");t.exports=function(t){return r[t]||(r[t]=n(t))}},6762:(t,e,i)=>{var s=i(2150),n=i(1604),r="__core-js_shared__",o=s[r]||n(r,{});t.exports=o},2645:(t,e,i)=>{var s=i(6555),n=i(6762);(t.exports=function(t,e){return n[t]||(n[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.33.3",mode:s?"pure":"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.33.3/LICENSE",source:"https://github.com/zloirock/core-js"})},4112:(t,e,i)=>{var s=i(7067),n=i(4694),r=i(2150).String;t.exports=!!Object.getOwnPropertySymbols&&!n((function(){var t=Symbol("symbol detection");return!r(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&s&&s<41}))},7352:(t,e,i)=>{var s=i(1680),n=Math.max,r=Math.min;t.exports=function(t,e){var i=s(t);return i<0?n(i+e,0):r(i,e)}},6854:(t,e,i)=>{var s=i(4347),n=i(1166);t.exports=function(t){return s(n(t))}},1680:(t,e,i)=>{var s=i(1787);t.exports=function(t){var e=+t;return e!=e||0===e?0:s(e)}},7331:(t,e,i)=>{var s=i(1680),n=Math.min;t.exports=function(t){return t>0?n(s(t),9007199254740991):0}},298:(t,e,i)=>{var s=i(1166),n=Object;t.exports=function(t){return n(s(t))}},1272:(t,e,i)=>{var s=i(8724),n=i(5309),r=i(7935),o=i(5383),a=i(110),h=i(2032),l=TypeError,c=h("toPrimitive");t.exports=function(t,e){if(!n(t)||r(t))return t;var i,h=o(t,c);if(h){if(void 0===e&&(e="default"),i=s(h,t,e),!n(i)||r(i))return i;throw new l("Can't convert object to primitive value")}return void 0===e&&(e="number"),a(t,e)}},2358:(t,e,i)=>{var s=i(1272),n=i(7935);t.exports=function(t){var e=s(t,"string");return n(e)?e:e+""}},2522:(t,e,i)=>{var s={};s[i(2032)("toStringTag")]="z",t.exports="[object z]"===String(s)},599:(t,e,i)=>{var s=i(1566),n=String;t.exports=function(t){if("Symbol"===s(t))throw new TypeError("Cannot convert a Symbol value to a string");return n(t)}},3397:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},5736:(t,e,i)=>{var s=i(9668),n=0,r=Math.random(),o=s(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+o(++n+r,36)}},4866:(t,e,i)=>{var s=i(4112);t.exports=s&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},2666:(t,e,i)=>{var s=i(9924),n=i(4694);t.exports=s&&n((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},4724:(t,e,i)=>{var s=i(2150),n=i(688),r=s.WeakMap;t.exports=n(r)&&/native code/.test(String(r))},2032:(t,e,i)=>{var s=i(2150),n=i(2645),r=i(4678),o=i(5736),a=i(4112),h=i(4866),l=s.Symbol,c=n("wks"),d=h?l.for||l:l&&l.withoutSetter||o;t.exports=function(t){return r(c,t)||(c[t]=a&&r(l,t)?l[t]:d("Symbol."+t)),c[t]}},7206:(t,e,i)=>{var s=i(5532),n=i(9668),r=i(1052),o=i(298),a=i(8344),h=i(955),l=i(599),c=i(4694),d=i(3097),u=i(567),p=i(9016),_=i(821),g=i(7067),m=i(4389),f=[],v=n(f.sort),x=n(f.push),y=c((function(){f.sort(void 0)})),w=c((function(){f.sort(null)})),b=u("sort"),C=!c((function(){if(g)return g<70;if(!(p&&p>3)){if(_)return!0;if(m)return m<603;var t,e,i,s,n="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(s=0;s<47;s++)f.push({k:e+s,v:i})}for(f.sort((function(t,e){return e.v-t.v})),s=0;s<f.length;s++)e=f[s].k.charAt(0),n.charAt(n.length-1)!==e&&(n+=e);return"DGBEFHACIJK"!==n}}));s({target:"Array",proto:!0,forced:y||!w||!b||!C},{sort:function(t){void 0!==t&&r(t);var e=o(this);if(C)return void 0===t?v(e):v(e,t);var i,s,n=[],c=a(e);for(s=0;s<c;s++)s in e&&x(n,e[s]);for(d(n,function(t){return function(e,i){return void 0===i?-1:void 0===e?1:void 0!==t?+t(e,i)||0:l(e)>l(i)?1:-1}}(t)),i=a(n),s=0;s<i;)e[s]=n[s++];for(;s<c;)h(e,s++);return e}})},9867:(t,e,i)=>{var s=i(5532),n=i(298),r=i(1728);s({target:"Object",stat:!0,forced:i(4694)((function(){r(1)}))},{keys:function(t){return r(n(t))}})}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var r=e[s]={id:s,exports:{}};return t[s].call(r.exports,r,r.exports,i),r.exports}i.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return i.d(e,{a:e}),e},i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var s={};return(()=>{i.r(s),i.d(s,{ActionContext:()=>ws,ActionQueue:()=>Qi,ActionSequence:()=>pr,ActionsComponent:()=>bs,ActionsSystem:()=>Pn,ActivateEvent:()=>H,Actor:()=>Es,AddedComponent:()=>zi,AddedEntity:()=>Qs,AffineMatrix:()=>kt,Animation:()=>fn,AnimationDirection:()=>_n,AnimationEvents:()=>mn,AnimationStrategy:()=>gn,ArcadeSolver:()=>cn,AudioContextFactory:()=>Te,Axes:()=>j,Axis:()=>Us,BaseAlign:()=>rs,Blink:()=>gs,BodyComponent:()=>Li,BoundingBox:()=>At,BroadphaseStrategy:()=>ei,BrowserComponent:()=>Wn,BrowserEvents:()=>Gn,Buttons:()=>Y,Camera:()=>qs,CameraEvents:()=>Vs,Canvas:()=>ke,Circle:()=>Zi,CircleCollider:()=>Ei,Clock:()=>tr,ClosestLine:()=>Ti,ClosestLineJumpTable:()=>Si,Collider:()=>bi,ColliderComponent:()=>ki,CollisionContact:()=>Pi,CollisionEndEvent:()=>O,CollisionGroup:()=>gi,CollisionGroupManager:()=>_i,CollisionJumpTable:()=>Di,CollisionPostSolveEvent:()=>z,CollisionPreSolveEvent:()=>L,CollisionResolutionStrategy:()=>ti,CollisionStartEvent:()=>U,CollisionSystem:()=>pn,CollisionType:()=>Ze,Color:()=>yt,ColorBlindFlags:()=>Un,ColorBlindnessMode:()=>Mn,ColorBlindnessPostProcessor:()=>zn,Component:()=>li,CompositeCollider:()=>Ci,Configurable:()=>xn,ConsoleAppender:()=>tt,ContactConstraintPoint:()=>dn,ContactEndEvent:()=>M,ContactStartEvent:()=>k,CoordPlane:()=>si,DeactivateEvent:()=>W,Debug:()=>On,DebugGraphicsComponent:()=>Rs,DebugSystem:()=>Sn,DebugText:()=>Zt,DegreeOfFreedom:()=>Mi,Delay:()=>fs,Detector:()=>Ke,Die:()=>vs,Direction:()=>as,DisplayMode:()=>we,DynamicTree:()=>xi,DynamicTreeCollisionProcessor:()=>wi,EX_VERSION:()=>Rr,EaseBy:()=>_s,EaseTo:()=>ps,EasingFunctions:()=>ji,EdgeCollider:()=>Bi,ElasticToActorStrategy:()=>Hs,EmitterType:()=>yn,Engine:()=>hr,EngineEvents:()=>or,EnterTriggerEvent:()=>q,EnterViewPortEvent:()=>V,Entity:()=>Wi,EntityEvents:()=>Hi,EntityManager:()=>en,EventDispatcher:()=>lr,EventEmitter:()=>d,EventTypes:()=>a,Events:()=>t,ExResponse:()=>Me,ExcaliburGraphicsContext2DCanvas:()=>ye,ExcaliburGraphicsContextWebGL:()=>fe,ExitTriggerEvent:()=>X,ExitViewPortEvent:()=>G,Fade:()=>ms,Flags:()=>l,Follow:()=>xs,Font:()=>Ts,FontCache:()=>As,FontStyle:()=>os,FontUnit:()=>ss,FpsSampler:()=>Jn,FrameStats:()=>Nn,Future:()=>Tt,GameEvent:()=>u,GameStartEvent:()=>m,GameStopEvent:()=>f,Gamepad:()=>Z,GamepadAxisEvent:()=>I,GamepadButtonEvent:()=>P,GamepadConnectEvent:()=>S,GamepadDisconnectEvent:()=>E,Gamepads:()=>K,Gif:()=>Cr,GlobalCoordinates:()=>Vn,Graphic:()=>Ht,GraphicsComponent:()=>Xi,GraphicsGroup:()=>vn,GraphicsLayer:()=>Vi,GraphicsLayers:()=>qi,GraphicsSystem:()=>Tn,HiddenEvent:()=>B,ImageFiltering:()=>Gt,ImageSource:()=>qt,InitializeEvent:()=>N,Input:()=>r,InputMapper:()=>rr,Integrator:()=>ii,IsometricEntityComponent:()=>In,IsometricEntitySystem:()=>Dn,IsometricMap:()=>ur,IsometricTile:()=>dr,KeyEvent:()=>st,Keyboard:()=>nt,Keys:()=>$,KillEvent:()=>p,Label:()=>cr,LimitCameraBoundsStrategy:()=>Gs,Line:()=>Pr,LineSegment:()=>Ai,Loader:()=>qe,LoaderEvents:()=>Ve,LockCameraToActorAxisStrategy:()=>Ns,LockCameraToActorStrategy:()=>Os,LogLevel:()=>Q,Logger:()=>J,Material:()=>pe,Matrix:()=>Ft,MatrixLocations:()=>Ct,MediaEvent:()=>Ue,Meet:()=>ys,MotionComponent:()=>pi,MotionSystem:()=>ln,MoveBy:()=>ts,MoveTo:()=>es,NativePointerButton:()=>Yn,NativeSoundEvent:()=>Oe,NativeSoundProcessedEvent:()=>Ne,Observable:()=>di,OffscreenSystem:()=>Bn,Pair:()=>mi,ParallaxComponent:()=>Bs,ParallelActions:()=>_r,ParseGif:()=>Er,Particle:()=>Cn,ParticleEmitter:()=>An,ParticleTransform:()=>wn,Physics:()=>ri,PhysicsStats:()=>Hn,PhysicsWorld:()=>Rn,PointerButton:()=>jn,PointerComponent:()=>Yi,PointerEvent:()=>qn,PointerEventReceiver:()=>$n,PointerScope:()=>rt,PointerSystem:()=>En,PointerType:()=>Qn,Polygon:()=>Ir,PolygonCollider:()=>Ri,Pool:()=>de,PostCollisionEvent:()=>F,PostDebugDrawEvent:()=>w,PostDrawEvent:()=>x,PostFrameEvent:()=>T,PostKillEvent:()=>g,PostUpdateEvent:()=>C,PreCollisionEvent:()=>R,PreDebugDrawEvent:()=>y,PreDrawEvent:()=>v,PreFrameEvent:()=>A,PreKillEvent:()=>_,PreUpdateEvent:()=>b,Projection:()=>fi,QuadIndexBuffer:()=>ae,QuadTree:()=>Fs,Query:()=>nn,QueryManager:()=>rn,RadiusAroundActorStrategy:()=>Ws,Random:()=>at,Raster:()=>Fe,Ray:()=>yi,RealisticSolver:()=>un,Rectangle:()=>Ki,RemovedComponent:()=>Oi,RemovedEntity:()=>Js,Repeat:()=>$i,RepeatForever:()=>Ji,Resolution:()=>be,Resource:()=>Ut,ResourceEvents:()=>zt,RotateBy:()=>ls,RotateTo:()=>hs,RotationType:()=>is,ScaleBy:()=>ds,ScaleTo:()=>cs,Scene:()=>kn,SceneEvents:()=>Fn,Screen:()=>Ae,ScreenAppender:()=>et,ScreenElement:()=>Is,ScreenEvents:()=>Ce,ScreenShader:()=>Ln,ScrollPreventionMode:()=>ar,Semaphore:()=>Br,Shader:()=>te,Shape:()=>Fi,Side:()=>bt,Sound:()=>Ge,SoundEvents:()=>We,Sprite:()=>Wt,SpriteFont:()=>Kt,SpriteSheet:()=>Xt,StandardClock:()=>er,StateMachine:()=>Le,StrategyContainer:()=>zs,Stream:()=>Sr,System:()=>js,SystemManager:()=>on,SystemType:()=>Ys,TagComponent:()=>ci,TestClock:()=>ir,Text:()=>Ss,TextAlign:()=>ns,TextureLoader:()=>Vt,Tile:()=>Ls,TileMap:()=>Ms,TileMapEvents:()=>ks,Timer:()=>Ds,Toaster:()=>nr,Transform:()=>hi,TransformComponent:()=>ui,TreeNode:()=>vi,Trigger:()=>Zs,TriggerEvents:()=>Xs,TwoPI:()=>ht,Util:()=>o,Vector:()=>vt,VectorView:()=>oi,VertexBuffer:()=>ee,VertexLayout:()=>ie,VisibleEvent:()=>D,WebAudio:()=>Se,WebAudioInstance:()=>ze,WheelDeltaMode:()=>Zn,WheelEvent:()=>Xn,World:()=>an,canonicalizeAngle:()=>ut,clamp:()=>dt,createId:()=>c,frac:()=>lt,hasGraphicsTick:()=>Gi,hasOnInitialize:()=>mr,hasOnPostUpdate:()=>yr,hasOnPreUpdate:()=>vr,hasPostDraw:()=>br,hasPreDraw:()=>wr,has_initialize:()=>gr,has_postupdate:()=>xr,has_preupdate:()=>fr,isAddedComponent:()=>Ui,isAddedSystemEntity:()=>$s,isRemoveSystemEntity:()=>tn,isRemovedComponent:()=>Ni,isScreenElement:()=>Ps,maxMessages:()=>Ye,obsolete:()=>Je,pixelSnapEpsilon:()=>ge,randomInRange:()=>mt,randomIntInRange:()=>ft,range:()=>gt,resetObsoleteCounter:()=>Qe,sign:()=>ct,toDegrees:()=>pt,toRadians:()=>_t,vec:()=>xt,webgl:()=>e});var t={};i.r(t),i.d(t,{ActivateEvent:()=>H,CollisionEndEvent:()=>O,CollisionPostSolveEvent:()=>z,CollisionPreSolveEvent:()=>L,CollisionStartEvent:()=>U,ContactEndEvent:()=>M,ContactStartEvent:()=>k,DeactivateEvent:()=>W,EnterTriggerEvent:()=>q,EnterViewPortEvent:()=>V,EventTypes:()=>a,ExitTriggerEvent:()=>X,ExitViewPortEvent:()=>G,GameEvent:()=>u,GameStartEvent:()=>m,GameStopEvent:()=>f,GamepadAxisEvent:()=>I,GamepadButtonEvent:()=>P,GamepadConnectEvent:()=>S,GamepadDisconnectEvent:()=>E,HiddenEvent:()=>B,InitializeEvent:()=>N,KillEvent:()=>p,PostCollisionEvent:()=>F,PostDebugDrawEvent:()=>w,PostDrawEvent:()=>x,PostFrameEvent:()=>T,PostKillEvent:()=>g,PostUpdateEvent:()=>C,PreCollisionEvent:()=>R,PreDebugDrawEvent:()=>y,PreDrawEvent:()=>v,PreFrameEvent:()=>A,PreKillEvent:()=>_,PreUpdateEvent:()=>b,VisibleEvent:()=>D});var e={};i.r(e),i.d(e,{getAttributeComponentSize:()=>$t,getAttributePointerType:()=>Jt,getGlTypeSizeBytes:()=>Qt});var n={};i.r(n),i.d(n,{circle:()=>Be,line:()=>Ee,point:()=>Pe,roundRect:()=>De,vector:()=>Ie});var r={};i.r(r),i.d(r,{Axes:()=>j,Buttons:()=>Y,Gamepad:()=>Z,Gamepads:()=>K,KeyEvent:()=>st,Keyboard:()=>nt,Keys:()=>$,NativePointerButton:()=>Yn,PointerButton:()=>jn,PointerComponent:()=>Yi,PointerEvent:()=>qn,PointerEventReceiver:()=>$n,PointerScope:()=>rt,PointerSystem:()=>En,PointerType:()=>Qn,WheelDeltaMode:()=>Zn,WheelEvent:()=>Xn});var o={};i.r(o),i.d(o,{ConsoleAppender:()=>tt,DrawUtil:()=>n,EasingFunctions:()=>ji,LogLevel:()=>Q,Logger:()=>J,Observable:()=>di,ScreenAppender:()=>et,addItemToArray:()=>Et,contains:()=>It,delay:()=>Bt,fail:()=>Dt,getPosition:()=>St,omit:()=>Rt,removeItemFromArray:()=>Pt});var a;i(1324),i(3571);function h(){if("undefined"==typeof window&&(window={audioContext:function(){}}),"undefined"==typeof window||window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){window.setInterval(t,1e3/60)}),"undefined"==typeof window||window.cancelAnimationFrame||(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),"undefined"!=typeof window&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise(((i,s)=>{t.call(this,e,i,s)}))}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}"undefined"==typeof window||window.devicePixelRatio||(window.devicePixelRatio=window.devicePixelRatio||1)}class l{static useCanvasGraphicsContext(){l.enable("use-canvas-context")}static freeze(){l._FROZEN=!0}static _reset(){l._FROZEN=!1,l._FLAGS={}}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");l._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");l._FLAGS[t]=!1}static isEnabled(t){return!!l._FLAGS[t]}static show(){return Object.keys(l._FLAGS)}}function c(t,e){return{type:t,value:e}}l._FROZEN=!1,l._FLAGS={};class d{constructor(){this._paused=!1,this._listeners={},this._listenersOnce={},this._pipes=[]}clear(){this._listeners={},this._listenersOnce={},this._pipes.length=0}on(t,e){var i;return this._listeners[t]=null!==(i=this._listeners[t])&&void 0!==i?i:[],this._listeners[t].push(e),{close:()=>this.off(t,e)}}once(t,e){var i;return this._listenersOnce[t]=null!==(i=this._listenersOnce[t])&&void 0!==i?i:[],this._listenersOnce[t].push(e),{close:()=>this.off(t,e)}}off(t,e){var i,s;if(e){const n=null===(i=this._listeners[t])||void 0===i?void 0:i.filter((t=>t!==e));this._listeners[t]=n;const r=null===(s=this._listenersOnce[t])||void 0===s?void 0:s.filter((t=>t!==e));this._listenersOnce[t]=r}else delete this._listeners[t]}emit(t,e){var i;if(this._paused)return;null===(i=this._listeners[t])||void 0===i||i.forEach((t=>t(e)));const s=this._listenersOnce[t];this._listenersOnce[t]=[],s&&s.forEach((t=>t(e))),this._pipes.forEach((i=>{i.emit(t,e)}))}pipe(t){if(this===t)throw Error("Cannot pipe to self");return this._pipes.push(t),{close:()=>{const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}}}unpipe(t){const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}pause(){this._paused=!0}unpause(){this._paused=!1}}!function(t){t.Kill="kill",t.PreKill="prekill",t.PostKill="postkill",t.PreDraw="predraw",t.PostDraw="postdraw",t.PreDebugDraw="predebugdraw",t.PostDebugDraw="postdebugdraw",t.PreUpdate="preupdate",t.PostUpdate="postupdate",t.PreFrame="preframe",t.PostFrame="postframe",t.PreCollision="precollision",t.CollisionStart="collisionstart",t.CollisionEnd="collisionend",t.PostCollision="postcollision",t.Initialize="initialize",t.Activate="activate",t.Deactivate="deactivate",t.ExitViewport="exitviewport",t.EnterViewport="enterviewport",t.ExitTrigger="exit",t.EnterTrigger="enter",t.Connect="connect",t.Disconnect="disconnect",t.Button="button",t.Axis="axis",t.Visible="visible",t.Hidden="hidden",t.Start="start",t.Stop="stop",t.PointerUp="pointerup",t.PointerDown="pointerdown",t.PointerMove="pointermove",t.PointerEnter="pointerenter",t.PointerLeave="pointerleave",t.PointerCancel="pointercancel",t.PointerWheel="pointerwheel",t.Up="up",t.Down="down",t.Move="move",t.Enter="enter",t.Leave="leave",t.Cancel="cancel",t.Wheel="wheel",t.Press="press",t.Release="release",t.Hold="hold",t.PointerDragStart="pointerdragstart",t.PointerDragEnd="pointerdragend",t.PointerDragEnter="pointerdragenter",t.PointerDragLeave="pointerdragleave",t.PointerDragMove="pointerdragmove"}(a||(a={}));class u{constructor(){this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class p extends u{constructor(t){super(),this.target=t}}class _ extends u{constructor(t){super(),this.target=t}}class g extends u{constructor(t){super(),this.target=t}}class m extends u{constructor(t){super(),this.target=t}}class f extends u{constructor(t){super(),this.target=t}}class v extends u{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class x extends u{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class y extends u{constructor(t,e){super(),this.ctx=t,this.target=e}}class w extends u{constructor(t,e){super(),this.ctx=t,this.target=e}}class b extends u{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class C extends u{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class A extends u{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class T extends u{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class S extends u{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class E extends u{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class P extends u{constructor(t,e,i){super(),this.button=t,this.value=e,this.target=i}}class I extends u{constructor(t,e,i){super(),this.axis=t,this.value=e,this.target=i}}class D extends u{constructor(t){super(),this.target=t}}class B extends u{constructor(t){super(),this.target=t}}class R extends u{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}}class F extends u{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class k{constructor(t,e,i){this.target=t,this.other=e,this.contact=i}}class M{constructor(t,e){this.target=t,this.other=e}}class L{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class z{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class U extends u{constructor(t,e,i){super(),this.other=e,this.contact=i,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class O extends u{constructor(t,e){super(),this.other=e,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class N extends u{constructor(t,e){super(),this.engine=t,this.target=e}}class H extends u{constructor(t,e){super(),this.context=t,this.target=e}}class W extends u{constructor(t,e){super(),this.context=t,this.target=e}}class G extends u{constructor(t){super(),this.target=t}}class V extends u{constructor(t){super(),this.target=t}}class q extends u{constructor(t,e){super(),this.target=t,this.actor=e}}class X extends u{constructor(t,e){super(),this.target=t,this.actor=e}}class K{constructor(){this.events=new d,this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter((t=>void 0!==typeof t)).length,i=t.buttons.filter((t=>void 0!==typeof t)).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}emit(t,e){this.events.emit(t,e)}on(t,e){return this._enableAndUpdate(),this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this._enableAndUpdate(),this.events.off(t,e)}update(){if(!this.enabled||!this.supported)return;this.init();const t=this._navigator.getGamepads();for(let e=0;e<t.length;e++){if(!t[e]){const t=this.at(e);t.connected&&this.events.emit("disconnect",new E(e,t)),t.connected=!1;continue}if(!this.at(e).connected&&this._isGamepadValid(t[e])&&this.events.emit("connect",new S(e,this.at(e))),this.at(e).connected=!0,this.at(e).update(),t[e].timestamp&&t[e].timestamp===this._gamePadTimeStamps[e])continue;let i,s,n,r,o;for(i in this._gamePadTimeStamps[e]=t[e].timestamp,this.at(e).navigatorGamepad=t[e],Y)s=Y[i],"number"==typeof s&&t[e].buttons[s]&&(o=t[e].buttons[s].value,o!==this._oldPads[e].getButton(s)&&(t[e].buttons[s].pressed?(this.at(e).updateButton(s,o),this.at(e).events.emit("button",new P(s,o,this.at(e)))):this.at(e).updateButton(s,0)));for(n in j)r=j[n],"number"==typeof r&&(o=t[e].axes[r],o!==this._oldPads[e].getAxes(r)&&(this.at(e).updateAxes(r,o),this.at(e).events.emit("axis",new I(r,o,this.at(e)))));this._oldPads[e]=this._clonePad(t[e])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new Z),this._oldPads.push(new Z);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter((t=>t.connected)).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new Z;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}K.MinAxisMoveThreshold=.05;class Z{constructor(){this.events=new d,this.connected=!1,this._axes=new Array(4),this._buttons=new Array(16),this._buttonsUp=new Array(16),this._buttonsDown=new Array(16);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}update(){this._buttonsDown=new Array(16),this._buttonsUp=new Array(16)}isButtonPressed(t,e=1){return this._buttons[t]>=e}isButtonHeld(t,e=1){return this._buttons[t]>=e}wasButtonPressed(t,e=1){return this._buttonsDown[t]>=e}wasButtonReleased(t){return Boolean(this._buttonsUp[t])}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<K.MinAxisMoveThreshold?0:e}updateButton(t,e){0===e&&this._buttons[t]?this._buttonsUp[t]=1:this._buttonsDown[t]=e,this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var Y,j,Q,$;!function(t){t[t.Face1=0]="Face1",t[t.Face2=1]="Face2",t[t.Face3=2]="Face3",t[t.Face4=3]="Face4",t[t.LeftBumper=4]="LeftBumper",t[t.RightBumper=5]="RightBumper",t[t.LeftTrigger=6]="LeftTrigger",t[t.RightTrigger=7]="RightTrigger",t[t.Select=8]="Select",t[t.Start=9]="Start",t[t.LeftStick=10]="LeftStick",t[t.RightStick=11]="RightStick",t[t.DpadUp=12]="DpadUp",t[t.DpadDown=13]="DpadDown",t[t.DpadLeft=14]="DpadLeft",t[t.DpadRight=15]="DpadRight"}(Y||(Y={})),function(t){t[t.LeftStickX=0]="LeftStickX",t[t.LeftStickY=1]="LeftStickY",t[t.RightStickX=2]="RightStickX",t[t.RightStickY=3]="RightStickY"}(j||(j={})),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"}(Q||(Q={}));class J{constructor(){if(this._appenders=[],this.defaultLevel=Q.Info,J._INSTANCE)throw new Error("Logger is a singleton");return J._INSTANCE=this,J._INSTANCE.addAppender(new tt),J._INSTANCE}static getInstance(){return null==J._INSTANCE&&(J._INSTANCE=new J),J._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){null==t&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}debug(...t){this._log(Q.Debug,t)}info(...t){this._log(Q.Info,t)}warn(...t){this._log(Q.Warn,t)}error(...t){this._log(Q.Error,t)}fatal(...t){this._log(Q.Fatal,t)}}J._INSTANCE=null;class tt{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+Q[t]+"] : "),t<Q.Warn?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<Q.Error?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class et{constructor(t,e){this._messages=[],this._canvas=document.createElement("canvas"),this._canvas.width=t||window.innerWidth,this._canvas.height=e||window.innerHeight,this._canvas.style.position="absolute",this._ctx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._messages.unshift("["+Q[t]+"] : "+i);let s=10,n=1;for(let t=0;t<this._messages.length;t++)this._ctx.fillStyle="rgba(255,255,255,"+n.toFixed(2)+")",this._ctx.fillText(this._messages[t],200,s),s+=10,n=n>0?n-.05:0}}function it(){try{const t=()=>{};window.top.addEventListener("blur",t),window.top.removeEventListener("blur",t)}catch(t){return!0}return!1}!function(t){t.Num0="Numpad0",t.Num1="Numpad1",t.Num2="Numpad2",t.Num3="Numpad3",t.Num4="Numpad4",t.Num5="Numpad5",t.Num6="Numpad6",t.Num7="Numpad7",t.Num8="Numpad8",t.Num9="Numpad9",t.NumAdd="NumpadAdd",t.NumSubtract="NumpadSubtract",t.NumMultiply="NumpadMultiply",t.NumDivide="NumpadDivide",t.NumDecimal="NumpadDecimal",t.Numpad0="Numpad0",t.Numpad1="Numpad1",t.Numpad2="Numpad2",t.Numpad3="Numpad3",t.Numpad4="Numpad4",t.Numpad5="Numpad5",t.Numpad6="Numpad6",t.Numpad7="Numpad7",t.Numpad8="Numpad8",t.Numpad9="Numpad9",t.NumpadAdd="NumpadAdd",t.NumpadSubtract="NumpadSubtract",t.NumpadMultiply="NumpadMultiply",t.NumpadDivide="NumpadDivide",t.NumpadDecimal="NumpadDecimal",t.NumLock="NumLock",t.ShiftLeft="ShiftLeft",t.ShiftRight="ShiftRight",t.AltLeft="AltLeft",t.AltRight="AltRight",t.ControlLeft="ControlLeft",t.ControlRight="ControlRight",t.MetaLeft="MetaLeft",t.MetaRight="MetaRight",t.Key0="Digit0",t.Key1="Digit1",t.Key2="Digit2",t.Key3="Digit3",t.Key4="Digit4",t.Key5="Digit5",t.Key6="Digit6",t.Key7="Digit7",t.Key8="Digit8",t.Key9="Digit9",t.Digit0="Digit0",t.Digit1="Digit1",t.Digit2="Digit2",t.Digit3="Digit3",t.Digit4="Digit4",t.Digit5="Digit5",t.Digit6="Digit6",t.Digit7="Digit7",t.Digit8="Digit8",t.Digit9="Digit9",t.F1="F1",t.F2="F2",t.F3="F3",t.F4="F4",t.F5="F5",t.F6="F6",t.F7="F7",t.F8="F8",t.F9="F9",t.F10="F10",t.F11="F11",t.F12="F12",t.A="KeyA",t.B="KeyB",t.C="KeyC",t.D="KeyD",t.E="KeyE",t.F="KeyF",t.G="KeyG",t.H="KeyH",t.I="KeyI",t.J="KeyJ",t.K="KeyK",t.L="KeyL",t.M="KeyM",t.N="KeyN",t.O="KeyO",t.P="KeyP",t.Q="KeyQ",t.R="KeyR",t.S="KeyS",t.T="KeyT",t.U="KeyU",t.V="KeyV",t.W="KeyW",t.X="KeyX",t.Y="KeyY",t.Z="KeyZ",t.KeyA="KeyA",t.KeyB="KeyB",t.KeyC="KeyC",t.KeyD="KeyD",t.KeyE="KeyE",t.KeyF="KeyF",t.KeyG="KeyG",t.KeyH="KeyH",t.KeyI="KeyI",t.KeyJ="KeyJ",t.KeyK="KeyK",t.KeyL="KeyL",t.KeyM="KeyM",t.KeyN="KeyN",t.KeyO="KeyO",t.KeyP="KeyP",t.KeyQ="KeyQ",t.KeyR="KeyR",t.KeyS="KeyS",t.KeyT="KeyT",t.KeyU="KeyU",t.KeyV="KeyV",t.KeyW="KeyW",t.KeyX="KeyX",t.KeyY="KeyY",t.KeyZ="KeyZ",t.Semicolon="Semicolon",t.Quote="Quote",t.Comma="Comma",t.Minus="Minus",t.Period="Period",t.Slash="Slash",t.Equal="Equal",t.BracketLeft="BracketLeft",t.Backslash="Backslash",t.BracketRight="BracketRight",t.Backquote="Backquote",t.Up="ArrowUp",t.Down="ArrowDown",t.Left="ArrowLeft",t.Right="ArrowRight",t.ArrowUp="ArrowUp",t.ArrowDown="ArrowDown",t.ArrowLeft="ArrowLeft",t.ArrowRight="ArrowRight",t.Space="Space",t.Backspace="Backspace",t.Delete="Delete",t.Esc="Escape",t.Escape="Escape",t.Enter="Enter",t.NumpadEnter="NumpadEnter",t.ContextMenu="ContextMenu"}($||($={}));class st extends u{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class nt{constructor(){this.events=new d,this._keys=[],this._keysUp=[],this._keysDown=[],this._releaseAllKeys=t=>{for(const e of this._keys){const i=new st(e,t.key,t);this.events.emit("up",i),this.events.emit("release",i)}this._keysUp=Array.from(new Set(this._keys.concat(this._keysUp))),this._keys.length=0},this._handleKeyDown=t=>{t.metaKey||!this._keys.includes($.MetaLeft)&&!this._keys.includes($.MetaRight)||this._releaseAllKeys(t);const e=t.code;if(-1===this._keys.indexOf(e)){this._keys.push(e),this._keysDown.push(e);const i=new st(e,t.key,t);this.events.emit("down",i),this.events.emit("press",i)}},this._handleKeyUp=t=>{const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new st(e,t.key,t);this.events.emit("up",s),this.events.emit("release",s),"Meta"===t.key&&this._releaseAllKeys(t)}}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}init(t){let{global:e}=t;const{grabWindowFocus:i}=t;e||(it()?(e=window,i&&window.focus(),J.getInstance().warn("Excalibur might be in a cross-origin iframe, in order to receive keyboard events it must be in focus")):e=window.top),e.addEventListener("blur",(()=>{this._keys.length=0})),e.addEventListener("keyup",this._handleKeyUp),e.addEventListener("keydown",this._handleKeyDown)}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.events.emit("hold",new st(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._keysDown.indexOf(t)>-1}isHeld(t){return this._keys.indexOf(t)>-1}wasReleased(t){return this._keysUp.indexOf(t)>-1}triggerEvent(t,e,i){"down"===t&&this._handleKeyDown(new KeyboardEvent("keydown",{code:e,key:null!=i?i:null})),"up"===t&&this._handleKeyUp(new KeyboardEvent("keyup",{code:e,key:null!=i?i:null}))}}var rt;!function(t){t.Canvas="Canvas",t.Document="Document"}(rt||(rt={}));const ot=4294967295;class at{constructor(t){this.seed=t,this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Date.now())>>>0;for(let t=1;t<this._n;t++){const e=this._mt[t-1]^this._mt[t-1]>>>this._w-2;this._mt[t]=(this._f*((4294901760&e)>>>16)<<16)+this._f*(65535&e)+t>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[1&e]&ot;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[1&e]&ot;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[1&e]&ot,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const t=this.integer(0,n.length-1);i[s++]=n[t],n.splice(t,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i=null;for(let t=0;t<e.length-2;t++){const s=this.integer(t,e.length-1);i=e[t],e[t]=e[s],e[s]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}}const ht=2*Math.PI;function lt(t){return t>=0?t-Math.floor(t):t-Math.ceil(t)}function ct(t){return 0===t?0:t<0?-1:1}function dt(t,e,i){return Math.min(Math.max(e,t),i)}function ut(t){let e=t;if(t>ht)for(;e>ht;)e-=ht;if(t<0)for(;e<0;)e+=ht;return e}function pt(t){return 180/Math.PI*t}function _t(t){return t/180*Math.PI}const gt=(t,e)=>Array.from(new Array(e-t+1),((e,i)=>i+t));function mt(t,e,i=new at){return i?i.floating(t,e):t+Math.random()*(e-t)}function ft(t,e,i=new at){return i?i.integer(t,e):Math.round(mt(t,e))}class vt{static get Zero(){return new vt(0,0)}static get One(){return new vt(1,1)}static get Half(){return new vt(.5,.5)}static get Up(){return new vt(0,-1)}static get Down(){return new vt(0,1)}static get Left(){return new vt(-1,0)}static get Right(){return new vt(1,0)}static fromAngle(t){return new vt(Math.cos(t),Math.sin(t))}static isValid(t){return null!=t&&(!isNaN(t.x)&&!isNaN(t.y)&&(t.x!==1/0&&t.y!==1/0&&t.x!==-1/0&&t.y!==-1/0))}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}static min(t,e){return new vt(Math.min(t.x,e.x),Math.min(t.y,e.y))}static max(t,e){return new vt(Math.max(t.x,e.x),Math.max(t.y,e.y))}constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=.001){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){if(!t)return Math.sqrt(this.x*this.x+this.y*this.y);const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}squareDistance(t){t||(t=vt.Zero);const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}clampMagnitude(t){const e=dt(this.size,0,t);return this.size=e,this}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}normalize(){const t=this.distance();return t>0?new vt(this.x/t,this.y/t):new vt(0,1)}average(t){return this.add(t).scale(.5)}scale(t,e){const i=e||new vt(0,0);return t instanceof vt?(i.x=this.x*t.x,i.y=this.y*t.y):(i.x=this.x*t,i.y=this.y*t),i}add(t,e){return e?(e.x=this.x+t.x,e.y=this.y+t.y,e):new vt(this.x+t.x,this.y+t.y)}sub(t){return new vt(this.x-t.x,this.y-t.y)}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return t instanceof vt?this.x*t.y-this.y*t.x:"number"==typeof t?new vt(t*this.y,-t*this.x):void 0}static cross(t,e){return new vt(-t*e.y,t*e.x)}perpendicular(){return new vt(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Math.atan2(this.y,this.x)}rotate(t,e){e||(e=new vt(0,0));const i=Math.sin(t),s=Math.cos(t),n=s*(this.x-e.x)-i*(this.y-e.y)+e.x,r=i*(this.x-e.x)+s*(this.y-e.y)+e.y;return new vt(n,r)}clone(t){const e=null!=t?t:new vt(0,0);return e.x=this.x,e.y=this.y,e}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}}function xt(t,e){return new vt(t,e)}class yt{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=null!=s?s:1}static fromRGB(t,e,i,s){return new yt(t,e,i,s)}static fromRGBString(t){let e=null;if(e=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i)){const t=parseInt(e[1],10),i=parseInt(e[2],10),s=parseInt(e[3],10);let n=1;return e[4]&&(n=parseFloat(e[4])),new yt(t,i,s,n)}throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){let e=null;if(e=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i)){const t=parseInt(e[1],16),i=parseInt(e[2],16),s=parseInt(e[3],16);let n=1;return e[4]&&(n=parseInt(e[4],16)/255),new yt(t,i,s,n)}throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new wt(t,e,i,s).toRGBA()}lighten(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=wt.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new yt(e,i,s,n)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new yt(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new yt(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=t.toString(16);return 1===e.length?"0"+e:e}toHex(){return"#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b)}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return void 0!==this.a||null!==this.a?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return wt.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(){return new yt(this.r,this.g,this.b,this.a)}static get Black(){return yt.fromHex("#000000")}static get White(){return yt.fromHex("#FFFFFF")}static get Gray(){return yt.fromHex("#808080")}static get LightGray(){return yt.fromHex("#D3D3D3")}static get DarkGray(){return yt.fromHex("#A9A9A9")}static get Yellow(){return yt.fromHex("#FFFF00")}static get Orange(){return yt.fromHex("#FFA500")}static get Red(){return yt.fromHex("#FF0000")}static get Vermilion(){return yt.fromHex("#FF5B31")}static get Rose(){return yt.fromHex("#FF007F")}static get Magenta(){return yt.fromHex("#FF00FF")}static get Violet(){return yt.fromHex("#7F00FF")}static get Blue(){return yt.fromHex("#0000FF")}static get Azure(){return yt.fromHex("#007FFF")}static get Cyan(){return yt.fromHex("#00FFFF")}static get Viridian(){return yt.fromHex("#59978F")}static get Green(){return yt.fromHex("#00FF00")}static get Chartreuse(){return yt.fromHex("#7FFF00")}static get Transparent(){return yt.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return yt.fromHex("#176BAA")}}class wt{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4}o/=6}return new wt(o,a,h,s)}toRGBA(){let t,e,i;if(0===this.s)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=wt.hue2rgb(n,s,this.h+1/3),e=wt.hue2rgb(n,s,this.h),i=wt.hue2rgb(n,s,this.h-1/3)}return new yt(255*t,255*e,255*i,this.a)}toString(){return`hsla(${this.h.toFixed(0)}, ${this.s.toFixed(0)}, ${this.l.toFixed(0)}, ${this.a.toFixed(0)})`}}var bt,Ct;!function(t){t.None="None",t.Top="Top",t.Bottom="Bottom",t.Left="Left",t.Right="Right"}(bt||(bt={})),function(t){t.getOpposite=function(e){return e===t.Top?t.Bottom:e===t.Bottom?t.Top:e===t.Left?t.Right:e===t.Right?t.Left:t.None},t.fromDirection=function(e){const i=[vt.Left,vt.Right,vt.Up,vt.Down],s=[t.Left,t.Right,t.Top,t.Bottom];let n=-Number.MAX_VALUE,r=-1;for(let t=0;t<i.length;t++)i[t].dot(e)>n&&(n=i[t].dot(e),r=t);return s[r]}}(bt||(bt={}));class At{constructor(t=0,e=0,i=0,s=0){"object"==typeof t?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):"number"==typeof t&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}clone(){return new At(this.left,this.top,this.right,this.bottom)}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?bt.Right:bt.Left:t.y<0?bt.Bottom:bt.Top:bt.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let r=0;r<t.length;r++)t[r].x<e&&(e=t[r].x),t[r].x>s&&(s=t[r].x),t[r].y<i&&(i=t[r].y),t[r].y>n&&(n=t[r].y);return new At(e,i,s,n)}static fromDimension(t,e,i=vt.Half,s=vt.Zero){return new At(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return 0===this.width||0===this.height}get center(){return new vt((this.left+this.right)/2,(this.top+this.bottom)/2)}translate(t){return new At(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=vt.Zero){const i=this.getPoints().map((i=>i.rotate(t,e)));return At.fromPoints(i)}scale(t,e=vt.Zero){const i=this.translate(e);return new At(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=t.data[0]*this.left,i=t.data[1]*this.left,s=t.data[0]*this.right,n=t.data[1]*this.right,r=t.data[2]*this.top,o=t.data[3]*this.top,a=t.data[2]*this.bottom,h=t.data[3]*this.bottom,l=t.getPosition(),c=Math.min(e,s)+Math.min(r,a)+l.x,d=Math.min(i,n)+Math.min(o,h)+l.y,u=Math.max(e,s)+Math.max(r,a)+l.x,p=Math.max(i,n)+Math.max(o,h)+l.y;return new At({left:c,top:d,right:u,bottom:p})}getPerimeter(){return 2*(this.width+this.height)}getPoints(){const t=[];return t.push(new vt(this.left,this.top)),t.push(new vt(this.right,this.top)),t.push(new vt(this.right,this.bottom)),t.push(new vt(this.left,this.bottom)),t}rayCast(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e}rayCastTime(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e?i:-1}contains(t){return t instanceof vt?this.left<=t.x&&this.top<=t.y&&this.bottom>=t.y&&this.right>=t.x:t instanceof At&&(this.left<=t.left&&this.top<=t.top&&t.bottom<=this.bottom&&t.right<=this.right)}combine(t){return new At(Math.min(this.left,t.left),Math.min(this.top,t.top),Math.max(this.right,t.right),Math.max(this.bottom,t.bottom))}get dimensions(){return new vt(this.width,this.height)}overlaps(t,e){const i=e||0;if(t.hasZeroDimensions())return this.contains(t);if(this.hasZeroDimensions())return t.contains(this);const s=this.combine(t);return s.width+i<t.width+this.width&&s.height+i<t.height+this.height}intersect(t){const e=this.combine(t);if(e.width<t.width+this.width&&e.height<t.height+this.height&&!e.dimensions.equals(t.dimensions)&&!e.dimensions.equals(this.dimensions)){let e=0;e=this.right>=t.left&&this.right<=t.right?t.left-this.right:t.right-this.left;let i=0;return i=this.top<=t.bottom&&this.top>=t.top?t.bottom-this.top:t.top-this.bottom,Math.abs(e)<Math.abs(i)?new vt(e,0):new vt(0,i)}if(e.dimensions.equals(t.dimensions)||e.dimensions.equals(this.dimensions)){let e=0;e=this.width-t.width>=0?this.right-t.right<=t.left-this.left?t.left-this.right:t.right-this.left:t.right-this.right<=this.left-t.left?this.left-t.right:this.right-t.left;let i=0;return i=this.height-t.height>=0?this.bottom-t.bottom<=t.top-this.top?t.top-this.bottom:t.bottom-this.top:t.bottom-this.bottom<=this.top-t.top?this.top-t.bottom:this.bottom-t.top,Math.abs(e)<Math.abs(i)?new vt(e,0):new vt(0,i)}return null}intersectWithSide(t){const e=this.intersect(t);return At.getSideFromIntersection(e)}draw(t,e=yt.Yellow){t.debug.drawRect(this.left,this.top,this.width,this.height,{color:e})}}class Tt{constructor(){this._isCompleted=!1,this.promise=new Promise(((t,e)=>{this._resolver=t,this._rejecter=e}))}get isCompleted(){return this._isCompleted}resolve(t){this._isCompleted||(this._isCompleted=!0,this._resolver(t))}reject(t){this._isCompleted||(this._isCompleted=!0,this._rejecter(t))}}function St(t){let e=0,i=0;const s=t=>{e+=t.offsetLeft,t.offsetParent&&s(t.offsetParent)},n=t=>{i+=t.offsetTop,t.offsetParent&&n(t.offsetParent)};return s(t),n(t),new vt(e,i)}function Et(t,e){return-1===e.indexOf(t)&&(e.push(t),!0)}function Pt(t,e){let i=-1;return(i=e.indexOf(t))>-1&&(e.splice(i,1),!0)}function It(t,e){for(let i=0;i<t.length;i++)if(t[i]===e)return!0;return!1}function Dt(t){throw new Error(t)}function Bt(t,e){var i;const s=new Tt;return(null!==(i=null==e?void 0:e.schedule.bind(e))&&void 0!==i?i:setTimeout)((()=>{s.resolve()}),t),s.promise}function Rt(t,e){const i={};for(const s in t)e.includes(s)||(i[s]=t[s]);return i}!function(t){t[t.X=12]="X",t[t.Y=13]="Y"}(Ct||(Ct={}));class Ft{constructor(){this.data=new Float32Array(16),this._scaleX=1,this._scaleSignX=1,this._scaleY=1,this._scaleSignY=1}static ortho(t,e,i,s,n,r){const o=new Ft;return o.data[0]=2/(e-t),o.data[1]=0,o.data[2]=0,o.data[3]=0,o.data[4]=0,o.data[5]=2/(s-i),o.data[6]=0,o.data[7]=0,o.data[8]=0,o.data[9]=0,o.data[10]=-2/(r-n),o.data[11]=0,o.data[12]=-(e+t)/(e-t),o.data[13]=-(s+i)/(s-i),o.data[14]=-(r+n)/(r-n),o.data[15]=1,o}clone(t){const e=t||new Ft;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e.data[6]=this.data[6],e.data[7]=this.data[7],e.data[8]=this.data[8],e.data[9]=this.data[9],e.data[10]=this.data[10],e.data[11]=this.data[11],e.data[12]=this.data[12],e.data[13]=this.data[13],e.data[14]=this.data[14],e.data[15]=this.data[15],e}toDOMMatrix(){return new DOMMatrix([...this.data])}static fromFloat32Array(t){const e=new Ft;return e.data=t,e}static identity(){const t=new Ft;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=Ft.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=Ft.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=Ft.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multiply(t,e){if(t instanceof vt){const i=e||new vt(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[4]+this.data[12],r=s.x*this.data[1]+s.y*this.data[5]+this.data[13];return i.x=n,i.y=r,i}{const i=e||new Ft,s=t,n=this.data[0],r=this.data[1],o=this.data[2],a=this.data[3],h=this.data[4],l=this.data[5],c=this.data[6],d=this.data[7],u=this.data[8],p=this.data[9],_=this.data[10],g=this.data[11],m=this.data[12],f=this.data[13],v=this.data[14],x=this.data[15],y=s.data[0],w=s.data[1],b=s.data[2],C=s.data[3],A=s.data[4],T=s.data[5],S=s.data[6],E=s.data[7],P=s.data[8],I=s.data[9],D=s.data[10],B=s.data[11],R=s.data[12],F=s.data[13],k=s.data[14],M=s.data[15];i.data[0]=n*y+h*w+u*b+m*C,i.data[1]=r*y+l*w+p*b+f*C,i.data[2]=o*y+c*w+_*b+v*C,i.data[3]=a*y+d*w+g*b+x*C,i.data[4]=n*A+h*T+u*S+m*E,i.data[5]=r*A+l*T+p*S+f*E,i.data[6]=o*A+c*T+_*S+v*E,i.data[7]=a*A+d*T+g*S+x*E,i.data[8]=n*P+h*I+u*D+m*B,i.data[9]=r*P+l*I+p*D+f*B,i.data[10]=o*P+c*I+_*D+v*B,i.data[11]=a*P+d*I+g*D+x*B,i.data[12]=n*R+h*F+u*k+m*M,i.data[13]=r*R+l*F+p*k+f*M,i.data[14]=o*R+c*F+_*k+v*M,i.data[15]=a*R+d*F+g*k+x*M;const L=this.getScale();return i._scaleSignX=ct(L.x)*ct(i._scaleSignX),i._scaleSignY=ct(L.y)*ct(i._scaleSignY),i}}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],_=this.data[12],g=this.data[13],m=this.data[14],f=this.data[15];return this.data[12]=i*t+o*e+0*c+1*_,this.data[13]=s*t+a*e+0*d+1*g,this.data[14]=n*t+h*e+0*u+1*m,this.data[15]=r*t+l*e+0*p+1*f,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return xt(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=this.data[4],o=this.data[5],a=this.data[6],h=this.data[7],l=Math.sin(t),c=Math.cos(t);return this.data[0]=c*e+l*r,this.data[1]=c*i+l*o,this.data[2]=c*s+l*a,this.data[3]=c*n+l*h,this.data[4]=c*r-l*e,this.data[5]=c*o-l*i,this.data[6]=c*a-l*s,this.data[7]=c*h-l*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=r*t,this.data[4]=o*e,this.data[5]=a*e,this.data[6]=h*e,this.data[7]=l*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){return ut(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=xt(this.data[0],this.data[4]).size;return this._scaleSignX*t}getScaleY(){const t=xt(this.data[1],this.data[5]).size;return this._scaleSignY*t}getScale(){return xt(this.getScaleX(),this.getScaleY())}setScaleX(t){if(this._scaleX===t)return;this._scaleSignX=ct(t);const e=xt(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t,this._scaleX=t}setScaleY(t){if(this._scaleY===t)return;this._scaleSignY=ct(t);const e=xt(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t,this._scaleY=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(t){const e=1/this.getBasisDeterminant(),i=this.data[0],s=this.data[4],n=this.data[1],r=this.data[5],o=t||Ft.identity();o.data[0]=r*e,o.data[1]=-n*e,o.data[4]=-s*e,o.data[5]=i*e;const a=this.data[12],h=this.data[13];return o.data[12]=-(a*o.data[0]+h*o.data[4]),o.data[13]=-(a*o.data[1]+h*o.data[5]),o}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&0===this.data[3]&&0===this.data[4]&&1===this.data[5]&&0===this.data[6]&&0===this.data[7]&&0===this.data[8]&&0===this.data[9]&&1===this.data[10]&&0===this.data[11]&&0===this.data[12]&&0===this.data[13]&&0===this.data[14]&&1===this.data[15]}toString(){return`\n[${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]\n[${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]\n[${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]\n[${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]\n`}}class kt{constructor(){this.data=new Float64Array(6),this._scale=new Float64Array([1,1]),this._scaleSignX=1,this._scaleSignY=1}toDOMMatrix(){return new DOMMatrix([...this.data])}static identity(){const t=new kt;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}static translation(t,e){const i=kt.identity();return i.data[4]=t,i.data[5]=e,i}static scale(t,e){const i=kt.identity();return i.data[0]=t,i.data[3]=e,i._scale[0]=t,i._scale[1]=e,i}static rotation(t){const e=kt.identity();return e.data[0]=Math.cos(t),e.data[1]=Math.sin(t),e.data[2]=-Math.sin(t),e.data[3]=Math.cos(t),e}setPosition(t,e){this.data[4]=t,this.data[5]=e}getPosition(){return xt(this.data[4],this.data[5])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=Math.sin(t),o=Math.cos(t);return this.data[0]=o*e+r*s,this.data[1]=o*i+r*n,this.data[2]=o*s-r*e,this.data[3]=o*n-r*i,this}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5];return this.data[4]=i*t+n*e+o,this.data[5]=s*t+r*e+a,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*e,this.data[3]=r*e,this._scale[0]=t,this._scale[1]=e,this}determinant(){return this.data[0]*this.data[3]-this.data[1]*this.data[2]}inverse(t){const e=1/this.determinant(),i=this.data[0],s=this.data[2],n=this.data[1],r=this.data[3],o=t||kt.identity();o.data[0]=r*e,o.data[1]=-n*e,o.data[2]=-s*e,o.data[3]=i*e;const a=this.data[4],h=this.data[5];return o.data[4]=-(a*o.data[0]+h*o.data[2]),o.data[5]=-(a*o.data[1]+h*o.data[3]),o}multiply(t,e){if(t instanceof vt){const i=e||new vt(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[2]+this.data[4],r=s.x*this.data[1]+s.y*this.data[3]+this.data[5];return i.x=n,i.y=r,i}{const i=e||new kt,s=t,n=this.data[0],r=this.data[1],o=this.data[2],a=this.data[3],h=this.data[4],l=this.data[5],c=s.data[0],d=s.data[1],u=s.data[2],p=s.data[3],_=s.data[4],g=s.data[5];i.data[0]=n*c+o*d,i.data[1]=r*c+a*d,i.data[2]=n*u+o*p,i.data[3]=r*u+a*p,i.data[4]=n*_+o*g+h,i.data[5]=r*_+a*g+l;const m=this.getScale();return i._scaleSignX=ct(m.x)*ct(i._scaleSignX),i._scaleSignY=ct(m.y)*ct(i._scaleSignY),i}}to4x4(){const t=new Ft;return t.data[0]=this.data[0],t.data[1]=this.data[1],t.data[2]=0,t.data[3]=0,t.data[4]=this.data[2],t.data[5]=this.data[3],t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=this.data[4],t.data[13]=this.data[5],t.data[14]=0,t.data[15]=1,t}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[2]=-i*e.x,this.data[3]=s*e.y}getRotation(){return ut(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=xt(this.data[0],this.data[2]).distance();return this._scaleSignX*t}getScaleY(){const t=xt(this.data[1],this.data[3]).distance();return this._scaleSignY*t}getScale(){return xt(this.getScaleX(),this.getScaleY())}setScaleX(t){if(t===this._scale[0])return;this._scaleSignX=ct(t);const e=xt(this.data[0]*this._scaleSignX,this.data[2]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[2]=e.y*t,this._scale[0]=t}setScaleY(t){if(t===this._scale[1])return;this._scaleSignY=ct(t);const e=xt(this.data[1]*this._scaleSignY,this.data[3]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[3]=e.y*t,this._scale[1]=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&1===this.data[3]&&0===this.data[4]&&0===this.data[5]}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}clone(t){const e=t||new kt;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e}toString(){return`\n[${this.data[0]} ${this.data[2]} ${this.data[4]}]\n[${this.data[1]} ${this.data[3]} ${this.data[5]}]\n[0 0 1]\n`}}class Mt{constructor(){this._transforms=[],this._currentTransform=kt.identity()}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone()}restore(){this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class Lt{constructor(){this._states=[],this._currentState=this._getDefaultState()}_getDefaultState(){return{opacity:1,z:0,tint:yt.White,material:null}}_cloneState(){return{opacity:this._currentState.opacity,z:this._currentState.z,tint:this._currentState.tint.clone(),material:this._currentState.material}}save(){this._states.push(this._currentState),this._currentState=this._cloneState()}restore(){this._currentState=this._states.pop()}get current(){return this._currentState}set current(t){this._currentState=t}}const zt={Complete:"complete",Load:"load",LoadStart:"loadstart",Progress:"progress",Error:"error"};class Ut{constructor(t,e,i=!1){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=J.getInstance(),this.events=new d}isLoaded(){return null!==this.data}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise(((t,e)=>{if(null!==this.data)return this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),void t(this.data);const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",(t=>this.events.emit("loadstart",t))),i.addEventListener("progress",(t=>this.events.emit("progress",t))),i.addEventListener("error",(t=>this.events.emit("error",t))),i.addEventListener("load",(t=>this.events.emit("load",t))),i.addEventListener("load",(()=>{if(0!==i.status&&200!==i.status)return this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),void e(new Error(i.statusText));this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)})),i.send()}))}}function Ot(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]!==s&&(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t)),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}function Nt(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}class Ht{isStale(){return this._transformStale}get flipHorizontal(){return this._flipHorizontal}set flipHorizontal(t){this._flipHorizontal=t,this._transformStale=!0}get flipVertical(){return this._flipVertical}set flipVertical(t){this._flipVertical=t,this._transformStale=!0}get rotation(){return this._rotation}set rotation(t){this._rotation=t,this._transformStale=!0}get scale(){return this._scale}set scale(t){this._scale=Ot(t,(()=>{this._transformStale=!0})),this._transformStale=!0}get origin(){return this._origin}set origin(t){this._origin=Ot(t,(()=>{this._transformStale=!0})),this._transformStale=!0}constructor(t){var e,i,s,n,r,o,a;this.id=Ht._ID++,this.transform=kt.identity(),this.tint=null,this._transformStale=!0,this.showDebug=!1,this._flipHorizontal=!1,this._flipVertical=!1,this._rotation=0,this.opacity=1,this._scale=vt.One,this._origin=null,this._width=0,this._height=0,t&&(this.origin=null!==(e=t.origin)&&void 0!==e?e:this.origin,this.flipHorizontal=null!==(i=t.flipHorizontal)&&void 0!==i?i:this.flipHorizontal,this.flipVertical=null!==(s=t.flipVertical)&&void 0!==s?s:this.flipVertical,this.rotation=null!==(n=t.rotation)&&void 0!==n?n:this.rotation,this.opacity=null!==(r=t.opacity)&&void 0!==r?r:this.opacity,this.scale=null!==(o=t.scale)&&void 0!==o?o:this.scale,this.tint=null!==(a=t.tint)&&void 0!==a?a:this.tint)}cloneGraphicOptions(){return{width:this.width/this.scale.x,height:this.height/this.scale.y,origin:this.origin?this.origin.clone():null,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():null,tint:this.tint?this.tint.clone():null}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t,this._transformStale=!0}set height(t){this._height=t,this._transformStale=!0}get localBounds(){return At.fromDimension(this.width,this.height,vt.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),this._transformStale&&(this.transform.reset(),this.transform.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(this.transform),this._flip(this.transform),this._transformStale=!1),t.multiply(this.transform),t.opacity=t.opacity*this.opacity,this.tint&&(t.tint=this.tint)}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=null!==(e=this.origin)&&void 0!==e?e:xt(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}Ht._ID=0;class Wt extends Ht{static from(t){return new Wt({image:t})}constructor(t){var e,i;super(t),this._logger=J.getInstance(),this._dirty=!0,this._logNotLoadedWarning=!1,this.image=t.image;const{width:s,height:n}=t;this.sourceView=null!==(e=t.sourceView)&&void 0!==e?e:{x:0,y:0,width:null!=s?s:0,height:null!=n?n:0},this.destSize=null!==(i=t.destSize)&&void 0!==i?i:{width:null!=s?s:0,height:null!=n?n:0},this._updateSpriteDimensions(),this.image.ready.then((()=>{this._updateSpriteDimensions()}))}get width(){return Math.abs(this.destSize.width*this.scale.x)}get height(){return Math.abs(this.destSize.height*this.scale.y)}set width(t){t/=Math.abs(this.scale.x),this.destSize.width=t,super.width=Math.ceil(this.destSize.width)}set height(t){t/=Math.abs(this.scale.y),this.destSize.height=t,super.height=Math.ceil(this.destSize.height)}_updateSpriteDimensions(){var t,e,i,s,n,r;const{width:o,height:a}=this.image;this.sourceView.width=(null===(t=this.sourceView)||void 0===t?void 0:t.width)||o,this.sourceView.height=(null===(e=this.sourceView)||void 0===e?void 0:e.height)||a,this.destSize.width=(null===(i=this.destSize)||void 0===i?void 0:i.width)||(null===(s=this.sourceView)||void 0===s?void 0:s.width)||o,this.destSize.height=(null===(n=this.destSize)||void 0===n?void 0:n.height)||(null===(r=this.sourceView)||void 0===r?void 0:r.height)||a,this.width=Math.ceil(this.destSize.width)*this.scale.x,this.height=Math.ceil(this.destSize.height)*this.scale.y}_preDraw(t,e,i){this.image.isLoaded()&&this._dirty&&(this._dirty=!1,this._updateSpriteDimensions()),super._preDraw(t,e,i)}_drawImage(t,e,i){this.image.isLoaded()?t.drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,e,i,this.destSize.width,this.destSize.height):(this._logNotLoadedWarning||this._logger.warn(`ImageSource ${this.image.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.\n\nRead https://excaliburjs.com/docs/imagesource for more information.`),this._logNotLoadedWarning=!0)}clone(){return new Wt({image:this.image,sourceView:{...this.sourceView},destSize:{...this.destSize},...this.cloneGraphicOptions()})}}var Gt;!function(t){t.Pixel="Pixel",t.Blended="Blended"}(Gt||(Gt={}));class Vt{constructor(t){this._textureMap=new Map,this._gl=t,Vt._MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE)}get(t){return this._textureMap.get(t)}has(t){return this._textureMap.has(t)}load(t,e,i=!1){const s=this._gl;if(!s)return null;let n=null;if(this.has(t)&&(n=this.get(t)),n)return i&&(s.bindTexture(s.TEXTURE_2D,n),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t)),n;n=s.createTexture(),Vt.checkImageSizeSupportedAndLog(t),s.bindTexture(s.TEXTURE_2D,n),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);const r=null!=e?e:Vt.filtering;return s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,r===Gt.Pixel?s.NEAREST:s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,r===Gt.Pixel?s.NEAREST:s.LINEAR),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t),this._textureMap.set(t,n),n}delete(t){const e=this._gl;if(!e)return null;let i=null;this.has(t)&&(i=this.get(t),e.deleteTexture(i))}static checkImageSizeSupportedAndLog(t){var e;const i=null!==(e=t.dataset.originalSrc)&&void 0!==e?e:"internal canvas bitmap";return t.width>Vt._MAX_TEXTURE_SIZE||t.height>Vt._MAX_TEXTURE_SIZE?(Vt._LOGGER.error(`The image [${i}] provided to Excalibur is too large for the device's maximum texture size of (${Vt._MAX_TEXTURE_SIZE}x${Vt._MAX_TEXTURE_SIZE}) please resize to an image for excalibur to render properly.\n\nImages will likely render as black rectangles.\n\nRead more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!1):((t.width>4096||t.height>4096)&&Vt._LOGGER.warn(`The image [${i}] provided to excalibur is too large may not work on all mobile devices, it is recommended you resize images to a maximum (4096x4096).\n\nImages will likely render as black rectangles on some mobile platforms.\n\nRead more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!0)}}Vt._LOGGER=J.getInstance(),Vt.filtering=Gt.Blended,Vt._MAX_TEXTURE_SIZE=4096;class qt{get width(){return this.image.naturalWidth}get height(){return this.image.naturalHeight}isLoaded(){return this._src||(this._src=this.data.src),!!this._src}get image(){return this.data}constructor(t,e=!1,i){this.path=t,this._logger=J.getInstance(),this.data=new Image,this._readyFuture=new Tt,this.ready=this._readyFuture.promise,this._resource=new Ut(t,"blob",e),this.filtering=i,(t.endsWith(".svg")||t.endsWith(".gif"))&&this._logger.warn(`Image type is not fully supported, you may have mixed results ${t}. Fully supported: jpg, bmp, and png`)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){if(this.isLoaded())return this.data;try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=await this._resource.load();t=URL.createObjectURL(e)}const e=new Image,i=new Tt;e.onload=()=>i.resolve(),e.src=t,e.setAttribute("data-original-src",this.path),await i.promise,this.data=e,Vt.checkImageSizeSupportedAndLog(this.data)}catch(t){throw`Error loading ImageSource from path '${this.path}' with error [${t.message}]`}return this.data.setAttribute("filtering",this.filtering),this._readyFuture.resolve(this.data),this.data}toSprite(){return Wt.from(this)}unload(){this.data=new Image}}class Xt{constructor(t){this._logger=J.getInstance(),this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=null!=i?i:1,this.columns=null!=s?s:this.sprites.length}getSprite(t,e){if(t>=this.columns||t<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1}`),null;if(e>=this.rows||e<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1}`),null;const i=t+e*this.columns;return this.sprites[i]}static fromImageSourceWithSourceViews(t){const e=t.sourceViews.map((e=>new Wt({image:t.image,sourceView:e})));return new Xt({sprites:e})}static fromImageSource(t){var e;const i=[];t.spacing=null!==(e=t.spacing)&&void 0!==e?e:{};const{image:s,grid:{rows:n,columns:r,spriteWidth:o,spriteHeight:a},spacing:{originOffset:h,margin:l}}=t,c={x:0,y:0,...h},d={x:0,y:0,...l};for(let t=0;t<r;t++)for(let e=0;e<n;e++)i[t+e*r]=new Wt({image:s,sourceView:{x:t*o+d.x*t+c.x,y:e*a+d.y*e+c.y,width:o,height:a},destSize:{height:a,width:o}});return new Xt({sprites:i,rows:n,columns:r})}clone(){return new Xt({sprites:this.sprites.map((t=>t.clone())),rows:this.rows,columns:this.columns})}}class Kt extends Ht{constructor(t){super(t),this._text="",this.alphabet="",this.shadow=null,this.caseInsensitive=!1,this.spacing=0,this._logger=J.getInstance(),this._alreadyWarnedAlphabet=!1,this._alreadyWarnedSpriteSheet=!1;const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:r}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=null!=s?s:this.caseInsensitive,this.spacing=null!=n?n:this.spacing,this.shadow=null!=r?r:this.shadow}_getCharacterSprites(t){const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let t=0;t<i.length;t++){const n=i[t];let r=s.indexOf(n);-1===r&&(r=0,this._alreadyWarnedAlphabet||(this._logger.warn(`SpriteFont - Cannot find letter '${n}' in configured alphabet '${s}'.`),this._logger.warn("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."),this._alreadyWarnedAlphabet=!0));const o=this.spriteSheet.sprites[r];o?e.push(o):this._alreadyWarnedSpriteSheet||(this._logger.warn(`SpriteFont - Cannot find sprite for '${n}' at index '${r}' in configured SpriteSheet`),this._logger.warn("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."),this._alreadyWarnedSpriteSheet=!0)}return e}measureText(t,e){const i=this._getLinesFromText(t,e),s=i.reduce(((t,e)=>t.length>e.length?t:e)),n=this._getCharacterSprites(s);let r=0,o=0;for(const t of n)r+=t.width+this.spacing,o=Math.max(o,t.height);return At.fromDimension(r,o*i.length,vt.Zero)}_drawImage(t,e,i,s){let n=0,r=0,o=0;const a=this._getLinesFromText(this._text,s);for(const s of a){for(const a of this._getCharacterSprites(s))a.draw(t,e+n,i+r),n+=a.width+this.spacing,o=Math.max(o,a.height);n=0,r+=o}}render(t,e,i,s,n,r){this._text=e;const o=this.measureText(e,r);this.width=o.width,this.height=o.height,this.shadow&&(t.save(),t.translate(this.shadow.offset.x,this.shadow.offset.y),this._preDraw(t,s,n),this._drawImage(t,0,0,r),this._postDraw(t),t.restore()),this._preDraw(t,s,n),this._drawImage(t,0,0,r),this._postDraw(t)}clone(){return new Kt({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}_getLinesFromText(t,e){if(this._cachedText===t&&this._cachedRenderWidth===e)return this._cachedLines;const i=t.split("\n");if(null==e)return i;for(let t=0;t<i.length;t++){let s=i[t],n="";if(this.measureText(s).width>e){for(;this.measureText(s).width>e;)n=s[s.length-1]+n,s=s.slice(0,-1);i[t]=s,i[t+1]=n}}return this._cachedText=t,this._cachedLines=i,this._cachedRenderWidth=e,i}}class Zt{constructor(){this.fontSheet="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABACAYAAAD1Xam+AAAAAXNSR0IArs4c6QAABlFJREFUeJztndmy4yoMRcWt/v9fdr8EWoDAaDD4JntVpeqcxBrMIGQDNhEAAAAAAAAAAAAAAOCrSbMfr+u6yoEpTY+906GV57YtPkjyXj9WZZ+wHWHfo2N3/bU6Tte9Rv6ptruqRyMvKvvIX/zY3I/vjLeqsg6l/CWdp0KHKO/1Y1H2EdsR9j06Ntdfp+N03SvkH2u7i3pu5XkQ+DNTkgNJSok+/183xpcdWZHjgUzpQ2pGD67vaf//KRAGAq3tdhCy2tcMQKPyXyz7iPqrdBjbX5h9g7xbtvWf4ZJvM4D/BKG24Sd+IkQ0TC9aW5NM5FbO2HgrPVzW2vmN50DZNv/QWtl5bfPy85SBtdy9dFmjsf2F2SehTBVE+u+tkE5+lAGcJlFwGuodwRRU2Qe3rx0FhPNflc3HWC7BEh8EDGVR5IMCiLnDONtPp87qhxVH/S/LvzUAuDs/kyGimA5oSONKR1w8vsLpv+v+S9vhmS71JRiX1xB5CWZNw7m6rMrllMag/RJyWb67BEgpDVMWSydc+K47pr35w05kWd7ReEq6116KaG4CsbJ7OmV9PdZLEKkONiC1/7ZONVgDsajLIJPYp2OUAXRpnPcGmnIE6eSK4nv5YQqqSYO52JqnYfYj/PdQXQIY7XszuMofMgZRT/1LdeC5h2I5/0EdWDMY2Yb05WDE1RodVdpSA5r85slArAVnSf+89iP896St0f5bZKVA7Gk/3ja8q+152/+wrLqBWZTem3IBADbRBoDuHgAA4HdAAADgh0EAAOCHQQAA4IdBAADgh0EAAOCHuVsKbJ3P9M7jjuxHzGfv8j9iDt47Dx7hP8cjq5F/o/0T62Aer//ZOgDrajBp6aNlOWTEajKLjgj/Pcs/vfZD/a++3Pc8hNfZ966EVeh5vP75luDRJUAl0KzJfnopaqbaTuzZiulc2BS5lltFXntu3dcQsXadl59Wn1H+dfYNtrt2d6D/LDF9HkCQw6eXFbr8P9X5W/un5Ol8gz1t39p5pWOPn0vLynbgdnfe8maEQw+UIPJdfxdOd/4oTtVD0IYg8wDywGas0I04T5O3P8/qf2UWwPpkn1PbOT1bN2tFe59EM7TvKf+TRFw+erZ2ey4hpS3hp9qBkqq/tjsSU1OYqucBWB1yynt5QxC42Mdk30pAEIio//zRG3feBzLUX+TTjCKwlH83aI/KbpQBVEHgUGF0j/SitcLofHem8q6AyH0wBhFv4WszuOjy0yK2vc/oRWQoP2X9ve78jfaLnpncbBqQSC6s0HnIRT0a2yNZjfxT8+ir8t+yDsDTWaS6X70GP33+d77stp+I5HtBdwEAAPBl8ECApcAA/DBvfSowAGAB7/05ZAAA/DAIAADMMU3fOuS2ggAAwBjrorKoxWiPBxHMAgAg490Ts0VeePdA+ZfJDKcCh7sBqY88mmjklZeOt9iXPrvx2I2QPRnN2/qzyJ84h4gNcbtfasq5mM1rZr+bBWh2A+bIIX13Z9wqL+nQvFno7v3oq4tJItCed7isUT6C/I7BUn9KP95wDicYBYpcjncrO2c/dmW4tBtw4RiRld1IDxDyYsoXMHxF1w3dyz0Nne8033AOFsT6VgRCafl89fenTZUfbm8CGhrgdDcS7anAsvnkkP0IeCfQ+JzYunky6jhNYj5bl7++4fJvN9WDSKS/292A0wyANyKDI91bfkm3kcH7ckaP/SKW/VHKRZAcI14pP3beu0fPyn/DuZQbWMogNnsc16sziE96f7H/iai7uTf0/3N8lwFz/e13T00Djt4OrInCnkeChXT+qOcKOLA21tJpsv/G8/COnGnw97J9QwbTvd6djYSv7fxEVTuV/LzNhj7nOawv6bfbAGCYEpQ6HxFtuxs6sq9tzOYHobQ6Nje+6vo5BwFrPZ4OgMayS4PPt1NlzdLfbRCYBoBc+NaO4JWPwLEf33oN3unY3InKPQBW6Z7nEZzEmrl4iZjC804lqgePPEOguQcwWghUphxm343wyt/pWpWR0OrR+jvyxavHajfb9pTjbt9bH07Z5/expM4TLWfwb7QQqMoC+UDWXZo/4RgA38LOgUvLJAAQ1Td9y9//0ylxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+g79apuVUsS5ZmwAAAABJRU5ErkJggg==",this.size=16,this.load()}load(){return this._imageSource=new qt(this.fontSheet),this._imageSource.load().then((()=>{this._spriteSheet=Xt.fromImageSource({image:this._imageSource,grid:{rows:4,columns:16,spriteWidth:16,spriteHeight:16}}),this._spriteFont=new Kt({alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,!'&.\"?-()+# ",caseInsensitive:!0,spriteSheet:this._spriteSheet,spacing:-6})}))}write(t,e,i){this._imageSource.isLoaded()&&this._spriteFont.render(t,e,null,i.x,i.y)}}class Yt{constructor(t,e){this._gl=t,this._texture=e}use(){const t=this._gl;t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture)}disable(){const t=this._gl;t.bindTexture(t.TEXTURE_2D,null)}}class jt{constructor(t){this.width=t.width,this.height=t.height,this._gl=t.gl,this._setupFramebuffer()}setResolution(t,e){const i=this._gl;this.width=t,this.height=e,i.bindTexture(i.TEXTURE_2D,this._frameTexture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null)}get frameBuffer(){return this._frameBuffer}get frameTexture(){return this._frameTexture}_setupFramebuffer(){const t=this._gl;this._frameTexture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this._frameTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);const e=t.COLOR_ATTACHMENT0;this._frameBuffer=t.createFramebuffer(),t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,e,t.TEXTURE_2D,this._frameTexture,0),this.disable()}toRenderSource(){return new Yt(this._gl,this._frameTexture)}use(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.viewport(0,0,this.width,this.height)}disable(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null)}}function Qt(t,e){switch(e){case t.FLOAT:return 4;case t.SHORT:case t.UNSIGNED_SHORT:return 2;case t.BYTE:case t.UNSIGNED_BYTE:default:return 1}}function $t(t,e){switch(e){case t.LOW_FLOAT:case t.HIGH_FLOAT:case t.FLOAT:return 1;case t.FLOAT_VEC2:return 2;case t.FLOAT_VEC3:return 3;case t.FLOAT_VEC4:return 4;case t.BYTE:case t.UNSIGNED_BYTE:case t.UNSIGNED_SHORT:case t.SHORT:default:return 1}}function Jt(t,e){switch(e){case t.LOW_FLOAT:case t.HIGH_FLOAT:case t.FLOAT:case t.FLOAT_VEC2:case t.FLOAT_VEC3:case t.FLOAT_VEC4:return t.FLOAT;case t.BYTE:return t.BYTE;case t.UNSIGNED_BYTE:return t.UNSIGNED_BYTE;case t.SHORT:return t.SHORT;case t.UNSIGNED_SHORT:return t.UNSIGNED_SHORT;default:return t.FLOAT}}class te{get compiled(){return this._compiled}constructor(t){this._logger=J.getInstance(),this.uniforms={},this.attributes={},this._compiled=!1;const{gl:e,vertexSource:i,fragmentSource:s}=t;this._gl=e,this.vertexSource=i,this.fragmentSource=s}use(){this._gl.useProgram(this.program),te._ACTIVE_SHADER_INSTANCE=this}isCurrentlyBound(){return te._ACTIVE_SHADER_INSTANCE===this}compile(){const t=this._gl,e=this._compileShader(t,this.vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this.fragmentSource,t.FRAGMENT_SHADER);this.program=this._createProgram(t,e,i);const s=this.getAttributes();for(const t of s)this.attributes[t.name]=t;const n=this.getUniforms();for(const t of n)this.uniforms[t.name]=t;return this._compiled=!0,this.program}getUniforms(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS),i=[];for(let s=0;s<e;s++){const e=t.getActiveUniform(this.program,s),n=t.getUniformLocation(this.program,e.name);i.push({name:e.name,glType:e.type,location:n})}return i}getAttributes(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES),i=[];for(let s=0;s<e;s++){const e=t.getActiveAttrib(this.program,s),n=t.getAttribLocation(this.program,e.name);i.push({name:e.name,glType:Jt(t,e.type),size:$t(t,e.type),location:n,normalized:!1})}return i}setTexture(t,e){const i=this._gl;i.activeTexture(i.TEXTURE0+t),i.bindTexture(i.TEXTURE_2D,e)}setUniformInt(t,e){this.setUniform("uniform1i",t,~~e)}trySetUniformInt(t,e){return this.trySetUniform("uniform1i",t,~~e)}setUniformIntArray(t,e){this.setUniform("uniform1iv",t,e)}trySetUniformIntArray(t,e){return this.trySetUniform("uniform1iv",t,e)}setUniformBoolean(t,e){this.setUniform("uniform1i",t,e?1:0)}trySetUniformBoolean(t,e){return this.trySetUniform("uniform1i",t,e?1:0)}setUniformFloat(t,e){this.setUniform("uniform1f",t,e)}trySetUniformFloat(t,e){return this.trySetUniform("uniform1f",t,e)}setUniformFloatArray(t,e){this.setUniform("uniform1fv",t,e)}trySetUniformFloatArray(t,e){return this.trySetUniform("uniform1fv",t,e)}setUniformFloatVector(t,e){this.setUniform("uniform2f",t,e.x,e.y)}trySetUniformFloatVector(t,e){return this.trySetUniform("uniform2f",t,e.x,e.y)}setUniformFloatColor(t,e){this.setUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}trySetUniformFloatColor(t,e){return this.trySetUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}setUniformMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,e.data)}trySetUniformMatrix(t,e){return this.trySetUniform("uniformMatrix4fv",t,!1,e.data)}setUniform(t,e,...i){if(!this._compiled)throw Error(`Must compile shader before setting a uniform ${t}:${e}`);if(!this.isCurrentlyBound())throw Error("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms");const s=this._gl.getUniformLocation(this.program,e);if(!s)throw Error(`Uniform ${t}:${e} doesn't exist or is not used in the shader source code, unused uniforms are optimized away by most browsers`);{const e=[s,...i];this._gl[t].apply(this._gl,e)}}trySetUniform(t,e,...i){if(!this._compiled)return this._logger.warn(`Must compile shader before setting a uniform ${t}:${e}`),!1;if(!this.isCurrentlyBound())return this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1;const s=this._gl.getUniformLocation(this.program,e);if(!s)return!1;{const e=[s,...i];this._gl[t].apply(this._gl,e)}return!0}_createProgram(t,e,i){const s=t.createProgram();if(null===s)throw Error("Could not create graphics shader program");t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s);if(!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.VERTEX_SHADER===i?"vertex":"fragment",n=t.createShader(i);if(null===n)throw Error(`Could not build shader: [${e}]`);t.shaderSource(n,e),t.compileShader(n);if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);throw Error(`Could not compile ${s} shader:\n\n${i}${this._processSourceForError(e,i)}`)}return n}_processSourceForError(t,e){if(!t)return e;const i=t.split("\n"),s=e.search(/\d:\d/),n=e.indexOf(" ",s),[r,o]=e.slice(s,n).split(":").map((t=>Number(t)));for(let t=0;t<i.length;t++)i[t]=`${t+1}: ${i[t]}${o===t+1?" <----- ERROR!":""}`;return"\n\nSource:\n"+i.join("\n")}}te._ACTIVE_SHADER_INSTANCE=null;class ee{constructor(t){this.type="dynamic";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=this._gl.createBuffer(),!n&&!i)throw Error("Must either provide data or a size to the VertexBuffer");this.bufferData=n||new Float32Array(i),this.type=null!=s?s:this.type,e.bindBuffer(e.ARRAY_BUFFER,this.buffer),e.bufferData(e.ARRAY_BUFFER,this.bufferData,"static"===this.type?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this.buffer)}upload(t){const e=this._gl;e.bindBuffer(e.ARRAY_BUFFER,this.buffer),t?e.bufferSubData(e.ARRAY_BUFFER,0,this.bufferData,0,t):e.bufferData(e.ARRAY_BUFFER,this.bufferData,"static"===this.type?e.STATIC_DRAW:e.DYNAMIC_DRAW)}}class ie{get vertexBuffer(){return this._vertexBuffer}get attributes(){return this._attributes}constructor(t){this._logger=J.getInstance(),this._layout=[],this._attributes=[],this._vertexTotalSizeBytes=0;const{gl:e,shader:i,vertexBuffer:s,attributes:n}=t;this._gl=e,this._vertexBuffer=s,this._attributes=n,this._shader=i,i&&this.initialize()}get totalVertexSizeBytes(){return this._vertexTotalSizeBytes}set shader(t){t&&this._shader!==t&&(this._shader=t,this.initialize())}get shader(){return this._shader}initialize(){if(!this._shader)return;if(!this._shader.compiled)throw Error("Shader not compiled, shader must be compiled before defining a vertex layout");this._vertexTotalSizeBytes=0,this._layout.length=0;const t=this._shader.attributes;for(const e of this._attributes){const i=t[e[0]];if(!i)throw Error(`The attribute named: ${e[0]} size ${e[1]} not found in the shader source code:\n ${this._shader.vertexSource}`);if(i.size!==e[1])throw Error(`VertexLayout size definition for attribute: [${e[0]}, ${e[1]}], doesnt match shader source size ${i.size}:\n ${this._shader.vertexSource}`);this._layout.push(i)}let e=0;for(const t of this._layout){const i=Qt(this._gl,t.glType);this._vertexTotalSizeBytes+=i*t.size,e+=t.size}this._vertexBuffer.bufferData.length%e!=0&&this._logger.warn(`The vertex component size (${e}) does divide evenly into the specified vertex buffer (${this._vertexBuffer.bufferData.length})`)}use(t=!1,e){if(!this._shader)throw Error("No shader is associated with this vertex layout, a shader must be set");const i=this._gl;if(!this._shader.isCurrentlyBound())throw Error("Shader associated with this vertex layout is not active! Call shader.use() before layout.use()");this._vertexBuffer.bind(),t&&this._vertexBuffer.upload(e);let s=0;for(const t of this._layout)i.vertexAttribPointer(t.location,t.size,t.glType,t.normalized,this.totalVertexSizeBytes,s),i.enableVertexAttribArray(t.location),s+=Qt(i,t.glType)*t.size}}class se{static clear(){se.DrawCallCount=0,se.DrawnImagesCount=0}}se.DrawCallCount=0,se.DrawnImagesCount=0;class ne{constructor(){this.type="ex.line",this.priority=0,this._maxLines=10922,this._vertexIndex=0,this._lineCount=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new te({gl:t,vertexSource:"#version 300 es\nin vec2 a_position;\nin vec4 a_color;\n\nout lowp vec4 v_color;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n\n // Passthrough the color\n v_color = a_color;\n}",fragmentSource:"#version 300 es\nprecision mediump float;\n\n// Color\nin lowp vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._vertexBuffer=new ee({gl:t,size:12*this._maxLines,type:"dynamic"}),this._layout=new ie({gl:t,vertexBuffer:this._vertexBuffer,shader:this._shader,attributes:[["a_position",2],["a_color",4]]})}draw(t,e,i){this._isFull()&&this.flush(),this._lineCount++;const s=this._context.getTransform(),n=s.multiply(t),r=s.multiply(e),o=this._vertexBuffer.bufferData;o[this._vertexIndex++]=n.x,o[this._vertexIndex++]=n.y,o[this._vertexIndex++]=i.r/255,o[this._vertexIndex++]=i.g/255,o[this._vertexIndex++]=i.b/255,o[this._vertexIndex++]=i.a,o[this._vertexIndex++]=r.x,o[this._vertexIndex++]=r.y,o[this._vertexIndex++]=i.r/255,o[this._vertexIndex++]=i.g/255,o[this._vertexIndex++]=i.b/255,o[this._vertexIndex++]=i.a}_isFull(){return this._lineCount>=this._maxLines}hasPendingDraws(){return 0!==this._lineCount}flush(){if(0===this._lineCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),t.drawArrays(t.LINES,0,2*this._lineCount),se.DrawnImagesCount+=this._lineCount,se.DrawCallCount++,this._vertexIndex=0,this._lineCount=0}}class re{constructor(){this.type="ex.point",this.priority=0,this._maxPoints=10922,this._pointCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new te({gl:t,vertexSource:"#version 300 es\nin vec2 a_position;\nin vec4 a_color;\nin float a_size;\nout lowp vec4 v_color;\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n gl_PointSize = a_size * 2.0;\n v_color = a_color;\n}",fragmentSource:'#version 300 es\n\nprecision mediump float;\nin lowp vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n float r = 0.0, delta = 0.0, alpha = 1.0;\n vec2 cxy = 2.0 * gl_PointCoord - 1.0;\n r = dot(cxy, cxy);\n\n delta = fwidth(r);\n alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r);\n // "premultiply" the color by alpha\n vec4 color = v_color;\n color.a = color.a * alpha;\n color.rgb = color.rgb * color.a;\n fragColor = color;\n}'}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._buffer=new ee({gl:t,size:7*this._maxPoints,type:"dynamic"}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_color",4],["a_size",1]]})}draw(t,e,i){this._isFull()&&this.flush(),this._pointCount++;const s=this._context.getTransform(),n=this._context.opacity,r=this._context.snapToPixel,o=s.multiply(t);r&&(o.x=~~(o.x+ge),o.y=~~(o.y+ge));const a=this._buffer.bufferData;a[this._vertexIndex++]=o.x,a[this._vertexIndex++]=o.y,a[this._vertexIndex++]=e.r/255,a[this._vertexIndex++]=e.g/255,a[this._vertexIndex++]=e.b/255,a[this._vertexIndex++]=e.a*n,a[this._vertexIndex++]=i*Math.max(s.getScaleX(),s.getScaleY())}_isFull(){return this._pointCount>=this._maxPoints}hasPendingDraws(){return 0!==this._pointCount}flush(){if(0===this._pointCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),t.drawArrays(t.POINTS,0,this._pointCount),se.DrawnImagesCount+=this._pointCount,se.DrawCallCount++,this._pointCount=0,this._vertexIndex=0}}class oe{constructor(t){this._gl=t,this._shader=new te({gl:t,vertexSource:"#version 300 es\nin vec2 a_position;\n\nin vec2 a_texcoord;\nout vec2 v_texcoord;\n\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n\n // Pass the texcoord to the fragment shader.\n v_texcoord = a_texcoord;\n}",fragmentSource:"#version 300 es\nprecision mediump float;\n\n// Passed in from the vertex shader.\nin vec2 v_texcoord;\n\n// The texture.\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texcoord);\n}"}),this._shader.compile(),this._buffer=new ee({gl:t,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}renderWithPostProcessor(t){const e=this._gl;t.getShader().use(),t.getLayout().use(),e.drawArrays(e.TRIANGLES,0,6)}renderToScreen(){const t=this._gl;this._shader.use(),this._layout.use(),t.drawArrays(t.TRIANGLES,0,6)}}class ae{constructor(t,e,i){this._logger=J.getInstance(),this._gl=t,this.buffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer);const s=6*e;if(i){const i=65535,n=Math.floor((i-1)/4);this.bufferGlType=t.UNSIGNED_SHORT,this.bufferData=new Uint16Array(s),e>n&&this._logger.warn(`Total quads exceeds hardware index buffer limit (uint16), max(${n}) requested quads(${e})`)}else this.bufferData=new Uint32Array(s);let n=0;for(let t=0;t<s;t+=6)this.bufferData[t+0]=n+0,this.bufferData[t+1]=n+1,this.bufferData[t+2]=n+2,this.bufferData[t+3]=n+2,this.bufferData[t+4]=n+1,this.bufferData[t+5]=n+3,n+=4;t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}get size(){return this.bufferData.length}upload(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer)}}class he{constructor(){this.type="ex.image",this.priority=0,this._maxImages=10922,this._maxTextures=0,this._imageCount=0,this._textures=[],this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._maxTextures=Math.min(t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),125);const i=this._transformFragmentSource("#version 300 es\nprecision mediump float;\n\n// UV coord\nin vec2 v_texcoord;\n\n// Texture index\nin lowp float v_textureIndex;\n\n// Textures in the current draw\nuniform sampler2D u_textures[%%count%%];\n\n// Opacity\nin float v_opacity;\n\nin vec4 v_tint;\n\nout vec4 fragColor;\n\nvoid main() {\n // In order to support the most efficient sprite batching, we have multiple\n // textures loaded into the gpu (usually 8) this picker logic skips over textures\n // that do not apply to a particular sprite.\n\n vec4 color = vec4(1.0, 0, 0, 1.0);\n\n // GLSL is templated out to pick the right texture and set the vec4 color\n %%texture_picker%%\n\n color.rgb = color.rgb * v_opacity;\n color.a = color.a * v_opacity;\n fragColor = color * v_tint;\n}",this._maxTextures);this._shader=new te({gl:t,fragmentSource:i,vertexSource:"#version 300 es\nin vec2 a_position;\n\n// Opacity \nin float a_opacity;\nout float v_opacity;\n\n// UV coordinate\nin vec2 a_texcoord;\nout vec2 v_texcoord;\n\n// Texture number\nin lowp float a_textureIndex;\nout lowp float v_textureIndex;\n\nin vec4 a_tint;\nout vec4 v_tint;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n\n // Pass through the Opacity to the fragment shader\n v_opacity = a_opacity;\n // Pass through the UV coord to the fragment shader\n v_texcoord = a_texcoord;\n // Pass through the texture number to the fragment shader\n v_textureIndex = a_textureIndex;\n // Pass through the tint\n v_tint = a_tint;\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map(((t,e)=>e))),this._buffer=new ee({gl:t,size:40*this._maxImages,type:"dynamic"}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_opacity",1],["a_texcoord",2],["a_textureIndex",1],["a_tint",4]]}),this._quads=new ae(t,this._maxImages,!0)}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let t=0;t<e;t++)s+=0===t?`if (v_textureIndex <= ${t}.5) {\n`:` else if (v_textureIndex <= ${t}.5) {\n`,s+=` color = texture(u_textures[${t}], v_texcoord);\n`,s+=" }\n";return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){const e=t.getAttribute("filtering");let i=null;e!==Gt.Blended&&e!==Gt.Pixel||(i=e);const s="true"===t.getAttribute("forceUpload"),n=this._context.textureLoader.load(t,i,s);t.removeAttribute("forceUpload"),-1===this._textures.indexOf(n)&&this._textures.push(n)}_bindTextures(t){for(let e=0;e<this._maxTextures;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this._textures[e]||this._textures[0])}_getTextureIdForImage(t){if(t){const e=this._context.textureLoader.get(t);return this._textures.indexOf(e)}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}draw(t,e,i,s,n,r,o,a,h){var l,c,d,u;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);let p=(null==t?void 0:t.width)||s||0,_=(null==t?void 0:t.height)||n||0,g=[0,0,null!==(l=null!=s?s:null==t?void 0:t.width)&&void 0!==l?l:0,null!==(c=null!=n?n:null==t?void 0:t.height)&&void 0!==c?c:0],m=[null!=e?e:1,null!=i?i:1];void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(g=[null!=e?e:1,null!=i?i:1,null!==(d=null!=s?s:null==t?void 0:t.width)&&void 0!==d?d:0,null!==(u=null!=n?n:null==t?void 0:t.height)&&void 0!==u?u:0],m=[r,o],p=a,_=h),e=g[0],i=g[1];const f=g[2],v=g[3],x=this._context.getTransform(),y=this._context.opacity,w=this._context.snapToPixel;let b=xt(m[0],m[1]),C=xt(m[0]+p,m[1]),A=xt(m[0],m[1]+_),T=xt(m[0]+p,m[1]+_);b=x.multiply(b),C=x.multiply(C),A=x.multiply(A),T=x.multiply(T),w&&(b.x=~~(b.x+ge),b.y=~~(b.y+ge),C.x=~~(C.x+ge),C.y=~~(C.y+ge),A.x=~~(A.x+ge),A.y=~~(A.y+ge),T.x=~~(T.x+ge),T.y=~~(T.y+ge));const S=this._context.tint,E=this._getTextureIdForImage(t),P=t.width||p,I=t.height||_,D=e/P,B=i/I,R=(e+f-.01)/P,F=(i+v-.01)/I,k=this._layout.vertexBuffer.bufferData;k[this._vertexIndex++]=b.x,k[this._vertexIndex++]=b.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=D,k[this._vertexIndex++]=B,k[this._vertexIndex++]=E,k[this._vertexIndex++]=S.r/255,k[this._vertexIndex++]=S.g/255,k[this._vertexIndex++]=S.b/255,k[this._vertexIndex++]=S.a,k[this._vertexIndex++]=A.x,k[this._vertexIndex++]=A.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=D,k[this._vertexIndex++]=F,k[this._vertexIndex++]=E,k[this._vertexIndex++]=S.r/255,k[this._vertexIndex++]=S.g/255,k[this._vertexIndex++]=S.b/255,k[this._vertexIndex++]=S.a,k[this._vertexIndex++]=C.x,k[this._vertexIndex++]=C.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=R,k[this._vertexIndex++]=B,k[this._vertexIndex++]=E,k[this._vertexIndex++]=S.r/255,k[this._vertexIndex++]=S.g/255,k[this._vertexIndex++]=S.b/255,k[this._vertexIndex++]=S.a,k[this._vertexIndex++]=T.x,k[this._vertexIndex++]=T.y,k[this._vertexIndex++]=y,k[this._vertexIndex++]=R,k[this._vertexIndex++]=F,k[this._vertexIndex++]=E,k[this._vertexIndex++]=S.r/255,k[this._vertexIndex++]=S.g/255,k[this._vertexIndex++]=S.b/255,k[this._vertexIndex++]=S.a}hasPendingDraws(){return 0!==this._imageCount}flush(){if(0===this._imageCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0,40*this._imageCount),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._bindTextures(t),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._imageCount,this._quads.bufferGlType,0),se.DrawnImagesCount+=this._imageCount,se.DrawCallCount++,this._imageCount=0,this._vertexIndex=0,this._textures.length=0}}class le{constructor(){this.type="ex.rectangle",this.priority=0,this._maxRectangles=10922,this._rectangleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new te({gl:t,fragmentSource:"#version 300 es\n\nprecision mediump float;\n\n// UV coord\nin vec2 v_uv;\n\nin vec2 v_size; // in pixels\n\n// Color coord to blend with image\nin lowp vec4 v_color;\n\n// Stroke color if used\nin lowp vec4 v_strokeColor;\n\n// Stroke thickness if used\nin lowp float v_strokeThickness; // in pixels\n\n// Opacity\nin float v_opacity;\n\nout vec4 fragColor;\n\nvoid main() {\n // modified from https://stackoverflow.com/questions/59197671/glsl-rounded-rectangle-with-variable-border\n vec2 uv = v_uv;\n vec2 fragCoord = uv * v_size;\n float maxX = v_size.x - v_strokeThickness;\n float minX = v_strokeThickness;\n float maxY = v_size.y - v_strokeThickness;\n float minY = v_strokeThickness;\n\n if (fragCoord.x < maxX && fragCoord.x > minX &&\n fragCoord.y < maxY && fragCoord.y > minY) {\n fragColor = v_color;\n } else {\n fragColor = v_strokeColor;\n }\n fragColor.a *= v_opacity;\n fragColor.rgb *= fragColor.a;\n\n // vec2 v2CenteredPos = abs(fragCoord - v_size.xy / 2.0);\n // vec2 v2HalfShapeSizePx = v_size.xy/2.0 - v_strokeThickness/2.0;\n\n // float fHalfBorderDist = 0.0;\n // float fHalfBorderThickness = 0.0;\n\n // if (fragCoord.x > max(v_radius, v_strokeThickness) && \n // fragCoord.x < v_size.x - max(v_radius, v_strokeThickness))\n // {\n // fHalfBorderDist = v2CenteredPos.y - v2HalfShapeSizePx.y;\n // fHalfBorderThickness = v_strokeThickness / 2.0;\n // }\n // else if (fragCoord.y > max(v_radius, v_strokeThickness) && \n // fragCoord.y < v_size.y - max(v_radius, v_strokeThickness))\n // {\n // fHalfBorderDist = v2CenteredPos.x - v2HalfShapeSizePx.x;\n // fHalfBorderThickness = v_strokeThickness / 2.0;\n // }\n // else\n // {\n // vec2 edgeVec = max(vec2(0.0), v_radius - vec2(\n // uv.x > 0.5 ? v_size.x - fragCoord.x : fragCoord.x,\n // uv.y > 0.5 ? v_size.y - fragCoord.y : fragCoord.y));\n \n // float ellipse_ab = v_radius-v_strokeThickness;\n // vec2 ellipse_isect = (v_strokeThickness > v_radius || v_strokeThickness > v_radius) ? vec2(0.0) :\n // edgeVec.xy * ellipse_ab*ellipse_ab / length(ellipse_ab*edgeVec.yx); \n \n // fHalfBorderThickness = (v_radius - length(ellipse_isect)) / 2.0;\n // fHalfBorderDist = length(edgeVec) - (v_radius - fHalfBorderThickness);\n // }\n\n // vec4 v4FromColor = v_strokeColor;\n // v4FromColor.rgb *= v4FromColor.a;\n // vec4 v4ToColor = vec4(0.0); // background color is transparent\n // if (fHalfBorderDist < 0.0) {\n // v4ToColor = v_color;\n // v4ToColor.rgb *= v4ToColor.a;\n // }\n\n // float mixPct = abs(fHalfBorderDist) - fHalfBorderThickness;\n\n // vec4 finalColor = mix(v4FromColor, v4ToColor, mixPct);\n // gl_FragColor = finalColor;\n}",vertexSource:"#version 300 es\nin vec2 a_position;\n\n// UV coordinate\nin vec2 a_uv;\nout vec2 v_uv;\n\nin vec2 a_size;\nout vec2 v_size;\n\n// Opacity \nin float a_opacity;\nout float v_opacity;\n\nin vec4 a_color;\nout vec4 v_color;\n\nin vec4 a_strokeColor;\nout vec4 v_strokeColor;\n\nin float a_strokeThickness;\nout float v_strokeThickness;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n\n // Pass through UV coords\n v_uv = a_uv;\n // Pass through size\n v_size = a_size;\n // Pass through the Opacity to the fragment shader\n v_opacity = a_opacity;\n // Pass through the color to the fragment shader\n v_color = a_color;\n // Pass through the stroke color to the fragment shader\n v_strokeColor = a_strokeColor;\n // Pass through the stroke thickenss to the fragment shader\n v_strokeThickness = a_strokeThickness;\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new ee({gl:t,size:64*this._maxRectangles,type:"dynamic"}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_size",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new ae(t,this._maxRectangles,!0)}_isFull(){return this._rectangleCount>=this._maxRectangles}draw(...t){t[0]instanceof vt&&t[1]instanceof vt?this.drawLine.apply(this,t):this.drawRectangle.apply(this,t)}drawLine(t,e,i,s=1){this._isFull()&&this.flush(),this._rectangleCount++;const n=this._context.getTransform(),r=this._context.opacity,o=this._context.snapToPixel,a=e.sub(t),h=a.size,l=a.normalize().perpendicular(),c=s/2,d=n.multiply(l.scale(c).add(t)),u=n.multiply(l.scale(-c).add(t)),p=n.multiply(l.scale(c).add(e)),_=n.multiply(l.scale(-c).add(e));o&&(d.x=~~(d.x+ge),d.y=~~(d.y+ge),p.x=~~(p.x+ge),p.y=~~(p.y+ge),u.x=~~(u.x+ge),u.y=~~(u.y+ge),_.x=~~(_.x+ge),_.y=~~(_.y+ge));const g=yt.Transparent,m=this._layout.vertexBuffer.bufferData;m[this._vertexIndex++]=d.x,m[this._vertexIndex++]=d.y,m[this._vertexIndex++]=0,m[this._vertexIndex++]=0,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=u.x,m[this._vertexIndex++]=u.y,m[this._vertexIndex++]=0,m[this._vertexIndex++]=1,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=p.x,m[this._vertexIndex++]=p.y,m[this._vertexIndex++]=1,m[this._vertexIndex++]=0,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0,m[this._vertexIndex++]=_.x,m[this._vertexIndex++]=_.y,m[this._vertexIndex++]=1,m[this._vertexIndex++]=1,m[this._vertexIndex++]=h,m[this._vertexIndex++]=s,m[this._vertexIndex++]=r,m[this._vertexIndex++]=i.r/255,m[this._vertexIndex++]=i.g/255,m[this._vertexIndex++]=i.b/255,m[this._vertexIndex++]=i.a,m[this._vertexIndex++]=g.r/255,m[this._vertexIndex++]=g.g/255,m[this._vertexIndex++]=g.b/255,m[this._vertexIndex++]=g.a,m[this._vertexIndex++]=0}drawRectangle(t,e,i,s,n=yt.Transparent,r=0){this._isFull()&&this.flush(),this._rectangleCount++;const o=this._context.getTransform(),a=this._context.opacity,h=this._context.snapToPixel,l=o.multiply(t.add(xt(0,0))),c=o.multiply(t.add(xt(e,0))),d=o.multiply(t.add(xt(e,i))),u=o.multiply(t.add(xt(0,i)));h&&(l.x=~~(l.x+ge),l.y=~~(l.y+ge),c.x=~~(c.x+ge),c.y=~~(c.y+ge),u.x=~~(u.x+ge),u.y=~~(u.y+ge),d.x=~~(d.x+ge),d.y=~~(d.y+ge));const p=this._layout.vertexBuffer.bufferData;p[this._vertexIndex++]=l.x,p[this._vertexIndex++]=l.y,p[this._vertexIndex++]=0,p[this._vertexIndex++]=0,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=u.x,p[this._vertexIndex++]=u.y,p[this._vertexIndex++]=0,p[this._vertexIndex++]=1,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=c.x,p[this._vertexIndex++]=c.y,p[this._vertexIndex++]=1,p[this._vertexIndex++]=0,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r,p[this._vertexIndex++]=d.x,p[this._vertexIndex++]=d.y,p[this._vertexIndex++]=1,p[this._vertexIndex++]=1,p[this._vertexIndex++]=e,p[this._vertexIndex++]=i,p[this._vertexIndex++]=a,p[this._vertexIndex++]=s.r/255,p[this._vertexIndex++]=s.g/255,p[this._vertexIndex++]=s.b/255,p[this._vertexIndex++]=s.a,p[this._vertexIndex++]=n.r/255,p[this._vertexIndex++]=n.g/255,p[this._vertexIndex++]=n.b/255,p[this._vertexIndex++]=n.a,p[this._vertexIndex++]=r}hasPendingDraws(){return 0!==this._rectangleCount}flush(){if(0===this._rectangleCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._rectangleCount,this._quads.bufferGlType,0),se.DrawnImagesCount+=this._rectangleCount,se.DrawCallCount++,this._rectangleCount=0,this._vertexIndex=0}}class ce{constructor(){this.type="ex.circle",this.priority=0,this._maxCircles=10922,this._circleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new te({gl:t,fragmentSource:"#version 300 es\nprecision highp float;\n\n// UV coord\nin vec2 v_uv;\n\n// Color coord to blend with image\nin lowp vec4 v_color;\n\n// Stroke color if used\nin lowp vec4 v_strokeColor;\n\n// Stroke thickness if used\nin lowp float v_strokeThickness;\n\n// Opacity\nin float v_opacity;\n\nout vec4 fragColor;\n\nvoid main() {\n // make (0, 0) the center the uv \n vec2 uv = v_uv * 2.0 - 1.0;\n\n vec4 color = v_color;\n vec4 strokeColor = v_strokeColor;\n\n // circle border is at radius 1.0 \n // dist is > 0 when inside the circle \n float d = length(uv);\n float dist = 1.0 - length(uv);\n\n // Fade based on fwidth\n float fade = fwidth(dot(uv, uv));\n\n // if dist is greater than 0 step to 1;\n // when we cross this 0 threshold add a smooth fade\n float fill = smoothstep(-fade/2.0, fade/2.0, dist);\n\n // if dist is greater than the stroke thickness step to 1\n float stroke = 1.0 - smoothstep(v_strokeThickness, v_strokeThickness + fade, dist);\n\n strokeColor.a *= fill * stroke;\n strokeColor.rgb *= strokeColor.a;\n\n color.a *= fill * (1.0 - stroke);\n color.rgb *= color.a;\n\n vec4 finalColor = mix(vec4(0.0), (color + strokeColor), fill);\n finalColor.rgb = finalColor.rgb * v_opacity;\n finalColor.a = finalColor.a * v_opacity;\n fragColor = finalColor;\n}",vertexSource:"#version 300 es\nin vec2 a_position;\n\n// UV coordinate\nin vec2 a_uv;\nout vec2 v_uv;\n\n// Opacity \nin float a_opacity;\nout float v_opacity;\n\nin vec4 a_color;\nout vec4 v_color;\n\nin vec4 a_strokeColor;\nout vec4 v_strokeColor;\n\nin float a_strokeThickness;\nout float v_strokeThickness;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n\n // Pass through UV coords\n v_uv = a_uv;\n // Pass through the Opacity to the fragment shader\n v_opacity = a_opacity;\n // Pass through the color to the fragment shader\n v_color = a_color;\n // Pass through the stroke color to the fragment shader\n v_strokeColor = a_strokeColor;\n // Pass through the stroke thickenss to the fragment shader\n v_strokeThickness = a_strokeThickness;\n}"}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new ee({gl:t,size:56*this._maxCircles,type:"dynamic"}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new ae(t,this._maxCircles,!0)}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=yt.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const r=this._context.getTransform(),o=this._context.opacity,a=this._context.snapToPixel,h=r.multiply(t.add(xt(-e,-e))),l=r.multiply(t.add(xt(e,-e))),c=r.multiply(t.add(xt(e,e))),d=r.multiply(t.add(xt(-e,e)));a&&(h.x=~~(h.x+ge),h.y=~~(h.y+ge),l.x=~~(l.x+ge),l.y=~~(l.y+ge),d.x=~~(d.x+ge),d.y=~~(d.y+ge),c.x=~~(c.x+ge),c.y=~~(c.y+ge));const u=this._layout.vertexBuffer.bufferData;u[this._vertexIndex++]=h.x,u[this._vertexIndex++]=h.y,u[this._vertexIndex++]=0,u[this._vertexIndex++]=0,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=d.x,u[this._vertexIndex++]=d.y,u[this._vertexIndex++]=0,u[this._vertexIndex++]=1,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=l.x,u[this._vertexIndex++]=l.y,u[this._vertexIndex++]=1,u[this._vertexIndex++]=0,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e,u[this._vertexIndex++]=c.x,u[this._vertexIndex++]=c.y,u[this._vertexIndex++]=1,u[this._vertexIndex++]=1,u[this._vertexIndex++]=o,u[this._vertexIndex++]=i.r/255,u[this._vertexIndex++]=i.g/255,u[this._vertexIndex++]=i.b/255,u[this._vertexIndex++]=i.a,u[this._vertexIndex++]=s.r/255,u[this._vertexIndex++]=s.g/255,u[this._vertexIndex++]=s.b/255,u[this._vertexIndex++]=s.a,u[this._vertexIndex++]=n/e}hasPendingDraws(){return 0!==this._circleCount}flush(){if(0===this._circleCount)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,6*this._circleCount,this._quads.bufferGlType,0),se.DrawnImagesCount+=this._circleCount,se.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}class de{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this.disableWarnings=!1,this._logger=J.getInstance()}preallocate(){for(let t=0;t<this.maxObjects;t++)this.objects[t]=this.builder()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){t(this.get()),this.index--}get(...t){if(this.index===this.maxObjects&&(this.disableWarnings||this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=2*this.maxObjects),this.objects[this.index])return this.recycler(this.objects[this.index++],...t);this.totalAllocations++;return this.objects[this.index++]=this.builder(...t)}done(...t){this.index=0;for(const e of t){const t=this.objects.indexOf(e);this.objects[t]=this.builder(),this.totalAllocations++}return t}}class ue{constructor(){this.z=0,this.priority=0,this.transform=kt.identity(),this.state={z:0,opacity:1,tint:yt.White,material:null}}}class pe{constructor(t){this._color=yt.Transparent,this._initialized=!1;const{color:e,name:i,vertexSource:s,fragmentSource:n}=t;this._name=i,this._vertexSource=null!=s?s:"#version 300 es\nin vec2 a_position;\n\nin vec2 a_uv;\nout vec2 v_uv;\n\nin vec2 a_screenuv;\nout vec2 v_screenuv;\n\nuniform mat4 u_matrix;\nuniform mat4 u_transform;\n\nvoid main() {\n // Set the vertex position using the ortho & transform matrix\n gl_Position = u_matrix * u_transform * vec4(a_position, 0.0, 1.0);\n\n // Pass through the UV coord to the fragment shader\n v_uv = a_uv;\n v_screenuv = a_screenuv;\n}\n",this._fragmentSource=n,this._color=null!=e?e:this._color}initialize(t,e){this._initialized||(this._shader=e.createShader({vertexSource:this._vertexSource,fragmentSource:this._fragmentSource}),this._shader.compile(),this._initialized=!0)}get name(){var t;return null!==(t=this._name)&&void 0!==t?t:"anonymous material"}get isUsingScreenTexture(){return this._fragmentSource.includes("u_screen_texture")}update(t){this._shader&&(this._shader.use(),t(this._shader))}getShader(){return this._shader}use(){if(!this._initialized)throw Error(`Material ${this.name} not yet initialized, use the ExcaliburGraphicsContext.createMaterial() to work around this.`);this._shader.use(),this._shader.trySetUniformFloatColor("u_color",this._color)}}class _e{constructor(){this.type="ex.material",this.priority=0,this._textures=[]}initialize(t,e){this._gl=t,this._context=e,this._buffer=new ee({gl:t,size:24,type:"dynamic"}),this._layout=new ie({gl:t,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_screenuv",2]]}),this._quads=new ae(t,1,!0)}draw(t,e,i,s,n,r,o,a,h){var l,c,d,u;const p=this._gl,_=this._context.material;_.initialize(p,this._context);const g=this._context.getTransform(),m=this._context.opacity,f=_.getShader(),v=this._layout.vertexBuffer.bufferData;let x=0,y=(null==t?void 0:t.width)||s||0,w=(null==t?void 0:t.height)||n||0,b=[0,0,null!==(l=null!=s?s:null==t?void 0:t.width)&&void 0!==l?l:0,null!==(c=null!=n?n:null==t?void 0:t.height)&&void 0!==c?c:0],C=[null!=e?e:1,null!=i?i:1];void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(b=[null!=e?e:1,null!=i?i:1,null!==(d=null!=s?s:null==t?void 0:t.width)&&void 0!==d?d:0,null!==(u=null!=n?n:null==t?void 0:t.height)&&void 0!==u?u:0],C=[r,o],y=a,w=h),e=b[0],i=b[1];const A=b[2],T=b[3],S=xt(C[0],C[1]),E=xt(C[0]+y,C[1]),P=xt(C[0],C[1]+w),I=xt(C[0]+y,C[1]+w),D=t.width||y,B=t.height||w,R=e/D,F=i/B,k=(e+A-.01)/D,M=(i+T-.01)/B,L=g.getPosition(),z=L.add(I),U=L.x/this._context.width,O=L.y/this._context.height,N=z.x/this._context.width,H=z.y/this._context.height;v[x++]=S.x,v[x++]=S.y,v[x++]=R,v[x++]=F,v[x++]=U,v[x++]=O,v[x++]=P.x,v[x++]=P.y,v[x++]=R,v[x++]=M,v[x++]=U,v[x++]=H,v[x++]=E.x,v[x++]=E.y,v[x++]=k,v[x++]=F,v[x++]=N,v[x++]=O,v[x++]=I.x,v[x++]=I.y,v[x++]=k,v[x++]=M,v[x++]=N,v[x++]=H;const W=this._addImageAsTexture(t);_.use(),this._layout.shader=f,this._layout.use(!0),f.trySetUniformFloat("u_time_ms",performance.now()),f.trySetUniformFloat("u_opacity",m),f.trySetUniformFloatVector("u_resolution",xt(this._context.width,this._context.height)),f.trySetUniformFloatVector("u_graphic_resolution",xt(D,B)),f.trySetUniformFloatVector("u_size",xt(A,T)),f.trySetUniformMatrix("u_matrix",this._context.ortho),f.trySetUniformMatrix("u_transform",g.to4x4()),p.activeTexture(p.TEXTURE0+0),p.bindTexture(p.TEXTURE_2D,W),f.trySetUniformInt("u_graphic",0),p.activeTexture(p.TEXTURE0+1),p.bindTexture(p.TEXTURE_2D,this._context.materialScreenTexture),f.trySetUniformInt("u_screen_texture",1),this._quads.bind(),p.drawElements(p.TRIANGLES,6,this._quads.bufferGlType,0),se.DrawnImagesCount++,se.DrawCallCount++}_addImageAsTexture(t){const e=t.getAttribute("filtering");let i=null;e!==Gt.Blended&&e!==Gt.Pixel||(i=e);const s="true"===t.getAttribute("forceUpload"),n=this._context.textureLoader.load(t,i,s);return t.removeAttribute("forceUpload"),-1===this._textures.indexOf(n)&&this._textures.push(n),n}hasPendingDraws(){return!1}flush(){}}const ge=1e-4;class me{constructor(t){this._webglCtx=t,this._debugText=new Zt}drawRect(t,e,i,s,n={color:yt.Black}){this.drawLine(xt(t,e),xt(t+i,e),{...n}),this.drawLine(xt(t+i,e),xt(t+i,e+s),{...n}),this.drawLine(xt(t+i,e+s),xt(t,e+s),{...n}),this.drawLine(xt(t,e+s),xt(t,e),{...n})}drawLine(t,e,i={color:yt.Black}){this._webglCtx.draw("ex.line",t,e,i.color)}drawPoint(t,e={color:yt.Black,size:5}){this._webglCtx.draw("ex.point",t,e.color,e.size)}drawText(t,e){this._debugText.write(this._webglCtx,t,e)}}class fe{get z(){return this._state.current.z}set z(t){this._state.current.z=t}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}get ortho(){return this._ortho}checkIfResolutionSupported(t){let e=!0;return(t.width>4096||t.height>4096)&&(e=!1),e}constructor(t){this._logger=J.getInstance(),this._renderers=new Map,this._isDrawLifecycle=!1,this.useDrawSorting=!0,this._drawCallPool=new de((()=>new ue),(t=>(t.priority=0,t.z=0,t.renderer=void 0,t.args=void 0,t)),4e3),this._drawCalls=[],this._postProcessTargets=[],this._postprocessors=[],this._transform=new Mt,this._state=new Lt,this.snapToPixel=!1,this.smoothing=!1,this.backgroundColor=yt.ExcaliburBlue,this._alreadyWarnedDrawLifecycle=!1,this.debug=new me(this),this._totalPostProcessorTime=0;const{canvasElement:e,enableTransparency:i,smoothing:s,snapToPixel:n,backgroundColor:r,useDrawSorting:o}=t;if(this.__gl=e.getContext("webgl2",{antialias:null!=s?s:this.smoothing,premultipliedAlpha:!1,alpha:null==i||i,depth:!0,powerPreference:"high-performance"}),!this.__gl)throw Error("Failed to retrieve webgl context from browser");this.textureLoader=new Vt(this.__gl),this.snapToPixel=null!=n?n:this.snapToPixel,this.smoothing=null!=s?s:this.smoothing,this.backgroundColor=null!=r?r:this.backgroundColor,this.useDrawSorting=null!=o?o:this.useDrawSorting,this._drawCallPool.disableWarnings=!0,this._drawCallPool.preallocate(),this._init()}_init(){const t=this.__gl;this._ortho=Ft.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA),this.register(new he),this.register(new _e),this.register(new le),this.register(new ce),this.register(new re),this.register(new ne),this.materialScreenTexture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this.materialScreenTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT),t.bindTexture(t.TEXTURE_2D,null),this._screenRenderer=new oe(t),this._renderTarget=new jt({gl:t,width:t.canvas.width,height:t.canvas.height}),this._postProcessTargets=[new jt({gl:t,width:t.canvas.width,height:t.canvas.height}),new jt({gl:t,width:t.canvas.width,height:t.canvas.height})]}register(t){this._renderers.set(t.type,t),t.initialize(this.__gl,this)}get(t){return this._renderers.get(t)}_isCurrentRenderer(t){return!this._currentRenderer||this._currentRenderer===t}beginDrawLifecycle(){this._isDrawLifecycle=!0}endDrawLifecycle(){this._isDrawLifecycle=!1}draw(t,...e){this._isDrawLifecycle||this._alreadyWarnedDrawLifecycle||(this._logger.warn("Attempting to draw outside the the drawing lifecycle (preDraw/postDraw) is not supported and is a source of bugs/errors.\nIf you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPostDraw handler."),this._alreadyWarnedDrawLifecycle=!0);const i=this._renderers.get(t);if(!i)throw Error(`No renderer with name ${t} has been registered`);if(this.useDrawSorting){const s=this._drawCallPool.get();s.z=this._state.current.z,s.priority=i.priority,s.renderer=t,this.getTransform().clone(s.transform),s.state.z=this._state.current.z,s.state.opacity=this._state.current.opacity,s.state.tint=this._state.current.tint,s.state.material=this._state.current.material,s.args=e,this._drawCalls.push(s)}else this._currentRenderer||(this._currentRenderer=i),this._isCurrentRenderer(i)||this._currentRenderer.flush(),i.draw(...e),this._currentRenderer=i}resetTransform(){this._transform.current=kt.identity()}updateViewport(t){const e=this.__gl;this._ortho=this._ortho=Ft.ortho(0,t.width,t.height,0,400,-400),this._renderTarget.setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[0].setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[1].setResolution(e.canvas.width,e.canvas.height)}drawImage(t,e,i,s,n,r,o,a,h){if(0!==s&&0!==n&&0!==a&&0!==h&&0!==t.width&&0!==t.height)return t?void(this._state.current.material?this.draw("ex.material",t,e,i,s,n,r,o,a,h):this.draw("ex.image",t,e,i,s,n,r,o,a,h)):(J.getInstance().warn("Cannot draw a null or undefined image"),void(console.trace&&console.trace()))}drawLine(t,e,i,s=1){this.draw("ex.rectangle",t,e,i,s)}drawRectangle(t,e,i,s,n,r){this.draw("ex.rectangle",t,e,i,s,n,r)}drawCircle(t,e,i,s,n){this.draw("ex.circle",t,e,i,s,n)}save(){this._transform.save(),this._state.save()}restore(){this._transform.restore(),this._state.restore()}translate(t,e){this._transform.translate(this.snapToPixel?~~(t+ge):t,this.snapToPixel?~~(e+ge):e)}rotate(t){this._transform.rotate(t)}scale(t,e){this._transform.scale(t,e)}transform(t){this._transform.current=t}getTransform(){return this._transform.current}multiply(t){this._transform.current.multiply(t,this._transform.current)}addPostProcessor(t){this._postprocessors.push(t),t.initialize(this.__gl)}removePostProcessor(t){const e=this._postprocessors.indexOf(t);-1!==e&&this._postprocessors.splice(e,1)}clearPostProcessors(){this._postprocessors.length=0}updatePostProcessors(t){for(const e of this._postprocessors){const i=e.getShader();i.use();const s=i.getUniforms();this._totalPostProcessorTime+=t,s.find((t=>"u_time_ms"===t.name))&&i.setUniformFloat("u_time_ms",this._totalPostProcessorTime),s.find((t=>"u_elapsed_ms"===t.name))&&i.setUniformFloat("u_elapsed_ms",t),s.find((t=>"u_resolution"===t.name))&&i.setUniformFloatVector("u_resolution",xt(this.width,this.height)),e.onUpdate&&e.onUpdate(t)}}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){const e=new pe(t);return e.initialize(this.__gl,this),e}createShader(t){const e=this.__gl,{vertexSource:i,fragmentSource:s}=t,n=new te({gl:e,vertexSource:i,fragmentSource:s});return n.compile(),n}clear(){const t=this.__gl;this._renderTarget.use(),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT)}flush(){const t=this.__gl;if(this._renderTarget.use(),this.useDrawSorting){const t=new Map;for(const[e]of this._renderers){const i=this._drawCalls.findIndex((t=>t.renderer===e));t.set(e,i)}this._drawCalls.sort(((e,i)=>{const s=e.z-i.z,n=t.get(e.renderer)-t.get(i.renderer),r=e.priority-i.priority;return 0===s?0===r?n:r:s}));const e=this._transform.current,i=this._state.current;if(this._drawCalls.length){let t=this._drawCalls[0].renderer,e=this._renderers.get(t);for(let i=0;i<this._drawCalls.length;i++){if(this._transform.current=this._drawCalls[i].transform,this._state.current=this._drawCalls[i].state,this._drawCalls[i].renderer!==t&&(e.flush(),t=this._drawCalls[i].renderer,e=this._renderers.get(t)),e instanceof _e&&this.material.isUsingScreenTexture){const t=this.__gl;t.bindTexture(t.TEXTURE_2D,this.materialScreenTexture),t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,this.width,this.height,0),this._renderTarget.use()}e.draw(...this._drawCalls[i].args)}e.hasPendingDraws()&&e.flush()}this._transform.current=e,this._state.current=i,this._drawCallPool.done(),this._drawCalls.length=0}else for(const t of this._renderers.values())t.hasPendingDraws()&&t.flush();this._renderTarget.disable();this._renderTarget.toRenderSource().use();for(let t=0;t<this._postprocessors.length;t++)this._postProcessTargets[t%2].use(),this._screenRenderer.renderWithPostProcessor(this._postprocessors[t]),this._postProcessTargets[t%2].toRenderSource().use();t.bindFramebuffer(t.FRAMEBUFFER,null),this._screenRenderer.renderToScreen()}}const ve=1e-4;class xe{constructor(t){this._ex=t,this._debugText=new Zt}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~(t+ve):t,this._ex.snapToPixel?~~(e+ve):e,this._ex.snapToPixel?~~(i+ve):i,this._ex.snapToPixel?~~(s+ve):s),this._ex.__ctx.restore()}drawLine(t,e,i={color:yt.Black}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=i.color.toString(),this._ex.__ctx.moveTo(this._ex.snapToPixel?~~(t.x+ve):t.x,this._ex.snapToPixel?~~(t.y+ve):t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~(e.x+ve):e.x,this._ex.snapToPixel?~~(e.y+ve):e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:yt.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+ve):t.x,this._ex.snapToPixel?~~(t.y+ve):t.y,e.size,0,2*Math.PI),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class ye{get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}constructor(t){this.useDrawSorting=!1,this.z=0,this.backgroundColor=yt.ExcaliburBlue,this._state=new Lt,this.snapToPixel=!1,this.debug=new xe(this);const{canvasElement:e,enableTransparency:i,snapToPixel:s,smoothing:n,backgroundColor:r}=t;this.__ctx=e.getContext("2d",{alpha:null==i||i}),this.backgroundColor=null!=r?r:this.backgroundColor,this.snapToPixel=null!=s?s:this.snapToPixel,this.smoothing=null!=n?n:this.smoothing}resetTransform(){this.__ctx.resetTransform()}updateViewport(t){}drawImage(t,e,i,s,n,r,o,a,h){if(0===s||0===n)return;if(0===a||0===h)return;if(0===t.width||0===t.height)return;this.__ctx.globalAlpha=this.opacity;const l=[t,e,i,s,n,r,o,a,h].filter((t=>void 0!==t)).map((t=>"number"==typeof t&&this.snapToPixel?~~t:t));this.__ctx.drawImage.apply(this.__ctx,l),se.DrawCallCount++,se.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~(t.x+ve):t.x,this.snapToPixel?~~(t.y+ve):t.y),this.__ctx.lineTo(this.snapToPixel?~~(e.x+ve):e.x,this.snapToPixel?~~(e.y+ve):e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~(t.x+ve):t.x,this.snapToPixel?~~(t.y+ve):t.y,this.snapToPixel?~~(e+ve):e,this.snapToPixel?~~(i+ve):i),this.__ctx.restore()}drawCircle(t,e,i,s,n){this.__ctx.save(),this.__ctx.beginPath(),s&&(this.__ctx.strokeStyle=s.toString()),n&&(this.__ctx.lineWidth=n),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~(t.x+ve):t.x,this.snapToPixel?~~(t.y+ve):t.y,e,0,2*Math.PI),this.__ctx.fill(),s&&this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save(),this._state.save()}restore(){this.__ctx.restore(),this._state.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~(t+ve):t,this.snapToPixel?~~(e+ve):e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}getTransform(){throw new Error("Not implemented")}multiply(t){this.__ctx.setTransform(this.__ctx.getTransform().multiply(t.toDOMMatrix()))}addPostProcessor(t){}removePostProcessor(t){}clearPostProcessors(){}updatePostProcessors(t){}beginDrawLifecycle(){}endDrawLifecycle(){}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){return null}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),se.clear()}flush(){}}var we;!function(t){t.Fixed="Fixed",t.FitContainerAndFill="FitContainerAndFill",t.FitScreenAndFill="FitScreenAndFill",t.FitContainerAndZoom="FitContainerAndZoom",t.FitScreenAndZoom="FitScreenAndZoom",t.FitScreen="FitScreen",t.FillScreen="FillScreen",t.FitContainer="FitContainer",t.FillContainer="FillContainer"}(we||(we={}));class be{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}const Ce={ScreenResize:"resize",PixelRatioChange:"pixelratio",FullScreenChange:"fullscreen"};class Ae{constructor(t){var e,i,s;this.events=new d,this._antialiasing=!0,this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullScreen=!1,this._isDisposed=!1,this._logger=J.getInstance(),this._fullscreenChangeHandler=()=>{this._isFullScreen=!this._isFullScreen,this._logger.debug("Fullscreen Change",this._isFullScreen),this.events.emit("fullscreen",{fullscreen:this.isFullScreen})},this._pixelRatioChangeHandler=()=>{this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._listenForPixelRatio(),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport(),this.events.emit("pixelratio",{pixelRatio:this.pixelRatio})},this._resizeHandler=()=>{const t=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(t),this.applyResolutionAndViewport(),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._alreadyWarned=!1,this._contentArea=new At,this.viewport=t.viewport,this.resolution=null!==(e=t.resolution)&&void 0!==e?e:{...this.viewport},this._contentResolution=this.resolution,this._displayMode=null!==(i=t.displayMode)&&void 0!==i?i:we.Fixed,this._canvas=t.canvas,this.graphicsContext=t.context,this._antialiasing=null!==(s=t.antialiasing)&&void 0!==s?s:this._antialiasing,this._browser=t.browser,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._listenForPixelRatio(),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}_listenForPixelRatio(){this._mediaQueryList&&!this._mediaQueryList.addEventListener&&this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler,{once:!0}):this._mediaQueryList.addListener(this._pixelRatioChangeHandler)}dispose(){this._isDisposed||(this._isDisposed=!0,this._browser.window.off("resize",this._resizeHandler),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler))}_calculateDevicePixelRatio(){if(window.devicePixelRatio<1)return 1;return window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get isHiDpi(){return 1!==this.pixelRatio}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){switch(this.displayMode){case we.FillContainer:case we.FitContainer:case we.FitContainerAndFill:case we.FitContainerAndZoom:return this.canvas.parentElement||document.body;default:return window}}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution={...this.resolution},this.viewport={...this.viewport}}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop()}applyResolutionAndViewport(){if(this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this.graphicsContext instanceof fe){this.graphicsContext.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})||this._alreadyWarned||(this._alreadyWarned=!0,this._logger.warn(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) and pixel ratio (${this.pixelRatio}) are too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`))}this._antialiasing?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",""===this._canvas.style.imageRendering&&(this._canvas.style.imageRendering="crisp-edges")),this._canvas.style.width=this.viewport.width+"px",this._canvas.style.height=this.viewport.height+"px",this.graphicsContext.updateViewport(this.resolution),this.graphicsContext.resetTransform(),this.graphicsContext.smoothing=this._antialiasing,this.graphicsContext instanceof ye&&this.graphicsContext.scale(this.pixelRatio,this.pixelRatio)}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this.graphicsContext.smoothing=this._antialiasing}get isFullScreen(){return this._isFullScreen}goFullScreen(t){if(t){const e=document.getElementById(t);if(e){e.getAttribute("ex-fullscreen-listener")||(e.setAttribute("ex-fullscreen-listener","true"),e.addEventListener("fullscreenchange",this._fullscreenChangeHandler));return e.requestFullscreen()}}return this._canvas.requestFullscreen()}exitFullScreen(){return document.exitFullscreen()}pageToScreenCoordinates(t){let e=t.x,i=t.y;if(this._isFullScreen||(e-=St(this._canvas).x,i-=St(this._canvas).y),this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio;i=(i-(window.innerHeight-t)/2)/t*this.viewport.height,e=e/window.innerWidth*this.viewport.width}else{const t=window.innerHeight*this.aspectRatio;e=(e-(window.innerWidth-t)/2)/t*this.viewport.width,i=i/window.innerHeight*this.viewport.height}return e=e/this.viewport.width*this.resolution.width,i=i/this.viewport.height*this.resolution.height,new vt(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;if(e=e/this.resolution.width*this.viewport.width,i=i/this.resolution.height*this.viewport.height,this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio,s=(window.innerHeight-t)/2;i=i/this.viewport.height*t+s,e=e/this.viewport.width*window.innerWidth}else{const t=window.innerHeight*this.aspectRatio,s=(window.innerWidth-t)/2;e=e/this.viewport.width*t+s,i=i/this.viewport.height*window.innerHeight}return this._isFullScreen||(e+=St(this._canvas).x,i+=St(this._canvas).y),new vt(e,i)}screenToWorldCoordinates(t){return this._camera?this._camera.inverse.multiply(t):t.sub(xt(this.resolution.width/2,this.resolution.height/2))}worldToScreenCoordinates(t){return this._camera?this._camera.transform.multiply(t):t.add(xt(this.resolution.width/2,this.resolution.height/2))}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){return At.fromDimension(this.resolution.width,this.resolution.height,vt.Half).scale(xt(1/this._camera.zoom,1/this._camera.zoom)).rotate(this._camera.rotation).translate(this._camera.pos)}getScreenBounds(){return At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero,vt.Zero)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return xt(this.halfDrawWidth,this.halfDrawHeight)}get contentArea(){return this._contentArea}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i},this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero)}_computeFitScreenAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndFill(t,e)}_computeFitContainerAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.canvas.parentElement,e=t.clientWidth,i=t.clientHeight;this._computeFitAndFill(e,i)}_computeFitAndFill(t,e){if(this.viewport={width:t,height:e},t/e<=this._contentResolution.width/this._contentResolution.height){this.resolution={width:t*this._contentResolution.width/t,height:t*this._contentResolution.width/t*e/t};const i=(this.resolution.height-this._contentResolution.height)/2;this._contentArea=new At({top:i,left:0,right:this._contentResolution.width,bottom:this.resolution.height-i})}else{this.resolution={width:e*this._contentResolution.height/e*t/e,height:e*this._contentResolution.height/e};const i=(this.resolution.width-this._contentResolution.width)/2;this._contentArea=new At({top:0,left:i,right:this.resolution.width-i,bottom:this._contentResolution.height})}}_computeFitScreenAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndZoom(t,e)}_computeFitContainerAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=this.canvas.parentElement;t.style.position="relative",t.style.overflow="hidden";const e=t.clientWidth,i=t.clientHeight;this._computeFitAndZoom(e,i)}_computeFitAndZoom(t,e){const i=this.aspectRatio;let s=0,n=0;t/i<e?(s=t,n=t/i):(s=e*i,n=e);const r=t/s,o=e/n,a=Math.max(r,o),h=s*a,l=n*a;this.canvas.style.left=h>t?-(h-t)/2+"px":"",this.canvas.style.top=l>e?-(l-e)/2+"px":"",this.viewport={width:h,height:l};const c=At.fromDimension(this.viewport.width,this.viewport.height,vt.Zero);if(this.viewport.width>t){const e=(this.viewport.width-t)/this.viewport.width*this.resolution.width;c.top=0,c.left=e/2,c.right=this.resolution.width-e/2,c.bottom=this.resolution.height}if(this.viewport.height>e){const t=(this.viewport.height-e)/this.viewport.height*this.resolution.height;c.top=t/2,c.left=0,c.bottom=this.resolution.height-t/2,c.right=this.resolution.width}this._contentArea=c}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0;const s=this.canvas.parentElement;s.clientWidth/t<s.clientHeight?(e=s.clientWidth,i=s.clientWidth/t):(e=s.clientHeight*t,i=s.clientHeight),this.viewport={width:e,height:i},this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero)}_applyDisplayMode(){this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver((()=>{this._resizeHandler()})),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler)}_setResolutionAndViewportByDisplayMode(t){this.displayMode===we.FillContainer&&(this.resolution={width:t.clientWidth,height:t.clientHeight},this.viewport=this.resolution),this.displayMode===we.FillScreen&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this._contentArea=At.fromDimension(this.resolution.width,this.resolution.height,vt.Zero),this.displayMode===we.FitScreen&&this._computeFit(),this.displayMode===we.FitContainer&&this._computeFitContainer(),this.displayMode===we.FitScreenAndFill&&this._computeFitScreenAndFill(),this.displayMode===we.FitContainerAndFill&&this._computeFitContainerAndFill(),this.displayMode===we.FitScreenAndZoom&&this._computeFitScreenAndZoom(),this.displayMode===we.FitContainerAndZoom&&this._computeFitContainerAndZoom()}}class Te{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}Te._INSTANCE=null;class Se{static unlock(){return new Promise(((t,e)=>{if(Se._UNLOCKED||!Te.create())return t(!0);const i=setTimeout((()=>{J.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),t(!1)}),200),s=Te.create();s.resume().then((()=>{const e=s.createBuffer(1,1,22050),n=s.createBufferSource();let r=!1;n.buffer=e,n.connect(s.destination),n.onended=()=>r=!0,n.start(0),setTimeout((()=>{!function(t){return!!t.playbackState}(n)?(s.currentTime>0||r)&&(Se._UNLOCKED=!0):n.playbackState!==n.PLAYING_STATE&&n.playbackState!==n.FINISHED_STATE||(Se._UNLOCKED=!0)}),0),clearTimeout(i),t(!0)}),(()=>{e()}))}))}static isUnlocked(){return this._UNLOCKED}}function Ee(t,e=yt.Red,i,s,n,r,o=1,a="butt"){t.save(),t.beginPath(),t.lineWidth=o,t.lineCap=a,t.strokeStyle=e.toString(),t.moveTo(i,s),t.lineTo(n,r),t.closePath(),t.stroke(),t.restore()}function Pe(t,e=yt.Red,i){t.beginPath(),t.strokeStyle=e.toString(),t.arc(i.x,i.y,5,0,2*Math.PI),t.closePath(),t.stroke()}function Ie(t,e,i,s,n=1){const r=e?e.toString():"blue",o=s.scale(n);t.beginPath(),t.strokeStyle=r,t.moveTo(i.x,i.y),t.lineTo(i.x+o.x,i.y+o.y),t.closePath(),t.stroke()}function De(t,e,i,s,n,r=5,o=yt.White,a=null){let h;if("number"==typeof r)h={tl:r,tr:r,br:r,bl:r};else{const t={tl:0,tr:0,br:0,bl:0};for(const e in t)if(t.hasOwnProperty(e)){const i=e;h[i]=r[i]||t[i]}}t.beginPath(),t.moveTo(e+h.tl,i),t.lineTo(e+s-h.tr,i),t.quadraticCurveTo(e+s,i,e+s,i+h.tr),t.lineTo(e+s,i+n-h.br),t.quadraticCurveTo(e+s,i+n,e+s-h.br,i+n),t.lineTo(e+h.bl,i+n),t.quadraticCurveTo(e,i+n,e,i+n-h.bl),t.lineTo(e,i+h.tl),t.quadraticCurveTo(e,i,e+h.tl,i),t.closePath(),a&&(t.fillStyle=a.toString(),t.fill()),o&&(t.strokeStyle=o.toString(),t.stroke())}function Be(t,e,i,s,n=yt.White,r=null){t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),r&&(t.fillStyle=r.toString(),t.fill()),n&&(t.strokeStyle=n.toString(),t.stroke())}Se._UNLOCKED=!1;var Re=i(1388);class Fe extends Ht{constructor(t){var e,i,s,n,r,o,a,h,l,c;super(Rt(t,["width","height"])),this.filtering=null,this.lineCap="butt",this.quality=1,this._dirty=!0,this._smoothing=!1,this._color=Ot(yt.Black,(()=>this.flagDirty())),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.quality=null!==(e=t.quality)&&void 0!==e?e:this.quality,this.color=null!==(i=t.color)&&void 0!==i?i:yt.Black,this.strokeColor=null==t?void 0:t.strokeColor,this.smoothing=null!==(s=t.smoothing)&&void 0!==s?s:this.smoothing,this.lineWidth=null!==(n=t.lineWidth)&&void 0!==n?n:this.lineWidth,this.lineDash=null!==(r=t.lineDash)&&void 0!==r?r:this.lineDash,this.lineCap=null!==(o=t.lineCap)&&void 0!==o?o:this.lineCap,this.padding=null!==(a=t.padding)&&void 0!==a?a:this.padding,this.filtering=null!==(h=t.filtering)&&void 0!==h?h:this.filtering),this._bitmap=document.createElement("canvas");const d=null!==(l=null==t?void 0:t.width)&&void 0!==l?l:this._bitmap.width,u=null!==(c=null==t?void 0:t.height)&&void 0!==c?c:this._bitmap.height;this.width=d,this.height=u;const p=this._bitmap.getContext("2d");if(!p)throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic");this._ctx=p}cloneRasterOptions(){return{color:this.color?this.color.clone():null,strokeColor:this.strokeColor?this.strokeColor.clone():null,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,lineCap:this.lineCap,quality:this.quality,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return Math.abs(this._getTotalWidth()*this.scale.x)}set width(t){t/=Math.abs(this.scale.x),this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return Math.abs(this._getTotalHeight()*this.scale.y)}set height(t){t/=Math.abs(this.scale.y),this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return 1*((null!==(t=this._originalWidth)&&void 0!==t?t:this._bitmap.width)+2*this.padding)}_getTotalHeight(){var t;return 1*((null!==(t=this._originalHeight)&&void 0!==t?t:this._bitmap.height)+2*this.padding)}get localBounds(){return At.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,vt.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){this.flagDirty(),this._color=Ot(t,(()=>this.flagDirty()))}get strokeColor(){return this._strokeColor}set strokeColor(t){this.flagDirty(),this._strokeColor=Ot(t,(()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperties(this._ctx),this.execute(this._ctx),this._ctx.restore()}_applyRasterProperties(t){var e,i,s;this._bitmap.width=this._getTotalWidth()*this.quality,this._bitmap.height=this._getTotalHeight()*this.quality,this._bitmap.setAttribute("filtering",this.filtering),this._bitmap.setAttribute("forceUpload","true"),t.scale(this.quality,this.quality),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash(null!==(e=this.lineDash)&&void 0!==e?e:t.getLineDash()),t.lineCap=this.lineCap,t.strokeStyle=null===(i=this.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=null===(s=this.color)||void 0===s?void 0:s.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.scale(1/this.quality,1/this.quality),t.drawImage(this._bitmap,e,i)}}class ke extends Fe{get ctx(){return this._ctx}constructor(t){super(t),this._options=t}clone(){return new ke({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(null===(e=this._options)||void 0===e?void 0:e.draw)&&(null===(i=this._options)||void 0===i||i.draw(t)),this._options.cache||this.flagDirty()}}class Me{}Me.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Le{constructor(){this.states=new Map}get currentState(){return this._currentState}set currentState(t){this._currentState=t}static create(t,e){const i=new Le;i.data=e;for(const e in t.states)i.states.set(e,{name:e,...t.states[e]});for(const t of i.states.values())for(const e of t.transitions)if("*"!==e&&!i.states.has(e))throw Error(`Invalid state machine, state [${t.name}] has a transition to another state that doesn't exist [${e}]`);return i.currentState=i.startState=i.states.get(t.start),i}in(t){return this.currentState.name===t}go(t,e){var i,s;if(this.currentState.transitions.includes(t)||this.currentState.transitions.includes("*")){const n=this.states.get(t);if(this.currentState.onExit){if(!1===(null===(i=this.currentState)||void 0===i?void 0:i.onExit({to:n.name,data:this.data})))return!1}if(null==n?void 0:n.onEnter){if(!1===(null==n?void 0:n.onEnter({from:this.currentState.name,eventData:e,data:this.data})))return!1}return this.currentState=n,(null===(s=this.currentState)||void 0===s?void 0:s.onState)&&this.currentState.onState(),!0}return!1}update(t){this.currentState.onUpdate&&this.currentState.onUpdate(this.data,t)}save(t){localStorage.setItem(t,JSON.stringify({currentState:this.currentState.name,data:this.data}))}restore(t){const e=JSON.parse(localStorage.getItem(t));this.currentState=this.states.get(e.currentState),this.data=e.data}}class ze{_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.value=this._playbackRate,this._instance.connect(this._volumeNode),this._volumeNode.connect(this._audioContext.destination)}_handleEnd(){this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)})}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)}))}get loop(){return this._loop}set volume(t){t=dt(t,0,1),this._volume=t,this._stateMachine.in("PLAYING")&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}get duration(){var t;return null!==(t=this._duration)&&void 0!==t?t:this.getTotalPlaybackDuration()}set duration(t){this._duration=t}constructor(t){this._src=t,this._audioContext=Te.create(),this._volumeNode=this._audioContext.createGain(),this._playingFuture=new Tt,this._stateMachine=Le.create({start:"STOPPED",states:{PLAYING:{onEnter:({data:t})=>{this._createNewBufferSource(),this._handleEnd(),this.loop?this._instance.start(0,t.pausedAt*this._playbackRate):this._instance.start(0,t.pausedAt*this._playbackRate,this.duration),t.startedAt=this._audioContext.currentTime-t.pausedAt,t.pausedAt=0},onState:()=>this._playStarted(),onExit:({to:t})=>{"STOPPED"===t&&this._playingFuture.resolve(!0),this._instance.onended=null,this._instance.disconnect(),this._instance.stop(0),this._instance=null},transitions:["STOPPED","PAUSED","SEEK"]},SEEK:{onEnter:({eventData:t,data:e})=>{e.pausedAt=(null!=t?t:0)/this._playbackRate,e.startedAt=0},transitions:["*"]},STOPPED:{onEnter:({data:t})=>{t.pausedAt=0,t.startedAt=0,this._playingFuture.resolve(!0)},transitions:["PLAYING","PAUSED","SEEK"]},PAUSED:{onEnter:({data:t})=>{t.pausedAt=this._audioContext.currentTime-t.startedAt},transitions:["PLAYING","STOPPED","SEEK"]}}},{startedAt:0,pausedAt:0}),this._volume=1,this._loop=!1,this._playStarted=()=>{},this._playbackRate=1,this._createNewBufferSource()}isPlaying(){return this._stateMachine.in("PLAYING")}isPaused(){return this._stateMachine.in("PAUSED")||this._stateMachine.in("SEEK")}isStopped(){return this._stateMachine.in("STOPPED")}play(t=(()=>{})){return this._playStarted=t,this._stateMachine.go("PLAYING"),this._playingFuture.promise}pause(){this._stateMachine.go("PAUSED")}stop(){this._stateMachine.go("STOPPED")}seek(t){this._stateMachine.go("PAUSED"),this._stateMachine.go("SEEK",t)}getTotalPlaybackDuration(){return this._src.duration}getPlaybackPosition(){const{pausedAt:t,startedAt:e}=this._stateMachine.data;return t?t*this._playbackRate:e?(this._audioContext.currentTime-e)*this._playbackRate:0}set playbackRate(t){this._instance.playbackRate.value=this._playbackRate=t}get playbackRate(){return this._instance.playbackRate.value}}class Ue extends u{set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}stopPropagation(){}action(){}propagate(){}layPath(t){}}class Oe extends Ue{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class Ne extends Ue{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}function He(t){try{const e=new Audio,i=/.*\.([A-Za-z0-9]+)(?:(?:\?|\#).*)*$/,s=t.match(i)[1];return!!e.canPlayType("audio/"+s)}catch(t){return J.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}const We={VolumeChange:"volumechange",Processed:"processed",Pause:"pause",Stop:"stop",PlaybackEnd:"playbackend",Resume:"resume",PlaybackStart:"playbackstart"};class Ge{set loop(t){this._loop=t;for(const t of this._tracks)t.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const t of this._tracks)t.volume=this._volume;this.events.emit("volumechange",new Oe(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}set duration(t){this._duration=t}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}constructor(...t){this.events=new d,this.logger=J.getInstance(),this._loop=!1,this._volume=1,this._isStopped=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._playbackRate=1,this._audioContext=Te.create(),this._resource=new Ut("",Me.type.arraybuffer);for(const e of t)if(He(e)){this.path=e;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",t.join(", ")),this.logger.warn("Attempting to use",t[0]),this.path=t[0])}isLoaded(){return!!this.data}async load(){var t,e;if(this.data)return this.data;const i=await this._resource.load(),s=await this.decodeAudio(i.slice(0));return this._duration=null!==(e=null!==(t=this._duration)&&void 0!==t?t:null==s?void 0:s.duration)&&void 0!==e?e:void 0,this.events.emit("processed",new Ne(this,s)),this.data=s}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(t){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),await Promise.reject()}}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",(()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())})),this._engine.on("visible",(()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)})),this._engine.on("start",(()=>{this._isStopped=!1})),this._engine.on("stop",(()=>{this.stop(),this._isStopped=!0})))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some((t=>t.isPlaying()))}isPaused(){return this._tracks.some((t=>t.isPaused()))}isStopped(){return this._tracks.some((t=>t.isStopped()))}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t||this.volume,this.isPaused()?this._resumePlayback():this._startPlayback()):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this.events.emit("pause",new Oe(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.events.emit("stop",new Oe(this)),this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._tracks.forEach((t=>{t.playbackRate=this._playbackRate}))}seek(t,e=0){0===this._tracks.length&&this._getTrackInstance(this.data),this._tracks[e].seek(t)}getTotalPlaybackDuration(){return this.data.duration}getPlaybackPosition(t=0){return this._tracks.length?this._tracks[t].getPlaybackPosition():0}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(){if(this.isPaused){const t=[];for(const e of this._tracks)t.push(e.play().then((()=>(this.events.emit("playbackend",new Oe(this,e)),this._tracks.splice(this.getTrackId(e),1),!0))));this.events.emit("resume",new Oe(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(t)}return!0}async _startPlayback(){const t=this._getTrackInstance(this.data),e=await t.play((()=>{this.events.emit("playbackstart",new Oe(this,t)),this.logger.debug("Playing new instance for sound",this.path)}));this.events.emit("playbackend",new Oe(this,t));const i=this.getTrackId(t);return-1!==i&&this._tracks.splice(i,1),e}_getTrackInstance(t){const e=new ze(t);return e.loop=this.loop,e.volume=this.volume,e.duration=this.duration,e.playbackRate=this._playbackRate,this._tracks.push(e),e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Ve={};class qe{get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.src=this.logo),this._imageElement}_getScreenParent(){return this._engine?this._engine.screen.canvas.parentElement:document.body}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");if(t&&(this._playButtonRootElement=t),!this._playButtonRootElement){this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute";this._getScreenParent().appendChild(this._playButtonRootElement)}return this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}constructor(t){this.events=new d,this.canvas=new ke({filtering:Gt.Blended,smoothing:!0,cache:!0,draw:this.draw.bind(this)}),this._resourceList=[],this._index=0,this._playButtonShown=!1,this._resourceCount=0,this._numLoaded=0,this._progressCounts={},this._totalCounts={},this.logo="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=yt.White,this.backgroundColor="#176BAA",this.suppressPlayButton=!1,this._playButtonStyles=Re.Z.toString(),this.playButtonText="Play game",this.startButtonFactory=()=>{let t=document.getElementById("excalibur-play");return t||(t=document.createElement("button")),t.id="excalibur-play",t.textContent=this.playButtonText,t.style.display="none",t},this._loaderResizeHandler=t=>{this._engine.screen.resolution=this._engine.screen.viewport,this._engine.screen.applyResolutionAndViewport(),this.canvas.width=t.viewport.width,this.canvas.height=t.viewport.height,this.canvas.flagDirty()},this._loadingFuture=new Tt,t&&this.addResources(t)}wireEngine(t){this._engine||(this._engine=t,this.canvas.width=this._engine.canvas.width,this.canvas.height=this._engine.canvas.height)}addResource(t){const e=this._index++;this._resourceList.push(t),this._progressCounts[e]=0,this._totalCounts[e]=1,this._resourceCount++}addResources(t){let e=0;const i=t.length;for(;e<i;e++)this.addResource(t[e])}isLoaded(){return this._numLoaded===this._resourceCount}async showPlayButton(){var t,e;if(!this.suppressPlayButton){const t=()=>{this._positionPlayButton()};(null===(e=this._engine)||void 0===e?void 0:e.browser)&&this._engine.browser.window.on("resize",t),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",(t=>{"Enter"===t.key&&this._playButton.click()})),this._positionPlayButton();const i=new Promise((e=>{const i=i=>{var s;i.stopPropagation(),this.hidePlayButton(),(null===(s=this._engine)||void 0===s?void 0:s.browser)&&this._engine.browser.window.off("resize",t),e()};this._playButton.addEventListener("click",i),this._playButton.addEventListener("touchend",i),this._playButton.addEventListener("pointerup",i)}));return await i}this.hidePlayButton(),await Bt(500,null===(t=this._engine)||void 0===t?void 0:t.clock)}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}update(t,e){}areResourcesLoaded(){return this._loadingFuture.promise}async load(){var t,e;this._engine.screen.events.on("resize",this._loaderResizeHandler),await(null===(t=this._image)||void 0===t?void 0:t.decode()),this.canvas.flagDirty(),await Promise.all(this._resourceList.map((async t=>{await t.load().finally((()=>{this._numLoaded++,this.canvas.flagDirty()}))})));for(const t of this._resourceList)t instanceof Ge&&t.wireEngine(this._engine);return this._loadingFuture.resolve(),await Bt(200,null===(e=this._engine)||void 0===e?void 0:e.clock),this.canvas.flagDirty(),await this.showPlayButton(),await Se.unlock(),this._engine.screen.events.off("resize",this._loaderResizeHandler),this.data=this._resourceList}markResourceComplete(){this._numLoaded++}get progress(){return this._resourceCount>0?dt(this._numLoaded,0,this._resourceCount)/this._resourceCount:1}_positionPlayButton(){if(this._engine){const t=this._engine.screen.viewport.height,e=this._engine.screen.viewport.width;if(this._playButtonRootElement){const i=this._engine.canvas.offsetLeft,s=this._engine.canvas.offsetTop,n=this._playButton.clientWidth,r=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=i+e/2-n/2+"px",this._playButtonRootElement.style.top=s+t/2-r/2+100+"px")}}}draw(t){const e=this._engine.canvasHeight/this._engine.pixelRatio,i=this._engine.canvasWidth/this._engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,.75*i);let r=i/2-n/2;this.logoPosition&&(r=this.logoPosition.x,s=this.logoPosition.y);const o=Math.floor(n*(this.logoHeight/this.logoWidth)),a=this._engine.getAntialiasing();if(this._engine.setAntialiasing(!0),this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s,n,o):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s-o-20,n,o),!this.suppressPlayButton&&this._playButtonShown)return void this._engine.setAntialiasing(a);let h=r,l=s;this.loadingBarPosition&&(h=this.loadingBarPosition.x,l=this.loadingBarPosition.y),t.lineWidth=2,De(t,h,l,n,20,10,this.loadingBarColor);const c=n*this.progress-10;De(t,h+5,l+5,c>10?c:10,10,5,null,this.loadingBarColor),this._engine.setAntialiasing(a)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Xe={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class Ke{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(t){return!1}return"arraybuffer"===t.responseType},dataUrlSupport:function(){return 0===document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return null===this._features&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t="%cSUPPORTED BROWSER FEATURES\n==========================%c\n";const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(Xe))i[s]?(t+="(%c✓%c)",e.push("font-weight: bold; color: green"),e.push("font-weight: normal; color: inherit")):(t+="(%c✗%c)",e.push("font-weight: bold; color: red"),e.push("font-weight: normal; color: inherit")),t+=" "+Xe[s]+"\n";e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:(()=>this._criticalTests.canvasSupport())(),arraybuffer:(()=>this._criticalTests.arrayBufferSupport())(),dataurl:(()=>this._criticalTests.dataUrlSupport())(),objecturl:(()=>this._criticalTests.objectUrlSupport())(),rgba:(()=>this._criticalTests.rgbaSupport())(),webaudio:(()=>this._warningTest.webAudioSupport())(),webgl:(()=>this._warningTest.webglSupport())(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),J.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const t in this._warningTest)this._warningTest[t]()||J.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",t);return!0}}var Ze;!function(t){t.PreventCollision="PreventCollision",t.Passive="Passive",t.Active="Active",t.Fixed="Fixed"}(Ze||(Ze={}));const Ye=5,je={},Qe=()=>{for(const t in je)je[t]=0},$e=(t,e)=>{const i=l.isEnabled("suppress-obsolete-message");je[t]<Ye&&!i&&(J.getInstance().warn(t),console.trace&&e.showStackTrace&&console.trace()),je[t]++};function Je(t){return t={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...t},function(e,i,s){if(s&&"function"!=typeof s.value&&"function"!=typeof s.get&&"function"!=typeof s.set)throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${e.name||""}${e.name&&i?".":""}${i||""}`} is marked obsolete: ${t.message}`+(t.alternateMethod?` Use ${t.alternateMethod} instead`:"");je[n]||(je[n]=0);const r=s?{...s}:e;if(!s){class e extends r{constructor(...e){$e(n,t),super(...e)}}return e}return s&&s.value?(r.value=function(){return $e(n,t),s.value.apply(this,arguments)},r):(s&&s.get&&(r.get=function(){return $e(n,t),s.get.apply(this,arguments)}),s&&s.set&&(r.set=function(){return $e(n,t),s.set.apply(this,arguments)}),r)}}var ti,ei,ii,si,ni=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t.Arcade="arcade",t.Realistic="realistic"}(ti||(ti={})),function(t){t[t.DynamicAABBTree=0]="DynamicAABBTree"}(ei||(ei={})),function(t){t[t.Euler=0]="Euler"}(ii||(ii={}));class ri{static get gravity(){return ri.acc}static set gravity(t){ri.acc=t}static useArcadePhysics(){ri.collisionResolutionStrategy=ti.Arcade}static useRealisticPhysics(){ri.collisionResolutionStrategy=ti.Realistic}static get dynamicTreeVelocityMultiplyer(){return ri.dynamicTreeVelocityMultiplier}static set dynamicTreeVelocityMultiplyer(t){ri.dynamicTreeVelocityMultiplier=t}}ri.acc=new vt(0,0),ri.enabled=!0,ri.broadphaseStrategy=ei.DynamicAABBTree,ri.collisionResolutionStrategy=ti.Arcade,ri.defaultMass=10,ri.integrator=ii.Euler,ri.dynamicTreeVelocityMultiplier=2,ri.boundsPadding=5,ri.positionIterations=3,ri.velocityIterations=8,ri.slop=1,ri.steeringFactor=.2,ri.warmStart=!0,ri.bodiesCanSleepByDefault=!1,ri.surfaceEpsilon=.1,ri.sleepEpsilon=.07,ri.wakeThreshold=3*ri.sleepEpsilon,ri.sleepBias=.9,ri.checkForFastBodies=!0,ri.disableMinimumSpeedForFastBody=!1,ni([Je({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"dynamicTreeVelocityMultiplier"})],ri,"dynamicTreeVelocityMultiplyer",null),function(t){t.World="world",t.Screen="screen"}(si||(si={}));class oi extends vt{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}class ai extends vt{constructor(t,e){super(t.x,t.y),this.original=t,this.change=e}get x(){return this._x=this.original.x}set x(t){this.change(t,this._y),this._x=this.original.x=t}get y(){return this._y=this.original.y}set y(t){this.change(this._x,t),this._y=this.original.y=t}}class hi{constructor(){this._parent=null,this._children=[],this._pos=xt(0,0),this._rotation=0,this._scale=xt(1,1),this._isDirty=!1,this._isInverseDirty=!1,this._matrix=kt.identity(),this._inverse=kt.identity()}get parent(){return this._parent}set parent(t){if(this._parent){const t=this._parent._children.indexOf(this);t>-1&&this._parent._children.splice(t,1)}this._parent=t,this._parent&&this._parent._children.push(this),this.flagDirty()}get children(){return this._children}set pos(t){t.equals(this._pos)||(this._pos.x=t.x,this._pos.y=t.y,this.flagDirty())}get pos(){return new ai(this._pos,((t,e)=>{t===this._pos.x&&e===this._pos.y||this.flagDirty()}))}set globalPos(t){let e=t.clone();this.parent&&(e=this.parent.inverse.multiply(t)),e.equals(this._pos)||(this._pos=e,this.flagDirty())}get globalPos(){return new oi({getX:()=>this.matrix.data[4],getY:()=>this.matrix.data[5],setX:t=>{if(this.parent){const{x:e}=this.parent.inverse.multiply(xt(t,this.pos.y));this.pos.x=e}else this.pos.x=t;t!==this.matrix.data[4]&&this.flagDirty()},setY:t=>{if(this.parent){const{y:e}=this.parent.inverse.multiply(xt(this.pos.x,t));this.pos.y=e}else this.pos.y=t;t!==this.matrix.data[5]&&this.flagDirty()}})}set rotation(t){const e=ut(t);e!==this._rotation&&this.flagDirty(),this._rotation=e}get rotation(){return this._rotation}set globalRotation(t){let e=0;this.parent&&(e=this.parent.globalRotation);const i=ut(t+e);i!==this._rotation&&this.flagDirty(),this._rotation=i}get globalRotation(){return this.parent?this.matrix.getRotation():this.rotation}set scale(t){t.equals(this._scale)||(this._scale.x=t.x,this._scale.y=t.y,this.flagDirty())}get scale(){return new ai(this._scale,((t,e)=>{t===this._scale.x&&e===this._scale.y||this.flagDirty()}))}set globalScale(t){let e=xt(1,1);this.parent&&(e=this.parent.globalScale),this.scale=t.scale(xt(1/e.x,1/e.y))}get globalScale(){return new oi({getX:()=>this.parent?this.matrix.getScaleX():this.scale.x,getY:()=>this.parent?this.matrix.getScaleY():this.scale.y,setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.scale.x=t/e}else this.scale.x=t},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.scale.y=t/e}else this.scale.y=t}})}get matrix(){return this._isDirty&&(null===this.parent?this._matrix=this._calculateMatrix():this._matrix=this.parent.matrix.multiply(this._calculateMatrix()),this._isDirty=!1),this._matrix}get inverse(){return this._isInverseDirty&&(this._inverse=this.matrix.inverse(),this._isInverseDirty=!1),this._inverse}_calculateMatrix(){return kt.identity().translate(this.pos.x,this.pos.y).rotate(this.rotation).scale(this.scale.x,this.scale.y)}flagDirty(){this._isDirty=!0,this._isInverseDirty=!0;for(let t=0;t<this._children.length;t++)this._children[t].flagDirty()}apply(t){return this.matrix.multiply(t)}applyInverse(t){return this.inverse.multiply(t)}setTransform(t,e,i){this._pos.x=t.x,this._pos.y=t.y,this._rotation=ut(e),this._scale.x=i.x,this._scale.y=i.y,this.flagDirty()}clone(t){const e=null!=t?t:new hi;return this._pos.clone(e._pos),e._rotation=this._rotation,this._scale.clone(e._scale),e.flagDirty(),e}}class li{constructor(){this.owner=null}clone(){const t=new this.constructor;for(const i in this)if(this.hasOwnProperty(i)){const s=this[i];(null==(e=s)?void 0:e.clone)&&"owner"!==i&&"clone"!==i?t[i]=s.clone():t[i]=s}var e;return t}}class ci extends li{constructor(t,e){super(),this.type=t,this.value=e}}class di{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);-1!==e&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);-1!==e&&this.subscriptions.splice(e,1)}notifyAll(t){const e=this.observers.length;for(let i=0;i<e;i++)this.observers[i].notify(t);const i=this.subscriptions.length;for(let e=0;e<i;e++)this.subscriptions[e](t)}clear(){this.observers.length=0,this.subscriptions.length=0}}class ui extends li{constructor(){super(...arguments),this.type="ex.transform",this._transform=new hi,this._addChildTransform=t=>{const e=t.get(ui);e&&(e._transform.parent=this._transform)},this.zIndexChanged$=new di,this._z=0,this.coordPlane=si.World}get(){return this._transform}onAdd(t){for(const e of t.children)this._addChildTransform(e);t.childrenAdded$.subscribe((t=>this._addChildTransform(t))),t.childrenRemoved$.subscribe((t=>{const e=t.get(ui);e&&(e._transform.parent=null)}))}onRemove(t){this._transform.parent=null}get z(){return this._z}set z(t){const e=this._z;this._z=t,e!==t&&this.zIndexChanged$.notifyAll(t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get globalPos(){return this._transform.globalPos}set globalPos(t){this._transform.globalPos=t}get rotation(){return this._transform.rotation}set rotation(t){this._transform.rotation=t}get globalRotation(){return this._transform.globalRotation}set globalRotation(t){this._transform.globalRotation=t}get scale(){return this._transform.scale}set scale(t){this._transform.scale=t}get globalScale(){return this._transform.globalScale}set globalScale(t){this._transform.globalScale=t}applyInverse(t){return this._transform.applyInverse(t)}apply(t){return this._transform.apply(t)}clone(){const t=new ui;return t._transform=this._transform.clone(),t._z=this._z,t}}class pi extends li{constructor(){super(...arguments),this.type="ex.motion",this.vel=vt.Zero,this.acc=vt.Zero,this.scaleFactor=vt.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1}}class _i{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t)){const i=this._GROUPS.get(t);if(i.mask===e)return i;throw new Error(`Collision group ${t} already exists with a different mask!`)}const i=new gi(t,this._CURRENT_BIT,void 0!==e?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}}_i._STARTING_BIT=1,_i._MAX_GROUPS=32,_i._CURRENT_GROUP=1,_i._CURRENT_BIT=_i._STARTING_BIT,_i._GROUPS=new Map;class gi{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){const e=this.category&t.mask,i=this.mask&t.category;return 0!==e&&0!==i}invert(){const t=_i.create("~("+this.name+")",0|~this.mask);return t._category=~this.category,t}static combine(t){const e=t.map((t=>t.name)).join("+"),i=~t.reduce(((t,e)=>e.category|t),0);return _i.create(e,i)}static collidesWith(t){const e=`collidesWith(${t.map((t=>t.name)).join("+")})`,i=t.reduce(((t,e)=>e.category|t),0);return _i.create(e,i)}toString(){return`\ncategory: ${this.category.toString(2).padStart(32,"0")}\nmask: ${(this.mask>>>0).toString(2).padStart(32,"0")}\n `}}gi.All=new gi("Collide with all groups",-1,-1);class mi{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=mi.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;const n=null===(i=null==t?void 0:t.owner)||void 0===i?void 0:i.get(Li),r=null===(s=null==e?void 0:e.owner)||void 0===s?void 0:s.get(Li);return t.id!==e.id&&((!t.owner||!e.owner||t.owner.id!==e.owner.id)&&(!t.localBounds.hasZeroDimensions()&&!e.localBounds.hasZeroDimensions()&&(!(!n||!r)&&(!!n.group.canCollide(r.group)&&((n.collisionType!==Ze.Fixed||r.collisionType!==Ze.Fixed)&&(r.collisionType!==Ze.PreventCollision&&n.collisionType!==Ze.PreventCollision&&!(!n.active||!r.active)))))))}get canCollide(){const t=this.colliderA,e=this.colliderB;return mi.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class fi{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class vi{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new At,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class xi{constructor(t=new At(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this.worldBounds=t,this.root=null,this.nodes={}}_insert(t){if(null===this.root)return this.root=t,void(this.root.parent=null);const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const t=i.left,s=i.right,n=i.bounds.getPerimeter(),r=i.bounds.combine(e).getPerimeter(),o=2*r,a=2*(r-n);let h=0;const l=e.combine(t.bounds);let c,d;t.isLeaf()?h=l.getPerimeter()+a:(d=t.bounds.getPerimeter(),c=l.getPerimeter(),h=c-d+a);let u=0;const p=e.combine(s.bounds);if(s.isLeaf()?u=p.getPerimeter()+a:(d=s.bounds.getPerimeter(),c=p.getPerimeter(),u=c-d+a),o<h&&o<u)break;i=h<u?t:s}const s=i.parent,n=new vi(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,null!==s?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let r=t.parent;for(;r;){if(r=this._balance(r),!r.left)throw new Error("Parent of current leaf cannot have a null left child"+r);if(!r.right)throw new Error("Parent of current leaf cannot have a null right child"+r);r.height=1+Math.max(r.left.height,r.right.height),r.bounds=r.left.bounds.combine(r.right.bounds),r=r.parent}}_remove(t){if(t===this.root)return void(this.root=null);const e=t.parent,i=e.parent;let s;if(s=e.left===t?e.right:e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let t=i;for(;t;)t=this._balance(t),t.bounds=t.left.bounds.combine(t.right.bounds),t.height=1+Math.max(t.left.height,t.right.height),t=t.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new vi;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return J.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=ri.boundsPadding,s.top-=ri.boundsPadding,s.right+=ri.boundsPadding,s.bottom+=ri.boundsPadding,t.owner){const i=null===(e=t.owner)||void 0===e?void 0:e.get(Li);if(i){const t=32*i.vel.x/1e3*ri.dynamicTreeVelocityMultiplier,e=32*i.vel.y/1e3*ri.dynamicTreeVelocityMultiplier;t<0?s.left+=t:s.right+=t,e<0?s.top+=e:s.bottom+=e}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(null===t)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,r=i,o=e.left,a=e.right,h=i.left,l=i.right,c=r.height-n.height;if(c>1)return r.left=s,r.parent=s.parent,s.parent=r,r.parent?r.parent.left===s?r.parent.left=r:r.parent.right=r:this.root=r,h.height>l.height?(r.right=h,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),r.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(n.height,l.height),r.height=1+Math.max(s.height,h.height)):(r.right=l,s.right=h,h.parent=s,s.bounds=n.bounds.combine(h.bounds),r.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,h.height),r.height=1+Math.max(s.height,l.height)),r;if(c<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return o.height>a.height?(n.right=o,s.left=a,a.parent=s,s.bounds=r.bounds.combine(a.bounds),n.bounds=s.bounds.combine(o.bounds),s.height=1+Math.max(r.height,a.height),n.height=1+Math.max(s.height,o.height)):(n.right=a,s.left=o,o.parent=s,s.bounds=r.bounds.combine(o.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(r.height,o.height),n.height=1+Math.max(s.height,a.height)),n}return t}getHeight(){return null===this.root?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.overlaps(i)){if(!n.isLeaf()||n.data===t)return s(n.left)||s(n.right);if(e.call(t,n.data))return!0}return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e)){if(!n.isLeaf())return s(n.left)||s(n.right);if(i.call(t,n.data))return!0}return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.draw(t,yt.Green):i.bounds.draw(t,yt.White),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class yi{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(0===this.dir.cross(t.getSlope())&&0!==e.cross(this.dir))return-1;const i=this.dir.cross(t.getSlope());if(0===i)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}class wi{constructor(){this._dynamicCollisionTree=new xi,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[]}getColliders(){return this._colliders}rayCast(t,e){var i,s,n;const r=[],o=null!==(i=null==e?void 0:e.maxDistance)&&void 0!==i?i:1/0,a=null==e?void 0:e.collisionGroup,h=a?a.category:null!==(s=null==e?void 0:e.collisionMask)&&void 0!==s?s:gi.All.category,l=null!==(n=null==e?void 0:e.searchAllColliders)&&void 0!==n&&n;return this._dynamicCollisionTree.rayCastQuery(t,o,(e=>{const i=e.owner.get(Li),s=0!=(h&i.group.category);if((null==i?void 0:i.group)&&!s)return!1;const n=e.rayCast(t,o);return!(!n||(r.push({distance:n.sub(t.pos).distance(),point:n,collider:e,body:i}),l))})),r}track(t){if(t)if(t instanceof Ci){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t);else J.getInstance().warn("Cannot track null collider")}untrack(t){if(t)if(t instanceof Ci){const e=t.getColliders();for(const t of e){const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}else{const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}else J.getInstance().warn("Cannot untrack a null collider")}_pairExists(t,e){const i=mi.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter((t=>{var e,i;const s=null===(e=t.owner)||void 0===e?void 0:e.get(Li);return(null===(i=t.owner)||void 0===i?void 0:i.active)&&s.collisionType!==Ze.PreventCollision}));let r;this._collisionPairCache=[],this._pairs.clear();for(let t=0,e=n.length;t<e;t++)r=n[t],this._dynamicCollisionTree.query(r,(t=>{if(!this._pairExists(r,t)&&mi.canCollide(r,t)){const e=new mi(r,t);this._pairs.add(e.id),this._collisionPairCache.push(e)}return!1}));if(i&&(i.physics.pairs=this._collisionPairCache.length),ri.checkForFastBodies)for(const t of n){const e=t.owner.get(Li);if(e.collisionType!==Ze.Active)continue;const n=e.vel.size*s+.5*e.acc.size*s*s,r=Math.min(t.bounds.height,t.bounds.width);if(ri.disableMinimumSpeedForFastBody||n>r/2){i&&i.physics.fastBodies++;const s=e.globalPos.sub(e.oldPos),r=t.center,o=t.getFurthestPoint(e.vel),a=o.sub(s),h=new yi(a,e.vel);let l;h.pos=h.pos.add(h.dir.scale(-2*ri.surfaceEpsilon));let c=new vt(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(h,n+2*ri.surfaceEpsilon,(e=>{if(!this._pairExists(t,e)&&mi.canCollide(t,e)){const t=e.rayCast(h,n+10*ri.surfaceEpsilon);if(t){const i=t.sub(a);i.size<c.size&&(c=i,l=e)}}return!1})),l&&vt.isValid(c)){const s=new mi(t,l);this._pairs.has(s.id)||(this._pairs.add(s.id),this._collisionPairCache.push(s));const n=r.sub(o);e.globalPos=a.add(n).add(c).add(h.dir.scale(10*ri.surfaceEpsilon)),t.update(e.transform.get()),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const t of n)e.physics.contacts.set(t.id,t)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}class bi{constructor(){this.id=c("collider",bi._ID++),this.__compositeColliderId=null,this.events=new d}touching(t){return!!this.collide(t)}}bi._ID=0;class Ci extends bi{constructor(t){super(),this._collisionProcessor=new wi,this._dynamicAABBTree=new xi,this._colliders=[];for(const e of t)this.addCollider(e)}clearColliders(){this._colliders=[]}addCollider(t){t.events.pipe(this.events),t.__compositeColliderId=this.id,this._colliders.push(t),this._collisionProcessor.track(t),this._dynamicAABBTree.trackCollider(t)}removeCollider(t){t.events.pipe(this.events),t.__compositeColliderId=null,Pt(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:vt.Zero}get center(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:vt.Zero}get bounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.bounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.bounds)&&void 0!==e?e:(new At).translate(this.worldPos))}get localBounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.localBounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new At)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const s of e)i.push(s.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const e of i){const i=e.dot(t);i>n&&(s=e,n=i)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof Ci&&(e=t.getColliders());const i=[];for(const t of e)this._dynamicAABBTree.query(t,(e=>(i.push(new mi(t,e)),!1)));let s=[];for(const t of i)s=s.concat(t.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof Ci){const s=t.getColliders();for(const t of e)for(const e of s){const s=t.getClosestLineBetween(e);s&&i.push(s)}}else for(const s of e){const e=t.getClosestLineBetween(s);e&&i.push(e)}if(i.length){let t=i[0].getLength(),e=i[0];for(const s of i){const i=s.getLength();i<t&&(t=i,e=s)}return e}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const i=n.rayCast(t,e);i&&s.push(i)}if(s.length){let e=s[0],i=e.dot(t.dir);for(const n of s){const s=t.dir.dot(n);s<i&&(e=n,i=s)}return e}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const e=s.project(t);e&&i.push(e)}if(i.length){const t=new fi(i[0].min,i[0].max);for(const e of i)t.min=Math.min(e.min,t.min),t.max=Math.max(e.max,t.max);return t}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}debug(t,e){const i=this.getColliders();for(const s of i)s.debug(t,e)}clone(){return new Ci(this._colliders.map((t=>t.clone())))}}class Ai{constructor(t,e){this.begin=t,this.end=e}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this._normal?this._normal:this._normal=this.end.sub(this.begin).normal()}dir(){return this._dir?this._dir:this._dir=this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){if(this._slope)return this._slope;const t=this.begin,e=this.end,i=t.distance(e);return this._slope=e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){if(this._length)return this._length;const t=this.begin,e=this.end,i=t.distance(e);return this._length=i}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new Ai(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e){let i=t;i=i.normalize();const s=i.dot(this.begin)-e,n=i.dot(this.end)-e,r=[];if(s<=0&&r.push(this.begin),n<=0&&r.push(this.end),s*n<0){const t=s/(s-n);r.push(this.begin.add(this.end.sub(this.begin).scale(t)))}return 2!==r.length?null:new Ai(r[0],r[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),r=((this.end.y-this.begin.y)*i-(this.end.x-this.begin.x)*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?r:Math.abs(r)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(null!==t)return new vt(t,i*t+s);if(null!==e)return new vt((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if("number"==typeof arguments[0]&&"number"==typeof arguments[1])t=new vt(arguments[0],arguments[1]),e=arguments[2]||0;else{if(!(arguments[0]instanceof vt))throw"Could not determine the arguments for Vector.hasPoint";t=arguments[0],e=arguments[1]||0}const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,r=this.end.y-this.begin.y,o=i*r-s*n;return!(Math.abs(o)>e)&&(Math.abs(n)>=Math.abs(r)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:r>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y)}}function Ti(t,e,i,s){const n=t.sub(i),r=e.dot(e),o=e.dot(s),a=s.dot(s),h=e.dot(n),l=s.dot(n),c=r*a-o*o;let d=c,u=c;if(0===c||c<=.01){const e=h/o;return new Ai(t,i.add(s.scale(e)))}let p=o*l-a*h,_=r*l-o*h;return p<0?(p=0,_=l,u=a):p>d&&(p=d,_=l+o,u=a),_<0?(_=0,-h<0?p=0:-h>r?p=d:(p=-h,d=r)):_>u&&(_=u,-h+o<0?p=0:-h+o>r?p=d:(p=-h+o,d=r)),p=Math.abs(p)<.001?0:p/d,_=Math.abs(_)<.001?0:_/u,new Ai(t.add(e.scale(p)),i.add(s.scale(_)))}const Si={PolygonPolygonClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=s.negate(),r=new yi(t.worldPos,s),o=new yi(i,n),a=t.rayCast(r).add(r.dir.scale(.1)),h=e.rayCast(o).add(o.dir.scale(.1)),l=t.getClosestFace(a),c=e.getClosestFace(h);return Ti(l.face.begin,l.face.getEdge(),c.face.begin,c.face.getEdge())},PolygonEdgeClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=new yi(t.worldPos,i),n=t.rayCast(s).add(s.dir.scale(.1)),r=t.getClosestFace(n),o=r.face.begin,a=r.face.getEdge(),h=e.asLine();return Ti(o,a,h.begin,h.getEdge())},PolygonCircleClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=new yi(t.worldPos,s.normalize()),r=t.rayCast(n).add(n.dir.scale(.1)),o=t.getClosestFace(r),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(i.x-a.x)+h.y*(i.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-i.x,2)+Math.pow(a.y+h.y*l-i.y,2))-e.radius,d=(a.x+h.x*l-i.x)*e.radius/(e.radius+c),u=(a.y+h.y*l-i.y)*e.radius/(e.radius+c);return new Ai(h.scale(l).add(a),new vt(i.x+d,i.y+u))},CircleCircleClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=t.worldPos.sub(e.worldPos),n=new yi(t.worldPos,i),r=new yi(e.worldPos,s),o=t.rayCast(n),a=e.rayCast(r);return new Ai(o,a)},CircleEdgeClosestLine(t,e){const i=t.worldPos,s=e.asLine(),n=s.begin,r=s.getEdge();let o=(r.x*(i.x-n.x)+r.y*(i.y-n.y))/(r.x*r.x+r.y*r.y);o>1?o=1:o<0&&(o=0);const a=Math.sqrt(Math.pow(n.x+r.x*o-i.x,2)+Math.pow(n.y+r.y*o-i.y,2))-t.radius,h=(n.x+r.x*o-i.x)*t.radius/(t.radius+a),l=(n.y+r.y*o-i.y)*t.radius/(t.radius+a);return new Ai(r.scale(o).add(n),new vt(i.x+h,i.y+l))},EdgeEdgeClosestLine(t,e){const i=t.asLine(),s=i.begin,n=i.getEdge(),r=e.asLine();return Ti(s,n,r.begin,r.getEdge())}};class Ei extends bi{get worldPos(){return this._globalMatrix.getPosition()}get radius(){var t;const e=this._transform,i=null!==(t=null==e?void 0:e.globalScale)&&void 0!==t?t:vt.One;return this._naturalRadius*Math.min(i.x,i.y)}set radius(t){var e;const i=this._transform,s=null!==(e=null==i?void 0:i.globalScale)&&void 0!==e?e:vt.One;this._naturalRadius=t/Math.min(s.x,s.y)}constructor(t){super(),this.offset=vt.Zero,this._globalMatrix=kt.identity(),this.offset=t.offset||vt.Zero,this.radius=t.radius||0,this._globalMatrix.translate(this.offset.x,this.offset.y)}clone(){return new Ei({offset:this.offset.clone(),radius:this.radius})}get center(){return this._globalMatrix.getPosition()}contains(t){var e,i;return(null!==(i=null===(e=this._transform)||void 0===e?void 0:e.pos)&&void 0!==i?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){const i=this.center,s=t.dir,n=t.pos,r=Math.sqrt(Math.pow(s.dot(n.sub(i)),2)-Math.pow(n.sub(i).distance(),2)+Math.pow(this.radius,2));if(r<0)return null;{let o=0;if(0===r)return o=-s.dot(n.sub(i)),o>0&&o<e?t.getPoint(o):null;{const o=-s.dot(n.sub(i))+r,a=-s.dot(n.sub(i))-r,h=[];o>=0&&h.push(o),a>=0&&h.push(a);const l=Math.min(...h);return l<=e?t.getPoint(l):null}}}getClosestLineBetween(t){if(t instanceof Ei)return Si.CircleCircleClosestLine(this,t);if(t instanceof Ri)return Si.PolygonCircleClosestLine(t,this).flip();if(t instanceof Bi)return Si.CircleEdgeClosestLine(this,t).flip();throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ei)return Di.CollideCircleCircle(this,t);if(t instanceof Ri)return Di.CollideCirclePolygon(this,t);if(t instanceof Bi)return Di.CollideCircleEdge(this,t);throw new Error("Circle could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){var t,e,i;const s=this._transform,n=null!==(t=null==s?void 0:s.globalScale)&&void 0!==t?t:vt.One,r=null!==(e=null==s?void 0:s.globalRotation)&&void 0!==e?e:0,o=null!==(i=null==s?void 0:s.globalPos)&&void 0!==i?i:vt.Zero;return new At(this.offset.x-this._naturalRadius,this.offset.y-this._naturalRadius,this.offset.x+this._naturalRadius,this.offset.y+this._naturalRadius).rotate(r).scale(n).translate(o)}get localBounds(){return new At(this.offset.x-this._naturalRadius,this.offset.y-this._naturalRadius,this.offset.x+this._naturalRadius,this.offset.y+this._naturalRadius)}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){var e;this._transform=t;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=this.center.dot(t);return e.push(i),e.push(i+this.radius),e.push(i-this.radius),new fi(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){var i,s,n,r;const o=this._transform,a=null!==(i=null==o?void 0:o.globalScale)&&void 0!==i?i:vt.One,h=null!==(s=null==o?void 0:o.globalRotation)&&void 0!==s?s:0,l=null!==(n=null==o?void 0:o.globalPos)&&void 0!==n?n:vt.Zero;t.save(),t.translate(l.x,l.y),t.rotate(h),t.scale(a.x,a.y),t.drawCircle(null!==(r=this.offset)&&void 0!==r?r:vt.Zero,this._naturalRadius,yt.Transparent,e,2),t.restore()}}class Pi{constructor(t,e,i,s,n,r,o,a){var h,l;this._canceled=!1,this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=r,this.localPoints=o,this.info=a,this.id=mi.calculatePairHash(t.id,e.id),(t.__compositeColliderId||e.__compositeColliderId)&&(this.id+="|"+mi.calculatePairHash(null!==(h=t.__compositeColliderId)&&void 0!==h?h:t.id,null!==(l=e.__compositeColliderId)&&void 0!==l?l:e.id))}matchAwake(){const t=this.colliderA.owner.get(Li),e=this.colliderB.owner.get(Li);t&&e&&t.sleeping!==e.sleeping&&(t.sleeping&&t.collisionType!==Ze.Fixed&&e.sleepMotion>=ri.wakeThreshold&&t.setSleeping(!1),e.sleeping&&e.collisionType!==Ze.Fixed&&t.sleepMotion>=ri.wakeThreshold&&e.setSleeping(!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}}class Ii{static findPolygonPolygonSeparation(t,e){let i=-Number.MAX_VALUE,s=null,n=null,r=-1,o=null;const a=t.getSides(),h=t.getLocalSides();for(let t=0;t<a.length;t++){const h=a[t],l=h.normal(),c=e.getFurthestPoint(l.negate()),d=h.distanceToPoint(c,!0);d>i&&(i=d,s=h,n=l,r=t,o=c)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:h[r],sideId:r,point:o,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}static findCirclePolygonSeparation(t,e){const i=e.axes,s=e.center.sub(t.worldPos),n=e.getFurthestPoint(s.negate());i.push(n.sub(t.worldPos).normalize());let r=Number.MAX_VALUE,o=null,a=-1;for(let s=0;s<i.length;s++){const n=e.project(i[s]),h=t.project(i[s]),l=n.getOverlap(h);if(l<=0)return null;l<r&&(r=l,o=i[s],a=s)}return a<0?null:o.normalize().scale(r)}}const Di={CollideCircleCircle(t,e){const i=t.worldPos,s=e.worldPos,n=t.radius+e.radius,r=i.distance(s);if(r>n)return[];const o=n-r,a=s.sub(i).normalize(),h=a.perpendicular(),l=a.scale(o),c=t.getFurthestPoint(a),d=t.getFurthestLocalPoint(a);return[new Pi(t,e,l,a,h,[c],[d],{collider:t,separation:o,axis:a,point:c})]},CollideCirclePolygon(t,e){var i,s;let n=Ii.findCirclePolygonSeparation(t,e);if(!n)return[];const r=n.dot(e.center.sub(t.center));n=r<0?n.negate():n;const o=t.getFurthestPoint(n),a=(null!==(s=null===(i=t.owner)||void 0===i?void 0:i.get(ui))&&void 0!==s?s:new ui).applyInverse(o),h=n.normalize(),l={collider:t,separation:-n.size,axis:h,point:o,localPoint:a,side:e.findSide(h.negate()),localSide:e.findLocalSide(h.negate())};return[new Pi(t,e,n,h,h.perpendicular(),[o],[a],l)]},CollideCircleEdge(t,e){const i=t.center,s=e.asLine(),n=s.end.sub(s.begin),r=n.dot(s.end.sub(i)),o=n.dot(i.sub(s.begin)),a=e.asLine(),h=e.asLocalLine();if(o<=0){const n=s.begin.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.begin,side:a,localSide:h};return[new Pi(t,e,o.scale(l),o,o.perpendicular(),[a.begin],[h.begin],c)]}if(r<=0){const n=s.end.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.end,side:a,localSide:h};return[new Pi(t,e,o.scale(l),o,o.perpendicular(),[a.end],[h.end],c)]}const l=n.dot(n),c=s.begin.scale(r).add(s.end.scale(o)).scale(1/l),d=i.sub(c),u=d.dot(d);if(u>t.radius*t.radius)return[];let p=n.perpendicular();p.dot(i.sub(s.begin))<0&&(p.x=-p.x,p.y=-p.y),p=p.normalize();const _=t.radius-Math.sqrt(u),g=p.scale(_),m={collider:t,separation:_,axis:p,point:c,side:a,localSide:h};return[new Pi(t,e,g,p.negate(),p.negate().perpendicular(),[c],[c.sub(e.worldPos)],m)]},CollideEdgeEdge:()=>[],CollidePolygonEdge(t,e){var i;const s=t.center,n=e.center.sub(s).normalize(),r=new Ri({points:[e.begin,e.end,e.end.add(n.scale(100)),e.begin.add(n.scale(100))],offset:e.offset});r.owner=e.owner;(null===(i=e.owner)||void 0===i?void 0:i.get(ui))&&r.update(e.owner.get(ui).get());const o=this.CollidePolygonPolygon(t,r);return o.length&&(o[0].colliderB=e,o[0].id=mi.calculatePairHash(t.id,e.id)),o},CollidePolygonPolygon(t,e){var i,s,n,r;const o=Ii.findPolygonPolygonSeparation(t,e);if(o.separation>0)return[];const a=Ii.findPolygonPolygonSeparation(e,t);if(a.separation>0)return[];const h=o.separation>a.separation?o:a,l=(h.collider===t?e:t).findSide(h.axis.negate()),c=h.side,d=c.dir().normalize(),u=l.clip(d.negate(),-d.dot(c.begin));let p=null;if(u&&(p=u.clip(d,d.dot(c.end))),p){const o=p.getPoints().filter((t=>c.below(t)));let a=h.axis,l=a.perpendicular();e.center.sub(t.center).dot(a)<0&&(a=a.negate(),l=a.perpendicular());let d=[];if(h.collider===t){const t=null!==(s=null===(i=e.owner)||void 0===i?void 0:i.get(ui))&&void 0!==s?s:new ui;d=o.map((e=>t.applyInverse(e)))}else{const e=null!==(r=null===(n=t.owner)||void 0===n?void 0:n.get(ui))&&void 0!==r?r:new ui;d=o.map((t=>e.applyInverse(t)))}return[new Pi(t,e,a.scale(-h.separation),a,l,o,d,h)]}return[]},FindContactSeparation(t,e){var i,s,n,r;const o=t.colliderA,a=null!==(s=null===(i=t.colliderA.owner)||void 0===i?void 0:i.get(ui))&&void 0!==s?s:new ui,h=t.colliderB,l=null!==(r=null===(n=t.colliderB.owner)||void 0===n?void 0:n.get(ui))&&void 0!==r?r:new ui;if(o instanceof Ei&&h instanceof Ei){return-(o.radius+h.radius-a.pos.distance(l.pos))}if(o instanceof Ri&&h instanceof Ri&&t.info.localSide){let i,s;return t.info.collider===o?(i=new Ai(a.apply(t.info.localSide.begin),a.apply(t.info.localSide.end)),s=l.apply(e)):(i=new Ai(l.apply(t.info.localSide.begin),l.apply(t.info.localSide.end)),s=a.apply(e)),i.distanceToPoint(s,!0)}if(o instanceof Ri&&h instanceof Ei||h instanceof Ri&&o instanceof Ei){const i=a.apply(e);if(t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Bi&&h instanceof Ri||h instanceof Bi&&o instanceof Ri){let i;if(i=t.info.collider===o?l.apply(e):a.apply(e),t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Ei&&h instanceof Bi||h instanceof Ei&&o instanceof Bi){const i=l.apply(e);let s;o instanceof Ei&&(s=o.getFurthestPoint(t.normal));const n=i.distance(s);if(t.info.side)return n>0?-n:0}return 0}};class Bi extends bi{constructor(t){var e;super(),this._globalMatrix=kt.identity(),this.begin=t.begin||vt.Zero,this.end=t.end||vt.Zero,this.offset=null!==(e=t.offset)&&void 0!==e?e:vt.Zero}clone(){return new Bi({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos.add(this.offset))&&void 0!==t?t:this.offset}get center(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.average(e)}_getTransformedBegin(){return this._globalMatrix.multiply(this.begin)}_getTransformedEnd(){return this._globalMatrix.multiply(this.end)}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){const i=this._getTransformedBegin().sub(t.pos);if(0===t.dir.cross(this.getSlope())&&0!==i.cross(t.dir))return null;const s=t.dir.cross(this.getSlope());if(0===s)return null;const n=i.cross(this.getSlope())/s;if(n>=0&&n<=e){const e=i.cross(t.dir)/s/this.getLength();if(e>=0&&e<=1)return t.getPoint(n)}return null}getClosestLineBetween(t){if(t instanceof Ei)return Si.CircleEdgeClosestLine(t,this);if(t instanceof Ri)return Si.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Bi)return Si.EdgeEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ei)return Di.CollideCircleEdge(t,this);if(t instanceof Ri)return Di.CollidePolygonEdge(t,this);if(t instanceof Bi)return Di.CollideEdgeEdge();throw new Error("Edge could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new At(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new Ai(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new Ai(this.begin,this.end)}get axes(){const t=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),e=[];return e.push(t),e.push(t.negate()),e.push(t.normal()),e.push(t.normal().negate()),e}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){var e;this._transform=t;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new fi(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.drawLine(i,s,e,2),t.drawCircle(i,2,e),t.drawCircle(s,2,e)}}class Ri extends bi{set points(t){this._localBoundsDirty=!0,this._localSidesDirty=!0,this._sidesDirty=!0,this._points=t}get points(){return this._points}constructor(t){var e,i;super(),this._logger=J.getInstance(),this._transformedPoints=[],this._sides=[],this._localSides=[],this._globalMatrix=kt.identity(),this._transformedPointsDirty=!0,this._sidesDirty=!0,this._localSidesDirty=!0,this._localBoundsDirty=!0,this.offset=null!==(e=t.offset)&&void 0!==e?e:vt.Zero,this._globalMatrix.translate(this.offset.x,this.offset.y),this.points=null!==(i=t.points)&&void 0!==i?i:[];this._isCounterClockwiseWinding(this.points)||this.points.reverse(),this.isConvex()||this._logger.warn("Excalibur only supports convex polygon colliders and will not behave properly.Call PolygonCollider.triangulate() to build a new collider composed of smaller convex triangles"),this._calculateTransformation()}_isCounterClockwiseWinding(t){let e=0;for(let i=0;i<t.length;i++)e+=(t[(i+1)%t.length].x-t[i].x)*(t[(i+1)%t.length].y+t[i].y);return e<0}isConvex(){if(this.points.length<3)return!1;let t=this.points[this.points.length-2],e=this.points[this.points.length-1],i=Math.atan2(e.y-t.y,e.x-t.x),s=0,n=0,r=0;for(const[o,a]of this.points.entries()){if(t=e,s=i,e=a,i=Math.atan2(e.y-t.y,e.x-t.x),t.equals(e))return!1;let h=i-s;if(h<=-Math.PI?h+=2*Math.PI:h>Math.PI&&(h-=2*Math.PI),0===o){if(0===h)return!1;n=h>0?1:-1}else if(n*h<=0)return!1;r+=h}return 1===Math.abs(Math.round(r/(2*Math.PI)))}tessellate(){const t=[];for(let e=1;e<this.points.length-2;e++)t.push([this.points[0],this.points[e+1],this.points[e+2]]);return t.push([this.points[0],this.points[1],this.points[2]]),new Ci(t.map((t=>Fi.Polygon(t))))}triangulate(){if(this.points.length<3)throw Error("Invalid polygon");function t(t,e){return t>=e.length?e[t%e.length]:t<0?e[t%e.length+e.length]:e[t]}function e(t,e,i,s){const n=i.sub(e),r=s.sub(i),o=e.sub(s),a=t.sub(e),h=t.sub(i),l=t.sub(s),c=n.cross(a),d=r.cross(h),u=o.cross(l);return!(c>0||d>0||u>0)}const i=[],s=[...this.points],n=gt(0,this.points.length-1);for(;n.length>3;)for(let r=0;r<n.length;r++){const o=n[r],a=t(r-1,n),h=t(r+1,n),l=s[o],c=s[a],d=s[h],u=c.sub(l);if(!(d.sub(l).cross(u)>0))continue;let p=!0;for(let t=0;t<n.length;t++){const i=n[t];if(i===o||i===a||i===h)continue;if(e(s[i],c,l,d)){p=!1;break}}if(p){i.push([c,l,d]),n.splice(r,1);break}}return i.push([s[n[0]],s[n[1]],s[n[2]]]),new Ci(i.map((t=>Fi.Polygon(t))))}clone(){return new Ri({offset:this.offset.clone(),points:this.points.map((t=>t.clone()))})}get worldPos(){return this._transform?this._transform.pos.add(this.offset):this.offset}get center(){return this.bounds.center}_calculateTransformation(){const t=this.points,e=t.length;this._transformedPoints.length=0;for(let i=0;i<e;i++)this._transformedPoints[i]=this._globalMatrix.multiply(t[i].clone())}getTransformedPoints(){return this._transformedPointsDirty&&(this._calculateTransformation(),this._transformedPointsDirty=!1),this._transformedPoints}getSides(){if(this._sidesDirty){const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new Ai(e[s],e[(s+1)%i]));this._sides=t,this._sidesDirty=!1}return this._sides}getLocalSides(){if(this._localSidesDirty){const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new Ai(e[s],e[(s+1)%i]));this._localSides=t,this._localSidesDirty=!1}return this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}get axes(){const t=[],e=this.getSides();for(let i=0;i<e.length;i++)t.push(e[i].normal());return t}update(t){var e;if(t){this._transform=t,this._transformedPointsDirty=!0,this._sidesDirty=!0;(null!==(e=t.matrix)&&void 0!==e?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}}contains(t){const e=new yi(t,new vt(1,0));return this.getSides().reduce((function(t,i){return e.intersect(i)>=0?t+1:t}),0)%2!=0}getClosestLineBetween(t){if(t instanceof Ei)return Si.PolygonCircleClosestLine(this,t);if(t instanceof Ri)return Si.PolygonPolygonClosestLine(this,t);if(t instanceof Bi)return Si.PolygonEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ei)return Di.CollideCirclePolygon(t,this);if(t instanceof Ri)return Di.CollidePolygonPolygon(this,t);if(t instanceof Bi)return Di.CollidePolygonEdge(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let r=0;r<e.length;r++){const o=e[r].distanceToPoint(t);o<i&&(i=o,s=r,n=o)}return-1!==s?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){return this.localBounds.transform(this._globalMatrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=At.fromPoints(this.points),this._localBoundsDirty=!1),this._localBounds}getInertia(t){if(this._cachedMass===t&&this._cachedInertia)return this._cachedInertia;let e=0,i=0;const s=this.points;for(let t=0;t<s.length;t++){const n=(t+1)%s.length,r=s[n].cross(s[t]);e+=r*(s[t].dot(s[t])+s[t].dot(s[n])+s[n].dot(s[n])),i+=r}return this._cachedMass=t,this._cachedInertia=t/6*(e/i)}rayCast(t,e=1/0){const i=this.getSides(),s=i.length;let n=Number.MAX_VALUE,r=-1;for(let o=0;o<s;o++){const s=t.intersect(i[o]);s>=0&&s<n&&s<=e&&(n=s,r=o)}return r>=0?t.getPoint(n):null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;r<i;r++){const i=e[r].dot(t);s=Math.min(s,i),n=Math.max(n,i)}return new fi(s,n)}debug(t,e){const i=this.getTransformedPoints()[0],s=[i,...this.getTransformedPoints(),i];for(let i=0;i<s.length-1;i++)t.drawLine(s[i],s[i+1],e,2),t.drawCircle(s[i],2,e),t.drawCircle(s[i+1],2,e)}}class Fi{static Box(t,e,i=vt.Half,s=vt.Zero){return new Ri({points:new At(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints(),offset:s})}static Polygon(t,e=vt.Zero){return new Ri({points:t,offset:e})}static Circle(t,e=vt.Zero){return new Ei({radius:t,offset:e})}static Edge(t,e){return new Bi({begin:t,end:e})}static Capsule(t,e,i=vt.Zero){const s=J.getInstance();t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider");if(e>=t){return new Ci([Fi.Circle(t/2,xt(0,-e/2+t/2).add(i)),Fi.Box(t,e-t,vt.Half,i),Fi.Circle(t/2,xt(0,e/2-t/2).add(i))])}return new Ci([Fi.Circle(e/2,xt(-t/2+e/2,0).add(i)),Fi.Box(t-e,e,vt.Half,i),Fi.Circle(e/2,xt(t/2-e/2,0).add(i))])}}class ki extends li{constructor(t){super(),this.type="ex.collider",this.events=new d,this.$colliderAdded=new di,this.$colliderRemoved=new di,this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,t.events.pipe(this.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this._collider.events.unpipe(this.events),this.$colliderRemoved.notifyAll(this._collider),this._collider.owner=null,this._collider=null)}clone(){return new ki(this._collider.clone())}get bounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.bounds)&&void 0!==e?e:new At}get localBounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new At}update(){var t;const e=null===(t=this.owner)||void 0===t?void 0:t.get(ui);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e.get()))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof Ci&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach((e=>{e.mtv=e.mtv.negate(),e.normal=e.normal.negate(),e.tangent=e.normal.perpendicular(),e.colliderA=this._collider,e.colliderB=t._collider})),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",(e=>{const i=e;t.events.emit("precollision",new R(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("postcollision",(e=>{const i=e;t.events.emit("postcollision",new F(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("collisionstart",(e=>{const i=e;t.events.emit("collisionstart",new U(i.target.owner,i.other.owner,i.contact))})),this.events.on("collisionend",(e=>{const i=e;t.events.emit("collisionend",new O(i.target.owner,i.other.owner))}))}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=vt.Half,s=vt.Zero){const n=Fi.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=vt.Zero){const i=Fi.Polygon(t,e);return this.set(i)}useCircleCollider(t,e=vt.Zero){const i=Fi.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=Fi.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new Ci(t))}}var Mi;!function(t){t.Rotation="rotation",t.X="x",t.Y="y"}(Mi||(Mi={}));class Li extends li{constructor(t){var e,i,s;super(),this.type="ex.body",this.dependencies=[ui,pi],this.id=c("body",Li._ID++),this.events=new d,this._oldTransform=new hi,this.__oldTransformCaptured=!1,this.enableFixedUpdateInterpolate=!0,this.collisionType=Ze.PreventCollision,this.group=gi.All,this._mass=ri.defaultMass,this.sleepMotion=5*ri.sleepEpsilon,this.canSleep=ri.bodiesCanSleepByDefault,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this.oldVel=new vt(0,0),this.oldAcc=vt.Zero,t&&(this.collisionType=null!==(e=t.type)&&void 0!==e?e:this.collisionType,this.group=null!==(i=t.group)&&void 0!==i?i:this.group,this.useGravity=null!==(s=t.useGravity)&&void 0!==s?s:this.useGravity)}get matrix(){return this.transform.get().matrix}get mass(){return this._mass}set mass(t){this._mass=t,this._cachedInertia=void 0,this._cachedInverseInertia=void 0}get inverseMass(){return this.collisionType===Ze.Fixed?0:1/this.mass}get sleeping(){return this._sleeping}setSleeping(t){this._sleeping=t,t?(this.vel=vt.Zero,this.acc=vt.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=5*ri.sleepEpsilon}updateMotion(){this._sleeping&&this.setSleeping(!0);const t=this.vel.size*this.vel.size+Math.abs(this.angularVelocity*this.angularVelocity),e=ri.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=dt(this.sleepMotion,0,10*ri.sleepEpsilon),this.canSleep&&this.sleepMotion<ri.sleepEpsilon&&this.setSleeping(!0)}get inertia(){if(this._cachedInertia)return this._cachedInertia;const t=this.owner.get(ki);if(t){t.$colliderAdded.subscribe((()=>{this._cachedInertia=null})),t.$colliderRemoved.subscribe((()=>{this._cachedInertia=null}));const e=t.get();if(e)return this._cachedInertia=e.getInertia(this.mass)}return 0}get inverseInertia(){return this._cachedInverseInertia?this._cachedInverseInertia:this._cachedInverseInertia=this.collisionType===Ze.Fixed?0:1/this.inertia}get active(){var t;return!!(null===(t=this.owner)||void 0===t?void 0:t.active)}get center(){return this.globalPos}get transform(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(ui)}get motion(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(pi)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get globalPos(){return this.transform.globalPos}set globalPos(t){this.transform.globalPos=t}get oldPos(){return this._oldTransform.pos}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get oldRotation(){return this._oldTransform.rotation}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get oldScale(){return this._oldTransform.scale}get scaleFactor(){return this.motion.scaleFactor}set scaleFactor(t){this.motion.scaleFactor=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==Ze.Active)return;const i=e.scale(this.inverseMass);if(this.limitDegreeOfFreedom.includes(Mi.X)&&(i.x=0),this.limitDegreeOfFreedom.includes(Mi.Y)&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes(Mi.Rotation)){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==Ze.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes(Mi.X)&&(e.x=0),this.limitDegreeOfFreedom.includes(Mi.Y)&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===Ze.Active&&!this.limitDegreeOfFreedom.includes(Mi.Rotation)){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.__oldTransformCaptured=!0,this.transform.get().clone(this._oldTransform),this.oldVel.setTo(this.vel.x,this.vel.y),this.oldAcc.setTo(this.acc.x,this.acc.y)}clone(){return super.clone()}}Li._ID=0;class zi{constructor(t){this.data=t,this.type="Component Added"}}function Ui(t){return!!t&&"Component Added"===t.type}class Oi{constructor(t){this.data=t,this.type="Component Removed"}}function Ni(t){return!!t&&"Component Removed"===t.type}const Hi={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class Wi{constructor(t,e){if(this.events=new d,this.id=Wi._ID++,this.scene=null,this._name="anonymous",this.active=!0,this._componentsToRemove=[],this._componentTypeToInstance=new Map,this._componentStringToInstance=new Map,this._tagsMemo=[],this._typesMemo=[],this.componentAdded$=new di,this.componentRemoved$=new di,this._parent=null,this.childrenAdded$=new di,this.childrenRemoved$=new di,this._children=[],this._isInitialized=!1,this._setName(e),t)for(const e of t)this.addComponent(e)}_setName(t){this._name=t||`Entity#${this.id}`}get name(){return this._name}set name(t){this._setName(t)}kill(){this.active&&(this.active=!1,this.unparent())}isKilled(){return!this.active}get tags(){return this._tagsMemo}hasTag(t){return this.tags.includes(t)}addTag(t){return this.addComponent(new ci(t))}removeTag(t,e=!1){return this.removeComponent(t,e)}get types(){return this._typesMemo}_rebuildMemos(){this._tagsMemo=Array.from(this._componentStringToInstance.values()).filter((t=>t instanceof ci)).map((t=>t.type)),this._typesMemo=Array.from(this._componentStringToInstance.keys())}getComponents(){return Array.from(this._componentStringToInstance.values())}_notifyAddComponent(t){this._rebuildMemos();const e=new zi({component:t,entity:this});this.componentAdded$.notifyAll(e)}_notifyRemoveComponent(t){const e=new Oi({component:t,entity:this});this.componentRemoved$.notifyAll(e),this._rebuildMemos()}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}addChild(t){if(null!==t.parent)throw new Error("Entity already has a parent, cannot add without unparenting");if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");return this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t),this}removeChild(t){return t.parent===this&&(Pt(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){for(let t=this.children.length-1;t>=0;t--)this.removeChild(this.children[t]);return this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();e=e.concat(i.children),t=t.concat(i.children)}return t}clone(){const t=new Wi;for(const e of this.types)t.addComponent(this.get(e).clone());for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const e of t.children)this.addChild(e.clone().addTemplate(e));return this}addComponent(t,e=!1){if(this.has(t.type)){if(!e)return this;this.removeComponent(t,!0)}if(t.dependencies&&t.dependencies.length)for(const e of t.dependencies)this.addComponent(new e);t.owner=this;const i=t.constructor;return this._componentTypeToInstance.set(i,t),this._componentStringToInstance.set(t.type,t),t.onAdd&&t.onAdd(this),this._notifyAddComponent(t),this}removeComponent(t,e=!1){return e?"string"==typeof t?this._removeComponentByType(t):t instanceof li&&this._removeComponentByType(t.type):this._componentsToRemove.push(t),this}clearComponents(){const t=this.getComponents();for(const e of t)this.removeComponent(e)}_removeComponentByType(t){if(this.has(t)){const e=this.get(t);e.owner=null,e.onRemove&&e.onRemove(this);const i=e.constructor;this._componentTypeToInstance.delete(i),this._componentStringToInstance.delete(e.type),this._notifyRemoveComponent(e)}}processComponentRemoval(){for(const t of this._componentsToRemove){const e="string"==typeof t?t:t.type;this._removeComponentByType(e)}this._componentsToRemove.length=0}has(t){return"string"==typeof t?this._componentStringToInstance.has(t):this._componentTypeToInstance.has(t)}get(t){return"string"==typeof t?this._componentStringToInstance.get(t):this._componentTypeToInstance.get(t)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0)}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}function Gi(t){return!!t.tick}Wi._ID=0;class Vi{constructor(t,e){this._options=t,this._graphics=e,this.graphics=[]}get name(){return this._options.name}hide(t){if(t){let e=null;e=t instanceof Ht?t:this._graphics.getGraphic(t),this.graphics=this.graphics.filter((t=>t.graphic!==e)),this._graphics.recalculateBounds()}else this.graphics.length=0}show(t,e){let i;return e={...e},t instanceof Ht?i=this._graphics.copyGraphics?t.clone():t:(i=this._graphics.getGraphic(t),i||J.getInstance().error(`No such graphic added to component named ${t}. These named graphics are available: `,this._graphics.getNames())),i?(this.graphics.push({graphic:i,options:e}),this._graphics.recalculateBounds(),i):null}use(t,e){return e={...e},this.hide(),this.show(t,e)}get order(){return this._options.order}set order(t){this._options.order=t}get offset(){var t;return null!==(t=this._options.offset)&&void 0!==t?t:vt.Zero}set offset(t){this._options.offset=t}get currentKeys(){var t;return null!==(t=this.name)&&void 0!==t?t:"anonymous"}clone(t){const e=new Vi({...this._options},t);return e.graphics=[...this.graphics.map((t=>({graphic:t.graphic.clone(),options:{...t.options}})))],e}}class qi{constructor(t){this._component=t,this._layers=[],this._layerMap={},this.default=new Vi({name:"default",order:0},t),this._maybeAddLayer(this.default)}create(t){const e=new Vi(t,this._component);return this._maybeAddLayer(e)}get(t){return t?this._getLayer(t):this._layers}currentKeys(){const t=[];for(const e of this._layers)t.push(e.currentKeys);return t}has(t){return t in this._layerMap}_maybeAddLayer(t){return this._layerMap[t.name]?this._layerMap[t.name]:(this._layerMap[t.name]=t,this._layers.push(t),this._layers.sort(((t,e)=>t.order-e.order)),t)}_getLayer(t){return this._layerMap[t]}clone(t){const e=new qi(t);e._layerMap={},e._layers=[],e.default=this.default.clone(t),e._maybeAddLayer(e.default);return this._layers.filter((t=>"default"!==t.name)).map((e=>e.clone(t))).forEach((t=>e._maybeAddLayer(t))),e}}class Xi extends li{getGraphic(t){return this._graphics[t]}getNames(){return Object.keys(this._graphics)}constructor(t){super(),this.type="ex.graphics",this._graphics={},this.visible=!0,this.opacity=1,this.offset=vt.Zero,this.anchor=vt.Half,this.flipHorizontal=!1,this.flipVertical=!1,this.copyGraphics=!1,this._localBounds=null,t={visible:this.visible,...t};const{current:e,anchor:i,opacity:s,visible:n,graphics:r,offset:o,copyGraphics:a,onPreDraw:h,onPostDraw:l}=t;this._graphics=r||{},this.offset=null!=o?o:this.offset,this.opacity=null!=s?s:this.opacity,this.anchor=null!=i?i:this.anchor,this.copyGraphics=null!=a?a:this.copyGraphics,this.onPreDraw=null!=h?h:this.onPreDraw,this.onPostDraw=null!=l?l:this.onPostDraw,this.visible=!!n,this.layers=new qi(this),e&&this._graphics[e]&&this.show(this._graphics[e])}get current(){return this.layers.default.graphics}get graphics(){return this._graphics}add(t,e){let i="default",s=null;return"string"==typeof t?(i=t,s=e):s=t,this._graphics[i]=this.copyGraphics?s.clone():s,"default"===i&&this.show("default"),s}show(t,e){const i=this.layers.default.show(t,e);return this.recalculateBounds(),i}use(t,e){const i=this.layers.default.use(t,e);return this.recalculateBounds(),i}hide(t){this.layers.default.hide(t)}set localBounds(t){this._localBounds=t}recalculateBounds(){let t=new At;for(const e of this.layers.get())for(const{graphic:i,options:s}of e.graphics){let n=this.anchor,r=this.offset;(null==s?void 0:s.anchor)&&(n=s.anchor),(null==s?void 0:s.offset)&&(r=s.offset);const o=i.localBounds,a=-o.width*n.x+r.x,h=-o.height*n.y+r.y;t=null==i?void 0:i.localBounds.translate(xt(a+e.offset.x,h+e.offset.y)).combine(t)}this._localBounds=t}get localBounds(){return this._localBounds&&!this._localBounds.hasZeroDimensions()||this.recalculateBounds(),this._localBounds}update(t,e=0){for(const i of this.layers.get())for(const{graphic:s}of i.graphics)Gi(s)&&(null==s||s.tick(t,e))}clone(){const t=new Xi;return t._graphics={...this._graphics},t.offset=this.offset.clone(),t.opacity=this.opacity,t.anchor=this.anchor.clone(),t.copyGraphics=this.copyGraphics,t.onPreDraw=this.onPreDraw,t.onPostDraw=this.onPostDraw,t.visible=this.visible,t.layers=this.layers.clone(t),t}}class Ki extends Fe{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new Ki({width:this.width,height:this.height,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class Zi extends Fe{get radius(){return this._radius}set radius(t){this._radius=t,this.width=2*this._radius,this.height=2*this._radius,this.flagDirty()}constructor(t){var e,i,s;super(t),this._radius=0;const n=null!==(e=t.lineWidth)&&void 0!==e?e:t.strokeColor?1:0;this.padding=null!==(i=t.padding)&&void 0!==i?i:2+n/2,this.radius=t.radius,this.filtering=null!==(s=t.filtering)&&void 0!==s?s:Gt.Blended,this.rasterize()}clone(){return new Zi({radius:this.radius,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,2*Math.PI),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class Yi extends li{constructor(){super(...arguments),this.type="ex.pointer",this.useColliderShape=!0,this.useGraphicsBounds=!1}}class ji{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new vt(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}}ji.Linear=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*t/s+e)),ji.EaseInQuad=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t+e)),ji.EaseOutQuad=ji.CreateReversibleEasingFunction(((t,e,i,s)=>-(i-=e)*(t/=s)*(t-2)+e)),ji.EaseInOutQuad=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e))),ji.EaseInCubic=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t*t+e)),ji.EaseOutCubic=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(t/=s,(i-=e)*(--t*t*t+1)+e))),ji.EaseInOutCubic=ji.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e)));class Qi{constructor(t){this._actions=[],this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}hasNext(){return this._actions.length>0}isComplete(){return 0===this._actions.length}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){this._actions.length>0&&(this._currentAction=this._actions[0],this._currentAction.update(t),this._currentAction.isComplete(this._entity)&&this._completedActions.push(this._actions.shift()))}}class $i{constructor(t,e,i){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new ws(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class Ji{constructor(t,e){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new ws(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}class ts{constructor(t,e,i,s){if(this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(ui),this._motion=t.get(pi),this._speed=s,this._offset=new vt(e,i),s<=0)throw J.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new vt(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.size,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(ui);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class es{constructor(t,e,i,s){this.entity=t,this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._end=new vt(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new vt(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=xt(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}isComplete(t){const e=t.get(ui);return this._stopped||new vt(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}var is,ss,ns,rs,os,as;!function(t){t[t.ShortestPath=0]="ShortestPath",t[t.LongestPath=1]="LongestPath",t[t.Clockwise=2]="Clockwise",t[t.CounterClockwise=3]="CounterClockwise"}(is||(is={}));class hs{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._end=e,this._speed=i,this._rotationType=s||is.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const t=Math.abs(this._end-this._start),e=ht-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+ht)%ht>=Math.PI,this._rotationType){case is.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case is.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case is.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case is.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class ls{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._speed=i,this._offset=e,this._rotationType=s||is.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const t=Math.abs(this._end-this._start),e=ht-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+ht)%ht>=Math.PI,this._rotationType){case is.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case is.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case is.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case is.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._start=void 0,this._currentNonCannonAngle=void 0,this._distance=void 0}}class cs{constructor(t,e,i,s,n){this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*t}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*t}this.isComplete()&&(this._tx.scale=xt(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startX)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class ds{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._offset=new vt(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class us{constructor(t){this._method=null,this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class ps{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new vt(0,0),this._lerpEnd=new vt(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._lerpDuration=s,this._lerpEnd=new vt(e,i)}_initialize(){this._lerpStart=new vt(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=xt((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=xt(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=vt.Zero)}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=xt(0,0),this._stopped=!0}}class _s{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new vt(0,0),this._lerpEnd=new vt(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._lerpDuration=s,this._offset=new vt(e,i)}_initialize(){this._lerpStart=new vt(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._lerpEnd=this._lerpStart.add(this._offset)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=xt((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=xt(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=vt.Zero)}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=xt(0,0),this._stopped=!0}}class gs{constructor(t,e,i,s=1){this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(Xi),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0,this._elapsedTime=0,this._totalTime=0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.visible&&this._elapsedTime>=this._timeVisible&&(this._graphics.visible=!1,this._elapsedTime=0),!this._graphics.visible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.visible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.visible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.visible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._elapsedTime=0,this._totalTime=0}}class ms{constructor(t,e,i){this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(Xi),this._endOpacity=e,this._speed=this._ogspeed=i}update(t){this._graphics&&(this._started||(this._started=!0,this._speed=this._ogspeed,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._speed>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._speed),this._speed-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),J.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||Math.abs(this._graphics.opacity-this._endOpacity)<.05}stop(){this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class fs{constructor(t){this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1,this._stopped=!1}}class vs{constructor(t){this._stopped=!1,this._entity=t}update(t){this._entity.get(bs).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class xs{constructor(t,e,i){this._started=!1,this._stopped=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._followTx=e.get(ui),this._followMotion=e.get(pi),this._current=new vt(this._tx.pos.x,this._tx.pos.y),this._end=new vt(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=void 0!==i?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(0!==e&&(this._speed=e),this._current=xt(this._tx.pos.x,this._tx.pos.y),this._end=xt(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const t=this._dir.scale(this._speed);this._motion.vel=xt(t.x,t.y)}else this._motion.vel=xt(0,0);this.isComplete()&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}stop(){this._motion.vel=xt(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1,this._stopped=!1}}class ys{constructor(t,e,i){this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tx=t.get(ui),this._motion=t.get(pi),this._meetTx=e.get(ui),this._meetMotion=e.get(pi),this._current=new vt(this._tx.pos.x,this._tx.pos.y),this._end=new vt(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,void 0!==i&&(this._speedWasSpecified=!0)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));0===e||this._speedWasSpecified||(this._speed=e),this._current=xt(this._tx.pos.x,this._tx.pos.y),this._end=xt(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=xt(i.x,i.y),this.isComplete()&&(this._tx.pos=xt(this._end.x,this._end.y),this._motion.vel=xt(0,0))}isComplete(){return this._stopped||this._distanceBetween<=1}stop(){this._motion.vel=xt(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._distanceBetween=void 0}}class ws{constructor(t){this._entity=t,this._queue=new Qi(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}runAction(t){return t.reset(),this._queue.add(t),this}easeTo(...t){var e,i;let s=0,n=0,r=0,o=ji.Linear;return t[0]instanceof vt?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new ps(this._entity,s,n,r,o)),this}easeBy(...t){var e,i;let s=0,n=0,r=0,o=ji.Linear;return t[0]instanceof vt?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new _s(this._entity,s,n,r,o)),this}moveTo(t,e,i){let s=0,n=0,r=0;return t instanceof vt?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new es(this._entity,s,n,r)),this}moveBy(t,e,i){let s=0,n=0,r=0;return t instanceof vt?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new ts(this._entity,s,n,r)),this}rotateTo(t,e,i){return this._queue.add(new hs(this._entity,t,e,i)),this}rotateBy(t,e,i){return this._queue.add(new ls(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,r=1,o=0,a=0;return t instanceof vt&&e instanceof vt&&(n=t.x,r=t.y,o=e.x,a=e.y),"number"==typeof t&&"number"==typeof e&&(n=t,r=e,o=i,a=s),this._queue.add(new cs(this._entity,n,r,o,a)),this}scaleBy(t,e,i){let s=1,n=1;return t instanceof vt&&(s=t.x,n=t.y,i=e),"number"==typeof t&&"number"==typeof e&&(s=t,n=e),this._queue.add(new ds(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new gs(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new ms(this._entity,t,e)),this}delay(t){return this._queue.add(new fs(t)),this}die(){return this._queue.add(new vs(this._entity)),this}callMethod(t){return this._queue.add(new us(t)),this}repeat(t,e){return e?(this._queue.add(new $i(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new Ji(this._entity,t)),this}follow(t,e){return void 0===e?this._queue.add(new xs(this._entity,t)):this._queue.add(new xs(this._entity,t,e)),this}meet(t,e){return void 0===e?this._queue.add(new ys(this._entity,t)):this._queue.add(new ys(this._entity,t,e)),this}toPromise(){return new Promise((t=>{this._queue.add(new us((()=>{t()})))}))}}class bs extends li{constructor(){super(...arguments),this.type="ex.actions",this.dependencies=[ui,pi]}onAdd(t){this._ctx=new ws(t)}onRemove(){this._ctx=null}getQueue(){var t;return null===(t=this._ctx)||void 0===t?void 0:t.getQueue()}runAction(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.runAction(t)}update(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.update(t)}clearActions(){var t;null===(t=this._ctx)||void 0===t||t.clearActions()}easeTo(...t){return this._ctx.easeTo.apply(this._ctx,t)}easeBy(...t){return this._ctx.easeBy.apply(this._ctx,t)}moveTo(t,e,i){return this._ctx.moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._ctx.moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._ctx.rotateTo(t,e,i)}rotateBy(t,e,i){return this._ctx.rotateBy(t,e,i)}scaleTo(t,e,i,s){return this._ctx.scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._ctx.scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._ctx.blink(t,e,i)}fade(t,e){return this._ctx.fade(t,e)}delay(t){return this._ctx.delay(t)}die(){return this._ctx.die()}callMethod(t){return this._ctx.callMethod(t)}repeat(t,e){return this._ctx.repeat(t,e)}repeatForever(t){return this._ctx.repeatForever(t)}follow(t,e){return this._ctx.follow(t,e)}meet(t,e){return this._ctx.meet(t,e)}toPromise(){return this._ctx.toPromise()}}!function(t){t.Em="em",t.Rem="rem",t.Px="px",t.Pt="pt",t.Percent="%"}(ss||(ss={})),function(t){t.Left="left",t.Right="right",t.Center="center",t.Start="start",t.End="end"}(ns||(ns={})),function(t){t.Top="top",t.Hanging="hanging",t.Middle="middle",t.Alphabetic="alphabetic",t.Ideographic="ideographic",t.Bottom="bottom"}(rs||(rs={})),function(t){t.Normal="normal",t.Italic="italic",t.Oblique="oblique"}(os||(os={})),function(t){t.LeftToRight="ltr",t.RightToLeft="rtl"}(as||(as={}));class Cs{constructor(t,e,i,s){this.font=t,this.text=e,this.color=i,this.maxWidth=s,this._textFragments=[],this.disposed=!1,this._dirty=!0,this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.dimensions=this.measureText(e),this._setDimension(this.dimensions,this.ctx),this._lastHashCode=this.getHashCode()}measureText(t,e){if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);let i=null;i=null!=e?this._getLinesFromText(t,e):t.split("\n");const s=i.reduce(((t,e)=>t.length>e.length?t:e));this._applyFont(this.ctx);const n=this.ctx.measureText(s);let r=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);const o=r*i.length;r=o;const a=o-Math.abs(n.actualBoundingBoxAscent);return new At({left:0-Math.abs(n.actualBoundingBoxLeft)-this.font.padding,top:0-Math.abs(n.actualBoundingBoxAscent)-this.font.padding,bottom:0+a+this.font.padding,right:0+Math.abs(n.actualBoundingBoxRight)+this.font.padding})}_setDimension(t,e){e.canvas.width=2*(t.width+2*this.font.padding)*this.font.quality,e.canvas.height=2*(t.height+2*this.font.padding)*this.font.quality}static getHashCode(t,e,i){var s;return e+"__hashcode__"+t.fontString+t.showDebug+t.textAlign+t.baseAlign+t.direction+JSON.stringify(t.shadow)+(t.padding.toString()+t.smoothing.toString()+t.lineWidth.toString()+t.lineDash.toString()+(null===(s=t.strokeColor)||void 0===s?void 0:s.toString())+(i?i.toString():t.color.toString()))}getHashCode(t=!0){return Cs.getHashCode(this.font,this.text,t?this.color:void 0)}_applyRasterProperties(t){var e,i;t.translate(this.font.padding,this.font.padding),t.imageSmoothingEnabled=this.font.smoothing,t.lineWidth=this.font.lineWidth,t.setLineDash(null!==(e=this.font.lineDash)&&void 0!==e?e:t.getLineDash()),t.strokeStyle=null===(i=this.font.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=this.color.toString()}_applyFont(t){t.resetTransform(),t.translate(this.font.padding+t.canvas.width/2,this.font.padding+t.canvas.height/2),t.scale(this.font.quality,this.font.quality),t.textAlign=this.font.textAlign,t.textBaseline=this.font.baseAlign,t.font=this.font.fontString,t.direction=this.font.direction,this.font.shadow&&(t.shadowColor=this.font.shadow.color.toString(),t.shadowBlur=this.font.shadow.blur,t.shadowOffsetX=this.font.shadow.offset.x,t.shadowOffsetY=this.font.shadow.offset.y)}_drawText(t,e,i){this._applyRasterProperties(t),this._applyFont(t);for(let s=0;s<e.length;s++){const n=e[s];this.color&&t.fillText(n,0,s*i),this.font.strokeColor&&t.strokeText(n,0,s*i)}this.font.showDebug&&(Ee(t,yt.Green,-t.canvas.width/2,0,t.canvas.width/2,0,2),Ee(t,yt.Red,0,-t.canvas.height/2,0,t.canvas.height/2,2))}_splitTextBitmap(t){const e=[];let i=0,s=0;const n=Math.min(4096,t.canvas.width),r=Math.min(4096,t.canvas.height);for(;i<t.canvas.width;){for(;s<t.canvas.height;){const o=document.createElement("canvas");o.width=n,o.height=r;o.getContext("2d").drawImage(t.canvas,i,s,n,r,0,0,n,r),e.push({x:i,y:s,canvas:o}),s+=r}i+=n,s=0}return e}flagDirty(){this._dirty=!0}render(t,e,i,s){if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);this._ex=t;const n=this.getHashCode();if(this._lastHashCode!==n&&(this._dirty=!0),this._dirty){this.dimensions=this.measureText(this.text,s),this._setDimension(this.dimensions,this.ctx);const e=this._getLinesFromText(this.text,s),i=this.dimensions.height/e.length;if(this._drawText(this.ctx,e,i),t instanceof fe)for(const e of this._textFragments)t.textureLoader.delete(e.canvas);if(this._textFragments=this._splitTextBitmap(this.ctx),t instanceof fe)for(const e of this._textFragments)t.textureLoader.load(e.canvas,this.font.filtering,!0);this._lastHashCode=n,this._dirty=!1}for(const s of this._textFragments)t.drawImage(s.canvas,0,0,s.canvas.width,s.canvas.height,s.x/this.font.quality+e-this.ctx.canvas.width/this.font.quality/2,s.y/this.font.quality+i-this.ctx.canvas.height/this.font.quality/2,s.canvas.width/this.font.quality,s.canvas.height/this.font.quality)}dispose(){if(this.disposed=!0,this.dimensions=void 0,this.canvas=void 0,this.ctx=void 0,this._ex instanceof fe)for(const t of this._textFragments)this._ex.textureLoader.delete(t.canvas);this._textFragments.length=0}_getLinesFromText(t,e){if(this._chachedText===t&&this._cachedRenderWidth===e)return this._chachedLines;const i=t.split("\n");if(null==e)return i;for(let t=0;t<i.length;t++){let s=i[t],n="";if(this.measureText(s).width>e){for(;this.measureText(s).width>e;)n=s[s.length-1]+n,s=s.slice(0,-1);i[t]=s,i[t+1]=n}}return this._chachedText=t,this._chachedLines=i,this._cachedRenderWidth=e,i}}class As{static measureText(t,e,i){const s=Cs.getHashCode(e,t);if(As._MEASURE_CACHE.has(s))return As._MEASURE_CACHE.get(s);As._LOGGER.debug("Font text measurement cache miss");const n=e.measureTextWithoutCache(t,i);return As._MEASURE_CACHE.set(s,n),n}static getTextInstance(t,e,i){const s=Cs.getHashCode(e,t,i);let n=As._TEXT_CACHE.get(s);return n||(n=new Cs(e,t,i),As._TEXT_CACHE.set(s,n),As._LOGGER.debug("Font text instance cache miss")),As._TEXT_USAGE.set(n,performance.now()),n}static checkAndClearCache(){const t=[],e=new Set;for(const[i,s]of As._TEXT_USAGE.entries())if(s+As.FONT_TIMEOUT<performance.now())As._LOGGER.debug(`Text cache entry timed out ${i.text}`),t.push(i),i.dispose();else{const t=i.getHashCode(!1);e.add(t)}t.forEach((t=>{As._TEXT_USAGE.delete(t)})),this._TEXT_CACHE.clear();for(const[t]of this._TEXT_USAGE.entries())this._TEXT_CACHE.set(t.getHashCode(),t);const i=new Map;for(const t of e)As._MEASURE_CACHE.has(t)&&i.set(t,As._MEASURE_CACHE.get(t));this._MEASURE_CACHE.clear(),this._MEASURE_CACHE=i}static get cacheSize(){return As._TEXT_USAGE.size}static clearCache(){for(const[t]of As._TEXT_USAGE.entries())t.dispose();As._TEXT_USAGE.clear(),As._TEXT_CACHE.clear(),As._MEASURE_CACHE.clear()}}As.FONT_TIMEOUT=500,As._LOGGER=J.getInstance(),As._TEXT_USAGE=new Map,As._TEXT_CACHE=new Map,As._MEASURE_CACHE=new Map;class Ts extends Ht{constructor(t={}){var e,i,s,n,r,o,a,h,l,c,d,u,p,_,g,m,f,v,x;super(t),this.filtering=Gt.Blended,this.quality=2,this.padding=2,this.smoothing=!1,this.lineWidth=1,this.lineDash=[],this.color=yt.Black,this.family="sans-serif",this.style=os.Normal,this.bold=!1,this.unit=ss.Px,this.textAlign=ns.Left,this.baseAlign=rs.Alphabetic,this.direction=as.LeftToRight,this.size=10,this.shadow=null,this._textBounds=new At,this._textMeasurement=new Cs(this,"",yt.Black),this.smoothing=null!==(e=null==t?void 0:t.smoothing)&&void 0!==e?e:this.smoothing,this.padding=null!==(i=null==t?void 0:t.padding)&&void 0!==i?i:this.padding,this.color=null!==(s=null==t?void 0:t.color)&&void 0!==s?s:this.color,this.strokeColor=null!==(n=null==t?void 0:t.strokeColor)&&void 0!==n?n:this.strokeColor,this.lineDash=null!==(r=null==t?void 0:t.lineDash)&&void 0!==r?r:this.lineDash,this.lineWidth=null!==(o=null==t?void 0:t.lineWidth)&&void 0!==o?o:this.lineWidth,this.filtering=null!==(a=null==t?void 0:t.filtering)&&void 0!==a?a:this.filtering,this.family=null!==(h=null==t?void 0:t.family)&&void 0!==h?h:this.family,this.style=null!==(l=null==t?void 0:t.style)&&void 0!==l?l:this.style,this.bold=null!==(c=null==t?void 0:t.bold)&&void 0!==c?c:this.bold,this.size=null!==(d=null==t?void 0:t.size)&&void 0!==d?d:this.size,this.unit=null!==(u=null==t?void 0:t.unit)&&void 0!==u?u:this.unit,this.textAlign=null!==(p=null==t?void 0:t.textAlign)&&void 0!==p?p:this.textAlign,this.baseAlign=null!==(_=null==t?void 0:t.baseAlign)&&void 0!==_?_:this.baseAlign,this.direction=null!==(g=null==t?void 0:t.direction)&&void 0!==g?g:this.direction,this.quality=null!==(m=null==t?void 0:t.quality)&&void 0!==m?m:this.quality,(null==t?void 0:t.shadow)&&(this.shadow={},this.shadow.blur=null!==(f=t.shadow.blur)&&void 0!==f?f:this.shadow.blur,this.shadow.offset=null!==(v=t.shadow.offset)&&void 0!==v?v:this.shadow.offset,this.shadow.color=null!==(x=t.shadow.color)&&void 0!==x?x:this.shadow.color)}clone(){return new Ts({...this.cloneGraphicOptions(),size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:null})}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get localBounds(){return this._textBounds}_drawImage(t,e,i){}_rotate(t){var e;const i=null!==(e=this.origin)&&void 0!==e?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}measureTextWithoutCache(t,e){return this._textMeasurement.measureText(t,e)}measureText(t,e){return As.measureText(t,this,e)}_postDraw(t){t.restore()}render(t,e,i,s,n,r){const o=As.getTextInstance(e,this,i);this._textBounds=o.dimensions,this._preDraw(t,s,n),o.render(t,s,n,r),this._postDraw(t)}}class Ss extends Ht{constructor(t){var e,i;super(t),this._text="",this._textWidth=0,this._textHeight=0,this.font=null!==(e=t.font)&&void 0!==e?e:new Ts,this.color=null!==(i=t.color)&&void 0!==i?i:this.color,this.text=t.text,this.maxWidth=t.maxWidth}clone(){var t,e;return new Ss({text:this.text.slice(),color:null!==(e=null===(t=this.color)||void 0===t?void 0:t.clone())&&void 0!==e?e:yt.Black,font:this.font.clone(),maxWidth:this.maxWidth})}get text(){return this._text}set text(t){this._text=t,this._calculateDimension()}get font(){return this._font}set font(t){this._font=t}get width(){return 0===this._textWidth&&this._calculateDimension(),this._textWidth*this.scale.x}get height(){return 0===this._textHeight&&this._calculateDimension(),this._textHeight*this.scale.y}_calculateDimension(){const{width:t,height:e}=this.font.measureText(this._text,this.maxWidth);this._textWidth=t,this._textHeight=e}get localBounds(){return this.font.measureText(this._text,this.maxWidth).scale(this.scale)}_rotate(t){}_flip(t){}_preDraw(t,e,i){(this.isStale()||this.font.isStale())&&(this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity),this.font.tint=this.tint,super._preDraw(t,e,i)}_drawImage(t,e,i){var s;let n=yt.Black;this.font instanceof Ts&&(n=null!==(s=this.color)&&void 0!==s?s:this.font.color);const{width:r,height:o}=this.font.measureText(this._text,this.maxWidth);this._textWidth=r,this._textHeight=o,this.font.render(t,this._text,n,e,i,this.maxWidth),this.font.showDebug&&(t.debug.drawRect(e-r,i-o,2*r,2*o),null!=this.maxWidth&&t.debug.drawRect(e,i,this.maxWidth,this.height,{color:yt.Yellow}))}}class Es extends Wi{get body(){return this.get(Li)}get transform(){return this.get(ui)}get motion(){return this.get(pi)}get graphics(){return this.get(Xi)}get collider(){return this.get(ki)}get pointer(){return this.get(Yi)}get actions(){return this.get(bs)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(ui).scale}set scale(t){this.get(ui).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=Ot(t,(t=>this._handleAnchorChange(t))),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get isOffScreen(){return this.hasTag("ex.offscreen")}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.events.on("pointerdragstart",this._pointerDragStartHandler),this.events.on("pointerdragend",this._pointerDragEndHandler),this.events.on("pointerdragmove",this._pointerDragMoveHandler),this.events.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.events.off("pointerdragstart",this._pointerDragStartHandler),this.events.off("pointerdragend",this._pointerDragEndHandler),this.events.off("pointerdragmove",this._pointerDragMoveHandler),this.events.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this._color}set color(t){var e;this._color=t.clone();const i=null===(e=this.graphics.layers.default.graphics[0])||void 0===e?void 0:e.graphic;(i instanceof Fe||i instanceof Ss)&&(i.color=this._color)}constructor(t){super(),this.events=new d,this._anchor=Ot(vt.Half,(t=>this._handleAnchorChange(t))),this.logger=J.getInstance(),this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this._pointerDragLeaveHandler=t=>{this._dragging&&(this.pos=t.worldPos)};const{name:e,x:i,y:s,pos:n,coordPlane:r,scale:o,width:a,height:h,radius:l,collider:c,vel:u,acc:p,rotation:_,angularVelocity:g,z:m,color:f,visible:v,anchor:x,collisionType:y,collisionGroup:w}={...t};this._setName(e),this.anchor=null!=x?x:Es.defaults.anchor.clone();const b=new ui;this.addComponent(b),this.pos=null!=n?n:xt(null!=i?i:0,null!=s?s:0),this.rotation=null!=_?_:0,this.scale=null!=o?o:xt(1,1),this.z=null!=m?m:0,b.coordPlane=null!=r?r:si.World,this.addComponent(new Yi),this.addComponent(new Xi({anchor:this.anchor})),this.addComponent(new pi),this.vel=null!=u?u:vt.Zero,this.acc=null!=p?p:vt.Zero,this.angularVelocity=null!=g?g:0,this.addComponent(new bs),this.addComponent(new Li),this.body.collisionType=null!=y?y:Ze.Passive,w&&(this.body.group=w),c?this.addComponent(new ki(c)):l?this.addComponent(new ki(Fi.Circle(l))):a>0&&h>0?this.addComponent(new ki(Fi.Box(a,h,this.anchor))):this.addComponent(new ki),this.graphics.visible=null==v||v,f&&(this.color=f,a&&h?this.graphics.add(new Ki({color:f,width:a,height:h})):l&&this.graphics.add(new Zi({color:f,radius:l})))}clone(){const t=new Es({color:this.color.clone(),anchor:this.anchor.clone()});t.clearComponents(),t.processComponentRemoval();const e=this.getComponents();for(const i of e)t.addComponent(i.clone(),!0);return t}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_prekill(t){this.events.emit("prekill",new _(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){this.events.emit("postkill",new g(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.events.emit("kill",new p(this)),super.kill(),this._postkill(this.scene)):this.logger.warn(`Cannot kill actor named "${this.name}", it was never added to the Scene`)}unkill(){this.active=!0}isKilled(){return!this.active}get z(){return this.get(ui).z}set z(t){this.get(ui).z=t}get center(){const t=this.getGlobalPos();return new vt(t.x+this.width/2-this.anchor.x*this.width,t.y+this.height/2-this.anchor.y*this.height)}get localCenter(){return new vt(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(ui).globalRotation}getGlobalPos(){return this.get(ui).globalPos}getGlobalScale(){return this.get(ui).globalScale}contains(t,e,i=!1){const s=xt(t,e),n=this.get(ki);n.update();const r=n.get();if(!r)return!1;const o=r.contains(s);return i?o||this.children.some((i=>i.contains(t,e,!0))):o}within(t,e){const i=this.get(ki),s=t.get(ki),n=i.get(),r=s.get();return!(!n||!r)&&n.getClosestLineBetween(r).getLength()<=e}update(t,e){this._initialize(t),this._preupdate(t,e),this._postupdate(t,e)}onPreUpdate(t,e){}onPostUpdate(t,e){}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}}function Ps(t){return t instanceof Is}Es.defaults={anchor:vt.Half};class Is extends Es{constructor(t){var e,i;super({...t}),this.get(ui).coordPlane=si.Screen,this.anchor=null!==(e=null==t?void 0:t.anchor)&&void 0!==e?e:xt(0,0),this.body.collisionType=null!==(i=null==t?void 0:t.collisionType)&&void 0!==i?i:Ze.PreventCollision,this.pointer.useGraphicsBounds=!0,this.pointer.useColliderShape=!1,!(null==t?void 0:t.collider)&&(null==t?void 0:t.width)>0&&(null==t?void 0:t.height)>0&&this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new vt(t,e));return super.contains(s.x,s.y)}}class Ds{get complete(){return this._complete}constructor(t,e,i,s,n,r){if(this._logger=J.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this.randomRange=[0,0],this._baseInterval=10,this._generateRandomInterval=()=>this._baseInterval+this.random.integer(this.randomRange[0],this.randomRange[1]),this._complete=!1,this.scene=null,"function"!=typeof t){const o=t;t=o.fcn,e=o.interval,i=o.repeats,s=o.numberOfRepeats,n=o.randomRange,r=o.random}if(s&&s>=0&&(this.maxNumberOfRepeats=s,!i))throw new Error("repeats must be set to true if numberOfRepeats is set");if(this.id=Ds._MAX_ID++,this._callbacks=[],this._baseInterval=this.interval=e,n){if(n[0]>n[1])throw new Error("min value must be lower than max value for range");this.random=null!=r?r:new at,this.randomRange=n,this.interval=this._generateRandomInterval(),this.on((()=>{this.interval=this._generateRandomInterval()}))}this.repeats=i||this.repeats,t&&this.on(t)}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach((t=>{t.call(this)})),this._numberOfTicks++,this.repeats||(this._complete=!0,this._running=!1),this._elapsedTime=0))}reset(t,e){if(t&&t>=0&&(this._baseInterval=this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}}Ds._MAX_ID=0;class Bs extends li{constructor(t){super(),this.type="ex.parallax",this.parallaxFactor=xt(1,1),this.parallaxFactor=null!=t?t:this.parallaxFactor}}class Rs extends li{constructor(t,e=!0){super(),this.draw=t,this.useTransform=e,this.type="ex.debuggraphics"}}class Fs{constructor(t,e){this.bounds=t,this.options=e,this._defaultOptions={maxDepth:10,capacity:10,level:0},this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null,this.options={...this._defaultOptions,...e},this.halfWidth=t.width/2,this.halfHeight=t.height/2}_split(){this._isDivided=!0;const t={maxDepth:this.options.maxDepth,capacity:this.options.capacity,level:this.options.level+1};this.topLeft=new Fs(new At({left:this.bounds.left,top:this.bounds.top,right:this.bounds.left+this.halfWidth,bottom:this.bounds.top+this.halfHeight}),t),this.topRight=new Fs(new At({left:this.bounds.left+this.halfWidth,top:this.bounds.top,right:this.bounds.right,bottom:this.bounds.top+this.halfHeight}),t),this.bottomLeft=new Fs(new At({left:this.bounds.left,top:this.bounds.top+this.halfHeight,right:this.bounds.left+this.halfWidth,bottom:this.bounds.bottom}),t),this.bottomRight=new Fs(new At({left:this.bounds.left+this.halfWidth,top:this.bounds.top+this.halfHeight,right:this.bounds.right,bottom:this.bounds.bottom}),t)}_insertIntoSubNodes(t){var e,i,s,n;(null===(e=this.topLeft)||void 0===e?void 0:e.bounds.overlaps(t.bounds))&&this.topLeft.insert(t),(null===(i=this.topRight)||void 0===i?void 0:i.bounds.overlaps(t.bounds))&&this.topRight.insert(t),(null===(s=this.bottomLeft)||void 0===s?void 0:s.bounds.overlaps(t.bounds))&&this.bottomLeft.insert(t),(null===(n=this.bottomRight)||void 0===n?void 0:n.bounds.overlaps(t.bounds))&&this.bottomRight.insert(t)}insert(t){if(this._isDivided)this._insertIntoSubNodes(t);else if(this.items.push(t),this.items.length>this.options.capacity&&this.options.level<this.options.maxDepth){this._isDivided||this._split();for(const t of this.items)this._insertIntoSubNodes(t);this.items.length=0}}remove(t){var e,i,s,n;if(this.bounds.overlaps(t.bounds))if(this._isDivided)(null===(e=this.topLeft)||void 0===e?void 0:e.bounds.overlaps(t.bounds))&&this.topLeft.remove(t),(null===(i=this.topRight)||void 0===i?void 0:i.bounds.overlaps(t.bounds))&&this.topRight.remove(t),(null===(s=this.bottomLeft)||void 0===s?void 0:s.bounds.overlaps(t.bounds))&&this.bottomLeft.remove(t),(null===(n=this.bottomRight)||void 0===n?void 0:n.bounds.overlaps(t.bounds))&&this.bottomRight.remove(t);else{const e=this.items.indexOf(t);e>-1&&this.items.splice(e,1)}}query(t){let e=this.items;return this._isDivided&&(this.topLeft.bounds.overlaps(t)&&(e=e.concat(this.topLeft.query(t))),this.topRight.bounds.overlaps(t)&&(e=e.concat(this.topRight.query(t))),this.bottomLeft.bounds.overlaps(t)&&(e=e.concat(this.bottomLeft.query(t))),this.bottomRight.bounds.overlaps(t)&&(e=e.concat(this.bottomRight.query(t)))),e=e.filter(((t,i)=>e.indexOf(t)>=i)),e}clear(){this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null}getAllItems(){let t=this.items;return this._isDivided&&(t=t.concat(this.topLeft.getAllItems()),t=t.concat(this.topRight.getAllItems()),t=t.concat(this.bottomLeft.getAllItems()),t=t.concat(this.bottomRight.getAllItems())),t=t.filter(((e,i)=>t.indexOf(e)>=i)),t}getTreeDepth(){return this._isDivided?1+Math.max(this.topLeft.getTreeDepth(),this.topRight.getTreeDepth(),this.bottomLeft.getTreeDepth(),this.bottomRight.getTreeDepth()):0}debug(t){this.bounds.draw(t,yt.Yellow),this._isDivided&&(this.topLeft.bounds.draw(t,yt.Yellow),this.topRight.bounds.draw(t,yt.Yellow),this.bottomLeft.bounds.draw(t,yt.Yellow),this.bottomRight.bounds.draw(t,yt.Yellow))}}const ks={PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw"};class Ms extends Wi{flagCollidersDirty(){this._collidersDirty=!0}flagTilesDirty(){for(let t=0;t<this.tiles.length;t++)this.tiles[t]&&this.tiles[t].flagDirty()}get x(){var t;return null!==(t=this._transform.pos.x)&&void 0!==t?t:0}set x(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this.get(ui).pos=xt(t,this.y))}get y(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos.y)&&void 0!==e?e:0}set y(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this._transform.pos=xt(this.x,t))}get z(){var t;return null!==(t=this._transform.z)&&void 0!==t?t:0}set z(t){this._transform&&(this._transform.z=t)}get rotation(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.rotation)&&void 0!==e?e:0}set rotation(t){this._transform&&(this._transform.rotation=t)}get scale(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.scale)&&void 0!==e?e:vt.One}set scale(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.scale)&&(this._transform.scale=t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}constructor(t){var e,i;super(null,t.name),this.events=new d,this._token=0,this.logger=J.getInstance(),this.tiles=[],this._rows=[],this._cols=[],this.renderFromTopOfGraphic=!1,this._collidersDirty=!0,this._originalOffsets=new WeakMap,this.addComponent(new ui),this.addComponent(new pi),this.addComponent(new Li({type:Ze.Fixed})),this.addComponent(new Xi({onPostDraw:(t,e)=>this.draw(t,e)})),this.addComponent(new Rs(((t,e)=>this.debug(t,e)),!1)),this.addComponent(new ki),this._graphics=this.get(Xi),this._transform=this.get(ui),this._motion=this.get(pi),this._collider=this.get(ki),this._composite=this._collider.useCompositeCollider([]),this._transform.pos=null!==(e=t.pos)&&void 0!==e?e:vt.Zero,this._oldPos=this._transform.pos.clone(),this._oldScale=this._transform.scale.clone(),this.renderFromTopOfGraphic=null!==(i=t.renderFromTopOfGraphic)&&void 0!==i?i:this.renderFromTopOfGraphic,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.rows=t.rows,this.columns=t.columns,this._quadTree=new Fs(At.fromDimension(this.columns*this.tileWidth,this.rows*this.tileHeight,vt.Zero,this.pos)),this.tiles=new Array(this.rows*this.columns),this._rows=new Array(this.rows),this._cols=new Array(this.columns);let s=[];for(let t=0;t<this.columns;t++){for(let e=0;e<this.rows;e++){const i=new Ls({x:t,y:e,map:this});i.map=this,this._quadTree.insert(i),this.tiles[t+e*this.columns]=i,s.push(i),this._rows[e]||(this._rows[e]=[]),this._rows[e].push(i)}this._cols[t]=s,s=[]}this._graphics.localBounds=new At({left:0,top:0,right:this.columns*this.tileWidth*this.scale.x,bottom:this.rows*this.tileHeight*this.scale.y})}_initialize(t){super._initialize(t),this._engine=t}_getOrSetColliderOriginalOffset(t){if(this._originalOffsets.has(t))return this._originalOffsets.get(t);{const e=t.offset;return this._originalOffsets.set(t,e),e}}_updateQuadTree(){this._quadTree=new Fs(At.fromDimension(this.columns*this.tileWidth,this.rows*this.tileHeight,vt.Zero,vt.Zero).scale(this.scale).translate(this.pos).rotate(this.rotation,this.pos));for(let t=0;t<this.tiles.length;t++)this._quadTree.insert(this.tiles[t])}_updateColliders(){this._collider.$colliderRemoved.notifyAll(this._composite),this._composite.clearColliders();const t=[];let e;this._composite=this._collider.useCompositeCollider([]);const i=(t,e)=>!(!t||!e)&&(t.top===e.top&&t.bottom===e.bottom&&t.right===e.left),s=(t,e,s=10)=>{if(!t)return!1;for(let n=e.length-1;n>=0;n--){if(s--<0)return!1;const r=e[n];if(i(r,t))return e[n]=r.combine(t),!0}return!1};for(let i=0;i<this.columns;i++){for(let n=0;n<this.rows;n++){const r=this.tiles[i+n*this.columns];if(r.solid)if(r.getColliders().length>0){for(const t of r.getColliders()){const e=this._getOrSetColliderOriginalOffset(t);t.offset=xt(r.x*this.tileWidth*this.scale.x,r.y*this.tileHeight*this.scale.y).add(e),t.owner=this,this._composite.addCollider(t)}e&&!s(e,t)&&t.push(e),e=null}else e=e?e.combine(r.defaultGeometry):r.defaultGeometry;else e&&!s(e,t)&&t.push(e),e=null}e&&!s(e,t)&&t.push(e),e=null}for(const e of t){const t=Fi.Box(e.width,e.height,vt.Zero,xt(e.left-this.pos.x,e.top-this.pos.y));t.owner=this,this._composite.addCollider(t)}this._collider.update(),this._collider.$colliderAdded.notifyAll(this._composite)}getTileByIndex(t){return this.tiles[t]}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=Math.floor((t.x-this.pos.x)/(this.tileWidth*this.scale.x)),i=Math.floor((t.y-this.pos.y)/(this.tileHeight*this.scale.y)),s=this.getTile(e,i);return e>=0&&i>=0&&e<this.columns&&i<this.rows&&s?s:null}getRows(){return this._rows}getColumns(){return this._cols}update(t,e){this.onPreUpdate(t,e),this.emit("preupdate",new b(t,e,this)),this._oldPos.equals(this.pos)&&this._oldRotation===this.rotation&&this._oldScale.equals(this.scale)||(this.flagCollidersDirty(),this.flagTilesDirty()),this._collidersDirty&&(this._collidersDirty=!1,this._updateColliders(),this._updateQuadTree()),this._token++,this.pos.clone(this._oldPos),this._oldRotation=this.rotation,this.scale.clone(this._oldScale),this._transform.pos=this.pos,this.onPostUpdate(t,e),this.emit("postupdate",new C(t,e,this))}draw(t,e){this.emit("predraw",new v(t,e,this));let i=this._engine.screen.getWorldBounds();const s=this._engine.screen.getScreenBounds();let n,r,o;const a=this._transform.coordPlane===si.Screen,h=this.get(Bs);if(h){let t=this.pos;const e=vt.One.sub(h.parallaxFactor),s=this._engine.currentScene.camera.pos.scale(e);t=t.sub(s),i=i.translate(t)}const l=this._quadTree.query(a?s:i);for(let i=0;i<l.length;i++){const s=l[i];for(n=s.getGraphics(),r=0,o=n.length;r<o;r++){const i=n[r];if(i){Gi(i)&&(null==i||i.tick(e,this._token));const n=this.renderFromTopOfGraphic?0:i.height-this.tileHeight;i.draw(t,s.x*this.tileWidth,s.y*this.tileHeight-n)}}}this.emit("postdraw",new x(t,e,this))}debug(t,e){const{showAll:i,showGrid:s,gridColor:n,gridWidth:r,showSolidBounds:o,solidBoundsColor:a,showColliderGeometry:h,colliderGeometryColor:l,showQuadTree:c}=e.tilemap,d=this.tileWidth*this.columns*this.scale.x,u=this.tileHeight*this.rows*this.scale.y,p=this.pos;if(s||i){for(let e=0;e<this.rows+1;e++){const i=xt(0,e*this.tileHeight*this.scale.y);t.drawLine(p.add(i),p.add(xt(d,i.y)),n,r)}for(let e=0;e<this.columns+1;e++){const i=xt(e*this.tileWidth*this.scale.x,0);t.drawLine(p.add(i),p.add(xt(i.x,u)),n,r)}}if(i||o||h){const e=this._composite.getColliders();t.save(),t.translate(this.pos.x,this.pos.y),t.scale(this.scale.x,this.scale.y);for(const i of e){const e=i.localBounds,s=i.worldPos.sub(this.pos);o&&t.drawRectangle(s,e.width,e.height,a)}if(t.restore(),h)for(const i of e)i.debug(t,l)}if(i||c||o){if(t.save(),t.z=999,c&&this._quadTree.debug(t),o)for(let e=0;e<this.tiles.length;e++)this.tiles[e].bounds.draw(t);t.restore()}}}class Ls extends Wi{get pos(){return this._posDirty&&(this._recalculate(),this._posDirty=!1),this._pos}get width(){return this._width}get height(){return this._height}get solid(){return this._solid}set solid(t){var e;null===(e=this.map)||void 0===e||e.flagCollidersDirty(),this._solid=t}getGraphics(){return this._graphics}addGraphic(t){this._graphics.push(t)}removeGraphic(t){Pt(t,this._graphics)}clearGraphics(){this._graphics.length=0}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}constructor(t){var e,i;super(),this._posDirty=!1,this._solid=!1,this._graphics=[],this._colliders=[],this.data=new Map,this.x=t.x,this.y=t.y,this.map=t.map,this._width=t.map.tileWidth*this.map.scale.x,this._height=t.map.tileHeight*this.map.scale.y,this.solid=null!==(e=t.solid)&&void 0!==e?e:this.solid,this._graphics=null!==(i=t.graphics)&&void 0!==i?i:[],this._recalculate()}flagDirty(){return this._posDirty=!0}_recalculate(){const t=this.map.pos.add(xt(this.x*this.map.tileWidth,this.y*this.map.tileHeight));this._geometry=new At(t.x,t.y,t.x+this.map.tileWidth,t.y+this.map.tileHeight),this._width=this.map.tileWidth*this.map.scale.x,this._height=this.map.tileHeight*this.map.scale.y,this._pos=this.map.pos.add(xt(this.x*this._width,this.y*this._height)),this._bounds=new At(this._pos.x,this._pos.y,this._pos.x+this._width,this._pos.y+this._height),this.map.rotation&&(this._bounds=this._bounds.rotate(this.map.rotation,this.map.pos)),this._posDirty=!1}get bounds(){return this._posDirty&&this._recalculate(),this._bounds}get defaultGeometry(){return this._geometry}get center(){return this._posDirty&&this._recalculate(),new vt(this._pos.x+this._width/2,this._pos.y+this._height/2)}}class zs{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new Os(t))}lockToActorAxis(t,e){this.camera.addStrategy(new Ns(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new Hs(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new Ws(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Gs(t))}}var Us;!function(t){t[t.X=0]="X",t[t.Y=1]="Y"}(Us||(Us={}));class Os{constructor(t){this.target=t,this.action=(t,e,i,s)=>t.center}}class Ns{constructor(t,e){this.target=t,this.axis=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus();return this.axis===Us.X?new vt(n.x,r.y):new vt(r.x,n.y)}}}class Hs{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(t,e,i,s)=>{const n=t.center;let r=e.getFocus(),o=e.vel.clone();const a=n.sub(r).scale(this.cameraElasticity);o=o.add(a);const h=o.scale(-1).scale(this.cameraFriction);return o=o.add(h),r=r.add(o),r}}}class Ws{constructor(t,e){this.target=t,this.radius=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus(),o=n.sub(r),a=o.size;if(a>=this.radius){const t=a-this.radius;return r.add(o.normalize().scale(t))}return r}}}class Gs{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(t,e,i,s)=>{const n=e.getFocus();this.boundSizeChecked||((t.bottom-t.top<i.drawHeight||t.right-t.left<i.drawWidth)&&J.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let r=n.x,o=n.y;return n.x<t.left+i.halfDrawWidth?r=t.left+i.halfDrawWidth:n.x>t.right-i.halfDrawWidth&&(r=t.right-i.halfDrawWidth),n.y<t.top+i.halfDrawHeight?o=t.top+i.halfDrawHeight:n.y>t.bottom-i.halfDrawHeight&&(o=t.bottom-i.halfDrawHeight),xt(r,o)}}}const Vs={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class qs{constructor(){this.events=new d,this.transform=kt.identity(),this.inverse=kt.identity(),this._cameraStrategies=[],this.strategy=new zs(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this._angularVelocity=0,this._posChanged=!1,this._pos=Nt(vt.Zero,(()=>this._posChanged=!0)),this.vel=vt.Zero,this.acc=vt.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._zoomEasing=ji.EaseInOutCubic,this._easing=ji.EaseInOutCubic,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this._angularVelocity}set angularVelocity(t){this._angularVelocity=t}get pos(){return this._pos}set pos(t){this._pos=Nt(t,(()=>this._posChanged=!0)),this._posChanged=!0}get x(){return this.pos.x}set x(t){this._follow||this._cameraMoving||(this.pos=xt(t,this.pos.y))}get y(){return this.pos.y}set y(t){this._follow||this._cameraMoving||(this.pos=xt(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=xt(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=xt(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=xt(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=xt(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=ji.EaseInOutCubic){if("function"!=typeof i)throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise((t=>{this._lerpResolve=t})),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=ji.EaseInOutCubic){return this._zoomPromise=new Promise((t=>{this._zoomResolve=t})),e?(this._isZooming=!0,this._zoomEasing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t,this._zoomPromise):(this._isZooming=!1,this.zoom=t,Promise.resolve(!0))}get viewport(){return this._viewport?this._viewport:new At(0,0,0,0)}addStrategy(t){this._cameraStrategies.push(t)}removeStrategy(t){Pt(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.events.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.events.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t,this._screen=t.screen;const e=this._screen.contentArea;let i=xt(e.width/2,e.height/2);if(!this._engine.loadingComplete){const t=this._screen.peekResolution();t&&(i=xt(t.width/2,t.height/2))}this._halfWidth=i.x,this._halfHeight=i.y,this._posChanged||(this.pos=i),this.updateTransform(),this.runStrategies(t,t.clock.elapsed()),this.updateViewport(),this.updateTransform(),this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0}}onInitialize(t){}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}runStrategies(t,e){for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e)}updateViewport(){this._viewport=new At(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){const t=(0,this._zoomEasing)(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration);this.zoom=t,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){const t=ji.CreateVectorEasingFunction(this._easing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration);this.pos=t,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const t=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(t)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=1+(Math.random()*this._shakeMagnitudeX|0),this._yShake=1+(Math.random()*this._shakeMagnitudeY|0)),this.runStrategies(t,e),this.updateViewport(),this.updateTransform(),this._postupdate(t,e)}draw(t){t.multiply(this.transform)}updateTransform(){const t=this._screen.resolution.width/this.zoom,e=this._screen.resolution.height/this.zoom,i=xt(-this.x+t/2+this._xShake,-this.y+e/2+this._yShake);this.transform.reset(),this.transform.scale(this.zoom,this.zoom),this.transform.translate(t/2,e/2),this.transform.rotate(this.rotation),this.transform.translate(-t/2,-e/2),this.transform.translate(i.x,i.y),this.transform.inverse(this.inverse)}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}const Xs={ExitTrigger:"exit",EnterTrigger:"enter"},Ks={pos:vt.Zero,width:10,height:10,visible:!1,action:()=>{},filter:()=>!0,repeat:-1};class Zs extends Es{constructor(t){super({x:t.pos.x,y:t.pos.y,width:t.width,height:t.height}),this.events=new d,this.action=()=>{},this.filter=()=>!0,this.repeat=-1,t={...Ks,...t},this.filter=t.filter||this.filter,this.repeat=t.repeat||this.repeat,this.action=t.action||this.action,t.target&&(this.target=t.target),this.graphics.visible=t.visible,this.body.collisionType=Ze.Passive,this.events.on("collisionstart",(t=>{this.filter(t.other)&&(this.events.emit("enter",new q(this,t.other)),this._dispatchAction(),0===this.repeat&&this.kill())})),this.events.on("collisionend",(t=>{this.filter(t.other)&&this.events.emit("exit",new X(this,t.other))}))}set target(t){this._target=t,this.filter=e=>e===t}get target(){return this._target}_initialize(t){super._initialize(t)}_dispatchAction(){0!==this.repeat&&(this.action.call(this),this.repeat--)}}var Ys;!function(t){t.Update="update",t.Draw="draw"}(Ys||(Ys={}));class js{constructor(){this.priority=0}notify(t){}}class Qs{constructor(t){this.data=t,this.type="Entity Added"}}function $s(t){return!!t&&"Entity Added"===t.type}class Js{constructor(t){this.data=t,this.type="Entity Removed"}}function tn(t){return!!t&&"Entity Removed"===t.type}class en{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._entitiesToRemove=[]}updateEntities(t,e){for(const i of this.entities)i.update(t.engine,e),i.active||this.removeEntity(i)}findEntitiesForRemoval(){for(const t of this.entities)t.active||this.removeEntity(t)}notify(t){Ui(t)&&this._world.queryManager.addEntity(t.data.entity),Ni(t)&&this._world.queryManager.removeComponent(t.data.entity,t.data.component)}addEntity(t){t.active=!0,t.scene=this._world.context,t&&!this._entityIndex[t.id]&&(this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.componentAdded$.register(this),t.componentRemoved$.register(this),t.children.forEach((e=>{e.scene=t.scene,this.addEntity(e)})),t.childrenAdded$.register({notify:t=>{this.addEntity(t)}}),t.childrenRemoved$.register({notify:t=>{this.removeEntity(t,!1)}}))}removeEntity(t,e=!0){var i;let s=0;s=t instanceof Wi?t.id:t;const n=this._entityIndex[s];n&&n.active&&(n.active=!1),n&&e?this._entitiesToRemove.push(n):(delete this._entityIndex[s],n&&(n.scene=null,Pt(n,this.entities),this._world.queryManager.removeEntity(n),n.componentAdded$.unregister(this),n.componentRemoved$.unregister(this),n.children.forEach((t=>{t.scene=null,this.removeEntity(t,e)})),n.childrenAdded$.clear(),n.childrenRemoved$.clear(),(null===(i=this._world.context)||void 0===i?void 0:i.engine)&&this._world.context.engine.stats.currFrame.actors.killed++))}processEntityRemovals(){for(const t of this._entitiesToRemove)t.active||this.removeEntity(t,!1);this._entitiesToRemove.length=0}processComponentRemovals(){for(const t of this.entities)t.processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter((e=>e.name===t))}clear(){for(let t=this.entities.length-1;t>=0;t--)this.removeEntity(this.entities[t])}}const sn=t=>[...t].sort(((t,e)=>t.localeCompare(e))).join("+");class nn extends di{get key(){return this._key?this._key:this._key=sn(this.types)}constructor(t){super(),this._entities=[],t[0]instanceof Function?this.types=t.map((t=>(new t).type)):this.types=t}getEntities(t){return t&&this._entities.sort(t),this._entities}addEntity(t){!It(this._entities,t)&&this.matches(t)&&(this._entities.push(t),this.notifyAll(new Qs(t)))}removeEntity(t){Pt(t,this._entities)&&this.notifyAll(new Js(t))}clear(){this._entities.length=0;for(let t=this.observers.length-1;t>=0;t--)this.unregister(this.observers[t])}matches(t){let e=[];e=t instanceof Wi?t.types:t;let i=!0;for(const t of this.types)if(i=i&&e.indexOf(t)>-1,!i)return!1;return i}contain(t){return this.types.indexOf(t)>-1}}class rn{constructor(t){this._world=t,this._queries={}}_addQuery(t){this._queries[sn(t.types)]=t;for(const e of this._world.entityManager.entities)t.addEntity(e)}maybeRemoveQuery(t){0===t.observers.length&&(t.clear(),delete this._queries[sn(t.types)])}addEntity(t){for(const e in this._queries)this._queries[e]&&this._queries[e].addEntity(t)}removeComponent(t,e){for(const i in this._queries)this._queries[i].contain(e.type)&&this._queries[i].removeEntity(t)}removeEntity(t){for(const e in this._queries)this._queries[e].removeEntity(t)}createQuery(t){const e=this.getQuery(t);if(e)return e;const i=new nn(t);return this._addQuery(i),i}getQuery(t){const e=sn(t);return this._queries[e]?this._queries[e]:null}}class on{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find((e=>e instanceof t))}addSystem(t){if(!t.types||0===t.types.length)throw new Error("Attempted to add a System without any types");const e=this._world.queryManager.createQuery(t.types);this.systems.push(t),this.systems.sort(((t,e)=>t.priority-e.priority)),e.register(t),this.initialized&&t.initialize&&t.initialize(this._world.context)}removeSystem(t){Pt(t,this.systems);const e=this._world.queryManager.getQuery(t.types);e&&(e.unregister(t),this._world.queryManager.maybeRemoveQuery(e))}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world.context)}}updateSystems(t,e,i){const s=this.systems.filter((e=>e.systemType===t));for(const t of s)t.preupdate&&t.preupdate(e,i);for(const t of s){const s=this._world.queryManager.getQuery(t.types).getEntities(t.sort);if(e instanceof kn)for(const t of s)t._initialize(null==e?void 0:e.engine);t.update(s,i)}for(const t of s)t.postupdate&&t.postupdate(e,i)}clear(){for(let t=this.systems.length-1;t>=0;t--)this.removeSystem(this.systems[t])}}class an{constructor(t){this.context=t,this.queryManager=new rn(this),this.entityManager=new en(this),this.systemManager=new on(this)}update(t,e){t===Ys.Update&&this.entityManager.updateEntities(this.context,e),this.systemManager.updateSystems(t,this.context,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){t instanceof Wi&&this.entityManager.addEntity(t),t instanceof js&&this.systemManager.addSystem(t)}remove(t,e=!0){t instanceof Wi&&this.entityManager.removeEntity(t,e),t instanceof js&&this.systemManager.removeSystem(t)}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}class hn{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n,hn._ACC)),t.pos.add(e.vel.scale(n,hn._VEL),hn._POS).addEqual(i.scale(.5*n*n,hn._VEL_ACC)),e.angularVelocity+=e.torque*(1/e.inertia)*n;const r=t.rotation+e.angularVelocity*n;t.scale.add(e.scaleFactor.scale(n,this._SCALE_FACTOR),hn._SCALE);t.get().setTransform(hn._POS,r,hn._SCALE)}}hn._POS=new vt(0,0),hn._SCALE=new vt(1,1),hn._ACC=new vt(0,0),hn._VEL=new vt(0,0),hn._VEL_ACC=new vt(0,0),hn._SCALE_FACTOR=new vt(0,0);class ln extends js{constructor(){super(...arguments),this.types=["ex.transform","ex.motion"],this.systemType=Ys.Update,this.priority=-1}update(t,e){let i,s;for(let n=0;n<t.length;n++){i=t[n].get(ui),s=t[n].get(pi);const r=t[n].get(Li);if(null==r?void 0:r.sleeping)continue;const o=s.acc.clone();(null==r?void 0:r.collisionType)===Ze.Active&&(null==r?void 0:r.useGravity)&&o.addEqual(ri.gravity),null==r||r.captureOldTransform(),hn.integrate(i,s,o,e)}}}class cn{constructor(){this.directionMap=new Map,this.distanceMap=new Map}solve(t){this.preSolve(t),(t=t.filter((t=>!t.isCanceled()))).sort(((t,e)=>this.distanceMap.get(t.id)-this.distanceMap.get(e.id)));for(const e of t)this.solvePosition(e),this.solveVelocity(e);return this.postSolve(t),t}preSolve(t){const e=1e-4;for(const i of t){if(Math.abs(i.mtv.x)<e&&Math.abs(i.mtv.y)<e){i.cancel();continue}const t=bt.fromDirection(i.mtv),s=i.mtv.negate(),n=i.colliderA.worldPos.squareDistance(i.colliderB.worldPos);this.distanceMap.set(i.id,n),i.colliderA.events.emit("precollision",new R(i.colliderA,i.colliderB,t,s)),i.colliderB.events.emit("precollision",new R(i.colliderB,i.colliderA,bt.getOpposite(t),s.negate()))}}postSolve(t){var e,i;for(const s of t){if(s.isCanceled())continue;const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Li),o=null===(i=n.owner)||void 0===i?void 0:i.get(Li);if(r&&o&&(r.collisionType===Ze.Passive||o.collisionType===Ze.Passive))continue;const a=bt.fromDirection(s.mtv),h=s.mtv.negate();s.colliderA.events.emit("postcollision",new F(s.colliderA,s.colliderB,a,h)),s.colliderB.events.emit("postcollision",new F(s.colliderB,s.colliderA,bt.getOpposite(a),h.negate()))}}solvePosition(t){var e,i;const s=1e-4;if(!t.colliderA.bounds.overlaps(t.colliderB.bounds,s))return void t.cancel();if(Math.abs(t.mtv.x)<s&&Math.abs(t.mtv.y)<s)return void t.cancel();let n=t.mtv;const r=t.colliderA,o=t.colliderB,a=null===(e=r.owner)||void 0===e?void 0:e.get(Li),h=null===(i=o.owner)||void 0===i?void 0:i.get(Li);if(a&&h){if(a.collisionType===Ze.Passive||h.collisionType===Ze.Passive)return;a.collisionType===Ze.Active&&h.collisionType===Ze.Active&&(n=n.scale(.5)),a.collisionType===Ze.Active&&(a.globalPos.x-=n.x,a.globalPos.y-=n.y,r.update(a.transform.get())),h.collisionType===Ze.Active&&(h.globalPos.x+=n.x,h.globalPos.y+=n.y,o.update(h.transform.get()))}}solveVelocity(t){var e,i;if(t.isCanceled())return;const s=t.colliderA,n=t.colliderB,r=null===(e=s.owner)||void 0===e?void 0:e.get(Li),o=null===(i=n.owner)||void 0===i?void 0:i.get(Li);if(r&&o){if(r.collisionType===Ze.Passive||o.collisionType===Ze.Passive)return;const e=t.normal,i=e.negate();if(r.collisionType===Ze.Active&&r.vel.normalize().dot(i)<0){const t=e.scale(e.dot(r.vel.negate()));r.vel=r.vel.add(t)}if(o.collisionType===Ze.Active&&o.vel.normalize().dot(e)<0){const t=i.scale(i.dot(o.vel.negate()));o.vel=o.vel.add(t)}}}}class dn{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new vt(0,0),this.bToContact=new vt(0,0),this.originalVelocityAndRestitution=0,this.update()}update(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Li),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Li);if(i&&s){const t=this.contact.normal,e=this.contact.tangent;this.aToContact=this.point.sub(i.globalPos),this.bToContact=this.point.sub(s.globalPos);const n=this.aToContact.cross(t),r=this.bToContact.cross(t);this.normalMass=i.inverseMass+s.inverseMass+i.inverseInertia*n*n+s.inverseInertia*r*r;const o=this.aToContact.cross(e),a=this.bToContact.cross(e);this.tangentMass=i.inverseMass+s.inverseMass+i.inverseInertia*o*o+s.inverseInertia*a*a}return this}getRelativeVelocity(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Li),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Li);if(i&&s){const t=i.vel.add(vt.cross(i.angularVelocity,this.aToContact));return s.vel.add(vt.cross(s.angularVelocity,this.bToContact)).sub(t)}return vt.Zero}}class un{constructor(){this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return null!==(e=this.idToContactConstraint.get(t))&&void 0!==e?e:[]}solve(t){return this.preSolve(t),t=t.filter((t=>!t.isCanceled())),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}preSolve(t){var e,i,s;const n=1e-4;for(const e of t){if(Math.abs(e.mtv.x)<n&&Math.abs(e.mtv.y)<n){e.cancel();continue}const t=bt.fromDirection(e.mtv);e.colliderA.events.emit("precollision",new R(e.colliderA,e.colliderB,t,e.mtv)),e.colliderA.events.emit("beforecollisionresolve",new L(e.colliderA,e.colliderB,t,e.mtv,e)),e.colliderB.events.emit("precollision",new R(e.colliderB,e.colliderA,bt.getOpposite(t),e.mtv.negate())),e.colliderB.events.emit("beforecollisionresolve",new L(e.colliderB,e.colliderA,bt.getOpposite(t),e.mtv.negate(),e)),e.matchAwake()}const r=Array.from(this.idToContactConstraint.keys());for(const n of t){const t=r.indexOf(n.id);t>-1&&r.splice(t,1);const o=null!==(e=this.idToContactConstraint.get(n.id))&&void 0!==e?e:[];let a=0;const h=n.colliderA.owner.get(Li),l=n.colliderB.owner.get(Li);if(h&&l)for(const t of n.points){const e=n.normal,r=n.tangent,c=t.sub(h.globalPos),d=t.sub(l.globalPos),u=c.cross(e),p=d.cross(e),_=h.inverseMass+l.inverseMass+h.inverseInertia*u*u+l.inverseInertia*p*p,g=c.cross(r),m=d.cross(r),f=h.inverseMass+l.inverseMass+h.inverseInertia*g*g+l.inverseInertia*m*m;o[a]&&(null===(s=null===(i=o[a])||void 0===i?void 0:i.point)||void 0===s?void 0:s.squareDistance(t))<4?(o[a].point=t,o[a].local=n.localPoints[a]):o[a]=new dn(t,n.localPoints[a],n),o[a].aToContact=c,o[a].bToContact=d,o[a].normalMass=1/_,o[a].tangentMass=1/f;const v=h.bounciness>l.bounciness?h.bounciness:l.bounciness,x=n.normal.dot(o[a].getRelativeVelocity());o[a].originalVelocityAndRestitution=0,x<-.1&&(o[a].originalVelocityAndRestitution=-v*x),a++}this.idToContactConstraint.set(n.id,o)}for(const t of r)this.idToContactConstraint.delete(t);if(ri.warmStart)this.warmStart(t);else for(const e of t){const t=this.getContactConstraints(e.id);for(const e of t)e.normalImpulse=0,e.tangentImpulse=0}}postSolve(t){for(const e of t){const t=e.colliderA.owner.get(Li),i=e.colliderB.owner.get(Li);if(t&&i){if(t.collisionType===Ze.Passive||i.collisionType===Ze.Passive)continue;t.updateMotion(),i.updateMotion()}const s=bt.fromDirection(e.mtv);e.colliderA.events.emit("postcollision",new F(e.colliderA,e.colliderB,s,e.mtv)),e.colliderA.events.emit("aftercollisionresolve",new z(e.colliderA,e.colliderB,s,e.mtv,e)),e.colliderB.events.emit("postcollision",new F(e.colliderB,e.colliderA,bt.getOpposite(s),e.mtv.negate())),e.colliderB.events.emit("aftercollisionresolve",new z(e.colliderB,e.colliderA,bt.getOpposite(s),e.mtv.negate(),e))}this.lastFrameContacts.clear();for(const e of t)this.lastFrameContacts.set(e.id,e)}warmStart(t){var e,i,s;for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Li),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Li);if(t&&r){const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e)if(ri.warmStart){const e=n.normal.scale(i.normalImpulse),s=n.tangent.scale(i.tangentImpulse),o=e.add(s);t.applyImpulse(i.point,o.negate()),r.applyImpulse(i.point,o)}else i.normalImpulse=0,i.tangentImpulse=0}}}solvePosition(t){var e,i,s;for(let n=0;n<ri.positionIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Li),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Li);if(t&&r){if(t.collisionType===Ze.Passive||r.collisionType===Ze.Passive)continue;const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e){const e=n.normal,s=Di.FindContactSeparation(n,i.local),o=-5,a=dt(ri.steeringFactor*(s+ri.slop),o,0),h=e.scale(-a*i.normalMass);if(t.collisionType===Ze.Active){const e=h.negate().scale(t.inverseMass);t.limitDegreeOfFreedom.includes(Mi.X)&&(e.x=0),t.limitDegreeOfFreedom.includes(Mi.Y)&&(e.y=0),t.globalPos=t.globalPos.add(e),t.limitDegreeOfFreedom.includes(Mi.Rotation)||(t.rotation-=i.aToContact.cross(h)*t.inverseInertia)}if(r.collisionType===Ze.Active){const t=h.scale(r.inverseMass);r.limitDegreeOfFreedom.includes(Mi.X)&&(t.x=0),r.limitDegreeOfFreedom.includes(Mi.Y)&&(t.y=0),r.globalPos=r.globalPos.add(t),r.limitDegreeOfFreedom.includes(Mi.Rotation)||(r.rotation+=i.bToContact.cross(h)*r.inverseInertia)}}}}}solveVelocity(t){var e,i,s;for(let n=0;n<ri.velocityIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Li),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Li);if(t&&r){if(t.collisionType===Ze.Passive||r.collisionType===Ze.Passive)continue;const e=Math.min(t.friction,r.friction),i=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const s of i){let i=-s.getRelativeVelocity().dot(n.tangent)*s.tangentMass;const o=e*s.normalImpulse,a=dt(s.tangentImpulse+i,-o,o);i=a-s.tangentImpulse,s.tangentImpulse=a;const h=n.tangent.scale(i);t.applyImpulse(s.point,h.negate()),r.applyImpulse(s.point,h)}for(const e of i){const i=e.getRelativeVelocity().dot(n.normal);let s=-e.normalMass*(i-e.originalVelocityAndRestitution);const o=Math.max(e.normalImpulse+s,0);s=o-e.normalImpulse,e.normalImpulse=o;const a=n.normal.scale(s);t.applyImpulse(e.point,a.negate()),r.applyImpulse(e.point,a)}}}}}class pn extends js{constructor(t){super(),this.types=["ex.transform","ex.motion","ex.collider"],this.systemType=Ys.Update,this.priority=-1,this._realisticSolver=new un,this._arcadeSolver=new cn,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._processor=t.collisionProcessor,this._trackCollider=t=>this._processor.track(t),this._untrackCollider=t=>this._processor.untrack(t)}notify(t){if($s(t)){const e=t.data.get(ki);e.$colliderAdded.subscribe(this._trackCollider),e.$colliderRemoved.subscribe(this._untrackCollider);const i=e.get();i&&this._processor.track(i)}else{const e=t.data.get(ki),i=e.get();e&&i&&this._processor.untrack(i)}}initialize(t){this._engine=t.engine}update(t,e){var i,s,n,r;if(!ri.enabled)return;let o=[];for(const e of t){const t=e.get(ki),s=null==t?void 0:t.get();if(t&&(null===(i=t.owner)||void 0===i?void 0:i.active)&&s)if(t.update(),s instanceof Ci){const t=s.getColliders();o=o.concat(t)}else o.push(s)}this._processor.update(o);const a=this._processor.broadphase(o,e);this._currentFrameContacts.clear();let h=this._processor.narrowphase(a,null===(r=null===(n=null===(s=this._engine)||void 0===s?void 0:s.debug)||void 0===n?void 0:n.stats)||void 0===r?void 0:r.currFrame);h=this.getSolver().solve(h);for(const t of h){const e=t.id.indexOf("|");if(e>0){const i=t.id.substring(e+1);this._currentFrameContacts.set(i,t)}else this._currentFrameContacts.set(t.id,t)}this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts)}getSolver(){return ri.collisionResolutionStrategy===ti.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionstart",new U(t,i,e)),t.events.emit("contactstart",new k(t,i,e)),i.events.emit("collisionstart",new U(i,t,e)),i.events.emit("contactstart",new k(i,t,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionend",new O(t,i)),t.events.emit("contactend",new M(t,i)),i.events.emit("collisionend",new O(i,t)),i.events.emit("contactend",new M(i,t))}}}var _n,gn;!function(t){t.Forward="forward",t.Backward="backward"}(_n||(_n={})),function(t){t.End="end",t.Loop="loop",t.PingPong="pingpong",t.Freeze="freeze"}(gn||(gn={}));const mn={Frame:"frame",Loop:"loop",End:"end"};class fn extends Ht{constructor(t){var e,i;super(t),this.events=new d,this.frames=[],this.strategy=gn.Loop,this.frameDuration=100,this.timeScale=1,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._pingPongDirection=1,this._done=!1,this._playing=!0,this._reversed=!1,this.frames=t.frames,this.strategy=null!==(e=t.strategy)&&void 0!==e?e:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:null!==(i=t.frameDuration)&&void 0!==i?i:this.frameDuration,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){return new fn({frames:this.frames.map((t=>({...t}))),frameDuration:this.frameDuration,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}get width(){const t=this.currentFrame;return t?Math.abs(t.graphic.width*this.scale.x):0}get height(){const t=this.currentFrame;return t?Math.abs(t.graphic.height*this.scale.y):0}static fromSpriteSheet(t,e,i,s=gn.Loop){const n=t.sprites.length-1,r=e.filter((t=>t<0||t>n));return r.length&&fn._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${r.join(",")} no frame will be shown`),new fn({frames:t.sprites.filter(((t,i)=>e.indexOf(i)>-1)).map((t=>({graphic:t,duration:i}))),strategy:s})}static fromSpriteSheetCoordinates(t){const{spriteSheet:e,frameCoordinates:i,durationPerFrameMs:s,strategy:n,reverse:r}=t,o=null!=s?s:100,a=[];for(const t of i){const{x:i,y:s,duration:n}=t,r=e.getSprite(i,s);r?a.push({graphic:r,duration:null!=n?n:o}):fn._LOGGER.warn(`Skipping frame! SpriteSheet does not have coordinate (${i}, ${s}), please check your SpriteSheet to confirm that sprite exists`)}return new fn({frames:a,strategy:n,reverse:r})}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get isPlaying(){return this._playing}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!(!this._reversed||1!==this._pingPongDirection)?_n.Backward:_n.Forward}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._done=!1,this._firstTick=!0,this._currentFrame=0}get canFinish(){switch(this.strategy){case gn.End:case gn.Freeze:return!0;default:return!1}}get done(){return this._done}goToFrame(t){this._currentFrame=t,this._timeLeftInFrame=this.frameDuration;const e=this.frames[this._currentFrame];e&&!this._done&&(this._timeLeftInFrame=(null==e?void 0:e.duration)||this.frameDuration,this.events.emit("frame",{...e,frameIndex:this.currentFrameIndex}))}_nextFrame(){const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case gn.Loop:e=(t+1)%this.frames.length,0===e&&this.events.emit("loop",this);break;case gn.End:e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break;case gn.Freeze:e=dt(t+1,0,this.frames.length-1),e>=this.frames.length-1&&(this._done=!0,this.events.emit("end",this));break;case gn.PingPong:t+this._pingPongDirection>=this.frames.length&&(this._pingPongDirection=-1,this.events.emit("loop",this)),t+this._pingPongDirection<0&&(this._pingPongDirection=1,this.events.emit("loop",this)),e=t+this._pingPongDirection%this.frames.length}return e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",{...this.currentFrame,frameIndex:this.currentFrameIndex})),this._timeLeftInFrame-=t*this.timeScale,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame())))}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic.draw(t,e,i)}}fn._LOGGER=J.getInstance();class vn extends Ht{constructor(t){super(t),this.members=[],this.members=t.members,this._updateDimensions()}clone(){return new vn({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){let t=new At;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return this.width=t.width,this.height=t.height,t}get localBounds(){let t=new At;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return t}_isAnimationOrGroup(t){return t instanceof fn||t instanceof vn}tick(t,e){for(const i of this.members){const s=i.graphic;this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){const e=t.graphic;this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){for(const s of this.members)t.save(),t.translate(e,i),s.graphic.draw(t,s.pos.x,s.pos.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}function xn(t){return class extends t{assign(t){for(const e in t)"function"!=typeof this[e]&&(this[e]=t[e])}constructor(...t){super(...t);1!==t.filter((function(t){return void 0!==t})).length||!t[0]||"object"!=typeof t[0]||t[0]instanceof Array||this.assign(t[0])}}}var yn,wn;!function(t){t[t.Circle=0]="Circle",t[t.Rectangle=1]="Rectangle"}(yn||(yn={}));class bn extends Wi{constructor(t,e,i,s,n,r,o,a,h,l){super(),this.position=new vt(0,0),this.velocity=new vt(0,0),this.acceleration=new vt(0,0),this.particleRotationalVelocity=0,this.currentRotation=0,this.focus=null,this.focusAccel=0,this.opacity=1,this.beginColor=yt.White,this.endColor=yt.White,this.life=300,this.fadeFlag=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=yt.White,this.emitter=null,this.particleSize=5,this.particleSprite=null,this.sizeRate=0,this.elapsedMultiplier=0,this.visible=!0,this.isOffscreen=!1;let c=t;if(c&&!(t instanceof An)){const d=t;c=d.emitter,e=d.life,i=d.opacity,n=d.endColor,s=d.beginColor,r=d.position,o=d.velocity,a=d.acceleration,h=d.startSize,l=d.endSize}if(this.emitter=c,this.life=e||this.life,this.opacity=i||this.opacity,this.endColor=n||this.endColor.clone(),this.beginColor=s||this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.emitter.particleTransform===wn.Global){const t=this.emitter.transform.globalPos;this.position=(r||this.position).add(t),this.velocity=(o||this.velocity).rotate(this.emitter.transform.globalRotation)}else this.velocity=o||this.velocity,this.position=r||this.position;this.acceleration=a||this.acceleration,this._rRate=(this.endColor.r-this.beginColor.r)/this.life,this._gRate=(this.endColor.g-this.beginColor.g)/this.life,this._bRate=(this.endColor.b-this.beginColor.b)/this.life,this._aRate=this.opacity/this.life,this.startSize=h||0,this.endSize=l||0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.particleSize=this.startSize),this.addComponent(this.transform=new ui),this.addComponent(this.graphics=new Xi),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=xt(1,1),this.particleSprite?(this.graphics.opacity=this.opacity,this.graphics.use(this.particleSprite)):(this.graphics.localBounds=At.fromDimension(this.particleSize,this.particleSize,vt.Half),this.graphics.onPostDraw=t=>{t.save(),this.graphics.opacity=this.opacity;const e=this._currentColor.clone();e.a=1,t.debug.drawPoint(xt(0,0),{color:e,size:this.particleSize}),t.restore()})}kill(){this.emitter.removeParticle(this)}update(t,e){if(this.life=this.life-e,this.elapsedMultiplier=this.elapsedMultiplier+e,this.life<0&&this.kill(),this.fadeFlag&&(this.opacity=dt(this._aRate*this.life,1e-4,1)),this.startSize>0&&this.endSize>0&&(this.particleSize=dt(this.sizeRate*e+this.particleSize,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=dt(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=dt(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=dt(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=dt(this.opacity,1e-4,1),this.focus){const t=this.focus.sub(this.position).normalize().scale(this.focusAccel).scale(e/1e3);this.velocity=this.velocity.add(t)}else this.velocity=this.velocity.add(this.acceleration.scale(e/1e3));this.position=this.position.add(this.velocity.scale(e/1e3)),this.particleRotationalVelocity&&(this.currentRotation=(this.currentRotation+this.particleRotationalVelocity*e/1e3)%(2*Math.PI)),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=xt(1,1),this.graphics.opacity=this.opacity}}class Cn extends(xn(bn)){constructor(t,e,i,s,n,r,o,a,h,l){super(t,e,i,s,n,r,o,a,h,l)}}!function(t){t.Global="global",t.Local="local"}(wn||(wn={}));class An extends Es{get opacity(){return super.graphics.opacity}set opacity(t){super.graphics.opacity=t}get particleSprite(){return this._sprite}set particleSprite(t){t&&(this._sprite=t)}constructor(t){var e,i;super({width:null!==(e=t.width)&&void 0!==e?e:0,height:null!==(i=t.height)&&void 0!==i?i:0}),this._particlesToEmit=0,this.numParticles=0,this.isEmitting=!0,this.particles=[],this.deadParticles=[],this.minVel=0,this.maxVel=0,this.acceleration=new vt(0,0),this.minAngle=0,this.maxAngle=0,this.emitRate=1,this.particleLife=2e3,this.fadeFlag=!1,this.focus=null,this.focusAccel=null,this.startSize=null,this.endSize=null,this.minSize=5,this.maxSize=5,this.beginColor=yt.White,this.endColor=yt.White,this._sprite=null,this.emitterType=yn.Rectangle,this.radius=0,this.particleRotationalVelocity=0,this.randomRotation=!1,this.particleTransform=wn.Global;const{x:s,y:n,pos:r,isEmitting:o,minVel:a,maxVel:h,acceleration:l,minAngle:c,maxAngle:d,emitRate:u,particleLife:p,opacity:_,fadeFlag:g,focus:m,focusAccel:f,startSize:v,endSize:x,minSize:y,maxSize:w,beginColor:b,endColor:C,particleSprite:A,emitterType:T,radius:S,particleRotationalVelocity:E,particleTransform:P,randomRotation:I,random:D}={...t};this.pos=null!=r?r:xt(null!=s?s:0,null!=n?n:0),this.isEmitting=null!=o?o:this.isEmitting,this.minVel=null!=a?a:this.minVel,this.maxVel=null!=h?h:this.maxVel,this.acceleration=null!=l?l:this.acceleration,this.minAngle=null!=c?c:this.minAngle,this.maxAngle=null!=d?d:this.maxAngle,this.emitRate=null!=u?u:this.emitRate,this.particleLife=null!=p?p:this.particleLife,this.opacity=null!=_?_:this.opacity,this.fadeFlag=null!=g?g:this.fadeFlag,this.focus=null!=m?m:this.focus,this.focusAccel=null!=f?f:this.focusAccel,this.startSize=null!=v?v:this.startSize,this.endSize=null!=x?x:this.endSize,this.minSize=null!=y?y:this.minSize,this.maxSize=null!=w?w:this.maxSize,this.beginColor=null!=b?b:this.beginColor,this.endColor=null!=C?C:this.endColor,this.particleSprite=null!=A?A:this.particleSprite,this.emitterType=null!=T?T:this.emitterType,this.radius=null!=S?S:this.radius,this.particleRotationalVelocity=null!=E?E:this.particleRotationalVelocity,this.randomRotation=null!=I?I:this.randomRotation,this.particleTransform=null!=P?P:this.particleTransform,this.body.collisionType=Ze.PreventCollision,this.random=null!=D?D:new at}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;for(let i=0;i<t;i++){const t=this._createParticle();this.particles.push(t),(null===(e=null==this?void 0:this.scene)||void 0===e?void 0:e.world)&&(this.particleTransform===wn.Global?this.scene.world.add(t):this.addChild(t))}}clearParticles(){this.particles.length=0}_createParticle(){let t=0,e=0;const i=mt(this.minAngle,this.maxAngle,this.random),s=mt(this.minVel,this.maxVel,this.random),n=this.startSize||mt(this.minSize,this.maxSize,this.random),r=s*Math.cos(i),o=s*Math.sin(i);if(this.emitterType===yn.Rectangle)t=mt(0,this.width,this.random),e=mt(0,this.height,this.random);else if(this.emitterType===yn.Circle){const s=mt(0,this.radius,this.random);t=s*Math.cos(i),e=s*Math.sin(i)}const a=new Cn(this,this.particleLife,this.opacity,this.beginColor,this.endColor,new vt(t,e),new vt(r,o),this.acceleration,this.startSize,this.endSize);return a.fadeFlag=this.fadeFlag,a.particleSize=n,this.particleSprite&&(a.particleSprite=this.particleSprite,a.graphics.opacity=this.opacity,a.graphics.use(this._sprite)),a.particleRotationalVelocity=this.particleRotationalVelocity,this.randomRotation&&(a.currentRotation=mt(0,2*Math.PI,this.random)),this.focus&&(a.focus=this.focus.add(new vt(this.pos.x,this.pos.y)),a.focusAccel=this.focusAccel),a}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let t=0;t<this.deadParticles.length;t++)Pt(this.deadParticles[t],this.particles),(null===(i=null==this?void 0:this.scene)||void 0===i?void 0:i.world)&&this.scene.world.remove(this.deadParticles[t],!1);this.deadParticles.length=0}}class Tn extends js{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=Ys.Draw,this.priority=0,this._token=0,this._sortedTransforms=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0}}get sortedTransforms(){return this._sortedTransforms}initialize(t){this._camera=t.camera,this._engine=t.engine}preupdate(){this._graphicsContext=this._engine.graphicsContext,this._zHasChanged&&(this._sortedTransforms.sort(((t,e)=>t.z-e.z)),this._zHasChanged=!1)}notify(t){if($s(t)){const e=t.data.get(ui);this._sortedTransforms.push(e),e.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}else{const e=t.data.get(ui);e.zIndexChanged$.unsubscribe(this._zIndexUpdate);const i=this._sortedTransforms.indexOf(e);i>-1&&this._sortedTransforms.splice(i,1)}}update(t,e){let i;this._token++,As.checkAndClearCache(),this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext);for(const t of this._sortedTransforms){const s=t.owner;if(s.hasTag("ex.offscreen"))continue;if(i=s.get(Xi),!i.visible)continue;t.coordPlane===si.Screen&&this._graphicsContext.restore(),this._graphicsContext.save(),t.coordPlane===si.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),i.update(e,this._token);const n=s.get(Bs);if(n){const t=vt.One.sub(n.parallaxFactor),e=this._camera.pos.scale(t);this._graphicsContext.translate(e.x,e.y)}this._applyTransform(s),i.material&&(this._graphicsContext.material=i.material),i.onPreDraw&&i.onPreDraw(this._graphicsContext,e);const r=s instanceof Cn?s.opacity:1;this._graphicsContext.opacity*=i.opacity*r,this._drawGraphicsComponent(i),i.onPostDraw&&i.onPostDraw(this._graphicsContext,e),this._graphicsContext.restore(),t.coordPlane===si.Screen&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}this._graphicsContext.restore()}_drawGraphicsComponent(t){var e,i;if(t.visible){const s=t.flipHorizontal,n=t.flipVertical;for(const r of t.layers.get())for(const{graphic:o,options:a}of r.graphics){let h=t.anchor,l=t.offset;(null==a?void 0:a.anchor)&&(h=a.anchor),(null==a?void 0:a.offset)&&(l=a.offset);const c=-o.width*h.x+l.x,d=-o.height*h.y+l.y,u=o.flipHorizontal,p=o.flipVertical;if((s||n)&&(o.flipHorizontal=s?!u:u,o.flipVertical=n?!p:p),null==o||o.draw(this._graphicsContext,c+r.offset.x,d+r.offset.y),(s||n)&&(o.flipHorizontal=u,o.flipVertical=p),(null===(e=this._engine)||void 0===e?void 0:e.isDebug)&&this._engine.debug.graphics.showBounds){const t=xt(c+r.offset.x,d+r.offset.y);if(o instanceof vn)for(const e of o.members)null===(i=e.graphic)||void 0===i||i.localBounds.translate(t.add(e.pos)).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor);else null==o||o.localBounds.translate(t).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}}}}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(ui),i=null==t?void 0:t.get(Li);let s=e.pos,n=e.scale,r=e.rotation;if(i&&this._engine.fixedUpdateFps&&i.__oldTransformCaptured&&i.enableFixedUpdateInterpolate){const t=this._engine.currentFrameLagMs/(1e3/this._engine.fixedUpdateFps);s=e.pos.scale(t).add(i.oldPos.scale(1-t)),n=e.scale.scale(t).add(i.oldScale.scale(1-t));const o=(1-t)*Math.cos(i.oldRotation)+t*Math.cos(e.rotation),a=(1-t)*Math.sin(i.oldRotation)+t*Math.sin(e.rotation);r=Math.atan2(a,o)}e&&(this._graphicsContext.z=e.z,this._graphicsContext.translate(s.x,s.y),this._graphicsContext.scale(n.x,n.y),this._graphicsContext.rotate(r))}}}class Sn extends js{constructor(){super(...arguments),this.types=["ex.transform"],this.systemType=Ys.Draw,this.priority=999}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine,this._collisionSystem=t.world.systemManager.get(pn)}update(t,e){var i;if(!this._engine.isDebug)return;const s=this._engine.debug.filter;let n,r;const o=this._engine.debug.entity;let a;const h=this._engine.debug.transform;let l;const c=this._engine.debug.motion;let d;const u=this._engine.debug.collider,p=this._engine.debug.physics;let _;const g=this._engine.debug.graphics;let m,f;const v=this._engine.debug.body,x=this._engine.debug.camera;for(const e of t){if(e.hasTag("offscreen"))continue;if(e instanceof Cn)continue;if(s.useFilter){if(!(0===s.ids.length||s.ids.includes(e.id)))continue;if(!(""===s.nameQuery||e.name.includes(s.nameQuery)))continue}let t=vt.Zero;const p=xt(0,16);if(n=e.id,r=e.name,a=e.get(ui),this._pushCameraTransform(a),this._graphicsContext.save(),this._applyTransform(e),a&&((h.showAll||h.showPosition)&&this._graphicsContext.debug.drawPoint(vt.Zero,{size:4,color:h.positionColor}),(h.showAll||h.showPositionLabel)&&(this._graphicsContext.debug.drawText(`pos${a.pos.toString(2)}`,t),t=t.add(p)),(h.showAll||h.showZIndex)&&(this._graphicsContext.debug.drawText(`z(${a.z.toFixed(1)})`,t),t=t.add(p)),(o.showAll||o.showId)&&(this._graphicsContext.debug.drawText(`id(${n}) ${e.parent?"child of id("+(null===(i=e.parent)||void 0===i?void 0:i.id)+")":""}`,t),t=t.add(p)),(o.showAll||o.showName)&&(this._graphicsContext.debug.drawText(`name(${r})`,t),t=t.add(p)),(h.showAll||h.showRotation)&&(this._graphicsContext.drawLine(vt.Zero,vt.fromAngle(a.rotation).scale(50).add(vt.Zero),h.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${pt(a.rotation).toFixed(2)})`,t),t=t.add(p)),(h.showAll||h.showScale)&&this._graphicsContext.drawLine(vt.Zero,a.scale.add(vt.Zero),h.scaleColor,2)),_=e.get(Xi),_&&(g.showAll||g.showBounds)){_.localBounds.draw(this._graphicsContext,g.boundsColor)}if(m=e.get(Rs),m&&(m.useTransform||this._graphicsContext.restore(),m.draw(this._graphicsContext,this._engine.debug),m.useTransform||(this._graphicsContext.save(),this._applyTransform(e))),f=e.get(Li),f&&((v.showAll||v.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${f.group.name})`,t),t=t.add(p)),(v.showAll||v.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${f.collisionType})`,t),t=t.add(p)),(v.showAll||v.showMass)&&(this._graphicsContext.debug.drawText(`mass(${f.mass})`,t),t=t.add(p)),(v.showAll||v.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${f.sleepMotion})`,t),t=t.add(p)),(v.showAll||v.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${f.canSleep?f.sleeping:"cant sleep"})`,t),t=t.add(p))),this._graphicsContext.restore(),l=e.get(pi),l&&((c.showAll||c.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${l.vel.toString(2)}`,t.add(a.globalPos)),this._graphicsContext.drawLine(a.globalPos,a.globalPos.add(l.vel),c.velocityColor,2),t=t.add(p)),(c.showAll||c.showAcceleration)&&this._graphicsContext.drawLine(a.globalPos,a.globalPos.add(l.acc),c.accelerationColor,2)),d=e.get(ki),d){const t=d.get();if((u.showAll||u.showGeometry)&&t&&t.debug(this._graphicsContext,u.geometryColor),u.showAll||u.showBounds)if(t instanceof Ci){const e=t.getColliders();for(const t of e){const e=t.bounds,i=xt(e.left,e.top);this._graphicsContext.debug.drawRect(i.x,i.y,e.width,e.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${t.owner.id})`,i)}d.bounds.draw(this._graphicsContext,u.boundsColor)}else if(t){const t=d.bounds,e=xt(t.left,t.top);this._graphicsContext.debug.drawRect(e.x,e.y,t.width,t.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${d.owner.id})`,e)}}this._popCameraTransform(a)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(p.showAll||p.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),p.showAll||p.showCollisionContacts||p.showCollisionNormals)for(const[t,e]of this._engine.debug.stats.currFrame.physics.contacts){if(p.showAll||p.showCollisionContacts)for(const t of e.points)this._graphicsContext.debug.drawPoint(t,{size:5,color:p.collisionContactColor});if(p.showAll||p.showCollisionNormals)for(const t of e.points)this._graphicsContext.debug.drawLine(t,e.normal.scale(30).add(t),{color:p.collisionNormalColor})}this._graphicsContext.restore(),x&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(x.showAll||x.showFocus)&&this._graphicsContext.drawCircle(this._camera.pos,4,x.focusColor),(x.showAll||x.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore()),this._graphicsContext.flush()}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(ui);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===si.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===si.World&&this._graphicsContext.restore()}}class En extends js{constructor(){super(...arguments),this.types=["ex.transform","ex.pointer"],this.systemType=Ys.Update,this.priority=-1,this.overrideUseColliderShape=!1,this.overrideUseGraphicsBounds=!1,this.lastFrameEntityToPointers=new Map,this.currentFrameEntityToPointers=new Map,this._sortedTransforms=[],this._sortedEntities=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0}}initialize(t){this._engine=t.engine}preupdate(){this._receiver=this._engine.input.pointers,this._zHasChanged&&(this._sortedTransforms.sort(((t,e)=>e.z-t.z)),this._sortedEntities=this._sortedTransforms.map((t=>t.owner)),this._zHasChanged=!1)}notify(t){if($s(t)){const e=t.data.get(ui);this._sortedTransforms.push(e),this._sortedEntities.push(e.owner),e.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}else{const e=t.data.get(ui);e.zIndexChanged$.unsubscribe(this._zIndexUpdate);const i=this._sortedTransforms.indexOf(e);i>-1&&(this._sortedTransforms.splice(i,1),this._sortedEntities.splice(i,1))}}entityCurrentlyUnderPointer(t,e){return this.currentFrameEntityToPointers.has(t.id)&&this.currentFrameEntityToPointers.get(t.id).includes(e)}entityWasUnderPointer(t,e){return this.lastFrameEntityToPointers.has(t.id)&&this.lastFrameEntityToPointers.get(t.id).includes(e)}entered(t,e){return this.entityCurrentlyUnderPointer(t,e)&&!this.lastFrameEntityToPointers.has(t.id)}left(t,e){return!this.currentFrameEntityToPointers.has(t.id)&&this.entityWasUnderPointer(t,e)}addPointerToEntity(t,e){if(!this.currentFrameEntityToPointers.has(t.id))return void this.currentFrameEntityToPointers.set(t.id,[e]);const i=this.currentFrameEntityToPointers.get(t.id);this.currentFrameEntityToPointers.set(t.id,i.concat(e))}update(t){this._processPointerToEntity(this._sortedEntities),this._dispatchEvents(this._sortedEntities),this._receiver.update(),this.lastFrameEntityToPointers.clear(),this.lastFrameEntityToPointers=new Map(this.currentFrameEntityToPointers),this.currentFrameEntityToPointers.clear(),this._receiver.clear()}_processPointerToEntity(t){var e;let i,s,n,r;for(const o of t){if(i=o.get(ui),r=null!==(e=o.get(Yi))&&void 0!==e?e:new Yi,s=o.get(ki),s&&(r.useColliderShape||this.overrideUseColliderShape)){s.update();const t=s.get();if(t)for(const[e,s]of this._receiver.currentFramePointerCoords.entries())t.contains(i.coordPlane===si.World?s.worldPos:s.screenPos)&&this.addPointerToEntity(o,e)}if(n=o.get(Xi),n&&(r.useGraphicsBounds||this.overrideUseGraphicsBounds)){const t=n.localBounds.transform(i.get().matrix);for(const[e,s]of this._receiver.currentFramePointerCoords.entries())t.contains(i.coordPlane===si.World?s.worldPos:s.screenPos)&&this.addPointerToEntity(o,e)}}}_processDownAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameDown)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerdown",i),this._receiver.isDragStart(i.pointerId)&&t.events.emit("pointerdragstart",i)),e.set(i.pointerId,i);return e}_processUpAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameUp)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerup",i),this._receiver.isDragEnd(i.pointerId)&&t.events.emit("pointerdragend",i)),e.set(i.pointerId,i);return e}_processMoveAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameMove)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointermove",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragmove",i)),e.set(i.pointerId,i);return e}_processEnterLeaveAndEmit(t,e){for(const i of e){if(i.active&&t.active&&this.entered(t,i.pointerId)){t.events.emit("pointerenter",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragenter",i);break}if(i.active&&t.active&&(this.left(t,i.pointerId)||this.entityCurrentlyUnderPointer(t,i.pointerId)&&"up"===i.type)){t.events.emit("pointerleave",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragleave",i);break}}}_processCancelAndEmit(t){for(const e of this._receiver.currentFrameCancel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,e.pointerId)&&t.events.emit("pointercancel",e)}_processWheelAndEmit(t){for(const e of this._receiver.currentFrameWheel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,0)&&t.events.emit("pointerwheel",e)}_dispatchEvents(t){const e=new Set(this.lastFrameEntityToPointers.keys()),i=new Set(this.currentFrameEntityToPointers.keys()),s=t.filter((t=>e.has(t.id)||i.has(t.id)));let n,r,o;for(const t of s){o=this._processDownAndEmit(t),r=this._processUpAndEmit(t),n=this._processMoveAndEmit(t);const e=[...n.values(),...o.values(),...r.values()];this._processEnterLeaveAndEmit(t,e),this._processCancelAndEmit(t),this._processWheelAndEmit(t)}}}class Pn extends js{constructor(){super(...arguments),this.types=["ex.actions"],this.systemType=Ys.Update,this.priority=-1,this._actions=[]}notify(t){if($s(t)){const e=t.data.get(bs);this._actions.push(e)}else{const e=t.data.get(bs),i=this._actions.indexOf(e);i>-1&&this._actions.splice(i,1)}}update(t,e){for(const t of this._actions)t.update(e)}}class In extends li{constructor(t){super(),this.type="ex.isometricentity",this.elevation=0,this.map=t}}class Dn extends js{constructor(){super(...arguments),this.types=["ex.transform","ex.isometricentity"],this.systemType=Ys.Update,this.priority=99}update(t,e){let i,s;for(const e of t){i=e.get(ui),s=e.get(In);const t=Math.max(s.map.columns*s.map.tileWidth,s.map.rows*s.map.tileHeight)*s.elevation+i.pos.y;i.z=t}}}class Bn extends js{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=Ys.Draw,this.priority=-1}initialize(t){this._camera=t.camera,this._screen=t.engine.screen}update(t){let e,i,s;this._worldBounds=this._screen.getWorldBounds();for(const n of t){let t;if(i=n.get(Xi),e=n.get(ui),s=n.get(Bs),s){const e=vt.One.sub(s.parallaxFactor);t=this._camera.pos.scale(e)}const r=this._isOffscreen(e,i,t);r&&!n.hasTag("ex.offscreen")&&(n.events.emit("exitviewport",new G(n)),n.addTag("ex.offscreen")),!r&&n.hasTag("ex.offscreen")&&(n.events.emit("enterviewport",new V(n)),n.removeTag("ex.offscreen"))}}_isOffscreen(t,e,i){if(t.coordPlane===si.World){let s=e.localBounds;i&&(s=s.translate(i));const n=s.transform(t.get().matrix);return!this._worldBounds.overlaps(n)}return!1}}class Rn{constructor(){this.collisionProcessor=new wi}rayCast(t,e){return this.collisionProcessor.rayCast(t,e)}}const Fn={Initialize:"initialize",Activate:"activate",Deactivate:"deactivate",PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw"};class kn{get actors(){return this.world.entityManager.entities.filter((t=>t instanceof Es))}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter((t=>t instanceof Zs))}get tileMaps(){return this.world.entityManager.entities.filter((t=>t instanceof Ms))}get timers(){return this._timers}constructor(){this._logger=J.getInstance(),this.events=new d,this.camera=new qs,this.world=new an(this),this.physics=new Rn,this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(new Pn),this.world.add(new ln),this.world.add(new pn(this.physics)),this.world.add(new En),this.world.add(new Dn),this.world.add(new Bn),this.world.add(new Tn),this.world.add(new Sn)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}onInitialize(t){}onActivate(t){}onDeactivate(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.engine=t,this.camera._initialize(t),this.world.systemManager.initialize(),this.onInitialize.call(this,t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0)}_activate(t){this._logger.debug("Scene.onActivate",this),this.onActivate(t)}_deactivate(t){this._logger.debug("Scene.onDeactivate",this),this.onDeactivate(t)}_preupdate(t,e){this.emit("preupdate",new b(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new C(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new v(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new x(t,e,this)),this.onPostDraw(t,e)}update(t,e){let i,s;for(this._preupdate(t,e),i=0,s=this._cancelQueue.length;i<s;i++)this.removeTimer(this._cancelQueue[i]);this._cancelQueue.length=0;for(const t of this._timers)t.update(e);this.world.update(Ys.Update,e),this.camera&&this.camera.update(t,e),this._collectActorStats(t),this._postupdate(t,e)}draw(t,e){var i;this._predraw(t,e),this.world.update(Ys.Draw,e),(null===(i=this.engine)||void 0===i?void 0:i.isDebug)&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new y(t,this)),this.emit("postdebugdraw",new w(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){this.emit("entityadded",{target:t}),this.world.add(t),t.scene=this,t instanceof Ds&&(It(this._timers,t)||this.addTimer(t))}transfer(t){let e;t instanceof Wi&&t.scene&&t.scene!==this&&(e=t.scene,t.scene.world.remove(t,!1)),t instanceof Ds&&t.scene&&(e=t.scene,t.scene.removeTimer(t)),null==e||e.emit("entityremoved",{target:t}),this.add(t)}remove(t){t instanceof Wi&&(this.emit("entityremoved",{target:t}),t.active&&t.kill(),this.world.remove(t)),t instanceof Ds&&this.removeTimer(t)}clear(t=!0){for(let e=this.entities.length-1;e>=0;e--)this.world.remove(this.entities[e],t);for(let t=this.timers.length-1;t>=0;t--)this.removeTimer(this.timers[t])}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return-1!==e&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return!!this.engine&&this.engine.currentScene===this}_collectActorStats(t){const e=this.actors.filter((t=>t instanceof Is));for(const i of e)t.stats.currFrame.actors.ui++;for(const e of this.actors){t.stats.currFrame.actors.alive++;for(const i of e.children)Ps(i)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}var Mn;!function(t){t.Protanope="Protanope",t.Deuteranope="Deuteranope",t.Tritanope="Tritanope"}(Mn||(Mn={}));class Ln{constructor(t,e){this._shader=new te({gl:t,vertexSource:"#version 300 es\n in vec2 a_position;\n in vec2 a_texcoord;\n out vec2 v_texcoord;\n\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n // Pass the texcoord to the fragment shader.\n v_texcoord = a_texcoord;\n }",fragmentSource:e}),this._shader.compile(),this._buffer=new ee({gl:t,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new ie({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}getShader(){return this._shader}getLayout(){return this._layout}}class zn{constructor(t,e=!1){this._colorBlindnessMode=t,this._simulate=!1,this._simulate=e}initialize(t){this._shader=new Ln(t,"#version 300 es\nprecision mediump float;\n// our texture\nuniform sampler2D u_image;\n// the texCoords passed in from the vertex shader.\nin vec2 v_texcoord;\n\n// color blind type\nuniform int u_type;\n\n// simulation?\nuniform bool u_simulate;\n\nout vec4 fragColor;\n\nvoid main() {\n vec4 o = texture(u_image, v_texcoord);\n // RGB to LMS matrix conversion\n float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);\n float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);\n float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);\n // Simulate color blindness\n float l;\n float m;\n float s;\n //MODE CODE//\n if (u_type == 0) {\n // Protanope\n l = 0.0 * L + 2.02344 * M + -2.52581 * S;\n m = 0.0 * L + 1.0 * M + 0.0 * S;\n s = 0.0 * L + 0.0 * M + 1.0 * S;;\n } else if (u_type == 1) {\n // Deuteranope\n l = 1.0 * L + 0.0 * M + 0.0 * S;\n m = 0.494207 * L + 0.0 * M + 1.24827 * S;\n s = 0.0 * L + 0.0 * M + 1.0 * S;\n } else if (u_type == 2) {\n // Tritanope\n l = 1.0 * L + 0.0 * M + 0.0 * S;\n m = 0.0 * L + 1.0 * M + 0.0 * S;\n s = -0.395913 * L + 0.801109 * M + 0.0 * S;\n }\n\n // LMS to RGB matrix conversion\n vec4 error; // simulate the colors\n error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);\n error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);\n error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);\n error.a = 1.0;\n vec4 diff = o - error;\n vec4 correction; // correct the colors\n correction.r = 0.0;\n correction.g = (diff.r * 0.7) + (diff.g * 1.0);\n correction.b = (diff.r * 0.7) + (diff.b * 1.0);\n correction = o + correction;\n correction.a = o.a;\n //SIMULATE//\n\n // sim \n if (u_simulate) {\n fragColor = error.rgba;\n } else {\n fragColor = correction.rgba;\n }\n}"),this.simulate=this._simulate,this.colorBlindnessMode=this._colorBlindnessMode}getShader(){return this._shader.getShader()}getLayout(){return this._shader.getLayout()}set colorBlindnessMode(t){if(this._colorBlindnessMode=t,this._shader){const t=this._shader.getShader();t.use(),this._colorBlindnessMode===Mn.Protanope?t.setUniformInt("u_type",0):this._colorBlindnessMode===Mn.Deuteranope?t.setUniformInt("u_type",1):this._colorBlindnessMode===Mn.Tritanope&&t.setUniformInt("u_type",2)}}get colorBlindnessMode(){return this._colorBlindnessMode}set simulate(t){if(this._simulate=t,this._shader){const e=this._shader.getShader();e.use(),e.setUniformBoolean("u_simulate",t)}}get simulate(){return this._simulate}}class Un{constructor(t){this._engine=t,this._colorBlindPostProcessor=new zn(Mn.Protanope)}correct(t){this._engine.graphicsContext instanceof fe&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!1,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}simulate(t){this._engine.graphicsContext instanceof fe&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!0,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}clear(){this._engine.graphicsContext.removePostProcessor(this._colorBlindPostProcessor)}}class On{constructor(t){this.stats={currFrame:new Nn,prevFrame:new Nn},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!0,showName:!1},this.transform={showAll:!1,showPosition:!1,showPositionLabel:!1,positionColor:yt.Yellow,showZIndex:!1,showScale:!1,scaleColor:yt.Green,showRotation:!1,rotationColor:yt.Blue},this.graphics={showAll:!1,showBounds:!0,boundsColor:yt.Yellow},this.collider={showAll:!1,showBounds:!0,boundsColor:yt.Blue,showOwner:!1,showGeometry:!0,geometryColor:yt.Green},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:yt.Cyan,showCollisionContacts:!0,collisionContactColor:yt.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:yt.Yellow,showAcceleration:!1,accelerationColor:yt.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:yt.Red,showZoom:!1},this.tilemap={showAll:!1,showGrid:!1,gridColor:yt.Red,gridWidth:.5,showSolidBounds:!1,solidBoundsColor:yt.fromHex("#8080807F"),showColliderGeometry:!0,colliderGeometryColor:yt.Green,showQuadTree:!1},this._engine=t,this.colorBlindMode=new Un(this._engine)}useTestClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toTestClock();return e&&i.start(),this._engine.clock=i,i}useStandardClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toStandardClock();return e&&i.start(),this._engine.clock=i,i}}class Nn{constructor(){this._id=0,this._delta=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new Hn,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.delta=t.delta,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.delta=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new Nn;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get delta(){return this._delta}set delta(t){this._delta=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class Hn{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new Hn;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}class Wn{on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}}class Gn{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new Wn(this._windowGlobal),this._documentComponent=new Wn(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class Vn{static fromPagePosition(t,e,i){let s,n,r,o;3===arguments.length?(s=t,n=e,r=new vt(s,n),o=i):(r=t,s=r.x,n=r.y,o=e);const a=o.screen.pageToScreenCoordinates(r),h=o.screen.screenToWorldCoordinates(a);return new Vn(h,r,a)}constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}}class qn{cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}constructor(t,e,i,s,n,r){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=r,this.active=!0}}class Xn{cancel(){this.active=!1}constructor(t,e,i,s,n,r,o,a,h,l,c,d){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=r,this.index=o,this.deltaX=a,this.deltaY=h,this.deltaZ=l,this.deltaMode=c,this.ev=d,this.active=!0}}class Kn{constructor(){this.events=new d,this.lastPagePos=vt.Zero,this.lastScreenPos=vt.Zero,this.lastWorldPos=vt.Zero,this._onPointerMove=t=>{this.lastPagePos=new vt(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new vt(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new vt(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new vt(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new vt(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new vt(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var Zn,Yn,jn,Qn;!function(t){t.Pixel="Pixel",t.Line="Line",t.Page="Page"}(Zn||(Zn={})),function(t){t[t.NoButton=-1]="NoButton",t[t.Left=0]="Left",t[t.Middle=1]="Middle",t[t.Right=2]="Right",t[t.Unknown=3]="Unknown"}(Yn||(Yn={})),function(t){t.Left="Left",t.Middle="Middle",t.Right="Right",t.Unknown="Unknown",t.NoButton="NoButton"}(jn||(jn={})),function(t){t.Touch="Touch",t.Mouse="Mouse",t.Pen="Pen",t.Unknown="Unknown"}(Qn||(Qn={}));class $n{constructor(t,e){this.target=t,this.engine=e,this.events=new d,this.primary=new Kn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerCoords=new Map,this.currentFramePointerCoords=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}recreate(t,e){const i=new $n(t,e);return i.primary=this.primary,i._pointers=this._pointers,i}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Kn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return null!==(e=this.currentFramePointerDown.get(t))&&void 0!==e&&e}wasDown(t){var e;return null!==(e=this.lastFramePointerDown.get(t))&&void 0!==e&&e}isDragging(t){return this.isDown(t)}isDragStart(t){return this.isDown(t)&&!this.wasDown(t)}isDragEnd(t){return!this.isDown(t)&&this.wasDown(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerCoords=new Map(this.currentFramePointerCoords);for(const t of this.currentFrameDown){this.emit("down",t);this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){this.emit("up",t);this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){this.emit("move",t);this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){this.emit("cancel",t);this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)this.emit("wheel",t),this.primary.emit("pointerwheel",t),this.primary.emit("wheel",t)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerCoords.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(t){var e;this.target===this.engine.canvas?this.engine.canvas.style.touchAction="none":document.body.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const i={passive:!(this.engine.pageScrollPreventionMode===ar.All||this.engine.pageScrollPreventionMode===ar.Canvas)};"onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,i):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel,i):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,i);if((null===(e=null==t?void 0:t.grabWindowFocus)||void 0===e||e)&&it()){const t=()=>{window.focus()};window.PointerEvent?this.target.addEventListener("pointerdown",t):(this.target.addEventListener("touchstart",t),this.target.addEventListener("mousedown",t))}}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const e=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort(((t,e)=>t-e)).findIndex((e=>e===t));return this._activeNativePointerIdsToNormalized.set(t,e),e}_handle(t){t.preventDefault();const e=new Map;let i,s;if(n=t,globalThis.TouchEvent&&n instanceof globalThis.TouchEvent){i=jn.Unknown,s=Qn.Touch;for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],n=Vn.fromPagePosition(s.pageX,s.pageY,this.engine),r=i+1,o=this._normalizePointerId(r);this.currentFramePointerCoords.set(o,n),e.set(o,n)}}else{i=this._nativeButtonToPointerButton(t.button),s=Qn.Mouse;const n=Vn.fromPagePosition(t.pageX,t.pageY,this.engine);let r=1;(function(t){return globalThis.PointerEvent&&t instanceof globalThis.PointerEvent})(t)&&(r=t.pointerId,s=this._stringToPointerType(t.pointerType));const o=this._normalizePointerId(r);this.currentFramePointerCoords.set(o,n),e.set(o,n)}var n;for(const[n,r]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new qn("down",n,i,s,r,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new qn("up",n,i,s,r,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new qn("move",n,i,s,r,t));break;case"touchcancel":case"pointercancel":this.currentFrameCancel.push(new qn("cancel",n,i,s,r,t))}}_handleWheel(t){(this.engine.pageScrollPreventionMode===ar.All||this.engine.pageScrollPreventionMode===ar.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(xt(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,r=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,o=t.deltaZ||0;let a=Zn.Pixel;t.deltaMode&&(1===t.deltaMode?a=Zn.Line:2===t.deltaMode&&(a=Zn.Page));const h=new Xn(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,r,o,a,t);this.currentFrameWheel.push(h)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.systemManager.get(En),n=this.engine.currentScene.world.queryManager.createQuery(s.types);s.preupdate(),s.update(n.getEntities())}_nativeButtonToPointerButton(t){switch(t){case Yn.NoButton:return jn.NoButton;case Yn.Left:return jn.Left;case Yn.Middle:return jn.Middle;case Yn.Right:return jn.Right;case Yn.Unknown:return jn.Unknown;default:return Dt(t)}}_stringToPointerType(t){switch(t){case"touch":return Qn.Touch;case"mouse":return Qn.Mouse;case"pen":return Qn.Pen;default:return Qn.Unknown}}}class Jn{constructor(t){var e;this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0,this._fps=t.initialFps,this._samplePeriod=null!==(e=t.samplePeriod)&&void 0!==e?e:this._samplePeriod,this._currentFrameTime=1e3/t.initialFps,this._nowFn=t.nowFn,this._previousSampleTime=this._nowFn()}start(){this._beginFrameTime=this._nowFn()}end(){this._frames++;const t=this._nowFn();this._currentFrameTime=t-this._beginFrameTime,t>=this._previousSampleTime+this._samplePeriod&&(this._fps=1e3*this._frames/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class tr{constructor(t){var e,i,s;this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._options=t,this.tick=t.tick,this._lastTime=null!==(e=this.now())&&void 0!==e?e:0,this._maxFps=null!==(i=t.maxFps)&&void 0!==i?i:this._maxFps,this._onFatalException=null!==(s=t.onFatalException)&&void 0!==s?s:this._onFatalException,this.fpsSampler=new Jn({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new ir({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new er({...this._options})}setFatalExceptionHandler(t){this._onFatalException=t}schedule(t,e=0){const i=this._totalElapsed+e;this._scheduledCbs.push([t,i])}_runScheduledCbs(){for(let t=this._scheduledCbs.length-1;t>-1;t--)this._scheduledCbs[t][1]<=this._totalElapsed&&(this._scheduledCbs[t][0](),this._scheduledCbs.splice(t,1))}update(t){try{this.fpsSampler.start();const e=this.now();let i=e-this._lastTime||1;const s=1e3/this._maxFps;if(i>=s){let n=0;0!==s&&(n=i%s,i-=n),i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this._runScheduledCbs(),this.tick(t||i),this._lastTime=0!==s?e-n:e,this.fpsSampler.end()}}catch(t){this._onFatalException(t),this.stop()}}}class er extends tr{constructor(t){super(t),this._running=!1}isRunning(){return this._running}start(){if(this._running)return;this._running=!0;const t=()=>{if(this._running)try{this._requestId=window.requestAnimationFrame(t),this.update()}catch(t){throw window.cancelAnimationFrame(this._requestId),t}};t()}stop(){this._running=!1}}class ir extends tr{constructor(t){super({...t}),this._logger=J.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return null!==(t=this._currentTime)&&void 0!==t?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=null!=t?t:this._updateMs;this._running?(this.update(e),this._currentTime+=e):this._logger.warn("The clock is not running, no step will be performed")}run(t,e){for(let i=0;i<t;i++)this.step(null!=e?e:this._updateMs)}}var sr=i(7379);class nr{constructor(){this._toasterCss=sr.Z.toString(),this._isInitialized=!1}_initialize(){this._isInitialized||(this._container=document.createElement("div"),this._container.id="ex-toast-container",document.body.appendChild(this._container),this._isInitialized=!0,this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._toasterCss,document.head.appendChild(this._styleBlock))}dispose(){this._container.parentElement.removeChild(this._container),this._styleBlock.parentElement.removeChild(this._styleBlock),this._isInitialized=!1}_createFragment(t){const e=document.createElement("span");return e.innerText=t,e}toast(t,e,i){this._initialize();const s=document.createElement("div");s.className="ex-toast-message";const n=t.split("[LINK]").map((t=>this._createFragment(t)));if(e){const t=document.createElement("a");t.href=e,t.innerText=i||e,n.splice(1,0,t)}const r=document.createElement("div");n.forEach((t=>{r.appendChild(t)})),s.appendChild(r);const o=document.createElement("button");o.innerText="x",o.addEventListener("click",(()=>{this._container.removeChild(s)})),s.appendChild(o);const a=t=>{if("Escape"===t.key)try{this._container.removeChild(s)}catch(t){}document.removeEventListener("keydown",a)};document.addEventListener("keydown",a);const h=this._container.firstChild;this._container.insertBefore(s,h)}}class rr{constructor(t){this.inputs=t,this._handlers=new Map}execute(){for(const[t,e]of this._handlers.entries()){const i=t(this.inputs);i&&e(i)}}on(t,e){this._handlers.set(t,e)}}h();const or={FallbackGraphicsContext:"fallbackgraphicscontext",Initialize:"initialize",Visible:"visible",Hidden:"hidden",Start:"start",Stop:"stop",PreUpdate:"preupdate",PostUpdate:"postupdate",PreFrame:"preframe",PostFrame:"postframe",PreDraw:"predraw",PostDraw:"postdraw"};var ar;!function(t){t[t.None=0]="None",t[t.Canvas=1]="Canvas",t[t.All=2]="All"}(ar||(ar={}));class hr{get canvasWidth(){return this.screen.canvasWidth}get halfCanvasWidth(){return this.screen.halfCanvasWidth}get canvasHeight(){return this.screen.canvasHeight}get halfCanvasHeight(){return this.screen.halfCanvasHeight}get drawWidth(){return this.screen.drawWidth}get halfDrawWidth(){return this.screen.halfDrawWidth}get drawHeight(){return this.screen.drawHeight}get halfDrawHeight(){return this.screen.halfDrawHeight}get isHiDpi(){return this.screen.isHiDpi}get stats(){return this.debug.stats}get isFullscreen(){return this.screen.isFullScreen}get displayMode(){return this.screen.displayMode}get pixelRatio(){return this.screen.pixelRatio}get isDebug(){return this._isDebug}get snapToPixel(){return this.graphicsContext.snapToPixel}set snapToPixel(t){this.graphicsContext.snapToPixel=t}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}constructor(t){var e,i,s,n,r,o;this.version=Rr,this.events=new d,this.maxFps=Number.POSITIVE_INFINITY,this.scenes={},this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.enableCanvasTransparency=!0,this.onFatalException=t=>{J.getInstance().fatal(t)},this._toaster=new nr,this._timescale=1,this._isInitialized=!1,this._deferredGoTo=null,this._originalOptions={},this._performanceThresholdTriggered=!1,this._fpsSamples=[],this._loadingComplete=!1,this._isReady=!1,this._isReadyPromise=new Promise((t=>{this._isReadyResolve=t})),this.currentFrameElapsedMs=0,this.currentFrameLagMs=0,this._lagMs=0,this._screenShotRequests=[],t={...hr._DEFAULT_ENGINE_OPTIONS,...t},this._originalOptions=t,l.freeze(),this.browser=new Gn(window,document);const a=new Ke;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=a.test())){const e=document.createElement("div");if(e.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(e),a.failedTests.forEach((function(t){const e=document.createElement("div");e.innerText="Browser feature missing "+t,document.body.appendChild(e)})),t.canvasElementId){const e=document.getElementById(t.canvasElementId);e&&e.parentElement.removeChild(e)}return}this._compatible=!0,console.log&&!t.suppressConsoleBootMessage&&(console.log(`%cPowered by Excalibur.js (v${Rr})`,"background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;"),console.log("\n /| ________________\nO|===|* >________________>\n \\|"),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=J.getInstance(),this._logger.defaultLevel===Q.Debug&&a.logBrowserFeatures(),this._logger.debug("Building engine..."),this.canvasElementId=t.canvasElementId,t.canvasElementId?(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),this.canvas=document.getElementById(t.canvasElementId)):t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"));let h=null!==(e=t.displayMode)&&void 0!==e?e:we.Fixed;t.width&&t.height||t.viewport?(void 0===t.displayMode&&(h=we.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),h=we.FitScreen),this._originalDisplayMode=h;let c=l.isEnabled("use-canvas-context");if(!c)try{this.graphicsContext=new fe({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})}catch(t){this._logger.warn(`Excalibur could not load webgl for some reason (${t.message}) and loaded a Canvas 2D fallback. Some features of Excalibur will not work in this mode. \n\nRead more about this issue at https://excaliburjs.com/docs/webgl`),c=!0}c&&(this.graphicsContext=new ye({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})),this.screen=new Ae({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(i=t.antialiasing)||void 0===i||i,browser:this.browser,viewport:null!==(s=t.viewport)&&void 0!==s?s:t.width&&t.height?{width:t.width,height:t.height}:be.SVGA,resolution:t.resolution,displayMode:h,pixelRatio:t.suppressHiDPIScaling?1:null!==(n=t.pixelRatio)&&void 0!==n?n:null}),Vt.filtering=t.antialiasing?Gt.Blended:Gt.Pixel,t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.maxFps=null!==(r=t.maxFps)&&void 0!==r?r:this.maxFps,this.fixedUpdateFps=null!==(o=t.fixedUpdateFps)&&void 0!==o?o:this.fixedUpdateFps,this.clock=new er({maxFps:this.maxFps,tick:this._mainloop.bind(this),onFatalException:t=>this.onFatalException(t)}),this.enableCanvasTransparency=t.enableCanvasTransparency,this._loader=new qe,this._loader.wireEngine(this),this.debug=new On(this),this._initialize(t),this.rootScene=this.currentScene=new kn,this.addScene("root",this.rootScene),window.___EXCALIBUR_DEVTOOL=this}_monitorPerformanceThresholdAndTriggerFallback(){const{allow:t}=this._originalOptions.configurePerformanceCanvas2DFallback;let{threshold:e,showPlayerMessage:i}=this._originalOptions.configurePerformanceCanvas2DFallback;if(void 0===e&&(e=hr._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.threshold),void 0===i&&(i=hr._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.showPlayerMessage),!l.isEnabled("use-canvas-context")&&t&&this.ready&&!this._performanceThresholdTriggered){this._fpsSamples.length===e.numberOfFrames&&this._fpsSamples.splice(0,1),this._fpsSamples.push(this.clock.fpsSampler.fps);let t=0;for(let e=0;e<this._fpsSamples.length;e++)t+=this._fpsSamples[e];const s=t/this._fpsSamples.length;this._fpsSamples.length===e.numberOfFrames&&s<=e.fps&&(this._performanceThresholdTriggered=!0,this._logger.warn('Switching to browser 2D Canvas fallback due to performance. Some features of Excalibur will not work in this mode.\nthis might mean your browser doesn\'t have webgl enabled or hardware acceleration is unavailable.\n\nIf in Chrome:\n * Visit Settings > Advanced > System, and ensure "Use Hardware Acceleration" is checked.\n * Visit chrome://flags/#ignore-gpu-blocklist and ensure "Override software rendering list" is "enabled"\nIf in Firefox, visit about:config\n * Ensure webgl.disabled = false\n * Ensure webgl.force-enabled = true\n * Ensure layers.acceleration.force-enabled = true\n\nRead more about this issue at https://excaliburjs.com/docs/performance'),i&&this._toaster.toast("Excalibur is encountering performance issues. It's possible that your browser doesn't have hardware acceleration enabled. Visit [LINK] for more information and potential solutions.","https://excaliburjs.com/docs/performance"),this.useCanvas2DFallback(),this.emit("fallbackgraphicscontext",this.graphicsContext))}}useCanvas2DFallback(){var t,e,i;const s=this.canvas.cloneNode(!1);this.canvas.parentNode.replaceChild(s,this.canvas),this.canvas=s;const n={...this._originalOptions,antialiasing:this.getAntialiasing()},r=this._originalDisplayMode;this.graphicsContext=new ye({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:n.antialiasing,backgroundColor:n.backgroundColor,snapToPixel:n.snapToPixel,useDrawSorting:n.useDrawSorting}),this.screen&&this.screen.dispose(),this.screen=new Ae({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(t=n.antialiasing)||void 0===t||t,browser:this.browser,viewport:null!==(e=n.viewport)&&void 0!==e?e:n.width&&n.height?{width:n.width,height:n.height}:be.SVGA,resolution:n.resolution,displayMode:r,pixelRatio:n.suppressHiDPIScaling?1:null!==(i=n.pixelRatio)&&void 0!==i?i:null}),this.screen.setCurrentCamera(this.currentScene.camera),this.input.pointers.detach();const o=n&&n.pointerScope===rt.Document?document:this.canvas;this.input.pointers=this.input.pointers.recreate(o,this),this.input.pointers.init()}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){t<=0?J.getInstance().error("Cannot set engine.timescale to a value of 0 or less than 0."):this._timescale=t}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e}removeScene(t){if(t instanceof kn)for(const e in this.scenes)this.scenes.hasOwnProperty(e)&&this.scenes[e]===t&&delete this.scenes[e];"string"==typeof t&&delete this.scenes[t]}add(t){2!==arguments.length?this._deferredGoTo&&this.scenes[this._deferredGoTo]?this.scenes[this._deferredGoTo].add(t):this.currentScene.add(t):this.addScene(arguments[0],arguments[1])}remove(t){t instanceof Wi&&this.currentScene.remove(t),t instanceof kn&&this.removeScene(t),"string"==typeof t&&this.removeScene(t)}goToScene(t,e){if(this.isInitialized)if(this.scenes[t]){const i=this.currentScene,s=this.scenes[t];if(this._logger.debug("Going to scene:",t),this.currentScene.isInitialized){const t={engine:this,previousScene:i,nextScene:s};this.currentScene._deactivate.apply(this.currentScene,[t,s]),this.currentScene.events.emit("deactivate",new W(t,this.currentScene))}this.currentScene=s,this.screen.setCurrentCamera(s.camera),this.currentScene._initialize(this);const n={engine:this,previousScene:i,nextScene:s,data:e};this.currentScene._activate.apply(this.currentScene,[n,s]),this.currentScene.events.emit("activate",new H(n,this.currentScene))}else this._logger.error("Scene",t,"does not exist!");else this._deferredGoTo=t}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){var e,i,s,n;this.pageScrollPreventionMode=t.scrollPreventionMode;const r=t&&t.pointerScope===rt.Document?document:this.canvas;this.input={keyboard:new nt,pointers:new $n(r,this),gamepads:new K},this.input.keyboard.init({grabWindowFocus:null===(i=null===(e=this._originalOptions)||void 0===e?void 0:e.grabWindowFocus)||void 0===i||i}),this.input.pointers.init({grabWindowFocus:null===(n=null===(s=this._originalOptions)||void 0===s?void 0:s.grabWindowFocus)||void 0===n||n}),this.input.gamepads.init(),this.inputMapper=new rr(this.input),this.browser.document.on("visibilitychange",(()=>{"hidden"===document.visibilityState?(this.events.emit("hidden",new B(this)),this._logger.debug("Window hidden")):"visible"===document.visibilityState&&(this.events.emit("visible",new D(this)),this._logger.debug("Window visible"))})),this.canvasElementId||t.canvasElement||document.body.appendChild(this.canvas)}onInitialize(t){}setAntialiasing(t){this.screen.antialiasing=t}getAntialiasing(){return this.screen.antialiasing}get isInitialized(){return this._isInitialized}_overrideInitialize(t){if(!this.isInitialized)if(this.onInitialize(t),this.events.emit("initialize",new N(t,this)),this._isInitialized=!0,this._deferredGoTo){const t=this._deferredGoTo;this._deferredGoTo=null,this.goToScene(t)}else this.goToScene("root")}_update(t){if(!this.ready)return this._loader.update(this,t),this.inputMapper.execute(),this.input.keyboard.update(),void this.input.gamepads.update();this._preupdate(t),this.currentScene.update(this,t),this.graphicsContext.updatePostProcessors(t),this._postupdate(t),this.inputMapper.execute(),this.input.keyboard.update(),this.input.gamepads.update()}_preupdate(t){this.emit("preupdate",new b(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new C(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){if(this.graphicsContext.beginDrawLifecycle(),this.graphicsContext.clear(),this._predraw(this.graphicsContext,t),!this._isReady)return this._loader.canvas.draw(this.graphicsContext,0,0),void this.graphicsContext.flush();this.graphicsContext.backgroundColor=this.backgroundColor,this.currentScene.draw(this.graphicsContext,t),this._postdraw(this.graphicsContext,t),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle(),this._checkForScreenShots()}_predraw(t,e){this.emit("predraw",new v(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new x(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return this._loadingComplete}get ready(){return this._isReady}isReady(){return this._isReadyPromise}async start(t){if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");return t&&(this.screen.pushResolutionAndViewport(),this.screen.resolution=this.screen.viewport,this.screen.applyResolutionAndViewport(),this._loader=t,this._loader.suppressPlayButton=this._suppressPlayButton||this._loader.suppressPlayButton,this._loader.wireEngine(this)),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this._logger.debug("Game clock started"),t&&(await this.load(this._loader),this._loadingComplete=!0,this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport()),this._loadingComplete=!0,this._overrideInitialize(this),this._isReady=!0,this._isReadyResolve(),this.emit("start",new m(this)),this._isReadyPromise}_mainloop(t){this.emit("preframe",new A(this,this.stats.prevFrame));const e=t*this.timescale;this.currentFrameElapsedMs=e;const i=this.stats.prevFrame.id+1;this.stats.currFrame.reset(),this.stats.currFrame.id=i,this.stats.currFrame.delta=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps,se.clear();const s=this.clock.now(),n=1e3/this.fixedUpdateFps;if(this.fixedUpdateFps)for(this._lagMs+=e;this._lagMs>=n;)this._update(n),this._lagMs-=n;else this._update(e);const r=this.clock.now();this.currentFrameLagMs=this._lagMs,this._draw(e);const o=this.clock.now();this.stats.currFrame.duration.update=r-s,this.stats.currFrame.duration.draw=o-r,this.stats.currFrame.graphics.drawnImages=se.DrawnImagesCount,this.stats.currFrame.graphics.drawCalls=se.DrawCallCount,this.emit("postframe",new T(this,this.stats.currFrame)),this.stats.prevFrame.reset(this.stats.currFrame),this._monitorPerformanceThresholdAndTriggerFallback()}stop(){this.clock.isRunning()&&(this.emit("stop",new f(this)),this.browser.pause(),this.clock.stop(),this._logger.debug("Game stopped"))}isRunning(){return this.clock.isRunning()}screenshot(t=!1){return new Promise((e=>{this._screenShotRequests.push({preserveHiDPIResolution:t,resolve:e})}))}_checkForScreenShots(){for(const t of this._screenShotRequests){const e=t.preserveHiDPIResolution?this.canvas.width:this.screen.resolution.width,i=t.preserveHiDPIResolution?this.canvas.height:this.screen.resolution.height,s=document.createElement("canvas");s.width=e,s.height=i;const n=s.getContext("2d");n.imageSmoothingEnabled=this.screen.antialiasing,n.drawImage(this.canvas,0,0,e,i);const r=new Image,o=s.toDataURL("image/png");r.src=o,t.resolve(r)}this._screenShotRequests.length=0}async load(t){try{await t.load()}catch(t){this._logger.error("Error loading resources, things may not behave properly",t),await Promise.resolve()}}}hr._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,useDrawSorting:!0,configurePerformanceCanvas2DFallback:{allow:!1,showPlayerMessage:!1,threshold:{fps:20,numberOfFrames:100}},canvasElementId:"",canvasElement:void 0,snapToPixel:!1,pointerScope:rt.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,grabWindowFocus:!0,scrollPreventionMode:ar.Canvas,backgroundColor:yt.fromHex("#2185d0")};class lr{constructor(){this._handlers={},this._wiredEventDispatchers=[],this._deferedHandlerRemovals=[]}clear(){this._handlers={},this._wiredEventDispatchers=[]}_processDeferredHandlerRemovals(){for(const t of this._deferedHandlerRemovals)this._removeHandler(t.name,t.handler);this._deferedHandlerRemovals.length=0}emit(t,e){if(this._processDeferredHandlerRemovals(),!t)return;let i,s;if(t=t.toLowerCase(),null==e&&(e=new u),this._handlers[t])for(i=0,s=this._handlers[t].length;i<s;i++)this._handlers[t][i](e);for(i=0,s=this._wiredEventDispatchers.length;i<s;i++)this._wiredEventDispatchers[i].emit(t,e)}on(t,e){this._processDeferredHandlerRemovals(),t=t.toLowerCase(),this._handlers[t]||(this._handlers[t]=[]),this._handlers[t].push(e)}off(t,e){this._deferedHandlerRemovals.push({name:t,handler:e})}_removeHandler(t,e){t=t.toLowerCase();const i=this._handlers[t];if(i)if(e){const s=i.indexOf(e);s>-1&&this._handlers[t].splice(s,1)}else this._handlers[t].length=0}once(t,e){this._processDeferredHandlerRemovals();const i=s=>{const n=s||new u;this.off(t,i),e(n)};this.on(t,i)}wire(t){t._wiredEventDispatchers.push(this)}unwire(t){const e=t._wiredEventDispatchers.indexOf(this);e>-1&&t._wiredEventDispatchers.splice(e,1)}}class cr extends Es{get font(){return this._font}set font(t){this._font=t,this._text.font=t}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text&&(this._text.color=t)}get opacity(){return this._text.opacity}set opacity(t){this._text.opacity=t}get spriteFont(){return this._spriteFont}set spriteFont(t){t&&(this._spriteFont=t,this._text.font=this._spriteFont)}constructor(t){super(t),this._font=new Ts,this._text=new Ss({text:"",font:this._font});const{text:e,pos:i,x:s,y:n,spriteFont:r,font:o,color:a}=t;this.pos=null!=i?i:s&&n?xt(s,n):this.pos,this.text=null!=e?e:this.text,this.font=null!=o?o:this.font,this.spriteFont=null!=r?r:this.spriteFont,this._text.color=null!=a?a:this.color;const h=this.get(Xi);h.anchor=vt.Zero,h.use(this._text)}_initialize(t){super._initialize(t)}getTextWidth(){return this._text.width}}class dr extends Wi{getGraphics(){return this._graphics}addGraphic(t){this._graphics.push(t),this._gfx.visible=!0,this._gfx.localBounds=this._recalculateBounds()}_recalculateBounds(){let t=this._tileBounds.clone();for(const e of this._graphics){const i=xt(this.map.graphicsOffset.x-this.map.tileWidth/2,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t=t.combine(e.localBounds.translate(i))}return t}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&this._graphics.splice(e,1),this._gfx.localBounds=this._recalculateBounds()}clearGraphics(){this._graphics.length=0,this._gfx.visible=!1,this._gfx.localBounds=this._recalculateBounds()}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}get pos(){return this.map.tileToWorld(xt(this.x,this.y))}get center(){return this.pos.add(xt(0,this.map.tileHeight/2))}constructor(t,e,i,s){super([new ui,new Xi({offset:null!=i?i:vt.Zero,onPostDraw:(t,e)=>this.draw(t,e)}),new In(s)]),this.solid=!1,this._tileBounds=new At,this._graphics=[],this._colliders=[],this.x=t,this.y=e,this.map=s,this._transform=this.get(ui),this._isometricEntityComponent=this.get(In);const n=this.map.tileWidth/2,r=this.map.tileHeight/2,o=(this.x-this.y)*n,a=(this.x+this.y)*r;this._transform.pos=xt(o,a),this._isometricEntityComponent.elevation=0,this._gfx=this.get(Xi),this._gfx.visible=!1;const h=this.map.tileWidth,l=this.map.tileHeight,c=xt(0,this.map.renderFromTopOfGraphic?l:0);this._gfx.localBounds=this._tileBounds=new At({left:-h/2,top:-l,right:h/2,bottom:l}).translate(c)}draw(t,e){const i=this.map.tileWidth/2;t.save(),t.translate(-i,0);for(const e of this._graphics)e.draw(t,this.map.graphicsOffset.x,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t.restore()}}class ur extends Wi{constructor(t){super([new ui,new Li({type:Ze.Fixed}),new ki,new Rs((t=>this.debug(t)),!1)],t.name),this.renderFromTopOfGraphic=!1,this.graphicsOffset=xt(0,0),this._collidersDirty=!1,this._originalOffsets=new WeakMap;const{pos:e,tileWidth:i,tileHeight:s,columns:n,rows:r,renderFromTopOfGraphic:o,graphicsOffset:a}=t;this.transform=this.get(ui),e&&(this.transform.pos=e),this.collider=this.get(ki),this.collider&&this.collider.set(this._composite=new Ci([])),this.renderFromTopOfGraphic=null!=o?o:this.renderFromTopOfGraphic,this.graphicsOffset=null!=a?a:this.graphicsOffset,this.tileWidth=i,this.tileHeight=s,this.columns=n,this.rows=r,this.tiles=new Array(n*r);for(let t=0;t<r;t++)for(let e=0;e<n;e++){const i=new dr(e,t,this.graphicsOffset,this);this.tiles[e+t*n]=i,this.addChild(i)}}update(){this._collidersDirty&&(this.updateColliders(),this._collidersDirty=!1)}flagCollidersDirty(){this._collidersDirty=!0}_getOrSetColliderOriginalOffset(t){if(this._originalOffsets.has(t))return this._originalOffsets.get(t);{const e=t.offset;return this._originalOffsets.set(t,e),e}}updateColliders(){this._composite.clearColliders();const t=this.get(ui).pos;for(const e of this.tiles)if(e.solid)for(const i of e.getColliders()){const s=this._getOrSetColliderOriginalOffset(i);i.offset=this.tileToWorld(xt(e.x,e.y)).sub(t).add(s).sub(xt(this.tileWidth/2,this.tileHeight)),i.owner=this,this._composite.addCollider(i)}this.collider.update()}worldToTile(t){t=t.sub(this.transform.globalPos);const e=this.tileWidth/2,i=this.tileHeight/2;return xt(~~((t.x/e+t.y/i)/2),~~((t.y/i-t.x/e)/2))}tileToWorld(t){const e=this.tileWidth/2,i=this.tileHeight/2;return xt((t.x-t.y)*e,(t.x+t.y)*i).add(this.transform.pos)}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=this.worldToTile(t);return this.getTile(e.x,e.y)}_getMaxZIndex(){let t=Number.NEGATIVE_INFINITY;for(const e of this.tiles){const i=e.get(ui).z;i>t&&(t=i)}return t}debug(t){t.save(),t.z=this._getMaxZIndex()+.5;for(let e=0;e<this.rows+1;e++){const i=this.tileToWorld(xt(0,e)),s=this.tileToWorld(xt(this.columns,e));t.drawLine(i,s,yt.Red,2)}for(let e=0;e<this.columns+1;e++){const i=this.tileToWorld(xt(e,0)),s=this.tileToWorld(xt(e,this.rows));t.drawLine(i,s,yt.Red,2)}for(const e of this.tiles)t.drawCircle(this.tileToWorld(xt(e.x,e.y)),3,yt.Yellow);t.restore()}}class pr{constructor(t,e){this._stopped=!1,this._sequenceBuilder=e,this._sequenceContext=new ws(t),this._actionQueue=this._sequenceContext.getQueue(),this._sequenceBuilder(this._sequenceContext)}update(t){this._actionQueue.update(t)}isComplete(){return this._stopped||this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._stopped=!1,this._actionQueue.reset()}clone(t){return new pr(t,this._sequenceBuilder)}}class _r{constructor(t){this._actions=t}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}isComplete(t){return this._actions.every((e=>e.isComplete(t)))}reset(){this._actions.forEach((t=>t.reset()))}stop(){this._actions.forEach((t=>t.stop()))}}function gr(t){return!!t._initialize}function mr(t){return!!t.onInitialize}function fr(t){return!!t._preupdate}function vr(t){return!!t.onPreUpdate}function xr(t){return!!t.onPostUpdate}function yr(t){return!!t.onPostUpdate}function wr(t){return!!t.onPreDraw}function br(t){return!!t.onPostDraw}class Cr{constructor(t,e=yt.Magenta,i=!1){this.path=t,this.color=e,this._stream=null,this._gif=null,this._textures=[],this._animation=null,this._transparentColor=null,this._resource=new Ut(t,"arraybuffer",i),this._transparentColor=e}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){const t=await this._resource.load();this._stream=new Sr(t),this._gif=new Er(this._stream,this._transparentColor);const e=this._gif.images.map((t=>new qt(t.src,!1)));return await Promise.all(e.map((t=>t.load()))),this.data=this._textures=e}isLoaded(){return!!this.data}toSprite(t=0){return this._textures[t].toSprite()}toSpriteSheet(){const t=this._textures.map((t=>t.toSprite()));return new Xt({sprites:t})}toAnimation(t){const e=this.toSpriteSheet(),i=e.sprites.length;return this._animation=fn.fromSpriteSheet(e,gt(0,i),t),this._animation}get readCheckBytes(){return this._gif.checkBytes}}const Ar=t=>t.reduce((function(t,e){return 2*t+e}),0),Tr=t=>{const e=[];for(let i=7;i>=0;i--)e.push(!!(t&1<<i));return e};class Sr{constructor(t){if(this.data=null,this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=t=>{const e=[];for(let i=0;i<t;i++)e.push(this.readByte());return e},this.read=t=>{let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.readByte());return e},this.readUnsigned=()=>{const t=this.readBytes(2);return(t[1]<<8)+t[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,0===this.len)throw new Error("No data loaded from file")}}class Er{constructor(t,e=yt.Magenta){this._st=null,this._handler={},this._transparentColor=null,this.frames=[],this.images=[],this.globalColorTable=[],this.checkBytes=[],this.parseColorTable=t=>{const e=[];for(let i=0;i<t;i++){const t="#"+this._st.readBytes(3).map((t=>{const e=t.toString(16);return 1===e.length?"0"+e:e})).join("");e.push(t)}return e},this.readSubBlocks=()=>{let t,e;e="";do{t=this._st.readByte(),e+=this._st.read(t)}while(0!==t);return e},this.parseHeader=()=>{const t={sig:null,ver:null,width:null,height:null,colorRes:null,globalColorTableSize:null,gctFlag:null,sorted:null,globalColorTable:[],bgColor:null,pixelAspectRatio:null};if(t.sig=this._st.read(3),t.ver=this._st.read(3),"GIF"!==t.sig)throw new Error("Not a GIF file.");t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Tr(this._st.readByte());t.gctFlag=e.shift(),t.colorRes=Ar(e.splice(0,3)),t.sorted=e.shift(),t.globalColorTableSize=Ar(e.splice(0,3)),t.bgColor=this._st.readByte(),t.pixelAspectRatio=this._st.readByte(),t.gctFlag&&(t.globalColorTable=this.parseColorTable(1<<t.globalColorTableSize+1),this.globalColorTable=t.globalColorTable),this._handler.hdr&&this._handler.hdr(t)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=t=>{const e=t=>{this.checkBytes.push(this._st.readByte());const e=Tr(this._st.readByte());t.reserved=e.splice(0,3),t.disposalMethod=Ar(e.splice(0,3)),t.userInput=e.shift(),t.transparencyGiven=e.shift(),t.delayTime=this._st.readUnsigned(),t.transparencyIndex=this._st.readByte(),t.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(t)&&this.checkBytes.push(this._handler.gce)},i=t=>{t.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(t)&&this.checkBytes.push(this._handler.com)},s=t=>{this.checkBytes.push(this._st.readByte()),t.ptHeader=this._st.readBytes(12),t.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(t)&&this.checkBytes.push(this._handler.pte)},n=t=>{const e=t=>{this.checkBytes.push(this._st.readByte()),t.unknown=this._st.readByte(),t.iterations=this._st.readUnsigned(),t.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(t)&&this.checkBytes.push(this._handler.app)},i=t=>{t.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[t.identifier]&&this._handler.app[t.identifier](t)&&this.checkBytes.push(this._handler.app[t.identifier])};if(this.checkBytes.push(this._st.readByte()),t.identifier=this._st.read(8),t.authCode=this._st.read(3),"NETSCAPE"===t.identifier)e(t);else i(t)},r=t=>{t.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(t)&&this.checkBytes.push(this._handler.unknown)};switch(t.label=this._st.readByte(),t.label){case 249:t.extType="gce",e(t);break;case 254:t.extType="com",i(t);break;case 1:t.extType="pte",s(t);break;case 255:t.extType="app",n(t);break;default:t.extType="unknown",r(t)}},this.parseImg=t=>{t.leftPos=this._st.readUnsigned(),t.topPos=this._st.readUnsigned(),t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Tr(this._st.readByte());t.lctFlag=e.shift(),t.interlaced=e.shift(),t.sorted=e.shift(),t.reserved=e.splice(0,2),t.lctSize=Ar(e.splice(0,3)),t.lctFlag&&(t.lct=this.parseColorTable(1<<t.lctSize+1)),t.lzwMinCodeSize=this._st.readByte();const i=this.readSubBlocks();t.pixels=function(t,e){let i=0;const s=function(t){let s=0;for(let n=0;n<t;n++)e.charCodeAt(i>>3)&1<<(7&i)&&(s|=1<<n),i++;return s},n=[],r=1<<t,o=r+1;let a=t+1,h=[];const l=function(){h=[],a=t+1;for(let t=0;t<r;t++)h[t]=[t];h[r]=[],h[o]=null};let c,d;for(;;)if(d=c,c=s(a),c!==r){if(c===o)break;if(c<h.length)d!==r&&h.push(h[d].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[d].concat(h[d][0]))}n.push.apply(n,h[c]),h.length===1<<a&&a<12&&a++}else l();return n}(t.lzwMinCodeSize,i),t.interlaced&&(t.pixels=((t,e)=>{const i=new Array(t.length),s=t.length/e,n=(s,n)=>{const r=t.slice(n*e,(n+1)*e);i.splice.apply(i,[s*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2];let a=0;for(let t=0;t<4;t++)for(let e=r[t];e<s;e+=o[t])n(e,a),a++;return i})(t.pixels,t.width)),this.frames.push(t),this.arrayToImage(t),this._handler.img&&this._handler.img(t)&&this.checkBytes.push(this._handler)},this.parseBlock=()=>{const t={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this._handler.eof&&this._handler.eof(t)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&this.parseBlock()},this.arrayToImage=t=>{let e=0;const i=document.createElement("canvas");i.id=e.toString(),i.width=t.width,i.height=t.height,e++;const s=i.getContext("2d");let n=0,r=0;for(let e=0;e<t.pixels.length;e++)r%t.width==0&&(n++,r=0),this.globalColorTable[t.pixels[e]]===this._transparentColor.toHex()?s.fillStyle="rgba(0, 0, 0, 0)":s.fillStyle=this.globalColorTable[t.pixels[e]],s.fillRect(r,n,1,1),r++;const o=new Image;o.src=i.toDataURL(),this.images.push(o)},this._st=t,this._handler={},this._transparentColor=e,this.parseHeader(),this.parseBlock()}}class Pr extends Ht{constructor(t){super(),this.color=yt.Black,this.thickness=1;const{start:e,end:i,color:s,thickness:n}=t;this.start=e,this.end=i,this.color=null!=s?s:this.color,this.thickness=null!=n?n:this.thickness,this._localBounds=this._calculateBounds();const{width:r,height:o}=this._localBounds;this.width=r,this.height=o}get localBounds(){return this._localBounds}_calculateBounds(){const t=this.end.sub(this.start).normal(),e=this.thickness/2,i=[this.start.add(t.scale(e)),this.end.add(t.scale(e)),this.end.add(t.scale(-e)),this.start.add(t.scale(-e))];return At.fromPoints(i)}_drawImage(t,e,i){t.drawLine(this.start,this.end,this.color,this.thickness)}clone(){return new Pr({start:this.start,end:this.end,color:this.color,thickness:this.thickness})}}class Ir extends Fe{get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce(((t,e)=>Math.max(e.x,t)),0)-e.x,this.height=this._points.reduce(((t,e)=>Math.max(e.y,t)),0)-e.y,this.flagDirty()}get minPoint(){return xt(this._points.reduce(((t,e)=>Math.min(e.x,t)),1/0),this._points.reduce(((t,e)=>Math.min(e.y,t)),1/0))}constructor(t){super(t),this.points=t.points,this.filtering=Gt.Blended,this.rasterize()}clone(){return new Ir({points:this.points.map((t=>t.clone())),...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach((i=>{t.lineTo(i.x+e.x,i.y+e.y)})),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}class Dr{constructor(){this._queue=[]}get length(){return this._queue.length}enqueue(){const t=new Tt;return this._queue.push(t),t.promise}dequeue(t){this._queue.shift().resolve(t)}}class Br{constructor(t){this._count=t,this._waitQueue=new Dr}get count(){return this._count}get waiting(){return this._waitQueue.length}async enter(){return 0!==this._count?(this._count--,Promise.resolve()):this._waitQueue.enqueue()}exit(t=1){if(0!==t){for(;0!==t&&0!==this._waitQueue.length;)this._waitQueue.dequeue(null),t--;this._count+=t}}}const Rr="0.29.0-alpha.2+5c28d4e";h()})(),s})()));
3
3
  //# sourceMappingURL=excalibur.min.js.map