excalibur 0.33.0-alpha.99 → 1.1.0-alpha.310

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 (345) hide show
  1. package/.nvmrc +1 -1
  2. package/CHANGELOG.md +206 -5
  3. package/build/esm/excalibur.development.js +37363 -35202
  4. package/build/esm/excalibur.js +37363 -35202
  5. package/build/esm/excalibur.min.development.js +18360 -23963
  6. package/build/esm/excalibur.min.js +18360 -23963
  7. package/build/{dist → esm/src/engine}/actions/action/move-by.d.ts +1 -4
  8. package/build/{dist → esm/src/engine}/actions/action/move-to.d.ts +1 -4
  9. package/build/{dist → esm/src/engine}/actions/action/repeat-forever.d.ts +8 -0
  10. package/build/{dist → esm/src/engine}/actions/action/rotate-by.d.ts +9 -3
  11. package/build/{dist → esm/src/engine}/actions/action-context.d.ts +9 -43
  12. package/build/{dist → esm/src/engine}/actions/actions-component.d.ts +3 -41
  13. package/build/{dist → esm/src/engine}/actions/actions-system.d.ts +2 -3
  14. package/build/{dist → esm/src/engine}/actions/index.d.ts +0 -2
  15. package/build/{dist → esm/src/engine}/actor.d.ts +19 -30
  16. package/build/{dist → esm/src/engine}/camera.d.ts +13 -10
  17. package/build/{dist → esm/src/engine}/collision/body-component.d.ts +11 -20
  18. package/build/{dist → esm/src/engine}/collision/bounding-box.d.ts +3 -10
  19. package/build/{dist → esm/src/engine}/collision/collider-component.d.ts +17 -2
  20. package/build/{dist → esm/src/engine}/collision/colliders/circle-collider.d.ts +8 -0
  21. package/build/{dist → esm/src/engine}/collision/colliders/closest-line-jump-table.d.ts +1 -1
  22. package/build/{dist → esm/src/engine}/collision/colliders/collider.d.ts +7 -1
  23. package/build/{dist/collision/colliders/shape.d.ts → esm/src/engine/collision/colliders/colliders.d.ts} +50 -0
  24. package/build/{dist → esm/src/engine}/collision/colliders/collision-jump-table.d.ts +2 -1
  25. package/build/{dist → esm/src/engine}/collision/colliders/edge-collider.d.ts +25 -1
  26. package/build/{dist → esm/src/engine}/collision/colliders/polygon-collider.d.ts +23 -0
  27. package/build/esm/src/engine/collision/colliders/sat-shape.d.ts +27 -0
  28. package/build/{dist → esm/src/engine}/collision/colliders/separating-axis.d.ts +11 -6
  29. package/build/{dist → esm/src/engine}/collision/collision-system.d.ts +9 -5
  30. package/build/{dist → esm/src/engine}/collision/detection/collision-contact.d.ts +6 -0
  31. package/build/{dist → esm/src/engine}/collision/detection/dynamic-tree.d.ts +9 -11
  32. package/build/{dist → esm/src/engine}/collision/detection/pair.d.ts +9 -0
  33. package/build/{dist → esm/src/engine}/collision/detection/quad-tree.d.ts +2 -2
  34. package/build/{dist → esm/src/engine}/collision/detection/sparse-hash-grid-collision-processor.d.ts +7 -2
  35. package/build/{dist → esm/src/engine}/collision/detection/sparse-hash-grid.d.ts +11 -3
  36. package/build/{dist → esm/src/engine}/collision/group/collision-group-manager.d.ts +1 -1
  37. package/build/{dist → esm/src/engine}/collision/index.d.ts +2 -1
  38. package/build/{dist → esm/src/engine}/collision/motion-system.d.ts +2 -3
  39. package/build/{dist → esm/src/engine}/collision/physics-config.d.ts +7 -0
  40. package/build/{dist → esm/src/engine}/collision/physics-world.d.ts +34 -33
  41. package/build/esm/src/engine/collision/solver/realistic-solver.d.ts +50 -0
  42. package/build/{dist → esm/src/engine}/collision/solver/solver.d.ts +4 -2
  43. package/build/{dist → esm/src/engine}/debug/debug-config.d.ts +16 -0
  44. package/build/{dist → esm/src/engine}/debug/debug-system.d.ts +3 -3
  45. package/build/esm/src/engine/deprecated.d.ts +1 -0
  46. package/build/{dist → esm/src/engine}/director/director.d.ts +13 -8
  47. package/build/{dist → esm/src/engine}/director/slide.d.ts +2 -2
  48. package/build/{dist → esm/src/engine}/director/transition.d.ts +1 -4
  49. package/build/{dist → esm/src/engine}/engine.d.ts +58 -8
  50. package/build/{dist → esm/src/engine}/entity-component-system/component.d.ts +1 -1
  51. package/build/{dist → esm/src/engine}/entity-component-system/components/motion-component.d.ts +1 -0
  52. package/build/{dist → esm/src/engine}/entity-component-system/components/pause-component.d.ts +2 -0
  53. package/build/{dist → esm/src/engine}/entity-component-system/components/tags-component.d.ts +1 -0
  54. package/build/{dist → esm/src/engine}/entity-component-system/components/transform-component.d.ts +1 -0
  55. package/build/{dist → esm/src/engine}/entity-component-system/entity.d.ts +0 -10
  56. package/build/{dist → esm/src/engine}/entity-component-system/index.d.ts +0 -1
  57. package/build/{dist → esm/src/engine}/entity-component-system/query.d.ts +1 -1
  58. package/build/{dist → esm/src/engine}/entity-component-system/system.d.ts +11 -4
  59. package/build/{dist → esm/src/engine}/entity-component-system/world.d.ts +1 -5
  60. package/build/{dist → esm/src/engine}/events/media-events.d.ts +3 -3
  61. package/build/{dist → esm/src/engine}/events.d.ts +4 -4
  62. package/build/{dist → esm/src/engine}/graphics/animation.d.ts +15 -5
  63. package/build/{dist → esm/src/engine}/graphics/context/circle-renderer/circle-renderer.d.ts +5 -0
  64. package/build/{dist → esm/src/engine}/graphics/context/debug-text.d.ts +13 -1
  65. package/build/{dist → esm/src/engine}/graphics/context/excalibur-graphics-context-2d-canvas.d.ts +13 -3
  66. package/build/{dist → esm/src/engine}/graphics/context/excalibur-graphics-context-webgl.d.ts +43 -6
  67. package/build/{dist → esm/src/engine}/graphics/context/excalibur-graphics-context.d.ts +108 -4
  68. package/build/esm/src/engine/graphics/context/framebuffer.d.ts +154 -0
  69. package/build/esm/src/engine/graphics/context/glsl.d.ts +47 -0
  70. package/build/{dist → esm/src/engine}/graphics/context/material-renderer/material-renderer.d.ts +1 -0
  71. package/build/esm/src/engine/graphics/context/material.d.ts +208 -0
  72. package/build/esm/src/engine/graphics/context/shader-pipeline/effects/bloom-effect.d.ts +80 -0
  73. package/build/esm/src/engine/graphics/context/shader-pipeline/effects/blur-passes.d.ts +75 -0
  74. package/build/esm/src/engine/graphics/context/shader-pipeline/effects/glow-passes.d.ts +93 -0
  75. package/build/esm/src/engine/graphics/context/shader-pipeline/shader-pass.d.ts +138 -0
  76. package/build/esm/src/engine/graphics/context/shader-pipeline/shader-pipeline.d.ts +91 -0
  77. package/build/{dist → esm/src/engine}/graphics/context/shader.d.ts +43 -6
  78. package/build/{dist → esm/src/engine}/graphics/context/texture-loader.d.ts +1 -1
  79. package/build/{dist → esm/src/engine}/graphics/context/webgl-util.d.ts +2 -2
  80. package/build/{dist → esm/src/engine}/graphics/debug-graphics-component.d.ts +1 -0
  81. package/build/{dist → esm/src/engine}/graphics/filtering.d.ts +1 -1
  82. package/build/{dist → esm/src/engine}/graphics/font-common.d.ts +2 -2
  83. package/build/{dist → esm/src/engine}/graphics/font-text-instance.d.ts +5 -5
  84. package/build/{dist → esm/src/engine}/graphics/font.d.ts +3 -3
  85. package/build/{dist → esm/src/engine}/graphics/graphics-component.d.ts +28 -15
  86. package/build/{dist → esm/src/engine}/graphics/graphics-group.d.ts +6 -0
  87. package/build/{dist → esm/src/engine}/graphics/graphics-system.d.ts +3 -3
  88. package/build/{dist → esm/src/engine}/graphics/image-source.d.ts +1 -1
  89. package/build/{dist → esm/src/engine}/graphics/index.d.ts +8 -0
  90. package/build/{dist → esm/src/engine}/graphics/offscreen-system.d.ts +2 -2
  91. package/build/{dist → esm/src/engine}/graphics/parallax-component.d.ts +1 -0
  92. package/build/{dist → esm/src/engine}/graphics/post-processor/color-blindness-post-processor.d.ts +3 -5
  93. package/build/esm/src/engine/graphics/post-processor/post-processor.d.ts +66 -0
  94. package/build/esm/src/engine/graphics/post-processor/shader-pipeline-post-processor.d.ts +45 -0
  95. package/build/{dist → esm/src/engine}/graphics/sprite-font.d.ts +3 -3
  96. package/build/{dist → esm/src/engine}/index.d.ts +5 -5
  97. package/build/{dist → esm/src/engine}/input/gamepad.d.ts +4 -7
  98. package/build/{dist → esm/src/engine}/input/keyboard.d.ts +3 -3
  99. package/build/{dist → esm/src/engine}/input/pointer-component.d.ts +1 -0
  100. package/build/{dist → esm/src/engine}/input/pointer-event-receiver.d.ts +13 -0
  101. package/build/{dist → esm/src/engine}/input/pointer-system.d.ts +3 -3
  102. package/build/{dist → esm/src/engine}/interfaces/index.d.ts +0 -2
  103. package/build/{dist → esm/src/engine}/label.d.ts +2 -2
  104. package/build/esm/src/engine/lighting/cone-light-component.d.ts +47 -0
  105. package/build/esm/src/engine/lighting/darkness-component.d.ts +34 -0
  106. package/build/esm/src/engine/lighting/flicker-options.d.ts +17 -0
  107. package/build/esm/src/engine/lighting/flicker-system.d.ts +19 -0
  108. package/build/esm/src/engine/lighting/index.d.ts +8 -0
  109. package/build/esm/src/engine/lighting/light-occluder-component.d.ts +66 -0
  110. package/build/esm/src/engine/lighting/lighting-config.d.ts +47 -0
  111. package/build/esm/src/engine/lighting/lighting-system.d.ts +153 -0
  112. package/build/esm/src/engine/lighting/point-light-component.d.ts +46 -0
  113. package/build/{dist → esm/src/engine}/math/affine-matrix.d.ts +8 -1
  114. package/build/esm/src/engine/math/coord-plane.d.ts +52 -0
  115. package/build/{dist → esm/src/engine}/math/graph.d.ts +2 -3
  116. package/build/{dist → esm/src/engine}/math/index.d.ts +2 -0
  117. package/build/{dist → esm/src/engine}/math/line-segment.d.ts +1 -1
  118. package/build/{dist → esm/src/engine}/math/matrix.d.ts +25 -0
  119. package/build/{dist → esm/src/engine}/math/ray.d.ts +1 -1
  120. package/build/{dist → esm/src/engine}/math/transform.d.ts +9 -0
  121. package/build/{dist → esm/src/engine}/math/vector.d.ts +16 -13
  122. package/build/esm/src/engine/math/vector3.d.ts +163 -0
  123. package/build/esm/src/engine/math/vector4.d.ts +157 -0
  124. package/build/{dist → esm/src/engine}/particles/gpu-particle-emitter.d.ts +2 -2
  125. package/build/{dist → esm/src/engine}/particles/particle-emitter.d.ts +2 -2
  126. package/build/{dist → esm/src/engine}/particles/particles.d.ts +6 -1
  127. package/build/esm/src/engine/plugin.d.ts +253 -0
  128. package/build/{dist → esm/src/engine}/resources/resource.d.ts +8 -0
  129. package/build/{dist → esm/src/engine}/resources/sound/index.d.ts +1 -1
  130. package/build/esm/src/engine/resources/sound/sound-manager.d.ts +378 -0
  131. package/build/esm/src/engine/resources/sound/sound-track.d.ts +176 -0
  132. package/build/esm/src/engine/resources/sound/sound.d.ts +351 -0
  133. package/build/{dist → esm/src/engine}/scene.d.ts +13 -7
  134. package/build/{dist → esm/src/engine}/screen-element.d.ts +2 -2
  135. package/build/{dist → esm/src/engine}/screen.d.ts +97 -29
  136. package/build/{dist → esm/src/engine}/tile-map/isometric-entity-component.d.ts +1 -0
  137. package/build/{dist → esm/src/engine}/tile-map/isometric-entity-system.d.ts +2 -3
  138. package/build/{dist → esm/src/engine}/tile-map/isometric-map.d.ts +0 -10
  139. package/build/{dist → esm/src/engine}/tile-map/tile-map.d.ts +2 -0
  140. package/build/{dist → esm/src/engine}/timer.d.ts +5 -8
  141. package/build/{dist/util/pool.d.ts → esm/src/engine/util/arena-pool.d.ts} +15 -4
  142. package/build/{dist → esm/src/engine}/util/browser.d.ts +8 -0
  143. package/build/{dist → esm/src/engine}/util/detector.d.ts +1 -1
  144. package/build/{dist → esm/src/engine}/util/draw-util.d.ts +2 -2
  145. package/build/{dist → esm/src/engine}/util/index.d.ts +0 -1
  146. package/build/{dist → esm/src/engine}/util/pause-system.d.ts +7 -1
  147. package/build/{dist → esm/src/engine}/util/rental-pool.d.ts +1 -0
  148. package/build/{dist → esm/src/engine}/util/serializer.d.ts +1 -1
  149. package/build/{dist → esm/src/engine}/util/state-machine.d.ts +1 -1
  150. package/package.json +38 -44
  151. package/tsconfig.json +38 -1
  152. package/.devcontainer/devcontainer.json +0 -26
  153. package/.git-blame-ignore-revs +0 -3
  154. package/.gitattributes +0 -70
  155. package/.gitmodules +0 -0
  156. package/.husky/pre-commit +0 -1
  157. package/.prettierrc +0 -8
  158. package/build/dist/collision/solver/realistic-solver.d.ts +0 -28
  159. package/build/dist/deprecated.d.ts +0 -0
  160. package/build/dist/entity-component-system/tag-query.d.ts +0 -28
  161. package/build/dist/excalibur.development.js +0 -35408
  162. package/build/dist/excalibur.js +0 -35408
  163. package/build/dist/excalibur.min.development.js +0 -931
  164. package/build/dist/excalibur.min.js +0 -931
  165. package/build/dist/graphics/context/material.d.ts +0 -102
  166. package/build/dist/graphics/context/render-source.d.ts +0 -7
  167. package/build/dist/graphics/context/render-target.d.ts +0 -60
  168. package/build/dist/graphics/post-processor/post-processor.d.ts +0 -36
  169. package/build/dist/interfaces/audio-implementation.d.ts +0 -25
  170. package/build/dist/interfaces/audio.d.ts +0 -55
  171. package/build/dist/math/coord-plane.d.ts +0 -15
  172. package/build/dist/resources/sound/sound-manager.d.ts +0 -102
  173. package/build/dist/resources/sound/sound.d.ts +0 -215
  174. package/build/dist/resources/sound/web-audio-instance.d.ts +0 -49
  175. package/build/dist/util/decorators.d.ts +0 -15
  176. package/build/dist/util/easing-functions.d.ts +0 -89
  177. package/build/dist/util/sound.d.ts +0 -5
  178. package/deno.json +0 -10
  179. package/eslint.config.mjs +0 -210
  180. package/playground/README.md +0 -71
  181. package/playground/index.html +0 -75
  182. package/playground/package-lock.json +0 -1976
  183. package/playground/package.json +0 -27
  184. package/playground/public/favicon.ico +0 -0
  185. package/playground/public/icon.png +0 -0
  186. package/playground/public/logo-white@2x.png +0 -0
  187. package/playground/public/logo@2x.png +0 -0
  188. package/playground/public/player-run.png +0 -0
  189. package/playground/public/rpg-audio/License.txt +0 -21
  190. package/playground/public/rpg-audio/audio/handleCoins.ogg +0 -0
  191. package/playground/public/social.jpg +0 -0
  192. package/playground/public/social.png +0 -0
  193. package/playground/public/tiny-town/License.txt +0 -22
  194. package/playground/public/tiny-town/tilemap/tilemap.png +0 -0
  195. package/playground/tsconfig.json +0 -26
  196. package/playground/tsdown.config.ts +0 -13
  197. package/playground/vite.config.ts +0 -5
  198. package/vite.config.common.js +0 -27
  199. package/vite.config.ts +0 -78
  200. package/vitest.config.ts +0 -41
  201. /package/build/{dist → esm/src/engine}/actions/action/action-sequence.d.ts +0 -0
  202. /package/build/{dist → esm/src/engine}/actions/action/blink.d.ts +0 -0
  203. /package/build/{dist → esm/src/engine}/actions/action/call-method.d.ts +0 -0
  204. /package/build/{dist → esm/src/engine}/actions/action/curve-by.d.ts +0 -0
  205. /package/build/{dist → esm/src/engine}/actions/action/curve-to.d.ts +0 -0
  206. /package/build/{dist → esm/src/engine}/actions/action/delay.d.ts +0 -0
  207. /package/build/{dist → esm/src/engine}/actions/action/die.d.ts +0 -0
  208. /package/build/{dist → esm/src/engine}/actions/action/ease-by.d.ts +0 -0
  209. /package/build/{dist → esm/src/engine}/actions/action/ease-to.d.ts +0 -0
  210. /package/build/{dist → esm/src/engine}/actions/action/fade.d.ts +0 -0
  211. /package/build/{dist → esm/src/engine}/actions/action/flash.d.ts +0 -0
  212. /package/build/{dist → esm/src/engine}/actions/action/follow.d.ts +0 -0
  213. /package/build/{dist → esm/src/engine}/actions/action/meet.d.ts +0 -0
  214. /package/build/{dist → esm/src/engine}/actions/action/parallel-actions.d.ts +0 -0
  215. /package/build/{dist → esm/src/engine}/actions/action/repeat.d.ts +0 -0
  216. /package/build/{dist → esm/src/engine}/actions/action/rotate-to.d.ts +0 -0
  217. /package/build/{dist → esm/src/engine}/actions/action/scale-by.d.ts +0 -0
  218. /package/build/{dist → esm/src/engine}/actions/action/scale-to.d.ts +0 -0
  219. /package/build/{dist → esm/src/engine}/actions/action-queue.d.ts +0 -0
  220. /package/build/{dist → esm/src/engine}/actions/action.d.ts +0 -0
  221. /package/build/{dist → esm/src/engine}/actions/actionable.d.ts +0 -0
  222. /package/build/{dist → esm/src/engine}/collision/colliders/composite-collider.d.ts +0 -0
  223. /package/build/{dist → esm/src/engine}/collision/collision-type.d.ts +0 -0
  224. /package/build/{dist → esm/src/engine}/collision/detection/collision-processor.d.ts +0 -0
  225. /package/build/{dist → esm/src/engine}/collision/detection/dynamic-tree-collision-processor.d.ts +0 -0
  226. /package/build/{dist → esm/src/engine}/collision/detection/ray-cast-hit.d.ts +0 -0
  227. /package/build/{dist → esm/src/engine}/collision/detection/ray-cast-options.d.ts +0 -0
  228. /package/build/{dist → esm/src/engine}/collision/detection/spatial-partition-strategy.d.ts +0 -0
  229. /package/build/{dist → esm/src/engine}/collision/group/collision-group.d.ts +0 -0
  230. /package/build/{dist → esm/src/engine}/collision/integrator.d.ts +0 -0
  231. /package/build/{dist → esm/src/engine}/collision/island.d.ts +0 -0
  232. /package/build/{dist → esm/src/engine}/collision/side.d.ts +0 -0
  233. /package/build/{dist → esm/src/engine}/collision/solver/arcade-solver.d.ts +0 -0
  234. /package/build/{dist → esm/src/engine}/collision/solver/contact-bias.d.ts +0 -0
  235. /package/build/{dist → esm/src/engine}/collision/solver/contact-constraint-point.d.ts +0 -0
  236. /package/build/{dist → esm/src/engine}/collision/solver-strategy.d.ts +0 -0
  237. /package/build/{dist → esm/src/engine}/color.d.ts +0 -0
  238. /package/build/{dist → esm/src/engine}/context.d.ts +0 -0
  239. /package/build/{dist → esm/src/engine}/debug/debug-flags.d.ts +0 -0
  240. /package/build/{dist → esm/src/engine}/debug/index.d.ts +0 -0
  241. /package/build/{dist → esm/src/engine}/director/cross-fade.d.ts +0 -0
  242. /package/build/{dist → esm/src/engine}/director/default-loader.d.ts +0 -0
  243. /package/build/{dist → esm/src/engine}/director/fade-in-out.d.ts +0 -0
  244. /package/build/{dist → esm/src/engine}/director/index.d.ts +0 -0
  245. /package/build/{dist → esm/src/engine}/director/loader.d.ts +0 -0
  246. /package/build/{dist → esm/src/engine}/entity-component-system/entity-manager.d.ts +0 -0
  247. /package/build/{dist → esm/src/engine}/entity-component-system/priority.d.ts +0 -0
  248. /package/build/{dist → esm/src/engine}/entity-component-system/query-manager.d.ts +0 -0
  249. /package/build/{dist → esm/src/engine}/entity-component-system/system-manager.d.ts +0 -0
  250. /package/build/{dist → esm/src/engine}/entity-component-system/types.d.ts +0 -0
  251. /package/build/{dist → esm/src/engine}/event-emitter.d.ts +0 -0
  252. /package/build/{dist → esm/src/engine}/events/ex-event.d.ts +0 -0
  253. /package/build/{dist → esm/src/engine}/events/pointer-events.d.ts +0 -0
  254. /package/build/{dist → esm/src/engine}/excalibur.d.ts +0 -0
  255. /package/build/{dist → esm/src/engine}/flags.d.ts +0 -0
  256. /package/build/{dist → esm/src/engine}/garbage-collector.d.ts +0 -0
  257. /package/build/{dist → esm/src/engine}/graphics/canvas.d.ts +0 -0
  258. /package/build/{dist → esm/src/engine}/graphics/circle.d.ts +0 -0
  259. /package/build/{dist → esm/src/engine}/graphics/context/debug-circle-renderer/debug-circle-renderer.d.ts +0 -0
  260. /package/build/{dist → esm/src/engine}/graphics/context/debug-line-renderer/debug-line-renderer.d.ts +0 -0
  261. /package/build/{dist → esm/src/engine}/graphics/context/debug-point-renderer/debug-point-renderer.d.ts +0 -0
  262. /package/build/{dist → esm/src/engine}/graphics/context/draw-call.d.ts +0 -0
  263. /package/build/{dist → esm/src/engine}/graphics/context/image-renderer/image-renderer.d.ts +0 -0
  264. /package/build/{dist → esm/src/engine}/graphics/context/image-renderer-v2/image-renderer-v2.d.ts +0 -0
  265. /package/build/{dist → esm/src/engine}/graphics/context/particle-renderer/particle-renderer.d.ts +0 -0
  266. /package/build/{dist → esm/src/engine}/graphics/context/quad-index-buffer.d.ts +0 -0
  267. /package/build/{dist → esm/src/engine}/graphics/context/rectangle-renderer/rectangle-renderer.d.ts +0 -0
  268. /package/build/{dist → esm/src/engine}/graphics/context/renderer.d.ts +0 -0
  269. /package/build/{dist → esm/src/engine}/graphics/context/screen-pass-painter/screen-pass-painter.d.ts +0 -0
  270. /package/build/{dist → esm/src/engine}/graphics/context/state-stack.d.ts +0 -0
  271. /package/build/{dist → esm/src/engine}/graphics/context/transform-stack.d.ts +0 -0
  272. /package/build/{dist → esm/src/engine}/graphics/context/uniform-buffer.d.ts +0 -0
  273. /package/build/{dist → esm/src/engine}/graphics/context/vertex-buffer.d.ts +0 -0
  274. /package/build/{dist → esm/src/engine}/graphics/context/vertex-layout.d.ts +0 -0
  275. /package/build/{dist → esm/src/engine}/graphics/debug.d.ts +0 -0
  276. /package/build/{dist → esm/src/engine}/graphics/font-cache.d.ts +0 -0
  277. /package/build/{dist → esm/src/engine}/graphics/graphic.d.ts +0 -0
  278. /package/build/{dist → esm/src/engine}/graphics/graphics-diagnostics.d.ts +0 -0
  279. /package/build/{dist → esm/src/engine}/graphics/line.d.ts +0 -0
  280. /package/build/{dist → esm/src/engine}/graphics/nine-slice.d.ts +0 -0
  281. /package/build/{dist → esm/src/engine}/graphics/polygon.d.ts +0 -0
  282. /package/build/{dist → esm/src/engine}/graphics/post-processor/color-blindness-mode.d.ts +0 -0
  283. /package/build/{dist → esm/src/engine}/graphics/post-processor/screen-shader.d.ts +0 -0
  284. /package/build/{dist → esm/src/engine}/graphics/raster.d.ts +0 -0
  285. /package/build/{dist → esm/src/engine}/graphics/rectangle.d.ts +0 -0
  286. /package/build/{dist → esm/src/engine}/graphics/sprite-sheet.d.ts +0 -0
  287. /package/build/{dist → esm/src/engine}/graphics/sprite.d.ts +0 -0
  288. /package/build/{dist → esm/src/engine}/graphics/text.d.ts +0 -0
  289. /package/build/{dist → esm/src/engine}/graphics/tiled-animation.d.ts +0 -0
  290. /package/build/{dist → esm/src/engine}/graphics/tiled-sprite.d.ts +0 -0
  291. /package/build/{dist → esm/src/engine}/graphics/transform-interpolation.d.ts +0 -0
  292. /package/build/{dist → esm/src/engine}/graphics/wrapping.d.ts +0 -0
  293. /package/build/{dist → esm/src/engine}/id.d.ts +0 -0
  294. /package/build/{dist → esm/src/engine}/input/capture-pointer-config.d.ts +0 -0
  295. /package/build/{dist → esm/src/engine}/input/input-host.d.ts +0 -0
  296. /package/build/{dist → esm/src/engine}/input/input-mapper.d.ts +0 -0
  297. /package/build/{dist → esm/src/engine}/input/native-pointer-button.d.ts +0 -0
  298. /package/build/{dist → esm/src/engine}/input/pointer-abstraction.d.ts +0 -0
  299. /package/build/{dist → esm/src/engine}/input/pointer-button.d.ts +0 -0
  300. /package/build/{dist → esm/src/engine}/input/pointer-event.d.ts +0 -0
  301. /package/build/{dist → esm/src/engine}/input/pointer-events-to-object-dispatcher.d.ts +0 -0
  302. /package/build/{dist → esm/src/engine}/input/pointer-scope.d.ts +0 -0
  303. /package/build/{dist → esm/src/engine}/input/pointer-type.d.ts +0 -0
  304. /package/build/{dist → esm/src/engine}/input/wheel-delta-mode.d.ts +0 -0
  305. /package/build/{dist → esm/src/engine}/input/wheel-event.d.ts +0 -0
  306. /package/build/{dist → esm/src/engine}/interfaces/clonable.d.ts +0 -0
  307. /package/build/{dist → esm/src/engine}/interfaces/evented.d.ts +0 -0
  308. /package/build/{dist → esm/src/engine}/interfaces/lifecycle-events.d.ts +0 -0
  309. /package/build/{dist → esm/src/engine}/interfaces/loadable.d.ts +0 -0
  310. /package/build/{dist → esm/src/engine}/interfaces/pointer-event-handlers.d.ts +0 -0
  311. /package/build/{dist → esm/src/engine}/math/bezier-curve.d.ts +0 -0
  312. /package/build/{dist → esm/src/engine}/math/easings.d.ts +0 -0
  313. /package/build/{dist → esm/src/engine}/math/global-coordinates.d.ts +0 -0
  314. /package/build/{dist → esm/src/engine}/math/lerp.d.ts +0 -0
  315. /package/build/{dist → esm/src/engine}/math/projection.d.ts +0 -0
  316. /package/build/{dist → esm/src/engine}/math/random.d.ts +0 -0
  317. /package/build/{dist → esm/src/engine}/math/rotation-type.d.ts +0 -0
  318. /package/build/{dist → esm/src/engine}/math/util.d.ts +0 -0
  319. /package/build/{dist → esm/src/engine}/math/vector-view.d.ts +0 -0
  320. /package/build/{dist → esm/src/engine}/math/watch-vector.d.ts +0 -0
  321. /package/build/{dist → esm/src/engine}/particles/emitter-type.d.ts +0 -0
  322. /package/build/{dist → esm/src/engine}/particles/gpu-particle-renderer.d.ts +0 -0
  323. /package/build/{dist → esm/src/engine}/particles/index.d.ts +0 -0
  324. /package/build/{dist → esm/src/engine}/polyfill.d.ts +0 -0
  325. /package/build/{dist → esm/src/engine}/resources/font.d.ts +0 -0
  326. /package/build/{dist → esm/src/engine}/resources/gif.d.ts +0 -0
  327. /package/build/{dist → esm/src/engine}/resources/index.d.ts +0 -0
  328. /package/build/{dist → esm/src/engine}/resources/sound/audio-context.d.ts +0 -0
  329. /package/build/{dist → esm/src/engine}/tile-map/index.d.ts +0 -0
  330. /package/build/{dist → esm/src/engine}/trigger.d.ts +0 -0
  331. /package/build/{dist → esm/src/engine}/util/assert.d.ts +0 -0
  332. /package/build/{dist → esm/src/engine}/util/clock.d.ts +0 -0
  333. /package/build/{dist → esm/src/engine}/util/coroutine.d.ts +0 -0
  334. /package/build/{dist → esm/src/engine}/util/fps.d.ts +0 -0
  335. /package/build/{dist → esm/src/engine}/util/future.d.ts +0 -0
  336. /package/build/{dist → esm/src/engine}/util/iframe.d.ts +0 -0
  337. /package/build/{dist → esm/src/engine}/util/log.d.ts +0 -0
  338. /package/build/{dist → esm/src/engine}/util/observable.d.ts +0 -0
  339. /package/build/{dist → esm/src/engine}/util/required.d.ts +0 -0
  340. /package/build/{dist → esm/src/engine}/util/semaphore.d.ts +0 -0
  341. /package/build/{dist → esm/src/engine}/util/string.d.ts +0 -0
  342. /package/build/{dist → esm/src/engine}/util/toaster.d.ts +0 -0
  343. /package/build/{dist → esm/src/engine}/util/util.d.ts +0 -0
  344. /package/build/{dist → esm/src/engine}/util/watch.d.ts +0 -0
  345. /package/build/{dist → esm/src/engine}/util/web-audio.d.ts +0 -0
@@ -1,931 +0,0 @@
1
- /*! excalibur - 0.33.0-alpha.99+77deb55 - 2026-4-2
2
- https://github.com/excaliburjs/Excalibur
3
- Copyright (c) 2026 Excalibur.js <https://github.com/excaliburjs/Excalibur/graphs/contributors>
4
- Licensed BSD-2-Clause
5
- @preserve */
6
- (function(u,ze){typeof exports=="object"&&typeof module!="undefined"?ze(exports):typeof define=="function"&&define.amd?define(["exports"],ze):(u=typeof globalThis!="undefined"?globalThis:u||self,ze(u.ex={}))})(this,function(u){"use strict";function ze(){if(typeof window=="undefined"&&(window={audioContext:function(){}}),typeof window!="undefined"&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(r){window.setInterval(r,1e3/60)}),typeof window!="undefined"&&!window.cancelAnimationFrame&&(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),typeof window!="undefined"&&!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}typeof window!="undefined"&&!window.devicePixelRatio&&(window.devicePixelRatio=window.devicePixelRatio||1),typeof window!="undefined"&&!window.requestIdleCallback&&(window.requestIdleCallback=window.requestIdleCallback||function(r){const t=Date.now();return setTimeout(function(){r({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})},1)},window.cancelIdleCallback=window.cancelIdleCallback||function(r){clearTimeout(r)})}const xs=class ie{static useCanvasGraphicsContext(){ie.enable("use-canvas-context")}static useLegacyImageRenderer(){ie.enable("use-legacy-image-renderer")}static freeze(){ie._FROZEN=!0}static _reset(){ie._FROZEN=!1,ie._FLAGS={}}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");ie._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");ie._FLAGS[t]=!1}static isEnabled(t){return!!ie._FLAGS[t]}static show(){return Object.keys(ie._FLAGS)}};xs._FROZEN=!1,xs._FLAGS={};let Ue=xs;function we(r,t){return{type:r,value:t}}class xt{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))}}class Y{constructor(){this._paused=!1,this._empty=!0,this._listeners={},this._listenersOnce={},this._pipes=[]}clear(){this._listeners={},this._listenersOnce={},this._pipes.length=0,this._empty=!0}on(t,e){var i;return this._empty=!1,this._listeners[t]=(i=this._listeners[t])!=null?i:[],this._listeners[t].push(e),{close:()=>this.off(t,e)}}once(t,e){var i;return this._empty=!1,this._listenersOnce[t]=(i=this._listenersOnce[t])!=null?i:[],this._listenersOnce[t].push(e),{close:()=>this.off(t,e)}}off(t,e){var i,s;if(e){const n=(i=this._listeners[t])==null?void 0:i.filter(a=>a!==e);this._listeners[t]=n;const o=(s=this._listenersOnce[t])==null?void 0:s.filter(a=>a!==e);this._listenersOnce[t]=o}else delete this._listeners[t]}emit(t,e){if(this._empty||this._paused)return;const i=this._listeners[t];if(i)for(let n=0;n<i.length;n++)i[n](e);const s=this._listenersOnce[t];if(this._listenersOnce[t]=[],s)for(let n=0;n<s.length;n++)s[n](e);for(let n=0;n<this._pipes.length;n++)this._pipes[n].emit(t,e)}pipe(t){if(this===t)throw Error("Cannot pipe to self");return this._empty=!1,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}}var Oe=(r=>(r.Canvas="Canvas",r.Document="Document",r))(Oe||{}),et=(r=>(r.ShortestPath="shortest-path",r.LongestPath="longest-path",r.Clockwise="clockwise",r.CounterClockwise="counter-clockwise",r))(et||{});const ys=4294967295,Ya=Date.now();let Za=0;class le{constructor(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||Ya+Za++)>>>0,this._seed=this._mt[0];for(let e=1;e<this._n;e++){const i=this._mt[e-1]^this._mt[e-1]>>>this._w-2;this._mt[e]=(this._f*((i&4294901760)>>>16)<<16)+this._f*(i&65535)+e>>>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[e&1]&ys;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[e&1]&ys;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[e&1]&ys,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 o=this.integer(0,n.length-1);i[s++]=n[o],n.splice(o,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;for(let s=0;s<e.length-2;s++){const n=this.integer(s,e.length-1);i=e[s],e[s]=e[n],e[n]=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)}get seed(){return this._seed}}const gt=Math.PI*2;function ja(r){return r>=0?r-Math.floor(r):r-Math.ceil(r)}function q(r){return r===0?0:r<0?-1:1}function L(r,t,e){return Math.min(Math.max(t,r),e)}function cr(r,t,e){return Math.abs(r-t)<e}function Ot(r){const t=2*Math.PI;return(r%t+t)%t}function dr(r,t){const e=2*Math.PI,i=Math.abs(r-t);return Math.min(i,e-i)}function ur(r){return 180/Math.PI*r}function Qa(r){return r/180*Math.PI}const Ja=(r,t)=>Array.from(new Array(t-r+1),(e,i)=>i+r);function Xt(r,t,e=new le){return e?e.floating(r,t):r+Math.random()*(t-r)}function Ka(r,t,e=new le){return e?e.integer(r,t):Math.round(Xt(r,t))}const _r=class ${constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}static get Zero(){return new $(0,0)}static get One(){return new $(1,1)}static get Half(){return new $(.5,.5)}static get Up(){return new $(0,-1)}static get Down(){return new $(0,1)}static get Left(){return new $(-1,0)}static get Right(){return new $(1,0)}static fromAngle(t){return new $(Math.cos(t),Math.sin(t))}static isValid(t){return!(t==null||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 $(Math.min(t.x,e.x),Math.min(t.y,e.y))}static max(t,e){return new $(Math.max(t.x,e.x),Math.max(t.y,e.y))}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=$.EQUALS_EPSILON){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=$.Zero);const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}clampMagnitude(t){const e=this.magnitude,i=L(e,0,t);return this.magnitude=i,this}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}get magnitude(){return this.distance()}set magnitude(t){this.normalize().scale(t,this)}normalize(){const t=this.distance();return t===0?$.Zero:new $(this.x/t,this.y/t)}average(t){return this.add(t).scale(.5)}scale(t,e){const i=e||new $(0,0);return t instanceof $?(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 $(this.x+t.x,this.y+t.y)}sub(t,e){const i=e||new $(0,0),s=this.x-t.x,n=this.y-t.y;return i.x=s,i.y=n,i}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){if(t instanceof $)return this.x*t.y-this.y*t.x;if(typeof t=="number")return new $(t*this.y,-t*this.x)}static cross(t,e){return new $(-t*e.y,t*e.x)}perpendicular(){return new $(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Ot(Math.atan2(this.y,this.x))}angleBetween(t,e){const i=this.toAngle(),s=Ot(t);let n=0,o=0;switch(s>i?n=s-i:n=(gt-i+s)%gt,o=(n-gt)%gt,e){case et.ShortestPath:return Math.abs(n)<Math.abs(o)?n:o;case et.LongestPath:return Math.abs(n)>Math.abs(o)?n:o;case et.Clockwise:return n;case et.CounterClockwise:return o}}rotate(t,e,i){const s=i||new $(0,0);e||(e=new $(0,0));const n=Math.sin(t),o=Math.cos(t),a=o*(this.x-e.x)-n*(this.y-e.y)+e.x,h=n*(this.x-e.x)+o*(this.y-e.y)+e.y;return s.x=a,s.y=h,s}clone(t){const e=t!=null?t:new $(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})`}lerp(t,e){e=L(e,0,1);const i=new $(0,0);return i.x=this.x+(t.x-this.x)*e,i.y=this.y+(t.y-this.y)*e,i}};_r.EQUALS_EPSILON=.001;let w=_r;function y(r,t){return new w(r,t)}class bs extends w{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}}var fr=(r=>(r[r.X=12]="X",r[r.Y=13]="Y",r))(fr||{});class St{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,o){const a=new St;return a.data[0]=2/(e-t),a.data[1]=0,a.data[2]=0,a.data[3]=0,a.data[4]=0,a.data[5]=2/(s-i),a.data[6]=0,a.data[7]=0,a.data[8]=0,a.data[9]=0,a.data[10]=-2/(o-n),a.data[11]=0,a.data[12]=-(e+t)/(e-t),a.data[13]=-(s+i)/(s-i),a.data[14]=-(o+n)/(o-n),a.data[15]=1,a}clone(t){const e=t||new St;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 St;return e.data=t,e}static identity(){const t=new St;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=St.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=St.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=St.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 w){const i=e||new w(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[4]+this.data[12],o=s.x*this.data[1]+s.y*this.data[5]+this.data[13];return i.x=n,i.y=o,i}else{const i=e||new St,s=t,n=this.data[0],o=this.data[1],a=this.data[2],h=this.data[3],l=this.data[4],c=this.data[5],d=this.data[6],_=this.data[7],f=this.data[8],m=this.data[9],p=this.data[10],x=this.data[11],v=this.data[12],g=this.data[13],b=this.data[14],S=this.data[15],A=s.data[0],M=s.data[1],C=s.data[2],z=s.data[3],O=s.data[4],st=s.data[5],W=s.data[6],ct=s.data[7],K=s.data[8],V=s.data[9],ut=s.data[10],ft=s.data[11],I=s.data[12],Be=s.data[13],Le=s.data[14],ke=s.data[15];i.data[0]=n*A+l*M+f*C+v*z,i.data[1]=o*A+c*M+m*C+g*z,i.data[2]=a*A+d*M+p*C+b*z,i.data[3]=h*A+_*M+x*C+S*z,i.data[4]=n*O+l*st+f*W+v*ct,i.data[5]=o*O+c*st+m*W+g*ct,i.data[6]=a*O+d*st+p*W+b*ct,i.data[7]=h*O+_*st+x*W+S*ct,i.data[8]=n*K+l*V+f*ut+v*ft,i.data[9]=o*K+c*V+m*ut+g*ft,i.data[10]=a*K+d*V+p*ut+b*ft,i.data[11]=h*K+_*V+x*ut+S*ft,i.data[12]=n*I+l*Be+f*Le+v*ke,i.data[13]=o*I+c*Be+m*Le+g*ke,i.data[14]=a*I+d*Be+p*Le+b*ke,i.data[15]=h*I+_*Be+x*Le+S*ke;const Ii=this.getScale();return i._scaleSignX=q(Ii.x)*q(i._scaleSignX),i._scaleSignY=q(Ii.y)*q(i._scaleSignY),i}}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7],d=this.data[8],_=this.data[9],f=this.data[10],m=this.data[11],p=this.data[12],x=this.data[13],v=this.data[14],g=this.data[15],b=0,S=1;return this.data[12]=i*t+a*e+d*b+p*S,this.data[13]=s*t+h*e+_*b+x*S,this.data[14]=n*t+l*e+f*b+v*S,this.data[15]=o*t+c*e+m*b+g*S,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return y(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],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=Math.sin(t),d=Math.cos(t);return this.data[0]=d*e+c*o,this.data[1]=d*i+c*a,this.data[2]=d*s+c*h,this.data[3]=d*n+c*l,this.data[4]=d*o-c*e,this.data[5]=d*a-c*i,this.data[6]=d*h-c*s,this.data[7]=d*l-c*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=o*t,this.data[4]=a*e,this.data[5]=h*e,this.data[6]=l*e,this.data[7]=c*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(){const t=Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX());return Ot(t)}getScaleX(){const t=y(this.data[0],this.data[4]).magnitude;return this._scaleSignX*t}getScaleY(){const t=y(this.data[1],this.data[5]).magnitude;return this._scaleSignY*t}getScale(){return y(this.getScaleX(),this.getScaleY())}setScaleX(t){if(this._scaleX===t)return;this._scaleSignX=q(t);const e=y(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=q(t);const e=y(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 i=1/this.getBasisDeterminant(),s=this.data[0],n=this.data[4],o=this.data[1],a=this.data[5],h=t||St.identity();h.data[0]=a*i,h.data[1]=-o*i,h.data[4]=-n*i,h.data[5]=s*i;const l=this.data[12],c=this.data[13];return h.data[12]=-(l*h.data[0]+c*h.data[4]),h.data[13]=-(l*h.data[1]+c*h.data[5]),h}isIdentity(){return this.data[0]===1&&this.data[1]===0&&this.data[2]===0&&this.data[3]===0&&this.data[4]===0&&this.data[5]===1&&this.data[6]===0&&this.data[7]===0&&this.data[8]===0&&this.data[9]===0&&this.data[10]===1&&this.data[11]===0&&this.data[12]===0&&this.data[13]===0&&this.data[14]===0&&this.data[15]===1}toString(){return`
7
- [${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]
8
- [${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]
9
- [${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]
10
- [${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]
11
- `}}class tt{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 tt;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=tt.identity();return i.data[4]=t,i.data[5]=e,i}static scale(t,e){const i=tt.identity();return i.data[0]=t,i.data[3]=e,i._scale[0]=t,i._scale[1]=e,i}static rotation(t){const e=tt.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 y(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],o=Math.sin(t),a=Math.cos(t);return this.data[0]=a*e+o*s,this.data[1]=a*i+o*n,this.data[2]=a*s-o*e,this.data[3]=a*n-o*i,this}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5];return this.data[4]=i*t+n*e+a,this.data[5]=s*t+o*e+h,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*e,this.data[3]=o*e,this._scale[0]=t,this._scale[1]=e,this._scaleSignX=q(t),this._scaleSignY=q(e),this}determinant(){return this.data[0]*this.data[3]-this.data[1]*this.data[2]}inverse(t){const e=this.determinant();let i=e;e!==0&&(i=1/e);const s=this.data[0],n=this.data[2],o=this.data[1],a=this.data[3],h=t||tt.identity();h.data[0]=a*i,h.data[1]=-o*i,h.data[2]=-n*i,h.data[3]=s*i;const l=this.data[4],c=this.data[5];return h.data[4]=-(l*h.data[0]+c*h.data[2]),h.data[5]=-(l*h.data[1]+c*h.data[3]),h}multiply(t,e){if(t instanceof w){const i=e||new w(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[2]+this.data[4],o=s.x*this.data[1]+s.y*this.data[3]+this.data[5];return i.x=n,i.y=o,i}else{const i=e||new tt,s=t,n=this.data[0],o=this.data[1],a=this.data[2],h=this.data[3],l=this.data[4],c=this.data[5],d=s.data[0],_=s.data[1],f=s.data[2],m=s.data[3],p=s.data[4],x=s.data[5];i.data[0]=n*d+a*_,i.data[1]=o*d+h*_,i.data[2]=n*f+a*m,i.data[3]=o*f+h*m,i.data[4]=n*p+a*x+l,i.data[5]=o*p+h*x+c;const v=this._scaleSignX,g=this._scaleSignY;return i._scaleSignX=v*q(i._scaleSignX),i._scaleSignY=g*q(i._scaleSignY),i}}multiplyQuadInPlace(t){const e=t[0]*this.data[0]+t[1]*this.data[2]+this.data[4],i=t[0]*this.data[1]+t[1]*this.data[3]+this.data[5];t[0]=e,t[1]=i;const s=t[2]*this.data[0]+t[3]*this.data[2]+this.data[4],n=t[2]*this.data[1]+t[3]*this.data[3]+this.data[5];t[2]=s,t[3]=n;const o=t[4]*this.data[0]+t[5]*this.data[2]+this.data[4],a=t[4]*this.data[1]+t[5]*this.data[3]+this.data[5];t[4]=o,t[5]=a;const h=t[6]*this.data[0]+t[7]*this.data[2]+this.data[4],l=t[6]*this.data[1]+t[7]*this.data[3]+this.data[5];t[6]=h,t[7]=l}to4x4(){const t=new St;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(){const t=Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX());return Ot(t)}getScaleX(){const t=this.data[0]*this.data[0]+this.data[2]*this.data[2];return t===1?this._scaleSignX:this._scaleSignX*Math.sqrt(t)}getScaleY(){const t=this.data[1]*this.data[1]+this.data[3]*this.data[3];return t===1?this._scaleSignY:this._scaleSignY*Math.sqrt(t)}getScale(){return y(this.getScaleX(),this.getScaleY())}setScaleX(t){if(t===this._scale[0])return;this._scaleSignX=q(t);const e=y(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=q(t);const e=y(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 this.data[0]===1&&this.data[1]===0&&this.data[2]===0&&this.data[3]===1&&this.data[4]===0&&this.data[5]===0}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 tt;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._scaleSignX=this._scaleSignX,e._scaleSignY=this._scaleSignY,e}toString(){return`
12
- [${this.data[0]} ${this.data[2]} ${this.data[4]}]
13
- [${this.data[1]} ${this.data[3]} ${this.data[5]}]
14
- [0 0 1]
15
- `}}class ce extends w{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){t!==this._x&&(this.change(t,this._y),this._x=this.original.x=t)}get y(){return this._y=this.original.y}set y(t){t!==this._y&&(this.change(this._x,t),this._y=this.original.y=t)}setTo(t,e){this.x=t,this.y=e}}class se{constructor(){this._parent=null,this._children=[],this._pos=new ce(y(0,0),()=>{this.flagDirty()}),this._globalPos=new bs({getX:()=>this.matrix.data[4],getY:()=>this.matrix.data[5],setX:t=>{if(this.parent){const{x:e}=this.parent.inverse.multiply(y(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(y(this.pos.x,t));this.pos.y=e}else this.pos.y=t;t!==this.matrix.data[5]&&this.flagDirty()}}),this._rotation=0,this._scale=new ce(y(1,1),()=>{this.flagDirty()}),this._globalScale=new bs({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}}),this._z=0,this._isDirty=!1,this._isInverseDirty=!1,this._matrix=tt.identity(),this._inverse=tt.identity(),this._scratch=tt.identity()}get parent(){return this._parent}set parent(t){if(this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._parent=t,this._parent&&this._parent._children.push(this),this.flagDirty()}get children(){return this._children}set pos(t){this._pos.x=t.x,this._pos.y=t.y}get pos(){return this._pos}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 this._globalPos}set rotation(t){const e=Ot(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=Ot(t+e);i!==this._rotation&&this.flagDirty(),this._rotation=i}get globalRotation(){return this.parent?this.matrix.getRotation():this.rotation}set scale(t){this._scale.x=t.x,this._scale.y=t.y}get scale(){return this._scale}set globalScale(t){let e=y(1,1);this.parent&&(e=this.parent.globalScale),this.scale=t.scale(y(1/e.x,1/e.y))}get globalScale(){return this._globalScale}set z(t){this._z=t,this.flagDirty()}get z(){return this._z}set globalZ(t){this.parent?this.z=t-this.parent.globalZ:this.z=t}get globalZ(){return this.parent?this.z+this.parent.globalZ:this.z}get matrix(){return this._isDirty&&(this.parent===null?this._calculateMatrix().clone(this._matrix):this.parent.matrix.multiply(this._calculateMatrix()).clone(this._matrix),this._isDirty=!1),this._matrix}get inverse(){return this._isInverseDirty&&(this.matrix.inverse(this._inverse),this._isInverseDirty=!1),this._inverse}_calculateMatrix(){return this._scratch.data[0]=Math.cos(this._rotation),this._scratch.data[1]=Math.sin(this._rotation),this._scratch.data[2]=-Math.sin(this._rotation),this._scratch.data[3]=Math.cos(this.rotation),this._scratch.data[4]=this._pos.x,this._scratch.data[5]=this._pos.y,this._scratch.scale(this._scale.x,this._scale.y),this._scratch}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=Ot(e),this._scale.x=i.x,this._scale.y=i.y,this.flagDirty()}isMirrored(){const t=q(this.scale.x)>>>31,e=q(this.scale.y)>>>31;return!!(t^e)}clone(t){const e=t!=null?t:new se;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.flagDirty(),e}cloneWithParent(t){const e=t!=null?t:new se;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.parent=this.parent,e.flagDirty(),e}toString(){return this.matrix.toString()}}var ht=(r=>(r.World="world",r.Screen="screen",r))(ht||{});class Ne{constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}static fromPagePosition(t,e,i){let s,n,o,a;arguments.length===3?(s=t,n=e,o=new w(s,n),a=i):(o=t,s=o.x,n=o.y,a=e);const h=a.screen.pageToScreenCoordinates(o),l=a.screen.screenToWorldCoordinates(h);return new Ne(l,o,h)}}class it{constructor(t,e){this.begin=t,this.end=e}clone(t){const e=t||new it(this.begin.clone(),this.end.clone());return e.begin=this.begin.clone(e.begin),e.end=this.end.clone(e.end),e}transform(t,e){const i=e||new it(w.Zero,w.Zero);return i.begin=t.multiply(this.begin,i.begin),i.end=t.multiply(this.end,i.end),i}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(){const t=this.begin,e=this.end;return t.distance(e)}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new it(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,i=!0){let s=t;i&&(s=s.normalize());const n=s.dot(this.begin)-e,o=s.dot(this.end)-e,a=[];if(n<=0&&a.push(this.begin),o<=0&&a.push(this.end),n*o<0){const h=n/(n-o);a.push(this.begin.add(this.end.sub(this.begin).scale(h)))}return a.length!==2?null:new it(a[0],a[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),o=this.end.y-this.begin.y,a=this.end.x-this.begin.x,h=(o*i-a*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?h:Math.abs(h)}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(t!==null)return new w(t,i*t+s);if(e!==null)return new w((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if(typeof arguments[0]=="number"&&typeof arguments[1]=="number")t=new w(arguments[0],arguments[1]),e=arguments[2]||0;else if(arguments[0]instanceof w)t=arguments[0],e=arguments[1]||0;else throw"Could not determine the arguments for Vector.hasPoint";const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,o=this.end.y-this.begin.y,a=i*o-s*n;return Math.abs(a)>e?!1:Math.abs(n)>=Math.abs(o)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:o>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y}}class ri{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 xe{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(this.dir.cross(t.getSlope())===0&&e.cross(this.dir)!==0)return-1;const i=this.dir.cross(t.getSlope());if(i===0)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))}}function X(r,t,e){return(1-e)*r+t*e}function Cs(r,t,e,i){const s=(r-t+gt)%gt>=Math.PI,n=Math.abs(t-r),o=gt-n;let a=0,h=0;n>o?(a=o,h=n):(a=n,h=o);let l=0,c=1;switch(e){case et.ShortestPath:l=a,c=s?1:-1;break;case et.LongestPath:l=h,c=s?-1:1;break;case et.Clockwise:c=1,l=s?a:h;break;case et.CounterClockwise:c=-1,l=s?h:a;break}return r+c*(l*i)}function oi(r,t,e){return r.scale(1-e).add(t.scale(e))}function gr(r,t,e){return(e-r)/(t-r)}function pr(r,t,e){const i=e.sub(r),s=t.sub(r),n=i.x/s.x,o=i.y/s.y;return Math.min(n,o)}function $t(r,t,e,i,s){const n=gr(r,t,s);return X(e,i,n)}function th(r,t,e,i,s){const n=pr(r,t,s);return oi(e,i,n)}class ai{constructor(t){this._distLookup=[],this.quality=4;var e;if(t.controlPoints.length!==4)throw new Error("Only cubic bezier curves are supported");this._controlPoints=[...t.controlPoints],this.quality=(e=t.quality)!=null?e:this.quality,this._calculateLookup()}get arcLength(){return this._arcLength}get controlPoints(){return this._controlPoints}set controlPoints(t){this._controlPoints=[...t],this._calculateLookup()}setControlPoint(t,e){this._controlPoints[t]=e,this._calculateLookup()}_calculateLookup(){let t=0;this._distLookup.length=0;let e=this.controlPoints[0];const i=this.controlPoints.length*this.quality;for(let s=0;s<i;s++){const n=s/(i-1),o=this.getPoint(n),a=e.distance(o);t+=a,this._distLookup.push(t),e=o}this._arcLength=t}_getTimeGivenDistance(t){const e=this._distLookup.length,i=this.arcLength;if(t>=0&&t<i){for(let s=0;s<e-1;s++)if(this._distLookup[s]<=t&&t<this._distLookup[s+1])return $t(this._distLookup[s],this._distLookup[s+1],s/(e-1),(s+1)/(e-1),t)}return t/i}getPoint(t){const e=[...this.controlPoints];for(let i=1;i<e.length;i++)for(let s=0;s<e.length-i;s++)e[s]=oi(e[s],e[s+1],t);return e[0]}getTangent(t){const e=t*t,i=this.controlPoints[0],s=this.controlPoints[1],n=this.controlPoints[2],o=this.controlPoints[3];return i.scale(-3*e+6*t-3).add(s.scale(9*e-12*t+3).add(n.scale(-9*e+6*t).add(o.scale(3*e)))).normalize()}getUniformTangent(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getTangent(i)}getNormal(t){return this.getTangent(t).normal()}getUniformNormal(t){return this.getUniformTangent(t).normal()}getUniformPoint(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getPoint(i)}clone(){return new ai({controlPoints:[...this.controlPoints],quality:this.quality})}}const eh=r=>(r==null?void 0:r.id)!==void 0&&typeof r.id=="string";class Ss{constructor(){this.id=Ps.generateUUID(),this._nodes=new Map,this._edges=new Set,this.adjacencyList=new Map}addNode(t,e){let i;return e?i=new mr(t,e):i=new As(t),this._nodes.set(i.id,i),this.adjacencyList.set(i.id,new Set),i}addNodes(t){for(const e of t)this.addNode(e);return this._nodes}deleteNode(t){const e=t.edges;for(const i of e)this.deleteEdge(i);return this.adjacencyList.forEach((i,s)=>{i.delete(t.id)}),this._nodes.delete(t.id),this.adjacencyList.delete(t.id),this._nodes}addEdge(t,e,i){var s,n;if(Array.from(this._edges).find(l=>l.source.id===t.id&&l.target.id===e.id))return[];let a;i?a="directed"in i?i.directed:!1:a=!1;const h=new Ts(t,e,i);if(this._edges.add(h),t.registerNewEdge(h),e.registerNewEdge(h),(s=this.adjacencyList.get(t.id))==null||s.add(e.id),!a){const l=new Ts(e,t,i);return(n=this.adjacencyList.get(e.id))==null||n.add(t.id),this._edges.add(l),e.registerNewEdge(l),t.registerNewEdge(l),h.linkWithPartner(l),l.linkWithPartner(h),[h,l]}return[h]}deleteEdge(t){t.source.breakEdge(t),t.target.breakEdge(t),this._edges.delete(t);const e=t.partnerEdge;e&&(e.source.breakEdge(e),e.target.breakEdge(e),this._edges.delete(e))}get nodes(){return this._nodes}getNode(t){return this._nodes.get(t)}get edges(){return this._edges}getNeighbors(t){var e;return Array.from((e=this.adjacencyList.get(t.id))!=null?e:[]).map(i=>this.nodes.get(i))}areNodesConnected(t,e){var i,s;return(s=(i=this.adjacencyList.get(t.id))==null?void 0:i.has(e.id))!=null?s:!1}reset(){this._nodes.clear(),this._edges.clear(),this.adjacencyList.clear()}bfs(t){if(!this._nodes.has(t.id))return[];const e=[t.id],i=new Set([t.id]);for(;e.length>0;){const s=e.shift(),n=this.adjacencyList.get(s)||new Set;for(const o of n)i.has(o)||(i.add(o),e.push(o))}return Array.from(i)}dfs(t,e=new Set){var i;const s=t.id;if(!this._nodes.has(s))return[];e.add(s);let n=[s];for(const o of(i=this.adjacencyList.get(s))!=null?i:[])e.has(o)||(n=n.concat(this.dfs(this._nodes.get(o),e)));return n}static createGraphFromNodes(t){const e=new Ss;return e.addNodes(t),e}dijkstra(t){const e=[],i=[],s=[];this.nodes.forEach(l=>{i.push(l),s.push({node:l,distance:1/0,previous:null})});const n=s.findIndex(l=>l.node===t);if(n===-1)return[];s[n].distance=0,e.push(t),i.splice(i.indexOf(t),1);let o=t;const a=o.edges,h=Array.from(a).filter(l=>l.target!==o);for(const l of h){const c=s.findIndex(d=>d.node===l.target);if(c===-1)return[];s[c].distance=l.weight,s[c].previous=o}for(;i.length>0;){let l=[],c=[];c=s.filter(m=>i.includes(m.node)),l=c.map(m=>m.node);let d=1/0,_=-1;if(l.length>0)for(let m=0;m<l.length;m++){const p=l[m],x=s.findIndex(v=>v.node===p);s[x].distance<d&&(d=s[x].distance,_=x)}else{d=1/0,_=-1;for(let m=0;m<i.length;m++){const p=i[m],x=s.findIndex(v=>v.node===p);s[x].distance<d&&(d=s[x].distance,_=x)}}if(_===-1)break;o=s[_].node;let f=Array.from(o.edges);f=f.filter(m=>!e.includes(m.source)&&!e.includes(m.target)&&m.target!==o),e.push(o),i.splice(i.indexOf(o),1);for(let m=0;m<f.length;m++){const p=f[m],x=s.findIndex(S=>S.node===p.target),v=s.findIndex(S=>S.node===p.source),b=s[v].distance+p.weight;b<s[x].distance&&(s[x].distance=b,s[x].previous=o)}}return s}shortestPathDijkstra(t,e){var i,s;const n=this.dijkstra(t);if(n.length===0)return{path:[],distance:1/0};const o=[];let a=e;const h=(i=n.find(l=>l.node===e))==null?void 0:i.distance;if(h===1/0)return{path:[],distance:1/0};for(;a!=null&&(o.push(a),a=(s=n.find(l=>l.node===a))==null?void 0:s.previous,a!=null););return o.reverse(),{path:o,distance:h}}aStar(t,e){if(!("pos"in t)||!("pos"in e))throw new Error("A* algorithm requires PositionNode with position vectors");const i=new Set([t.id]),s=new Set,n=new Set,o=new Map,a=new Map,h=new Map,l=new Map,c=new Map;for(const[d,_]of this._nodes)"pos"in _?c.set(d,_):n.add(d);for(const[d]of c)o.set(d,this._euclideanDistance(c.get(d),t)),a.set(d,this._euclideanDistance(c.get(d),e)),h.set(d,o.get(d)+a.get(d)),l.set(d,null);for(;i.size>0;){let d=null,_=1/0;for(const p of i){const x=h.get(p)||1/0;x<_&&(_=x,d=p)}if(d===null)break;if(d===e.id){const p=[];let x=e.id;for(;x!==null;){const v=this._nodes.get(x);p.unshift(v),x=l.get(x)}return{path:p,pathSteps:p.length-1,distance:o.get(e.id)||1/0,skippedNodes:n}}i.delete(d),s.add(d);const f=this._nodes.get(d),m=this.getNeighbors(f);for(const p of m){const x=p.id;s.has(x)||!("pos"in p)||!Array.from(f.edges).find(b=>b.source.id===d&&b.target.id===x)||(l.set(x,d),i.has(x)||i.add(x))}}return{path:[],pathSteps:0,distance:1/0,skippedNodes:n}}_euclideanDistance(t,e){const i=t.pos,s=e.pos;return Math.sqrt((s.x-i.x)**2+(s.y-i.y)**2)}}class Ts{constructor(t,e,i){this._id=Ps.generateUUID(),this._weight=0,this._partnerEdge=null,this._source=t,this._target=e,i&&i.weight?this._weight=i.weight:i&&i.useEuclidean?this._weight=t.pos.distance(e.pos):this._weight=0}linkWithPartner(t){this._partnerEdge=t}get id(){return this._id}get source(){return this._source}get target(){return this._target}get weight(){return this._weight}get partnerEdge(){return this._partnerEdge}}class As{constructor(t){this._id=eh(t)?t.id:Ps.generateUUID(),this._data=t,this._edges=new Set}get id(){return this._id}get data(){return this._data}get edges(){return this._edges}registerNewEdge(t){this._edges.add(t)}breakEdge(t){this._edges.delete(t)}getConnectedNodes(){return Array.from(this._edges).map(t=>t.target)}}class mr extends As{constructor(t,e){super(t),this.pos=e}}const vr=class Ga{static generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const s=Ga.rng.next()*16|0;return(i==="x"?s:s&3|8).toString(16)})}};vr.rng=new le;let Ps=vr;function Mi(r){return r}function ih(r,t,e){return r=L((r-t)/(e-t),0,1),r*r*(3-2*r)}function sh(r,t,e){return r=L((r-t)/(e-t),0,1),r*r*r*(r*(6*r-15)+10)}function nh(r){return-1*Math.cos(r*(Math.PI/2))+1}function rh(r){return Math.sin(r*(Math.PI/2))}function oh(r){return-.5*(Math.cos(Math.PI*r)-1)}function ah(r){return r*r}function hh(r){return r*(2-r)}function lh(r){return r<.5?2*r*r:-1+(4-2*r)*r}function ch(r){return r*r*r}function dh(r){const t=r-1;return t*t*t+1}function Es(r){return r<.5?4*r*r*r:(r-1)*(2*r-2)*(2*r-2)+1}function uh(r){return r*r*r*r}function _h(r){const t=r-1;return 1-t*t*t*t}function fh(r){const t=r-1;return r<.5?8*r*r*r*r:1-8*t*t*t*t}function gh(r){return r*r*r*r*r}function ph(r){const t=r-1;return 1+t*t*t*t*t}function mh(r){const t=r-1;return r<.5?16*r*r*r*r*r:1+16*t*t*t*t*t}function vh(r){return r===0?0:Math.pow(2,10*(r-1))}function wh(r){return r===1?1:-Math.pow(2,-10*r)+1}function xh(r){if(r===0||r===1)return r;const t=r*2,e=t-1;return t<1?.5*Math.pow(2,10*e):.5*(-Math.pow(2,-10*e)+2)}function yh(r){const t=r/1;return-1*(Math.sqrt(1-t*r)-1)}function bh(r){const t=r-1;return Math.sqrt(1-t*t)}function Ch(r){const t=r*2,e=t-2;return t<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-e*e)+1)}function Sh(r,t=1.70158){return r*r*((t+1)*r-t)}function Th(r,t=1.70158){const e=r/1-1;return e*e*((t+1)*e+t)+1}function Ah(r,t=1.70158){const e=r*2,i=e-2,s=t*1.525;return e<1?.5*e*e*((s+1)*e-s):.5*(i*i*((s+1)*i+s)+2)}function Ph(r,t=.7){if(r===0||r===1)return r;const i=r/1-1,s=1-t,n=s/(2*Math.PI)*Math.asin(1);return-(Math.pow(2,10*i)*Math.sin((i-n)*(2*Math.PI)/s))}function Eh(r,t=.7){if(r===0||r===1)return r;const e=1-t,i=r*2,s=e/(2*Math.PI)*Math.asin(1);return Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}function Ih(r,t=.65){if(r===0||r===1)return r;const e=1-t,i=r*2,s=i-1,n=e/(2*Math.PI)*Math.asin(1);return i<1?-.5*(Math.pow(2,10*s)*Math.sin((s-n)*(2*Math.PI)/e)):Math.pow(2,-10*s)*Math.sin((s-n)*(2*Math.PI)/e)*.5+1}function Is(r){const t=r/1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const e=t-.5454545454545454;return 7.5625*e*e+.75}else if(t<2.5/2.75){const e=t-.8181818181818182;return 7.5625*e*e+.9375}else{const e=t-.9545454545454546;return 7.5625*e*e+.984375}}function wr(r){return 1-Is(1-r)}function Rh(r){return r<.5?wr(r*2)*.5:Is(r*2-1)*.5+.5}class T{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=s!=null?s:1}get hashCode(){const t=Math.round(this.r)&255,e=Math.round(this.g)&255,i=Math.round(this.b)&255,s=Math.round(this.a*255)&255;let n=0;return n=(n<<5)-n+t,n=(n<<5)-n+e,n=(n<<5)-n+i,n=(n<<5)-n+s,n|0}static fromRGB(t,e,i,s){return new T(t,e,i,s)}static fromRGBString(t){const e=/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],10),n=parseInt(i[2],10),o=parseInt(i[3],10);let a=1;return i[4]&&(a=parseFloat(i[4])),new T(s,n,o,a)}else throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){const e=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],16),n=parseInt(i[2],16),o=parseInt(i[3],16);let a=1;return i[4]&&(a=parseInt(i[4],16)/255),new T(s,n,o,a)}else throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new yt(t,e,i,s).toRGBA()}static fromFloatArray(t){var e,i,s;const n=[(e=t[0])!=null?e:0,(i=t[1])!=null?i:0,(s=t[2])!=null?s:0].map(o=>Math.round(o*255));return new T(...n,t[3])}lighten(t=.1){const e=yt.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=yt.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=yt.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=yt.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 T(e,i,s,n)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new T(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 T(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=Math.max(Math.round(t),0).toString(16);return e.length===1?"0"+e:e}static _COMPONENT_TO_LINEAR(t,e=2.2){return Math.pow(t,e)}static _COMPONENT_FROM_LINEAR(t,e=2.2){return Math.pow(t,1/e)}toHex(){let t="#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b);return this.a!==1&&(t+=this._componentToHex(this.a*255)),t}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return this.a!==void 0||this.a!==null?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return yt.fromRGBA(this.r,this.g,this.b,this.a).toString()}toFloatArray(t){let e=[this.r/255,this.g/255,this.b/255];return t&&(e=e.map(i=>parseFloat(i.toFixed(t)))),e.push(this.a),e}fillStyle(){return this.toString()}clone(t){const e=t||new T(this.r,this.g,this.b,this.a);return e.r=this.r,e.g=this.g,e.b=this.b,e.a=this.a,e}static lerp(t,e,i,s="hsl"){switch(s){case"hsl":return T.lerpHSL(t,e,i);case"rgb":return T.lerpRGB(t,e,i);case"lrgb":return T.lerpLRGB(t,e,i)}}static lerpHSL(t,e,i){const s=yt.fromRGBA(t.r,t.g,t.b,t.a),n=yt.fromRGBA(e.r,e.g,e.b,e.a);return yt.lerp(s,n,i).toRGBA()}static lerpRGB(t,e,i){return new T(X(t.r,e.r,i),X(t.g,e.g,i),X(t.b,e.b,i),X(t.a,e.a,i))}static lerpLRGB(t,e,i,s=2.2){const n=T._COMPONENT_TO_LINEAR(t.r,s),o=T._COMPONENT_TO_LINEAR(t.g,s),a=T._COMPONENT_TO_LINEAR(t.b,s),h=T._COMPONENT_TO_LINEAR(e.r,s),l=T._COMPONENT_TO_LINEAR(e.g,s),c=T._COMPONENT_TO_LINEAR(e.b,s),d=X(n,h,i),_=X(o,l,i),f=X(a,c,i);return new T(T._COMPONENT_FROM_LINEAR(d,s),T._COMPONENT_FROM_LINEAR(_,s),T._COMPONENT_FROM_LINEAR(f,s),X(t.a,e.a,i))}static random(t){const e=t!=null?t:new le;return new T(e.integer(0,255),e.integer(0,255),e.integer(0,255))}static get Black(){return T.fromHex("#000000")}static get White(){return T.fromHex("#FFFFFF")}static get Gray(){return T.fromHex("#808080")}static get LightGray(){return T.fromHex("#D3D3D3")}static get DarkGray(){return T.fromHex("#A9A9A9")}static get Yellow(){return T.fromHex("#FFFF00")}static get Orange(){return T.fromHex("#FFA500")}static get Red(){return T.fromHex("#FF0000")}static get Vermilion(){return T.fromHex("#FF5B31")}static get Rose(){return T.fromHex("#FF007F")}static get Pink(){return T.fromHex("#FFC0CB")}static get Magenta(){return T.fromHex("#FF00FF")}static get Violet(){return T.fromHex("#7F00FF")}static get Purple(){return T.fromHex("#800080")}static get Blue(){return T.fromHex("#0000FF")}static get Azure(){return T.fromHex("#007FFF")}static get Cyan(){return T.fromHex("#00FFFF")}static get Viridian(){return T.fromHex("#59978F")}static get Teal(){return T.fromHex("#008080")}static get Green(){return T.fromHex("#00FF00")}static get Chartreuse(){return T.fromHex("#7FFF00")}static get Transparent(){return T.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return T.fromHex("#176BAA")}static get Brown(){return T.fromHex("#964B00")}}class yt{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+(e-t)*6*i:i<1/2?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),o=Math.min(t,e,i);let a,h;const l=(n+o)/2;if(n===o)a=h=0;else{const c=n-o;switch(h=l>.5?c/(2-n-o):c/(n+o),n){case t:a=(e-i)/c+(e<i?6:0);break;case e:a=(i-t)/c+2;break;case i:a=(t-e)/c+4;break}a/=6}return new yt(a,h,l,s)}toRGBA(){let t,e,i;if(this.s===0)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=yt.hue2rgb(n,s,this.h+1/3),e=yt.hue2rgb(n,s,this.h),i=yt.hue2rgb(n,s,this.h-1/3)}return new T(t*255,e*255,i*255,this.a)}toString(){const t=this.h.toFixed(0),e=this.s.toFixed(0),i=this.l.toFixed(0),s=this.a.toFixed(0);return`hsla(${t}, ${e}, ${i}, ${s})`}static lerp(t,e,i){i=Math.max(0,Math.min(1,i));let s=e.h-t.h;s>.5?s-=1:s<-.5&&(s+=1);const n=(t.h+s*i+1)%1,o=t.s+(e.s-t.s)*i,a=t.l+(e.l-t.l)*i,h=t.a+(e.a-t.a)*i;return new yt(n,o,a,h)}}var He=(r=>(r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Fatal=4]="Fatal",r))(He||{});const xr=class ae{constructor(){if(this._appenders=[],this.defaultLevel=1,this._logOnceSet=new Set,ae._INSTANCE)throw new Error("Logger is a singleton");return ae._INSTANCE=this,ae._INSTANCE.addAppender(new Rs),ae._INSTANCE}static getInstance(){return ae._INSTANCE==null&&(ae._INSTANCE=new ae),ae._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){t==null&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}_logOnce(t,e){const i=t+e.join("+");this._logOnceSet.has(i)||(this._logOnceSet.add(i),this._log(t,e))}debug(...t){this._log(0,t)}debugOnce(...t){this._logOnce(0,t)}info(...t){this._log(1,t)}infoOnce(...t){this._logOnce(1,t)}warn(...t){this._log(2,t)}warnOnce(...t){this._logOnce(2,t)}error(...t){this._log(3,t)}errorOnce(...t){this._logOnce(3,t)}fatal(...t){this._log(4,t)}fatalOnce(...t){this._logOnce(4,t)}};xr._INSTANCE=null;let F=xr;class Rs{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+He[t]+"] : "),t<2?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<3?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 yr{constructor(t){this._messages=[],this._pos=10,this._color=T.Black;var e,i;this._options=t,this.canvas=document.createElement("canvas"),this._ctx=this.canvas.getContext("2d"),this.canvas.style.position="absolute",this.canvas.style.zIndex=(i=(e=t.zIndex)==null?void 0:e.toString())!=null?i:"99",this.canvas.style.pointerEvents="none",this.canvas.style.userSelect="none",document.body.appendChild(this.canvas),this._positionScreenAppenderCanvas(),t.engine.screen.events.on("resize",()=>{this._positionScreenAppenderCanvas()})}_positionScreenAppenderCanvas(){var t,e,i,s;const n=this._options;this.canvas.width=(t=n.width)!=null?t:n.engine.screen.resolution.width,this.canvas.height=(e=n.height)!=null?e:n.engine.screen.resolution.height,this.canvas.style.position="absolute";const o=n.engine.screen.screenToPageCoordinates(y(0,0));this.canvas.style.left=o.x+"px",this.canvas.style.top=o.y+"px",this._pos=(i=n.xPos)!=null?i:this._pos,this._color=(s=n.color)!=null?s:this._color}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this._messages.unshift("["+He[t]+"] : "+i);let s=10;this._messages=this._messages.slice(0,1e3);for(let n=0;n<this._messages.length;n++)this._ctx.fillStyle=this._color.toRGBA(),this._ctx.fillText(this._messages[n],this._pos,s),s+=10}}var R=(r=>(r.PreventCollision="PreventCollision",r.Passive="Passive",r.Active="Active",r.Fixed="Fixed",r))(R||{});function br(r){return!!r&&!!r.prototype&&!!r.prototype.constructor}function Mh(r){return!!(r!=null&&r.clone)}class Rt{constructor(){this.owner=void 0}clone(){const t=new this.constructor;for(const e in this)if(this.hasOwnProperty(e)){const i=this[e];Mh(i)&&e!=="owner"&&e!=="clone"?t[e]=i.clone():t[e]=i}return t}toJSON(t=!1){return JSON.stringify(this.serialize(),null,t?2:0)}serialize(){const t={type:this.constructor.name};for(const e in this)this.hasOwnProperty(e)&&(e==="owner"||e==="dependencies"||e.startsWith("_")||typeof this[e]=="function"||!this._isSerializable(this[e])||(t[e]=this._serializeValue(this[e])));return t}deserialize(t){for(const e in t)e==="type"||e==="owner"||e==="dependencies"||this.hasOwnProperty(e)&&(this[e]=this._deserializeValue(t[e],this[e]))}_serializeValue(t){if(t==null)return t;if(t&&typeof t=="object"&&"x"in t&&"y"in t&&typeof t.x=="number"&&typeof t.y=="number")return{x:t.x,y:t.y};if(Array.isArray(t))return t.map(e=>this._serializeValue(e));if(t&&typeof t=="object"&&t.constructor===Object){const e={};for(const i in t)t.hasOwnProperty(i)&&(e[i]=this._serializeValue(t[i]));return e}if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t}_deserializeValue(t,e){return t==null?t:e&&typeof e=="object"&&"x"in e&&"y"in e&&t&&typeof t=="object"&&"x"in t&&"y"in t?(e.x=t.x,e.y=t.y,e):t}_isSerializable(t){if(t==null)return!0;const e=typeof t;return e==="string"||e==="number"||e==="boolean"?!0:!(e==="object"&&t.subscribe||e==="function")}}class pt{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);e!==-1&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);e!==-1&&this.subscriptions.splice(e,1)}notifyAll(t){const e=this.observers.length;for(let s=0;s<e;s++)this.observers[s].notify(t);const i=this.subscriptions.length;for(let s=0;s<i;s++)this.subscriptions[s](t)}clear(){this.observers.length=0,this.subscriptions.length=0}}class E extends Rt{constructor(){super(...arguments),this._logger=F.getInstance(),this._parentComponent=null,this._transform=new se,this._addChildTransform=t=>{const e=t.get(E);e&&(e._transform.parent=this._transform,e._parentComponent=this)},this.zIndexChanged$=new pt,this._coordPlane=ht.World}get(){return this._transform}onAdd(t){for(const e of t.children)this._addChildTransform(e);t.childrenAdded$.subscribe(e=>this._addChildTransform(e)),t.childrenRemoved$.subscribe(e=>{const i=e.get(E);i&&(i._transform.parent=null,i._parentComponent=null)})}onRemove(t){this._transform.parent=null,this._parentComponent=null}get z(){return this._transform.z}set z(t){const e=this._transform.z;this._transform.z=t,e!==t&&this.zIndexChanged$.notifyAll(t)}get globalZ(){return this._transform.globalZ}set globalZ(t){this._transform.globalZ=t}get coordPlane(){return this._parentComponent?this._parentComponent.coordPlane:this._coordPlane}set coordPlane(t){var e;this._parentComponent?this._logger.warn(`Cannot set coordinate plane on child entity ${(e=this.owner)==null?void 0:e.name}, children inherit their coordinate plane from their parents.`):this._coordPlane=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 E;return t._transform=this._transform.clone(),t}serialize(){const e={type:this.constructor.name,pos:{x:this.pos.x,y:this.pos.y},rotation:this.rotation,scale:{x:this.scale.x,y:this.scale.y},z:this.z};return this._parentComponent||(e.coordPlane=this._coordPlane),e}deserialize(t){this.pos={x:t.pos.x,y:t.pos.y},this.rotation=t.rotation,this.scale={x:t.scale.x,y:t.scale.y},this.z=t.z,t.coordPlane!==void 0&&!this._parentComponent&&(this._coordPlane=t.coordPlane)}}class H extends Rt{constructor(){super(...arguments),this.vel=w.Zero,this.maxVel=w.One.scaleEqual(1/0),this.acc=w.Zero,this.scaleFactor=w.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1,this.integration={onScreenOnly:!1}}}const ye=class{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 s=this._GROUPS.get(t);if(s.mask===e)return s;throw new Error(`Collision group ${t} already exists with a different mask!`)}const i=new Yt(t,this._CURRENT_BIT,e!==void 0?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}};ye._STARTING_BIT=1,ye._MAX_GROUPS=32,ye._CURRENT_GROUP=1,ye._CURRENT_BIT=ye._STARTING_BIT,ye._GROUPS=new Map;let Fi=ye;const Ms=class{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 e!==0&&i!==0}invert(){const t=Fi.create("~("+this.name+")",~this.mask|0);return t._category=~this.category,t}static combine(t){const e=t.map(n=>n.name).join("+"),s=~t.reduce((n,o)=>o.category|n,0);return Fi.create(e,s)}static collidesWith(t){const e=`collidesWith(${t.map(s=>s.name).join("+")})`,i=t.reduce((s,n)=>n.category|s,0);return Fi.create(e,i)}toString(){return`
16
- category: ${this.category.toString(2).padStart(32,"0")}
17
- mask: ${(this.mask>>>0).toString(2).padStart(32,"0")}
18
- `}};Ms.All=new Ms("Collide with all groups",-1,-1);let Yt=Ms;var Fs=(r=>(r.Kill="kill",r.PreKill="prekill",r.PostKill="postkill",r.PreDraw="predraw",r.PostDraw="postdraw",r.PreDebugDraw="predebugdraw",r.PostDebugDraw="postdebugdraw",r.PreUpdate="preupdate",r.PostUpdate="postupdate",r.PreFrame="preframe",r.PostFrame="postframe",r.PreCollision="precollision",r.CollisionStart="collisionstart",r.CollisionEnd="collisionend",r.PostCollision="postcollision",r.Initialize="initialize",r.Activate="activate",r.Deactivate="deactivate",r.ExitViewport="exitviewport",r.EnterViewport="enterviewport",r.ExitTrigger="exit",r.EnterTrigger="enter",r.Connect="connect",r.Disconnect="disconnect",r.Button="button",r.Axis="axis",r.Visible="visible",r.Hidden="hidden",r.Start="start",r.Stop="stop",r.PointerUp="pointerup",r.PointerDown="pointerdown",r.PointerMove="pointermove",r.PointerEnter="pointerenter",r.PointerLeave="pointerleave",r.PointerCancel="pointercancel",r.PointerWheel="pointerwheel",r.Up="up",r.Down="down",r.Move="move",r.Enter="enter",r.Leave="leave",r.Cancel="cancel",r.Wheel="wheel",r.Press="press",r.Release="release",r.Hold="hold",r.PointerDragStart="pointerdragstart",r.PointerDragEnd="pointerdragend",r.PointerDragEnter="pointerdragenter",r.PointerDragLeave="pointerdragleave",r.PointerDragMove="pointerdragmove",r.ActionStart="actionstart",r.ActionComplete="actioncomplete",r.Add="add",r.Remove="remove",r))(Fs||{});class k{constructor(){this.other=null,this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class Ds extends k{constructor(t){super(),this.self=t,this.target=t}}class Bs extends k{constructor(t){super(),this.self=t,this.target=t}}class Ls extends k{constructor(t){super(),this.self=t,this.target=t}}class ks extends k{constructor(t){super(),this.self=t,this.target=t}}class zs extends k{constructor(t){super(),this.self=t,this.target=t}}class Ge extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class We extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Us extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Os extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Ns extends k{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class Hs extends k{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class de extends k{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class ue extends k{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class Gs extends k{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class Ws extends k{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class Vs extends k{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class qs extends k{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Xs extends k{constructor(t,e,i,s){super(),this.button=t,this.index=e,this.value=i,this.self=s,this.target=s}}class $s extends k{constructor(t,e,i){super(),this.axis=t,this.value=e,this.self=i,this.target=i}}class Ys extends k{constructor(t){super(),this.self=t,this.target=t}}class Zs extends k{constructor(t){super(),this.self=t,this.target=t}}class be extends k{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class Ce extends k{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class Di{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.contact=s}}class Bi{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.lastContact=s}}class Li{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class ki{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class hi extends k{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.contact=s,this.target=t}}class li extends k{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.lastContact=s,this.target=t}}class Ve extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class js extends k{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class Qs extends k{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class Js extends k{constructor(t){super(),this.self=t,this.target=t}}class Ks extends k{constructor(t){super(),this.self=t,this.target=t}}class tn extends k{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class en extends k{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class sn extends k{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class nn extends k{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class rn extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class on extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class Cr extends k{constructor(t){super(),this.self=t,this.target=t}}class Sr extends k{constructor(t){super(),this.self=t,this.target=t}}const Fh=Object.freeze(Object.defineProperty({__proto__:null,ActionCompleteEvent:nn,ActionStartEvent:sn,ActivateEvent:js,AddEvent:rn,CollisionEndEvent:li,CollisionPostSolveEvent:ki,CollisionPreSolveEvent:Li,CollisionStartEvent:hi,ContactEndEvent:Bi,ContactStartEvent:Di,DeactivateEvent:Qs,EnterTriggerEvent:tn,EnterViewPortEvent:Ks,EventTypes:Fs,ExitTriggerEvent:en,ExitViewPortEvent:Js,GameEvent:k,GameStartEvent:ks,GameStopEvent:zs,GamepadAxisEvent:$s,GamepadButtonEvent:Xs,GamepadConnectEvent:Vs,GamepadDisconnectEvent:qs,HiddenEvent:Zs,InitializeEvent:Ve,KillEvent:Ds,PauseEvent:Cr,PostCollisionEvent:Ce,PostDebugDrawEvent:Hs,PostDrawEvent:We,PostFrameEvent:Ws,PostKillEvent:Ls,PostTransformDrawEvent:Os,PostUpdateEvent:ue,PreCollisionEvent:be,PreDebugDrawEvent:Ns,PreDrawEvent:Ge,PreFrameEvent:Gs,PreKillEvent:Bs,PreTransformDrawEvent:Us,PreUpdateEvent:de,RemoveEvent:on,ResumeEvent:Sr,VisibleEvent:Ys},Symbol.toStringTag,{value:"Module"}));function Tr(r){if(r.length===0)throw new Error("Cannot find minIndex of array.length == 0");let t=r[0],e=0;for(let i=1;i<r.length;i++)r[i]<t&&(t=r[i],e=i);return e}function ci(r){if(r&&r.getBoundingClientRect){const t=r.getBoundingClientRect();return y(t.x+window.scrollX,t.y+window.scrollY)}return w.Zero}function Dh(r,t){return t.indexOf(r)===-1?(t.push(r),!0):!1}function qe(r,t){let e=-1;return(e=t.indexOf(r))>-1?(t.splice(e,1),!0):!1}function Ar(r,t){for(let e=0;e<r.length;e++)if(r[e]===t)return!0;return!1}function Pr(r){throw new Error(r)}function zi(r,t){var e;const i=new xt;return((e=t==null?void 0:t.schedule.bind(t))!=null?e:setTimeout)(()=>{i.resolve()},r),i.promise}function Er(r,t){const e={};for(const i in r)t.includes(i)||(e[i]=r[i]);return e}function Ui(r){return r&&typeof r=="object"&&!Array.isArray(r)}function Oi(r,...t){if(!t.length)return r;const e=t.shift();if(Ui(r)&&Ui(e))for(const i in e)Ui(e[i])?(r[i]||Object.assign(r,{[i]:{}}),Oi(r[i],e[i])):Object.assign(r,{[i]:e[i]});return Oi(r,...t)}class Bh{constructor(t){this.data=t,this.type="Component Added"}}function Lh(r){return!!r&&r.type==="Component Added"}class kh{constructor(t){this.data=t,this.type="Component Removed"}}function zh(r){return!!r&&r.type==="Component Removed"}const Uh={Add:"add",Remove:"remove",Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate",Kill:"kill"},Ir=class ar{constructor(t,e){this.id=ar._ID++,this.name=`Entity#${this.id}`,this.events=new Y,this._tags=new Set,this.componentAdded$=new pt,this.componentRemoved$=new pt,this.tagAdded$=new pt,this.tagRemoved$=new pt,this.components=new Map,this.componentValues=[],this._componentsToRemove=[],this.scene=null,this.isActive=!0,this._parent=null,this.childrenAdded$=new pt,this.childrenRemoved$=new pt,this._children=[],this._isInitialized=!1,this._isAdded=!1;let i,s;if(Array.isArray(t))i=t,s=e;else if(t&&typeof t=="object"){const{components:n,name:o}=t;i=n!=null?n:[],s=o}if(s&&(this.name=s),i)for(const n of i)this.addComponent(n)}get active(){return this.isActive}set active(t){this.isActive=t}kill(){this.isActive&&(this.isActive=!1,this.unparent()),this.emit("kill",new Ds(this))}isKilled(){return!this.isActive}get tags(){return this._tags}hasTag(t){return this._tags.has(t)}addTag(t){return this._tags.add(t),this.tagAdded$.notifyAll(t),this}removeTag(t){return this._tags.delete(t),this.tagRemoved$.notifyAll(t),this}get types(){return Array.from(this.components.keys())}getComponents(){return Array.from(this.components.values())}hasAll(t){for(let e=0;e<t.length;e++)if(!this.components.has(t[e]))return!1;return!0}hasAllTags(t){for(let e=0;e<t.length;e++)if(!this.tags.has(t[e]))return!1;return!0}get(t){return this.components.get(t)}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}hasChild(t,e=!1){if(!e)return t.parent===this;for(const i of this.children)if(i===t||e&&i.hasChild(t,!0))return!0;return!1}addChild(t){if(t.parent===null){if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t)}else throw new Error("Entity already has a parent, cannot add without unparenting");return this}removeChild(t){return t.parent===this&&(qe(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();i&&(e=e.concat(i.children),t=t.concat(i.children))}return t}clone(){const t=new ar;for(const e of this.types){const i=this.get(e);i&&t.addComponent(i.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 i of t.children)this.addChild(i.clone().addTemplate(i));return this}_getClassHierarchyRoot(t){var e,i;let s=t,n=(e=Object.getPrototypeOf(s.prototype))==null?void 0:e.constructor;for(;n&&n!==Object&&n!==Rt;)s=n,n=(i=Object.getPrototypeOf(s.prototype))==null?void 0:i.constructor;return s}addComponent(t,e=!1){if(this.has(t.constructor))if(e)this.removeComponent(t.constructor,!0);else return this;if(t.dependencies&&t.dependencies.length)for(const s of t.dependencies)this.addComponent(new s);t.owner=this;const i=this._getClassHierarchyRoot(t.constructor);return this.components.set(i,t),this.components.set(t.constructor,t),this.componentValues.push(t),t.onAdd&&t.onAdd(this),this.componentAdded$.notifyAll(t),this}removeComponent(t,e=!1){let i;if(br(t)?i=t:i=t.constructor,e){const s=this.components.get(i);if(s){this.componentRemoved$.notifyAll(s),s.owner=void 0,s.onRemove&&s.onRemove(this);const o=this.componentValues.indexOf(s);o>-1&&this.componentValues.splice(o,1)}const n=this._getClassHierarchyRoot(i);this.components.delete(n),this.components.delete(i)}else this._componentsToRemove.push(i);return this}clearComponents(){const t=this.types;for(const e of t)this.removeComponent(e)}processComponentRemoval(){for(const t of this._componentsToRemove)this.removeComponent(t,!0);this._componentsToRemove.length=0}has(t){return this.components.has(t)}get isInitialized(){return this._isInitialized}get isAdded(){return this._isAdded}_initialize(t){this.isInitialized||(this.onInitialize(t),this.events.emit("initialize",new Ve(t,this)),this._isInitialized=!0)}_add(t){!this.isAdded&&this.isActive&&(this.onAdd(t),this.events.emit("add",new rn(t,this)),this._isAdded=!0)}_remove(t){this.isAdded&&!this.isActive&&(this.onRemove(t),this.events.emit("remove",new on(t,this)),this._isAdded=!1)}_preupdate(t,e){this.events.emit("preupdate",new de(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new ue(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onAdd(t){}onRemove(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e),this._remove(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){e?this.events.off(t,e):this.events.off(t)}};Ir._ID=0;let Tt=Ir;class Rr{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._childAddedHandlerMap=new Map,this._childRemovedHandlerMap=new Map,this._createChildAddedHandler=()=>e=>{this.addEntity(e)},this._createChildRemovedHandler=()=>e=>{this.removeEntity(e,!1)},this._entitiesToRemove=[]}updateEntities(t,e){for(let i=0;i<this.entities.length;i++){const s=this.entities[i];s.update(t.engine,e),s.isActive||this.removeEntity(s)}}findEntitiesForRemoval(){for(let t=0;t<this.entities.length;t++){const e=this.entities[t];e.isActive||this.removeEntity(e)}}addEntity(t){if(t.isActive=!0,t.scene=this._world.scene,t&&!this._entityIndex[t.id]){this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.children.forEach(s=>{s.scene=t.scene,this.addEntity(s)});const e=this._createChildAddedHandler();this._childAddedHandlerMap.set(t,e);const i=this._createChildRemovedHandler();this._childRemovedHandlerMap.set(t,i),t.childrenAdded$.subscribe(e),t.childrenRemoved$.subscribe(i)}}removeEntity(t,e=!0){var i,s,n,o;let a=0;t instanceof Tt?a=t.id:a=t;const h=this._entityIndex[a];if(h&&h.isActive&&(h.isActive=!1),h&&e){this._entitiesToRemove.push(h);return}if(delete this._entityIndex[a],h){h.scene=null,qe(h,this.entities),this._world.queryManager.removeEntity(h),h.children.forEach(d=>{d.scene=null,this.removeEntity(d,e)});const l=this._childAddedHandlerMap.get(h);l&&(h.childrenAdded$.unsubscribe(l),this._childAddedHandlerMap.delete(h));const c=this._childRemovedHandlerMap.get(h);c&&(h.childrenRemoved$.unsubscribe(c),this._childRemovedHandlerMap.delete(h)),h._remove((s=(i=this._world)==null?void 0:i.scene)==null?void 0:s.engine),(o=(n=this._world)==null?void 0:n.scene)!=null&&o.engine&&this._world.scene.engine.stats.currFrame.actors.killed++}}processEntityRemovals(){for(let t=0;t<this._entitiesToRemove.length;t++){const e=this._entitiesToRemove[t];e.isActive||this.removeEntity(e,!1)}this._entitiesToRemove.length=0}processComponentRemovals(){for(let t=0;t<this.entities.length;t++)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])}}class Nt{constructor(t){this._entities=[],this.entitiesSet=new Set,this.entityAdded$=new pt,this.entityRemoved$=new pt,this.filter={components:{all:new Set,any:new Set,not:new Set},tags:{all:new Set,any:new Set,not:new Set}},this._dirty=!1;var e,i,s,n,o,a,h,l,c,d,_,f;Array.isArray(t)&&(t={components:{all:t}}),this.filter.components.all=new Set((i=(e=t.components)==null?void 0:e.all)!=null?i:[]),this.filter.components.any=new Set((n=(s=t.components)==null?void 0:s.any)!=null?n:[]),this.filter.components.not=new Set((a=(o=t.components)==null?void 0:o.not)!=null?a:[]),this.filter.tags.all=new Set((l=(h=t.tags)==null?void 0:h.all)!=null?l:[]),this.filter.tags.any=new Set((d=(c=t.tags)==null?void 0:c.any)!=null?d:[]),this.filter.tags.not=new Set((f=(_=t.tags)==null?void 0:_.not)!=null?f:[]),this.id=Nt.createId(t)}get entities(){return this._dirty&&(this._entities=Array.from(this.entitiesSet),this._dirty=!1),this._entities}static createId(t){var e,i,s,n,o,a,h,l,c,d,_,f;Array.isArray(t)&&(t={components:{all:t}});const m=(e=t.components)!=null&&e.any?`any_${Nt.hashComponents(new Set((i=t.components)==null?void 0:i.any))}`:"",p=(s=t.components)!=null&&s.all?`all_${Nt.hashComponents(new Set((n=t.components)==null?void 0:n.all))}`:"",x=(o=t.components)!=null&&o.not?`not_${Nt.hashComponents(new Set((a=t.components)==null?void 0:a.not))}`:"",v=(h=t.tags)!=null&&h.any?`any_${Nt.hashTags(new Set((l=t.tags)==null?void 0:l.any))}`:"",g=(c=t.tags)!=null&&c.all?`all_${Nt.hashTags(new Set((d=t.tags)==null?void 0:d.all))}`:"",b=(_=t.tags)!=null&&_.not?`not_${Nt.hashTags(new Set((f=t.tags)==null?void 0:f.not))}`:"";return[m,p,x,v,g,b].filter(Boolean).join("-")}static hashTags(t){return Array.from(t).map(e=>`t_${e}`).sort().join("-")}static hashComponents(t){return Array.from(t).map(e=>`c_${e.name}`).sort().join("-")}matchesNotFilter(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!0;for(const i of this.filter.tags.not)if(t.hasTag(i))return!0;return!1}matches(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!1;for(const i of this.filter.tags.not)if(t.hasTag(i))return!1;for(const i of this.filter.components.all)if(i===e||!t.has(i))return!1;for(const i of this.filter.tags.all)if(!t.hasTag(i))return!1;if(this.filter.components.any.size>0){let i=!1;for(const s of this.filter.components.any)if(t.has(s)){i=!0;break}if(!i)return!1}if(this.filter.tags.any.size>0){let i=!1;for(const s of this.filter.tags.any)if(t.hasTag(s)){i=!0;break}if(!i)return!1}return!0}checkAndModify(t,e){const i=this.entitiesSet.has(t);if(i&&this.matchesNotFilter(t,e))return this.removeEntity(t),!1;const s=this.matches(t,e);return i&&!s?(this.removeEntity(t),!1):!i&&s?(this._dirty=!0,this.entitiesSet.add(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){this.entitiesSet.delete(t)&&(this._dirty=!0,this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class an{constructor(t){if(this.requiredTags=t,this.tags=new Set,this.entities=[],this.entityAdded$=new pt,this.entityRemoved$=new pt,t.length===0)throw new Error("Cannot create tag query without tags");for(const e of t)this.tags.add(e);this.id=an.createId(t)}static createId(t){return t.slice().sort().join("-")}checkAndAdd(t){return!this.entities.includes(t)&&t.hasAllTags(Array.from(this.tags))?(this.entities.push(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){const e=this.entities.indexOf(t);e>-1&&(this.entities.splice(e,1),this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class Mr{constructor(t){this._world=t,this._queries=new Map,this._addComponentHandlers=new Map,this._removeComponentHandlers=new Map,this._componentToQueriesIndex=new Map,this._tagToQueriesIndex=new Map,this._addTagHandlers=new Map,this._removeTagHandlers=new Map,this._createAddComponentHandler=e=>i=>{this.addComponent(e,i)},this._createRemoveComponentHandler=e=>i=>{this.removeComponent(e,i)},this._createAddTagHandler=e=>i=>{this.addTag(e,i)},this._createRemoveTagHandler=e=>i=>{this.removeTag(e,i)}}createQuery(t){const e=Nt.createId(t);if(this._queries.has(e))return this._queries.get(e);const i=new Nt(t);this._queries.set(i.id,i);for(const s of[...i.filter.components.all,...i.filter.components.any,...i.filter.components.not]){const n=this._componentToQueriesIndex.get(s);n?n.push(i):this._componentToQueriesIndex.set(s,[i])}for(const s of[...i.filter.tags.all,...i.filter.tags.any,...i.filter.tags.not]){const n=this._tagToQueriesIndex.get(s);n?n.push(i):this._tagToQueriesIndex.set(s,[i])}for(const s of this._world.entities)this.addEntity(s);return i}addEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t),s=e!=null?e:this._createAddComponentHandler(t),n=i!=null?i:this._createRemoveComponentHandler(t);this._addComponentHandlers.set(t,s),this._removeComponentHandlers.set(t,n);const o=this._addTagHandlers.get(t),a=this._removeTagHandlers.get(t),h=o!=null?o:this._createAddTagHandler(t),l=a!=null?a:this._createRemoveTagHandler(t);this._addTagHandlers.set(t,h),this._removeTagHandlers.set(t,l);for(const c of this._queries.values())c.checkAndModify(t);t.componentAdded$.subscribe(s),t.componentRemoved$.subscribe(n),t.tagAdded$.subscribe(h),t.tagRemoved$.subscribe(l)}removeEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t);for(const o of this._queries.values())o.removeEntity(t);e&&(t.componentAdded$.unsubscribe(e),this._addComponentHandlers.delete(t)),i&&(t.componentRemoved$.unsubscribe(i),this._removeComponentHandlers.delete(t));const s=this._addTagHandlers.get(t),n=this._removeTagHandlers.get(t);s&&(t.tagAdded$.unsubscribe(s),this._addTagHandlers.delete(t)),n&&(t.tagRemoved$.unsubscribe(n),this._removeTagHandlers.delete(t))}addComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t,e.constructor)}addTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.removeEntity(t),n.checkAndModify(t)}}const Zt={Highest:-1/0,Higher:-5,Average:0,Lower:5,Lowest:1/0};var At=(r=>(r.Update="update",r.Draw="draw",r))(At||{});class Pt{}Pt.priority=Zt.Average;function Fr(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Dr{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find(e=>e instanceof t)}addSystem(t){let e;t instanceof Pt?e=t:e=new t(this._world),this.systems.push(e),this.systems.sort((i,s)=>i.constructor.priority-s.constructor.priority),this.initialized&&e.initialize&&e.initialize(this._world,this._world.scene)}removeSystem(t){qe(t,this.systems)}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world,this._world.scene)}}updateSystems(t,e,i){var s,n,o;const a=this.systems.filter(_=>_.systemType===t),h=(o=(n=(s=e==null?void 0:e.engine)==null?void 0:s.stats)==null?void 0:n.currFrame)!=null?o:{systemDuration:{}};let l,c;const d=a.length;for(let _=0;_<d;_++)a[_].preupdate&&(l=performance.now(),a[_].preupdate(e,i),c=performance.now(),h.systemDuration[`${t}:${a[_].constructor.name}.preupdate`]=c-l);for(let _=0;_<d;_++)l=performance.now(),a[_].update(i),c=performance.now(),h.systemDuration[`${t}:${a[_].constructor.name}.update`]=c-l;for(let _=0;_<d;_++)a[_].postupdate&&(l=performance.now(),a[_].postupdate(e,i),c=performance.now(),h.systemDuration[`${t}:${a[_].constructor.name}.postupdate`]=c-l)}clear(){for(let t=this.systems.length-1;t>=0;t--)this.removeSystem(this.systems[t])}}class Br{constructor(t){this.scene=t,this._logger=F.getInstance(),this.queryManager=new Mr(this),this.entityManager=new Rr(this),this.systemManager=new Dr(this)}query(t){return this.queryManager.createQuery(t)}queryTags(t){return this.queryManager.createQuery({tags:{all:t}})}update(t,e){t===At.Update&&this.entityManager.updateEntities(this.scene,e),this.systemManager.updateSystems(t,this.scene,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){if(t instanceof Tt){this.entityManager.addEntity(t);return}if(t instanceof Pt||Fr(t)){this.systemManager.addSystem(t);return}this._logger.warn(`Could not add entity/system ${t.constructor.name} to Excalibur!
19
-
20
- If this looks like an Excalibur type, this can be caused by 2 versions of excalibur being included on the page.
21
-
22
- Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get(t){return this.systemManager.get(t)}remove(t,e=!0){if(t instanceof Tt){this.entityManager.removeEntity(t,e);return}if(t instanceof Pt){this.systemManager.removeSystem(t);return}this._logger.warn(`Could not remove entity/system ${t.constructor.name} to Excalibur!
23
-
24
- If this looks like an Excalibur type, this can be caused by 2 versions of excalibur being included on the page.
25
-
26
- Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get entities(){return this.entityManager.entities}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}class Mt extends Rt{constructor(t={}){var e;super(),this.paused=!1,this.canPause=!0,this.canPause=(e=t.canPause)!=null?e:!1}}u.Side=(r=>(r.None="None",r.Top="Top",r.Bottom="Bottom",r.Left="Left",r.Right="Right",r))(u.Side||{}),(r=>{function t(i){return i==="Top"?"Bottom":i==="Bottom"?"Top":i==="Left"?"Right":i==="Right"?"Left":"None"}r.getOpposite=t;function e(i){return Math.abs(i.x)>=Math.abs(i.y)?i.x<=0?"Left":"Right":i.y<=0?"Top":"Bottom"}r.fromDirection=e})(u.Side||(u.Side={}));const Lr=class wt{constructor(t=0,e=0,i=0,s=0){this._points=[],typeof t=="object"?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):typeof t=="number"&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}clone(t){const e=t||new wt(0,0,0,0);return e.left=this.left,e.right=this.right,e.top=this.top,e.bottom=this.bottom,e}reset(){this.left=0,this.top=0,this.bottom=0,this.right=0}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?u.Side.Right:u.Side.Left:t.y<0?u.Side.Bottom:u.Side.Top:u.Side.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let o=0;o<t.length;o++)t[o].x<e&&(e=t[o].x),t[o].x>s&&(s=t[o].x),t[o].y<i&&(i=t[o].y),t[o].y>n&&(n=t[o].y);return new wt(e,i,s,n)}static fromDimension(t,e,i=w.Half,s=w.Zero){return new wt(-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 this.width===0||this.height===0}get center(){return new w((this.left+this.right)/2,(this.top+this.bottom)/2)}get topLeft(){return new w(this.left,this.top)}get bottomRight(){return new w(this.right,this.bottom)}get topRight(){return new w(this.right,this.top)}get bottomLeft(){return new w(this.left,this.bottom)}translate(t){return new wt(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=w.Zero){const i=this.getPoints().map(s=>s.rotate(t,e));return wt.fromPoints(i)}scale(t,e=w.Zero){const i=this.translate(e);return new wt(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,o=t.data[2]*this.top,a=t.data[3]*this.top,h=t.data[2]*this.bottom,l=t.data[3]*this.bottom,c=t.getPosition(),d=Math.min(e,s)+Math.min(o,h)+c.x,_=Math.min(i,n)+Math.min(a,l)+c.y,f=Math.max(e,s)+Math.max(o,h)+c.x,m=Math.max(i,n)+Math.max(a,l)+c.y;return new wt({left:d,top:_,right:f,bottom:m})}getPerimeter(){const t=this.width,e=this.height;return 2*(t+e)}getPoints(){return(this._left!==this.left||this._right!==this.right||this._top!==this.top||this._bottom!==this.bottom)&&(this._points.length=0,this._points.push(new w(this.left,this.top)),this._points.push(new w(this.right,this.top)),this._points.push(new w(this.right,this.bottom)),this._points.push(new w(this.left,this.bottom)),this._left=this.left,this._right=this.right,this._top=this.top,this._bottom=this.bottom),this._points}rayCast(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e}rayCastTime(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e?s:-1}contains(t){return t instanceof w?this.left<=t.x&&this.top<=t.y&&t.y<=this.bottom&&t.x<=this.right:t instanceof wt?this.left<=t.left&&this.top<=t.top&&t.bottom<=this.bottom&&t.right<=this.right:!1}combine(t,e){const i=e||new wt(0,0,0,0),s=Math.min(this.left,t.left),n=Math.min(this.top,t.top),o=Math.max(this.right,t.right),a=Math.max(this.bottom,t.bottom);return i.left=s,i.top=n,i.right=o,i.bottom=a,i}get dimensions(){return new w(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){if(this.bottom<=t.top||t.bottom<=this.top||this.right<=t.left||t.right<=this.left)return null;const e=this.bottom-t.top;wt._SCRATCH_INTERSECT[0]=e;const i=t.bottom-this.top;wt._SCRATCH_INTERSECT[1]=i;const s=this.right-t.left;wt._SCRATCH_INTERSECT[2]=s;const n=t.right-this.left;wt._SCRATCH_INTERSECT[3]=n;const o=Tr(wt._SCRATCH_INTERSECT);switch(o){case 0:return new w(0,-e);case 1:return new w(0,i);case 2:return new w(-s,0);case 3:return new w(n,0);default:const a=o;throw new Error(`Unreachable index: [${a}] on bounding box intersection!`)}}intersectWithSide(t){const e=this.intersect(t);return wt.getSideFromIntersection(e)}draw(t,e={color:T.Yellow}){t.debug.drawRect(this.left,this.top,this.width,this.height,e)}debug(t,e={color:T.Yellow}){t.debug.drawRect(this.left,this.top,this.width,this.height,e)}};Lr._SCRATCH_INTERSECT=[0,0,0,0];let D=Lr;class mt{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=mt.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;if(t.id===e.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.localBounds.hasZeroDimensions()||e.localBounds.hasZeroDimensions())return!1;const n=(i=t==null?void 0:t.owner)==null?void 0:i.get(U),o=(s=e==null?void 0:e.owner)==null?void 0:s.get(U);return!(!n||!o||!n.group.canCollide(o.group)||n.collisionType===R.Fixed&&o.collisionType===R.Fixed||o.collisionType===R.PreventCollision||n.collisionType===R.PreventCollision||!n.isActive||!o.isActive)}get canCollide(){const t=this.colliderA,e=this.colliderB;return mt.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 Se{constructor(t,e,i,s,n,o,a,h){this._canceled=!1,this.bodyA=null,this.bodyB=null;var l,c,d,_,f,m;if(this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=o,this.localPoints=a,this.info=h,this.id=mt.calculatePairHash(t.id,e.id),t.composite||e.composite){const p=((l=t.composite)==null?void 0:l.compositeStrategy)==="separate"?t.id:(d=(c=t.composite)==null?void 0:c.id)!=null?d:t.id,x=((_=e.composite)==null?void 0:_.compositeStrategy)==="separate"?e.id:(m=(f=e.composite)==null?void 0:f.id)!=null?m:e.id;this.id+="|"+mt.calculatePairHash(p,x)}this.colliderA.owner&&(this.bodyA=this.colliderA.owner.get(U)),this.colliderB.owner&&(this.bodyB=this.colliderB.owner.get(U))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}bias(t){if(t!==this.colliderA&&t!==this.colliderB)throw new Error("Collider must be either colliderA or colliderB from this contact");if(t===this.colliderA)return this;const e=this.colliderA,i=this.colliderB;return this.colliderB=e,this.colliderA=i,this.mtv=this.mtv.negate(),this.normal=this.normal.negate(),this.tangent=this.tangent.negate(),this}}const kr=class Wa{constructor(){this.id=we("collider",Wa._ID++),this.composite=null,this.events=new Y,this.offset=w.Zero}touching(t){const e=this.collide(t);return!!(e&&e.length>0)}};kr._ID=0;let di=kr;function hn(r,t){const i=r.dir(),s=t.dir(),n=i.dot(i),o=s.dot(s);if(n<1e-9&&o<1e-9)return new it(r.begin,t.begin);if(n<1e-9){const x=L(s.dot(r.begin.sub(t.begin))/o,0,1),v=t.begin.add(s.scale(x));return new it(r.begin,v)}if(o<1e-9){const x=L(i.dot(t.begin.sub(r.begin))/n,0,1),v=r.begin.add(i.scale(x));return new it(v,t.begin)}const a=r.begin.sub(t.begin),h=n,l=o,c=s.dot(a),d=h*l-Math.pow(i.dot(s),2);let _=0,f=0;Math.abs(d)>1e-9?_=L((i.dot(s)*c-l*i.dot(a))/d,0,1):_=L(i.dot(a)/h,0,1),Math.abs(l)>1e-9?f=L((i.dot(s)*_+c)/l,0,1):f=0;const m=r.begin.add(i.scale(_)),p=t.begin.add(s.scale(f));return new it(m,p)}const jt={PolygonPolygonClosestLine(r,t){const e=r.getSides(),i=t.getSides();let s=Number.MAX_VALUE,n=null;for(let o=0;o<e.length;o++)for(let a=0;a<i.length;a++){const h=hn(e[o],i[a]),l=h.getLength();l<s&&(s=l,n=h)}return n},PolygonEdgeClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),s=new xe(r.worldPos,i),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=t.asLine();return hn(o.face,a)},PolygonCircleClosestLine(r,t){const e=t.worldPos,i=e.sub(r.worldPos),s=new xe(r.worldPos,i.normalize()),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(e.x-a.x)+h.y*(e.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-e.x,2)+Math.pow(a.y+h.y*l-e.y,2))-t.radius,d=(a.x+h.x*l-e.x)*t.radius/(t.radius+c),_=(a.y+h.y*l-e.y)*t.radius/(t.radius+c);return new it(h.scale(l).add(a),new w(e.x+d,e.y+_))},CircleCircleClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),n=r.worldPos.sub(t.worldPos),o=new xe(r.worldPos,i),a=new xe(t.worldPos,n),h=r.rayCast(o),l=t.rayCast(a);return new it(h.point,l.point)},CircleEdgeClosestLine(r,t){const e=r.worldPos,i=t.asLine(),s=i.begin,n=i.getEdge(),o=s,a=n;let h=(a.x*(e.x-o.x)+a.y*(e.y-o.y))/(a.x*a.x+a.y*a.y);h>1?h=1:h<0&&(h=0);const l=Math.sqrt(Math.pow(o.x+a.x*h-e.x,2)+Math.pow(o.y+a.y*h-e.y,2))-r.radius,c=(o.x+a.x*h-e.x)*r.radius/(r.radius+l),d=(o.y+a.y*h-e.y)*r.radius/(r.radius+l);return new it(a.scale(h).add(o),new w(e.x+c,e.y+d))},EdgeEdgeClosestLine(r,t){const e=r.asLine(),i=t.asLine();return hn(e,i)}};class Et extends di{constructor(t){var e;super(),this._globalMatrix=tt.identity(),this.begin=t.begin||w.Zero,this.end=t.end||w.Zero,this.offset=(e=t.offset)!=null?e:w.Zero}clone(){return new Et({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return(t=e==null?void 0:e.globalPos.add(this.offset))!=null?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){var i;const s=this._getTransformedBegin().sub(t.pos);if(t.dir.cross(this.getSlope())===0&&s.cross(t.dir)!==0)return null;const n=t.dir.cross(this.getSlope());if(n===0)return null;const o=s.cross(this.getSlope())/n;if(o>=0&&o<=e){const a=s.cross(t.dir)/n/this.getLength();if(a>=0&&a<=1)return{distance:o,normal:this.asLine().normal(),collider:this,body:(i=this.owner)==null?void 0:i.get(U),point:t.getPoint(o)}}return null}getClosestLineBetween(t){if(t instanceof dt)return jt.CircleEdgeClosestLine(t,this);if(t instanceof lt)return jt.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Et)return jt.EdgeEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ht.CollideCircleEdge(t,this);if(t instanceof lt)return Ht.CollidePolygonEdge(t,this);if(t instanceof Et)return Ht.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 D(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 it(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new it(this.begin,this.end)}get axes(){const e=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),i=[];return i.push(e),i.push(e.negate()),i.push(e.normal()),i.push(e.normal().negate()),i}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){var e;this._transform=t,((e=t.matrix)!=null?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 ri(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.debug.drawLine(i,s,{color:e,lineWidth:2}),t.debug.drawCircle(i,2,e),t.debug.drawCircle(s,2,e)}}class ln{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new D,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class cn{constructor(t,e=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this._config=t,this.worldBounds=e,this.root=null,this.nodes={}}_insert(t){if(this.root===null){this.root=t,this.root.parent=null;return}const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const a=i.left,h=i.right,l=i.bounds.getPerimeter(),d=i.bounds.combine(e).getPerimeter(),_=2*d,f=2*(d-l);let m=0;const p=e.combine(a.bounds);let x,v;a.isLeaf()?m=p.getPerimeter()+f:(v=a.bounds.getPerimeter(),x=p.getPerimeter(),m=x-v+f);let g=0;const b=e.combine(h.bounds);if(h.isLeaf()?g=b.getPerimeter()+f:(v=h.bounds.getPerimeter(),x=b.getPerimeter(),g=x-v+f),_<m&&_<g)break;m<g?i=a:i=h}const s=i.parent,n=new ln(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,s!==null?(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 o=t.parent;for(;o;){if(o=this._balance(o),!o.left)throw new Error("Parent of current leaf cannot have a null left child"+o);if(!o.right)throw new Error("Parent of current leaf cannot have a null right child"+o);o.height=1+Math.max(o.left.height,o.right.height),o.bounds=o.left.bounds.combine(o.right.bounds),o=o.parent}}_remove(t){if(t===this.root){this.root=null;return}const e=t.parent,i=e.parent;let s;if(e.left===t?s=e.right:s=e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let n=i;for(;n;)n=this._balance(n),n.bounds=n.left.bounds.combine(n.right.bounds),n.height=1+Math.max(n.left.height,n.right.height),n=n.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new ln;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 F.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-=this._config.boundsPadding,s.top-=this._config.boundsPadding,s.right+=this._config.boundsPadding,s.bottom+=this._config.boundsPadding,t.owner){const n=(e=t.owner)==null?void 0:e.get(U);if(n){const o=n.vel.x*32/1e3*this._config.velocityMultiplier,a=n.vel.y*32/1e3*this._config.velocityMultiplier;o<0?s.left+=o:s.right+=o,a<0?s.top+=a:s.bottom+=a}}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(t===null)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,o=i,a=e.left,h=e.right,l=i.left,c=i.right,d=o.height-n.height;if(d>1)return o.left=s,o.parent=s.parent,s.parent=o,o.parent?o.parent.left===s?o.parent.left=o:o.parent.right=o:this.root=o,l.height>c.height?(o.right=l,s.right=c,c.parent=s,s.bounds=n.bounds.combine(c.bounds),o.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,c.height),o.height=1+Math.max(s.height,l.height)):(o.right=c,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),o.bounds=s.bounds.combine(c.bounds),s.height=1+Math.max(n.height,l.height),o.height=1+Math.max(s.height,c.height)),o;if(d<-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 a.height>h.height?(n.right=a,s.left=h,h.parent=s,s.bounds=o.bounds.combine(h.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(o.height,h.height),n.height=1+Math.max(s.height,a.height)):(n.right=h,s.left=a,a.parent=s,s.bounds=o.bounds.combine(a.bounds),n.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(o.height,a.height),n.height=1+Math.max(s.height,h.height)),n}return t}getHeight(){return this.root===null?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){if(e.call(t,n.data))return!0}else return s(n.left)||s(n.right);return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e))if(n.isLeaf()){if(i.call(t,n.data))return!0}else return s(n.left)||s(n.right);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.debug(t,{color:T.Green}):i.bounds.debug(t,{color:T.White}),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class Ni{constructor(t){this._config=t,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[],this._dynamicCollisionTree=new cn(t.dynamicTree)}getColliders(){return this._colliders}query(t){const e=[];return t instanceof D?this._dynamicCollisionTree.query({id:we("collider",-1),owner:null,bounds:t},i=>(e.push(i),!1)):this._dynamicCollisionTree.query({id:we("collider",-1),owner:null,bounds:new D(t.x,t.y,t.x,t.y)},i=>(e.push(i),!1)),e}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:Yt.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1;return this._dynamicCollisionTree.rayCastQuery(t,a,d=>{const f=d.owner.get(U);if(e!=null&&e.ignoreCollisionGroupAll&&f.group===Yt.All)return!1;const m=(l&f.group.category)!==0;if(f!=null&&f.group&&!m)return!1;const p=d.rayCast(t,a);if(p){if(e!=null&&e.filter){if(e.filter(p)&&(o.push(p),!c))return!0}else if(o.push(p),!c)return!0}return!1}),o}track(t){if(!t){F.getInstance().warn("Cannot track null collider");return}if(t instanceof nt){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)}untrack(t){if(!t){F.getInstance().warn("Cannot untrack a null collider");return}if(t instanceof nt){const e=t.getColliders();for(const i of e){const s=this._colliders.indexOf(i);s!==-1&&this._colliders.splice(s,1),this._dynamicCollisionTree.untrackCollider(i)}}else{const e=this._colliders.indexOf(t);e!==-1&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}_pairExists(t,e){const i=mt.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter(a=>{var h,l;const c=(h=a.owner)==null?void 0:h.get(U);return((l=a.owner)==null?void 0:l.isActive)&&c.collisionType!==R.PreventCollision});this._collisionPairCache=[],this._pairs.clear();let o;for(let a=0,h=n.length;a<h;a++)o=n[a],this._dynamicCollisionTree.query(o,l=>{if(!this._pairExists(o,l)&&mt.canCollide(o,l)){const c=new mt(o,l);this._pairs.add(c.id),this._collisionPairCache.push(c)}return!1});if(i&&(i.physics.pairs=this._collisionPairCache.length),this._config.continuous.checkForFastBodies)for(const a of n){const h=a.owner.get(U);if((h==null?void 0:h.collisionType)!==R.Active)continue;const l=h.vel.magnitude*s+h.acc.magnitude*.5*s*s,c=Math.min(a.bounds.height,a.bounds.width);if(this._config.continuous.disableMinimumSpeedForFastBody||l>c/2){i&&i.physics.fastBodies++;const d=h.globalPos.sub(h.oldPos),_=a.center,f=a.getFurthestPoint(h.vel),m=f.sub(d),p=new xe(m,h.vel);p.pos=p.pos.add(p.dir.scale(-2*this._config.continuous.surfaceEpsilon));let x,v=new w(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(p,l+this._config.continuous.surfaceEpsilon*2,g=>{if(!this._pairExists(a,g)&&mt.canCollide(a,g)){const b=g.rayCast(p,l+this._config.continuous.surfaceEpsilon*10);if(b){const S=b.point.sub(m);S.magnitude<v.magnitude&&(v=S,x=g)}}return!1}),x&&w.isValid(v)){const g=new mt(a,x);this._pairs.has(g.id)||(this._pairs.add(g.id),this._collisionPairCache.push(g));const b=_.sub(f);h.globalPos=m.add(b).add(v).add(p.dir.scale(10*this._config.continuous.surfaceEpsilon)),a.update(h.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 o of n)e.physics.contacts.set(o.id,o)}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)}}var ui=(r=>(r.Arcade="arcade",r.Realistic="realistic",r))(ui||{}),_e=(r=>(r.None="none",r.VerticalFirst="vertical-first",r.HorizontalFirst="horizontal-first",r))(_e||{});const dn={vertical:1,horizontal:2},un={horizontal:1,vertical:2},_n={horizontal:0,vertical:0};var _i=(r=>(r.DynamicTree="dynamic-tree",r.SparseHashGrid="sparse-hash-grid",r))(_i||{});const ne=()=>({enabled:!0,integration:{onScreenOnly:!1},gravity:y(0,0).clone(),solver:ui.Arcade,substep:1,colliders:{compositeStrategy:"together"},continuous:{checkForFastBodies:!0,disableMinimumSpeedForFastBody:!1,surfaceEpsilon:.1},bodies:{canSleepByDefault:!0,sleepEpsilon:.07,wakeThreshold:.07*3,sleepBias:.5,sleepTimeThreshold:1e3,defaultMass:10},spatialPartition:_i.SparseHashGrid,sparseHashGrid:{size:100},dynamicTree:{boundsPadding:5,velocityMultiplier:2},arcade:{contactSolveBias:_e.None},realistic:{contactSolveBias:_e.None,positionIterations:3,velocityIterations:8,slop:1,steeringFactor:.2,warmStart:!0}});class nt extends di{constructor(t){super(),this._collisionProcessor=new Ni({...ne()}),this._dynamicAABBTree=new cn({boundsPadding:5,velocityMultiplier:2}),this._colliders=[];for(const e of t)this.addCollider(e)}set compositeStrategy(t){this._compositeStrategy=t}get compositeStrategy(){return this._compositeStrategy}clearColliders(){this._colliders=[]}addCollider(t){let e;t instanceof nt?(e=t.getColliders(),e.forEach(i=>i.offset.addEqual(t.offset))):e=[t];for(const i of e)i.events.pipe(this.events),i.composite=this,this._colliders.push(i),this._collisionProcessor.track(i),this._dynamicAABBTree.trackCollider(i)}removeCollider(t){t.events.pipe(this.events),t.composite=null,qe(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:w.Zero).add(this.offset)}get center(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:w.Zero).add(this.offset)}get bounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.bounds),(e=(t=i[0])==null?void 0:t.bounds)!=null?e:new D().translate(this.worldPos)).translate(this.offset)}get localBounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.localBounds),(e=(t=i[0])==null?void 0:t.localBounds)!=null?e:new D)}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 o of e)i.push(o.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const o of i){const a=o.dot(t);a>n&&(s=o,n=a)}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 nt&&(e=t.getColliders());const i=[];for(const n of e)this._dynamicAABBTree.query(n,o=>(i.push(new mt(n,o)),!1));let s=[];for(const n of i)s=s.concat(n.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof nt){const s=t.getColliders();for(const n of e)for(const o of s){const a=n.getClosestLineBetween(o);a&&i.push(a)}}else for(const s of e){const n=t.getClosestLineBetween(s);n&&i.push(n)}if(i.length){let s=i[0].getLength(),n=i[0];for(const o of i){const a=o.getLength();a<s&&(s=a,n=o)}return n}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 o=n.rayCast(t,e);o&&s.push(o)}if(s.length){let n=s[0],o=n.point.dot(t.dir);for(const a of s){const h=t.dir.dot(a.point);h<o&&(n=a,o=h)}return n}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const n=s.project(t);n&&i.push(n)}if(i.length){const s=new ri(i[0].min,i[0].max);for(const n of i)s.min=Math.min(n.min,s.min),s.max=Math.max(n.max,s.max);return s}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,i){const s=this.getColliders();t.save(),t.translate(this.offset.x,this.offset.y);for(const n of s)n.debug(t,e,i);t.restore()}clone(){const t=new nt(this._colliders.map(e=>e.clone()));return t.offset=this.offset.clone(),t}}class rt{static Box(t,e,i=w.Half,s=w.Zero){return new lt({points:new D(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints().slice(),offset:s})}static Polygon(t,e=w.Zero,i=!1){return new lt({points:t,offset:e,suppressConvexWarning:i})}static Circle(t,e=w.Zero){return new dt({radius:t,offset:e})}static Edge(t,e){return new Et({begin:t,end:e})}static Capsule(t,e,i=w.Zero){const s=F.getInstance();if(t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider"),e>=t){const o=new nt([rt.Circle(t/2,y(0,-e/2+t/2).add(i)),rt.Box(t,e-t,w.Half,i),rt.Circle(t/2,y(0,e/2-t/2).add(i))]);return o.compositeStrategy="together",o}else{const o=new nt([rt.Circle(e/2,y(-t/2+e/2,0).add(i)),rt.Box(t-e,e,w.Half,i),rt.Circle(e/2,y(t/2-e/2,0).add(i))]);return o.compositeStrategy="together",o}}}class lt extends di{constructor(t){var e;super(),this._logger=F.getInstance(),this._transform=new se,this._transformedPoints=[],this._sides=[],this._localSides=[],this._transformedPointsDirty=!0,this._sidesDirty=!0,this._localSidesDirty=!0,this._localBoundsDirty=!0,this.offset=(e=t.offset)!=null?e:w.Zero,this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y,this.points=t.points,this.isConvex()||t.suppressConvexWarning||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()}flagDirty(){this._localBoundsDirty=!0,this._localSidesDirty=!0,this._transformedPointsDirty=!0,this._sidesDirty=!0}get normals(){return this._normals}set points(t){if(t.length<3)throw new Error("PolygonCollider cannot be created with less that 3 points");this._points=t,this._checkAndUpdateWinding(this._points),this._calculateNormals(),this.flagDirty()}_calculateNormals(){const t=[];for(let e=0;e<this._points.length;e++)t.push(this._points[(e+1)%this._points.length].sub(this._points[e]).normal());this._normals=t}get points(){return this._points}get transform(){return this._transform}_checkAndUpdateWinding(t){this._isCounterClockwiseWinding(t)||t.reverse()}_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,o=0;for(const[a,h]of this.points.entries()){if(t=e,s=i,e=h,i=Math.atan2(e.y-t.y,e.x-t.x),t.equals(e))return!1;let l=i-s;if(l<=-Math.PI?l+=Math.PI*2:l>Math.PI&&(l-=Math.PI*2),a===0){if(l===0)return!1;n=l>0?1:-1}else if(n*l<=0)return!1;o+=l}return Math.abs(Math.round(o/(Math.PI*2)))===1}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 nt(t.map(e=>rt.Polygon(e)))}triangulate(){if(this.points.length<3)throw Error("Invalid polygon");const t=[],e=[...this.points].reverse();let i=e.length;function s(d){return d===0?i-1:d-1}function n(d){return d===i-1?0:d+1}function o(d){const _=s(d),f=n(d),m=e[_],p=e[d],x=e[f],v=m.sub(p),g=x.sub(p);return!(v.cross(g)<0)}const a=e.map((d,_)=>o(_));function h(d,_,f,m){const p=f.sub(_),x=m.sub(f),v=_.sub(m),g=d.sub(_),b=d.sub(f),S=d.sub(m),A=p.cross(g),M=x.cross(b),C=v.cross(S);return!(A>0||M>0||C>0)}function l(){for(let d=0;d<i;d++)if(a[d]){const _=s(d),f=n(d),m=e[_],p=e[d],x=e[f];let v=!0;for(let g=0;g<i;g++){if(g===d||g===_||g===f)continue;const b=e[g];if(h(b,m,p,x)){v=!1;break}}if(v)return d}for(let d=0;d<i;d++)if(a[d])return d;return 0}function c(d){const _=s(d),f=n(d),m=e[_],p=e[d],x=e[f];t.push([m,p,x]),e.splice(d,1),a.splice(d,1),i--}for(;i>3;){const d=l();c(d);for(let _=0;_<i;_++)a[_]=o(_)}return t.push([e[0],e[1],e[2]]),new nt(t.map(d=>rt.Polygon(d,w.Zero,!0)))}clone(){return new lt({offset:this.offset.clone(),points:this.points.map(t=>t.clone())})}get worldPos(){return this._transform.pos}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._transform.apply(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 it(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 it(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 o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}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 o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}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){t&&(t.cloneWithParent(this._transform),this._transformedPointsDirty=!0,this._sidesDirty=!0,(this.offset.x!==0||this.offset.y!==0)&&(this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y),this._transform.isMirrored()&&(this.points=this.points.map(e=>y(e.x*q(this._transform.scale.x),e.y*q(this._transform.scale.y))),this._transform.scale.x=Math.abs(this._transform.scale.x),this._transform.scale.y=Math.abs(this._transform.scale.y)))}contains(t){const e=this._transform.applyInverse(t),i=new xe(e,new w(1,0));let s=0;const n=this.getLocalSides();for(let o=0;o<n.length;o++){const a=n[o];i.intersect(a)>=0&&s++}return s%2!==0}getClosestLineBetween(t){if(t instanceof dt)return jt.PolygonCircleClosestLine(this,t);if(t instanceof lt)return jt.PolygonPolygonClosestLine(this,t);if(t instanceof Et)return jt.PolygonEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ht.CollideCirclePolygon(t,this);if(t instanceof lt)return Ht.CollidePolygonPolygon(this,t);if(t instanceof Et)return Ht.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 o=t.dot(e[n]);o>s&&(s=o,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 o=t.dot(e[n]);o>s&&(s=o,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let o=0;o<e.length;o++){const a=e[o].distanceToPoint(t);a<i&&(i=a,s=o,n=a)}return s!==-1?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){return this.localBounds.transform(this._transform.matrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=D.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 n=0;n<s.length;n++){const o=(n+1)%s.length,a=s[o].cross(s[n]);e+=a*(s[n].dot(s[n])+s[n].dot(s[o])+s[o].dot(s[o])),i+=a}return this._cachedMass=t,this._cachedInertia=t/6*(e/i)}rayCast(t,e=1/0){var i;const s=this.getSides(),n=s.length;let o=Number.MAX_VALUE,a,h=-1;for(let l=0;l<n;l++){const c=t.intersect(s[l]);c>=0&&c<o&&c<=e&&(o=c,a=s[l],h=l)}return h>=0?{collider:this,distance:o,body:(i=this.owner)==null?void 0:i.get(U),point:t.getPoint(o),normal:a.normal()}:null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let o=0;o<i;o++){const a=e[o].dot(t);s=Math.min(s,a),n=Math.max(n,a)}return new ri(s,n)}debug(t,e,i){const s=this.getTransformedPoints();It.drawPolygon(s,{color:e})}}class Hi{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=F.getInstance()}dispose(){this.objects.length=0}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){const e=this.get();t(e),this.index--}get(){return this.index===this.maxObjects&&(this.disableWarnings||this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=this.maxObjects*2),this.objects[this.index]?this.recycler?this.recycler(this.objects[this.index++]):this.objects[this.index++]:(this.totalAllocations++,this.objects[this.index++]=this.builder())}done(...t){this.index=0;for(const e of t){const i=this.objects.indexOf(e);this.objects[i]=this.builder(),this.totalAllocations++}return t}}class zr{constructor(){this.axis=y(0,0),this.localAxis=y(0,0),this.side=new it(y(0,0),y(0,0)),this.localSide=new it(y(0,0),y(0,0)),this.point=y(0,0),this.localPoint=y(0,0)}}const Te=class he{static findPolygonPolygonSeparation(t,e){if(e.transform.matrix.determinant()===0)return he.findPolygonPolygonSeparationDegenerate(t,e);let i=-Number.MAX_VALUE,s=-1,n;const o=e.transform.inverse.multiply(t.transform.matrix,he._SCRATCH_MATRIX),a=o.getRotation(),h=t.normals,l=t.points,c=e.points;for(let f=0;f<l.length;f++){const m=h[f].rotate(a,he._ZERO,he._SCRATCH_NORMAL),p=o.multiply(l[f],he._SCRATCH_POINT);let x=Number.MAX_VALUE,v;for(let g=0;g<c.length;g++){const b=m.dot(c[g].sub(p,he._SCRATCH_SUB_POINT));b<x&&(x=b,v=c[g])}x>i&&(i=x,s=f,n=v)}const d=(s+1)%l.length,_=he.SeparationPool.get();return _.collider=t,_.separation=i,i>0||(h[s].clone(_.localAxis),h[s].rotate(t.transform.rotation,he._ZERO,_.axis),t.transform.matrix.multiply(l[s],_.side.begin),t.transform.matrix.multiply(l[d],_.side.end),e.transform.matrix.multiply(n,_.point),_.sideId=s,n.clone(_.localPoint),l[s].clone(_.localSide.begin),l[d].clone(_.localSide.end)),_}static findCirclePolygonSeparation(t,e){const i=e.axes,n=e.center.sub(t.worldPos),o=e.getFurthestPoint(n.negate());i.push(o.sub(t.worldPos).normalize());let a=Number.MAX_VALUE,h=null,l=-1;for(let c=0;c<i.length;c++){const d=e.project(i[c]),_=t.project(i[c]),f=d.getOverlap(_);if(f<=0)return null;f<a&&(a=f,h=i[c],l=c)}return l<0?null:h.normalize().scale(a)}static findPolygonPolygonSeparationDegenerate(t,e){let i=-Number.MAX_VALUE,s=null,n=null,o=-1,a=null;const h=t.getSides(),l=t.getLocalSides();for(let c=0;c<h.length;c++){const d=h[c],_=d.normal(),f=e.getFurthestPoint(_.negate()),m=d.distanceToPoint(f,!0);m>i&&(i=m,s=d,n=_,o=c,a=f)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:l[o],sideId:o,point:a,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}};Te.SeparationPool=new Hi(()=>new zr,r=>r,500),Te._ZERO=y(0,0),Te._SCRATCH_POINT=y(0,0),Te._SCRATCH_SUB_POINT=y(0,0),Te._SCRATCH_NORMAL=y(0,0),Te._SCRATCH_MATRIX=tt.identity();let Xe=Te;Xe.SeparationPool.disableWarnings=!0;const Oh=w.Zero,Nh=w.Zero,Hh=tt.identity(),Ht={CollideCircleCircle(r,t){const e=r.worldPos,i=t.worldPos,s=r.radius+t.radius,n=e.distance(i);if(n>s)return[];const o=s-n,a=i.sub(e).normalize(),h=a.perpendicular(),l=a.scale(o),c=r.getFurthestPoint(a),d=r.getFurthestLocalPoint(a),_={collider:r,separation:o,axis:a,point:c};return[new Se(r,t,l,a,h,[c],[d],_)]},CollideCirclePolygon(r,t){var e,i;let s=Xe.findCirclePolygonSeparation(r,t);if(!s)return[];s=s.dot(t.center.sub(r.center))<0?s.negate():s;const o=r.getFurthestPoint(s),h=((i=(e=r.owner)==null?void 0:e.get(E))!=null?i:new E).applyInverse(o),l=s.normalize(),c={collider:r,separation:-s.magnitude,axis:l,point:o,localPoint:h,side:t.findSide(l.negate()),localSide:t.findLocalSide(l.negate())};return[new Se(r,t,s,l,l.perpendicular(),[o],[h],c)]},CollideCircleEdge(r,t){const e=r.center,i=t.asLine(),s=i.end.sub(i.begin),n=s.dot(i.end.sub(e)),o=s.dot(e.sub(i.begin)),a=t.asLine(),h=t.asLocalLine();if(o<=0){const v=i.begin.sub(e),g=v.dot(v);if(g>r.radius*r.radius)return[];const b=v.normalize(),S=r.radius-Math.sqrt(g),A={collider:r,separation:S,axis:b,point:a.begin,side:a,localSide:h};return[new Se(r,t,b.scale(S),b,b.perpendicular(),[a.begin],[h.begin],A)]}if(n<=0){const v=i.end.sub(e),g=v.dot(v);if(g>r.radius*r.radius)return[];const b=v.normalize(),S=r.radius-Math.sqrt(g),A={collider:r,separation:S,axis:b,point:a.end,side:a,localSide:h};return[new Se(r,t,b.scale(S),b,b.perpendicular(),[a.end],[h.end],A)]}const l=s.dot(s),c=i.begin.scale(n).add(i.end.scale(o)).scale(1/l),d=e.sub(c),_=d.dot(d);if(_>r.radius*r.radius)return[];let f=s.perpendicular();f.dot(e.sub(i.begin))<0&&(f.x=-f.x,f.y=-f.y),f=f.normalize();const m=r.radius-Math.sqrt(_),p=f.scale(m),x={collider:r,separation:m,axis:f,point:c,side:a,localSide:h};return[new Se(r,t,p,f.negate(),f.negate().perpendicular(),[c],[c.sub(t.worldPos)],x)]},CollideEdgeEdge(){return[]},CollidePolygonEdge(r,t){var e;const i=r.center,n=t.center.sub(i).normalize(),o=new lt({points:[t.begin,t.end,t.end.add(n.scale(100)),t.begin.add(n.scale(100))],offset:t.offset});o.owner=t.owner,((e=t.owner)==null?void 0:e.get(E))&&o.update(t.owner.get(E).get());const h=this.CollidePolygonPolygon(r,o);return h.length&&(h[0].colliderB=t,h[0].id=mt.calculatePairHash(r.id,t.id)),h},CollidePolygonPolygon(r,t){const e=Xe.findPolygonPolygonSeparation(r,t);if(e.separation>0)return[];const i=Xe.findPolygonPolygonSeparation(t,r);if(i.separation>0)return[];const s=e.separation>i.separation?e:i,n=s.collider===r?t:r,o=s.collider===r?r:t,a=n.transform.inverse.multiply(o.transform.matrix,Hh),h=a.getRotation(),l=o.normals[s.sideId].rotate(h,Oh,Nh);let c=Number.MAX_VALUE,d=0;for(let v=0;v<n.normals.length;v++){const g=l.dot(n.normals[v]);g<c&&(c=g,d=v)}if(!s.localSide||!s.localAxis||!s.axis)return[];const _=s.localSide.transform(a),f=s.localAxis.perpendicular().negate().rotate(h),p=new it(n.points[d],n.points[(d+1)%n.points.length]).clip(f.negate(),-f.dot(_.begin),!1);let x=null;if(p&&(x=p.clip(f,f.dot(_.end),!1)),x){const v=[],g=[],b=x.getPoints();for(let M=0;M<b.length;M++){const C=b[M];_.below(C)&&(v.push(C),g.push(n.transform.apply(C)))}let S=s.axis,A=S.perpendicular();return t.center.sub(r.center).dot(S)<0&&(S=S.negate(),A=S.perpendicular()),[new Se(r,t,S.scale(-s.separation),S,A,g,v,s)]}return[]},FindContactSeparation(r,t){var e,i,s,n;const o=r.colliderA,a=(i=(e=r.bodyA)==null?void 0:e.transform)!=null?i:new E,h=r.colliderB,l=(n=(s=r.bodyB)==null?void 0:s.transform)!=null?n:new E;if(o instanceof dt&&h instanceof dt){const c=o.radius+h.radius,d=a.pos.distance(l.pos);return-(c-d)}if(o instanceof lt&&h instanceof lt&&r.info.localSide){let c,d;return r.info.collider===o?(c=new it(a.apply(r.info.localSide.begin).add(o.offset),a.apply(r.info.localSide.end).add(o.offset)),d=l.apply(t).add(h.offset)):(c=new it(l.apply(r.info.localSide.begin).add(h.offset),l.apply(r.info.localSide.end).add(h.offset)),d=a.apply(t).add(o.offset)),c.distanceToPoint(d,!0)}if(o instanceof lt&&h instanceof dt||h instanceof lt&&o instanceof dt){const c=a.apply(t);if(r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof Et&&h instanceof lt||h instanceof Et&&o instanceof lt){let c;if(r.info.collider===o?c=l.apply(t):c=a.apply(t),r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof dt&&h instanceof Et||h instanceof dt&&o instanceof Et){const c=l.apply(t);let d;o instanceof dt&&(d=o.getFurthestPoint(r.normal));const _=c.distance(d);if(r.info.side)return _>0?-_:0}return 0}};class dt extends di{constructor(t){super(),this.offset=w.Zero,this._globalMatrix=tt.identity(),this._localBoundsDirty=!0,this.offset=t.offset||w.Zero,this.radius=t.radius||0,this._globalMatrix.translate(this.offset.x,this.offset.y)}get worldPos(){return this._globalMatrix.getPosition()}get radius(){var t;if(this._radius)return this._radius;const e=this._transform,i=(t=e==null?void 0:e.globalScale)!=null?t:w.One;return this._radius=this._naturalRadius*Math.min(i.x,i.y)}set radius(t){var e;const i=this._transform,s=(e=i==null?void 0:i.globalScale)!=null?e:w.One;this._naturalRadius=t/Math.min(s.x,s.y),this._localBoundsDirty=!0,this._radius=t}clone(){return new dt({offset:this.offset.clone(),radius:this.radius})}get center(){return this._globalMatrix.getPosition()}contains(t){var e,i;return((i=(e=this._transform)==null?void 0:e.pos)!=null?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){var i,s;const n=this.center,o=t.dir,a=t.pos,h=n.sub(a),l=o.scale(h.dot(o)),d=h.sub(l).magnitude;if(d>this.radius)return null;{let _=0;if(cr(d,this.radius,1e-4)){if(_=-o.dot(a.sub(n)),_>0&&_<e){const f=t.getPoint(_);return{point:f,normal:f.sub(n).normalize(),collider:this,body:(i=this.owner)==null?void 0:i.get(U),distance:_}}return null}else{const f=Math.sqrt(Math.pow(o.dot(a.sub(n)),2)-Math.pow(a.sub(n).distance(),2)+Math.pow(this.radius,2)),m=-o.dot(a.sub(n))+f,p=-o.dot(a.sub(n))-f,x=[];m>=0&&x.push(m),p>=0&&x.push(p);const v=Math.min(...x);if(v<=e){const g=t.getPoint(v);return{point:g,normal:g.sub(n).normalize(),collider:this,body:(s=this.owner)==null?void 0:s.get(U),distance:v}}return null}}}getClosestLineBetween(t){if(t instanceof dt)return jt.CircleCircleClosestLine(this,t);if(t instanceof lt)return jt.PolygonCircleClosestLine(t,this).flip();if(t instanceof Et)return jt.CircleEdgeClosestLine(this,t).flip();throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ht.CollideCircleCircle(this,t);if(t instanceof lt)return Ht.CollideCirclePolygon(this,t);if(t instanceof Et)return Ht.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(){return this.localBounds.transform(this._globalMatrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=new D(-this._naturalRadius,-this._naturalRadius,+this._naturalRadius,+this._naturalRadius),this._localBoundsDirty=!1),this._localBounds}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){var e;this._transform=t,((e=t.matrix)!=null?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y),this._radius=void 0}project(t){const e=[],s=this.center.dot(t);return e.push(s),e.push(s+this.radius),e.push(s-this.radius),new ri(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e,i){var s,n,o,a;const{lineWidth:h}={lineWidth:1,...i},l=this._transform,c=(s=l==null?void 0:l.globalScale)!=null?s:w.One,d=(n=l==null?void 0:l.globalRotation)!=null?n:0,_=(o=l==null?void 0:l.globalPos)!=null?o:w.Zero;t.save(),t.translate(_.x,_.y),t.rotate(d),t.scale(c.x,c.y),t.debug.drawCircle((a=this.offset)!=null?a:w.Zero,this._naturalRadius,T.Transparent,e,h),t.restore()}}function Ft(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,{set:(e,i,s)=>(e[i]!==s&&(e[i]=s,typeof i=="string"&&i[0]!=="_"&&t(e)),!0),get:(e,i)=>i!=="__isProxy"?e[i]:!0}):r)}const Ur=(r=[],t,e)=>({get:(i,s)=>s==="__isProxy"?!0:typeof i[s]=="object"&&i[s]!=null?new Proxy(i[s],Ur([...r,s],t,e)):i[s],set:(i,s,n)=>(typeof s=="string"&&s[0]!=="_"&&t(e),i[s]=n,!0)});function Gh(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,Ur([],t,r)):r)}const Or=class Va{constructor(t){this.id=Va._ID++,this.transform=tt.identity(),this._transformStale=!0,this.showDebug=!1,this._flipHorizontal=!1,this._flipVertical=!1,this._rotation=0,this.opacity=1,this._scale=w.One,this._width=0,this._height=0;var e,i,s,n,o,a,h;t&&(this.origin=(e=t.origin)!=null?e:this.origin,this.flipHorizontal=(i=t.flipHorizontal)!=null?i:this.flipHorizontal,this.flipVertical=(s=t.flipVertical)!=null?s:this.flipVertical,this.rotation=(n=t.rotation)!=null?n:this.rotation,this.opacity=(o=t.opacity)!=null?o:this.opacity,this.scale=(a=t.scale)!=null?a:this.scale,this.tint=(h=t.tint)!=null?h:this.tint,t.width&&(this._width=t.width),t.height&&(this._height=t.height))}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=Ft(t,()=>{this._transformStale=!0}),this._transformStale=!0}get origin(){return this._origin}set origin(t){t&&(this._origin=Ft(t,()=>{this._transformStale=!0})),this._transformStale=!0}cloneGraphicOptions(){return{width:this.width/this.scale.x,height:this.height/this.scale.y,origin:this.origin?this.origin.clone():void 0,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():void 0,tint:this.tint?this.tint.clone():void 0}}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 D.fromDimension(this.width,this.height,w.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=(e=this.origin)!=null?e:y(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()}};Or._ID=0;let ot=Or;var Nr=(r=>(r.Forward="forward",r.Backward="backward",r))(Nr||{}),Hr=(r=>(r.End="end",r.Loop="loop",r.PingPong="pingpong",r.Freeze="freeze",r))(Hr||{});const Wh={Frame:"frame",Loop:"loop",End:"end"},Gr=class hr extends ot{constructor(t){var e,i,s;super(t),this.events=new Y,this.frames=[],this.strategy="loop",this.frameDuration=100,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._pingPongDirection=1,this._done=!1,this._playing=!0,this._speed=1,this._wasResetDuringFrameCalc=!1,this._reversed=!1,this.frames=t.frames,this.speed=(e=t.speed)!=null?e:this.speed,this.strategy=(i=t.strategy)!=null?i:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:(s=t.frameDuration)!=null?s:this.frameDuration,this.data=t.data?new Map(Object.entries(t.data)):new Map,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){const t=this.constructor;return new t({frames:this.frames.map(e=>({...e})),frameDuration:this.frameDuration,speed:this.speed,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}get width(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.width*this.scale.x):0}get height(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.height*this.scale.y):0}static fromSpriteSheet(t,e,i,s="loop",n){const o=t.sprites.length-1,a=[],h=[];return e.forEach(l=>{l<0||l>o?h.push(l):a.push(l)}),h.length&&hr._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: frames ${h.join(",")} will not be shown`),new this({frames:a.map(l=>({graphic:t.sprites[l],duration:i})),strategy:s,data:n})}static fromSpriteSheetCoordinates(t){var e;const{spriteSheet:i,frameCoordinates:s,durationPerFrame:n,durationPerFrameMs:o,speed:a,strategy:h,reverse:l,data:c}=t,d=(e=n!=null?n:o)!=null?e:100,_=[];for(const f of s){const{x:m,y:p,duration:x,options:v}=f,g=i.getSprite(m,p,v);g?_.push({graphic:g,duration:x!=null?x:d}):hr._LOGGER.warn(`Skipping frame! SpriteSheet does not have coordinate (${m}, ${p}), please check your SpriteSheet to confirm that sprite exists`)}return new this({frames:_,strategy:h,speed:a,reverse:l,data:c})}get speed(){return this._speed}set speed(t){this._speed=L(Math.abs(t),0,1/0)}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get currentFrameTimeLeft(){return this._timeLeftInFrame}get isPlaying(){return this._playing}get isReversed(){return this._reversed}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!!(this._reversed&&this._pingPongDirection===1)?"backward":"forward"}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._wasResetDuringFrameCalc=!0,this._done=!1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=this.frameDuration;const t=this.frames[this._currentFrame];t&&(this._timeLeftInFrame=(t==null?void 0:t.duration)||this.frameDuration)}get canFinish(){switch(this.strategy){case"end":case"freeze":return!0;default:return!1}}get done(){return this._done}goToFrame(t,e){this._currentFrame=t,this._timeLeftInFrame=e!=null?e:this.frameDuration;const i=this.frames[this._currentFrame];i&&!this._done&&(this._timeLeftInFrame=e!=null?e:(i==null?void 0:i.duration)||this.frameDuration,this.events.emit("frame",{...i,frameIndex:this.currentFrameIndex}))}_nextFrame(){this._wasResetDuringFrameCalc=!1;const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case"loop":{e=(t+1)%this.frames.length,e===0&&this.events.emit("loop",this);break}case"end":{e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break}case"freeze":{e=L(t+1,0,this.frames.length-1),t+1>=this.frames.length&&(this._done=!0,this.events.emit("end",this));break}case"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;break}}return this._wasResetDuringFrameCalc?(this._wasResetDuringFrameCalc=!1,this._currentFrame):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._speed,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame())))}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic&&this.currentFrame.graphic.draw(t,e,i)}};Gr._LOGGER=F.getInstance();let Gi=Gr;class $e extends ot{constructor(t){var e;super(t),this._logger=F.getInstance(),this.useAnchor=!0,this.members=[],this.members=t.members,this.useAnchor=(e=t.useAnchor)!=null?e:this.useAnchor,this._updateDimensions()}clone(){return new $e({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){const t=this.localBounds;return this.width=t.width,this.height=t.height,t}get localBounds(){const t=new D;for(const e of this.members)if(e instanceof ot)e.localBounds.combine(t,t);else{const{graphic:i,offset:s,useBounds:n}=e;i?(n===void 0?!0:n)&&i.localBounds.translate(s).combine(t,t):this._logger.warnOnce(`Graphics group member has an null or undefined graphic, member definition: ${JSON.stringify(e)}.`)}return t}_isAnimationOrGroup(t){return t instanceof Gi||t instanceof $e}tick(t,e){for(const i of this.members){let s;i instanceof ot?s=i:s=i.graphic,this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){let e;t instanceof ot?e=t:e=t.graphic,this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,this.useAnchor?e:0,this.useAnchor?i:0)}_drawImage(t,e,i){const s=w.Zero;for(const n of this.members){let o;n instanceof ot?o=n:(o=n.graphic,n.offset.clone(s)),o&&(t.save(),t.translate(e,i),o.draw(t,s.x,s.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore())}}}const Vh={Complete:"complete",Load:"load",LoadStart:"loadstart",Progress:"progress",Error:"error"};class fi{constructor(t,e,i=!1){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=F.getInstance(),this.events=new Y}isLoaded(){return this.data!==null}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise((t,e)=>{if(this.data!==null){this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),t(this.data);return}const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",s=>this.events.emit("loadstart",s)),i.addEventListener("progress",s=>this.events.emit("progress",s)),i.addEventListener("error",s=>this.events.emit("error",s)),i.addEventListener("load",s=>this.events.emit("load",s)),i.addEventListener("load",()=>{if(i.status!==0&&i.status!==200){this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),e(new Error(i.statusText));return}if(i.response instanceof Blob&&i.response.type==="text/html"){const s=`Expected blob (usually image) data from the server when loading ${this.path}, but got HTML content instead!
27
-
28
- Check your server configuration, for example Vite serves static files from the /public folder`;this.events.emit("error",i.response),e(new Error(s));return}this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)}),i.send()})}}class zt extends ot{constructor(t){var e,i;super(t),this._logger=F.getInstance(),this._dirty=!0,this.image=t.image;const{width:s,height:n}=t;this.sourceView=(e=t.sourceView)!=null?e:{x:0,y:0,width:s!=null?s:0,height:n!=null?n:0},this.destSize=(i=t.destSize)!=null?i:{width:s!=null?s:0,height:n!=null?n:0},this._updateSpriteDimensions(),this.image.ready.then(()=>{this._updateSpriteDimensions()})}static from(t,e){return new zt({image:t,...e})}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,o;const{width:a,height:h}=this.image;this.sourceView.width=((t=this.sourceView)==null?void 0:t.width)||a,this.sourceView.height=((e=this.sourceView)==null?void 0:e.height)||h,this.destSize.width=((i=this.destSize)==null?void 0:i.width)||((s=this.sourceView)==null?void 0:s.width)||a,this.destSize.height=((n=this.destSize)==null?void 0:n.height)||((o=this.sourceView)==null?void 0:o.height)||h,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._logger.warnOnce(`ImageSource ${this.image.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.
29
-
30
- Read https://excaliburjs.com/docs/imagesource for more information.`)}clone(){return new zt({image:this.image,sourceView:{...this.sourceView},destSize:{...this.destSize},...this.cloneGraphicOptions()})}}var vt=(r=>(r.Pixel="Pixel",r.Blended="Blended",r))(vt||{});function Ye(r){switch(r){case"Pixel":return"Pixel";case"Blended":return"Blended";default:return}}var _t=(r=>(r.Clamp="Clamp",r.Repeat="Repeat",r.Mirror="Mirror",r))(_t||{});function Gt(r){switch(r){case"Clamp":return"Clamp";case"Repeat":return"Repeat";case"Mirror":return"Mirror";default:return"Clamp"}}const gi=class kt{constructor(t,e){this._garbageCollector=e,this._textureMap=new Map,this._collect=s=>{var n;if(this._gl){const o=(n=s.dataset.originalSrc)!=null?n:s.constructor.name;return kt._LOGGER.debug(`WebGL Texture for ${o} collected`),this.delete(s),!0}return!1};var i;this._gl=t,kt._MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE),this._garbageCollector&&(kt._LOGGER.debug("WebGL Texture collection interval:",this._garbageCollector.collectionInterval),(i=this._garbageCollector.garbageCollector)==null||i.registerCollector("texture",this._garbageCollector.collectionInterval,this._collect))}dispose(){for(const[t]of this._textureMap)this.delete(t);this._textureMap.clear(),this._gl=null}get(t){return this._textureMap.get(t)}has(t){return this._textureMap.has(t)}load(t,e,i=!1){var s,n;const o=this._gl;if(!o)return null;const{filtering:a,wrapping:h}={...e};let l=null;if(this.has(t)&&(l=this.get(t)),l)return i&&(o.bindTexture(o.TEXTURE_2D,l),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t)),(s=this._garbageCollector)==null||s.garbageCollector.touch(t),l;l=o.createTexture(),kt.checkImageSizeSupportedAndLog(t),o.bindTexture(o.TEXTURE_2D,l),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0);let c;h&&(typeof h=="string"?c={x:h,y:h}:c={x:h.x,y:h.y});const{x:d,y:_}=c!=null?c:kt.wrapping;switch(d){case _t.Clamp:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE);break;case _t.Repeat:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.REPEAT);break;case _t.Mirror:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.MIRRORED_REPEAT);break;default:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE)}switch(_){case _t.Clamp:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);break;case _t.Repeat:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.REPEAT);break;case _t.Mirror:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.MIRRORED_REPEAT);break;default:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE)}const f=a!=null?a:kt.filtering;return o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,f===vt.Pixel?o.NEAREST:o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,f===vt.Pixel?o.NEAREST:o.LINEAR),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t),this._textureMap.set(t,l),(n=this._garbageCollector)==null||n.garbageCollector.addCollectableResource("texture",t),l}delete(t){const e=this._gl;if(e&&this.has(t)){const i=this.get(t);i&&(this._textureMap.delete(t),e.deleteTexture(i))}}static checkImageSizeSupportedAndLog(t){var e;const i=(e=t.dataset.originalSrc)!=null?e:"internal canvas bitmap";return t.width>kt._MAX_TEXTURE_SIZE||t.height>kt._MAX_TEXTURE_SIZE?(kt._LOGGER.error(`The image [${i}] provided to Excalibur is too large for the device's maximum texture size of (${kt._MAX_TEXTURE_SIZE}x${kt._MAX_TEXTURE_SIZE}) please resize to an image for excalibur to render properly.
31
-
32
- Images will likely render as black rectangles.
33
-
34
- Read 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)&&kt._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).
35
-
36
- Images will likely render as black rectangles on some mobile platforms.
37
-
38
- Read more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!0)}};gi._LOGGER=F.getInstance(),gi.filtering=vt.Blended,gi.wrapping={x:_t.Clamp,y:_t.Clamp},gi._MAX_TEXTURE_SIZE=4096;let Ze=gi;const N={Filtering:"filtering",WrappingX:"wrapping-x",WrappingY:"wrapping-y",ForceUpload:"forceUpload"};class Wt{constructor(t,e,i){this._logger=F.getInstance(),this.data=new Image,this._readyFuture=new xt,this.ready=this._readyFuture.promise,this.path=t;let s=!1,n;typeof e=="boolean"?s=e:{filtering:i,wrapping:n,bustCache:s}={...e},this._resource=new fi(t,"blob",s),this.filtering=i!=null?i:this.filtering,typeof n=="string"?this.wrapping={x:n,y:n}:this.wrapping=n!=null?n:this.wrapping,t.endsWith(".gif")&&this._logger.warn(`Use the ex.Gif type to load gifs, you may have mixed results with ${t} in ex.ImageSource. Fully supported: svg, jpg, bmp, and png`)}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}static fromHtmlImageElement(t,e){const i=new Wt("");if(i._src="image-element",i.data=t,i.data.setAttribute("data-original-src","image-element"),e!=null&&e.filtering?i.data.setAttribute(N.Filtering,e==null?void 0:e.filtering):i.data.setAttribute(N.Filtering,vt.Blended),e!=null&&e.wrapping){let s;typeof e.wrapping=="string"?s={x:e.wrapping,y:e.wrapping}:s={x:e.wrapping.x,y:e.wrapping.y},i.data.setAttribute(N.WrappingX,s.x),i.data.setAttribute(N.WrappingY,s.y)}else i.data.setAttribute(N.WrappingX,_t.Clamp),i.data.setAttribute(N.WrappingY,_t.Clamp);return Ze.checkImageSizeSupportedAndLog(t),i._readyFuture.resolve(t),i}static fromHtmlCanvasElement(t,e){const i=new Wt("");if(i._src="canvas-element-blob",i.data.setAttribute("data-original-src","canvas-element-blob"),e!=null&&e.filtering?i.data.setAttribute(N.Filtering,e==null?void 0:e.filtering):i.data.setAttribute(N.Filtering,vt.Blended),e!=null&&e.wrapping){let s;typeof e.wrapping=="string"?s={x:e.wrapping,y:e.wrapping}:s={x:e.wrapping.x,y:e.wrapping.y},i.data.setAttribute(N.WrappingX,s.x),i.data.setAttribute(N.WrappingY,s.y)}else i.data.setAttribute(N.WrappingX,_t.Clamp),i.data.setAttribute(N.WrappingY,_t.Clamp);return Ze.checkImageSizeSupportedAndLog(t),t.toBlob(s=>{const n=URL.createObjectURL(s);i.image.onload=()=>{URL.revokeObjectURL(n),i.data=i.image,i._readyFuture.resolve(i.image)},i.image.src=n}),i}static fromSvgString(t,e){const i=new Blob([t],{type:"image/svg+xml"}),s=URL.createObjectURL(i);return new Wt(s,e)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){var t,e,i,s;if(this.isLoaded())return this.data;try{let n;if(this.path.includes("data:image/"))n=this.path;else{const h=await this._resource.load();n=URL.createObjectURL(h)}const o=new Image,a=new xt;o.onload=()=>a.resolve(),o.src=n,o.setAttribute("data-original-src",this.path),await a.promise,this.data=o,Ze.checkImageSizeSupportedAndLog(this.data)}catch(n){throw`Error loading ImageSource from path '${this.path}' with error [${n.message}]`}return this.data.setAttribute(N.Filtering,this.filtering),this.data.setAttribute(N.WrappingX,(e=(t=this.wrapping)==null?void 0:t.x)!=null?e:_t.Clamp),this.data.setAttribute(N.WrappingY,(s=(i=this.wrapping)==null?void 0:i.y)!=null?s:_t.Clamp),this._readyFuture.resolve(this.data),this.data}toSprite(t){return zt.from(this,t)}unload(){this.data=new Image}}class je extends ot{constructor(t){var e,i,s,n,o,a,h,l,c,d;super(Er({...t},["width","height"])),this.lineCap="butt",this.quality=1,this._dirty=!0,this._smoothing=!1,this._color=Ft(T.Black,()=>this.flagDirty()),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.quality=(e=t.quality)!=null?e:this.quality,this.color=(i=t.color)!=null?i:T.Black,this.strokeColor=t==null?void 0:t.strokeColor,this.smoothing=(s=t.smoothing)!=null?s:this.smoothing,this.lineWidth=(n=t.lineWidth)!=null?n:this.lineWidth,this.lineDash=(o=t.lineDash)!=null?o:this.lineDash,this.lineCap=(a=t.lineCap)!=null?a:this.lineCap,this.padding=(h=t.padding)!=null?h:this.padding,this.filtering=(l=t.filtering)!=null?l:this.filtering),this._bitmap=document.createElement("canvas");const _=(c=t==null?void 0:t.width)!=null?c:this._bitmap.width,f=(d=t==null?void 0:t.height)!=null?d:this._bitmap.height;this.width=_,this.height=f;const m=this._bitmap.getContext("2d");if(m)this._ctx=m;else throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic")}cloneRasterOptions(){return{color:this.color?this.color.clone():void 0,strokeColor:this.strokeColor?this.strokeColor.clone():void 0,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(((t=this._originalWidth)!=null?t:this._bitmap.width)+this.padding*2)*1}_getTotalHeight(){var t;return(((t=this._originalHeight)!=null?t:this._bitmap.height)+this.padding*2)*1}get localBounds(){return D.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,w.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=Ft(t,()=>this.flagDirty())}get strokeColor(){return this._strokeColor}set strokeColor(t){this.flagDirty(),t&&(this._strokeColor=Ft(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,n;this._bitmap.width=this._getTotalWidth()*this.quality,this._bitmap.height=this._getTotalHeight()*this.quality,this._bitmap.setAttribute(N.Filtering,this.filtering),this._bitmap.setAttribute(N.ForceUpload,"true"),t.scale(this.quality,this.quality),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash((e=this.lineDash)!=null?e:t.getLineDash()),t.lineCap=this.lineCap,t.strokeStyle=(s=(i=this.strokeColor)==null?void 0:i.toString())!=null?s:"",t.fillStyle=(n=this.color)==null?void 0:n.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.scale(1/this.quality,1/this.quality),t.drawImage(this._bitmap,e,i)}}var fn=(r=>(r.Em="em",r.Rem="rem",r.Px="px",r.Pt="pt",r.Percent="%",r))(fn||{}),gn=(r=>(r.Left="left",r.Right="right",r.Center="center",r.Start="start",r.End="end",r))(gn||{}),pn=(r=>(r.Top="top",r.Hanging="hanging",r.Middle="middle",r.Alphabetic="alphabetic",r.Ideographic="ideographic",r.Bottom="bottom",r))(pn||{}),mn=(r=>(r.Normal="normal",r.Italic="italic",r.Oblique="oblique",r))(mn||{}),vn=(r=>(r.LeftToRight="ltr",r.RightToLeft="rtl",r))(vn||{});class Qe{constructor(t,e,i=1){this.builder=t,this.cleaner=e,this._pool=[],this._size=0,this.grow(i)}grow(t){if(t>0){this._size+=t;for(let e=0;e<t;e++)this._pool.push(this.builder())}}rent(t=!1){return this._pool.length===0&&this.grow(this._size),t?this.cleaner(this._pool.pop()):this._pool.pop()}return(t){this._pool.push(t)}}class qh{constructor(){this._pool=new Qe(()=>tt.identity(),t=>t.reset(),100),this._transforms=[],this._currentTransform=this._pool.rent(!0)}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone(this._pool.rent())}restore(){this._pool.return(this._currentTransform),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)}reset(){this._currentTransform.reset()}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class Xh{constructor(){this.opacity=1,this.z=0,this.tint=T.White,this.material=null}}class Wr{constructor(){this._pool=new Qe(()=>new Xh,t=>(t.opacity=1,t.z=0,t.tint=T.White,t.material=null,t),100),this.current=this._pool.rent(!0),this._states=[]}_cloneState(t){var e;return t.opacity=this.current.opacity,t.z=this.current.z,t.tint=(e=this.current.tint)==null?void 0:e.clone(),t.material=this.current.material,t}save(){this._states.push(this.current),this.current=this._cloneState(this._pool.rent())}restore(){this._pool.return(this.current),this.current=this._states.pop()}}class Wi extends ot{constructor(t){super(t),this._text="",this.alphabet="",this.shadow=void 0,this.caseInsensitive=!1,this.spacing=0,this.lineHeight=void 0,this._logger=F.getInstance();const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:o,lineHeight:a}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=s!=null?s:this.caseInsensitive,this.spacing=n!=null?n:this.spacing,this.shadow=o!=null?o:this.shadow,this.lineHeight=a!=null?a:this.lineHeight}_getCharacterSprites(t){const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let n=0;n<i.length;n++){const o=i[n];let a=s.indexOf(o);a===-1&&(a=0,this._logger.warnOnce(`SpriteFont - Cannot find letter '${o}' in configured alphabet '${s}'.`),this._logger.warnOnce("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."));const h=this.spriteSheet.sprites[a];h?e.push(h):(this._logger.warnOnce(`SpriteFont - Cannot find sprite for '${o}' at index '${a}' in configured SpriteSheet`),this._logger.warnOnce("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."))}return e}measureText(t,e){const i=this._getLinesFromText(t,e),s=i.reduce((h,l)=>h.length>l.length?h:l),n=this._getCharacterSprites(s);let o=0,a=0;for(const h of n)o+=h.width+this.spacing,a=Math.max(a,h.height);return D.fromDimension(o*this.scale.x,a*i.length*this.scale.y,w.Zero)}_drawImage(t,e,i,s){var n;let o=0,a=0,h=0;const l=this._getLinesFromText(this._text,s);for(const c of l){for(const d of this._getCharacterSprites(c))d.draw(t,e+o,i+a),o+=d.width+this.spacing,h=Math.max(h,d.height);o=0,a+=(n=this.lineHeight)!=null?n:h}}render(t,e,i,s,n,o){this._text=e;const a=this.measureText(e,o);this.width=a.width,this.height=a.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,o),this._postDraw(t),t.restore()),this._preDraw(t,s,n),this._drawImage(t,0,0,o),this._postDraw(t)}clone(){return new Wi({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}_getLinesFromText(t,e){var i;if(this._cachedText===t&&this._cachedRenderWidth===e&&((i=this._cachedLines)!=null&&i.length))return this._cachedLines;const s=t.split(`
39
- `);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class pi extends zt{constructor(t){super({image:t.image,sourceView:t.sourceView,destSize:{width:t.width,height:t.height},flipHorizontal:t.flipHorizontal,flipVertical:t.flipVertical,rotation:t.rotation,scale:t.scale,opacity:t.opacity,tint:t.tint,origin:t.origin}),this._ready=new xt,this.ready=this._ready.promise,this._options=t,this.image.isLoaded()?this._applyTiling():this.image.ready.then(()=>this._applyTiling())}static fromSprite(t,e){return new pi({sourceView:{...t.sourceView},width:t.width,height:t.height,...e,image:t.image})}_applyTiling(){const{width:t,height:e,filtering:i,wrapping:s}={...this._options},n=document.createElement("canvas");n.width=this.sourceView.width,n.height=this.sourceView.height,n.getContext("2d").drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,0,0,this.sourceView.width,this.sourceView.height);const a=Wt.fromHtmlCanvasElement(n,{wrapping:s!=null?s:_t.Repeat,filtering:i});t&&(this.destSize.width=t,this.sourceView.width=t),e&&(this.destSize.height=e,this.sourceView.height=e),this.sourceView.x=0,this.sourceView.y=0,this.image=a,this.image.ready.then(()=>this._ready.resolve())}}class Ae{constructor(t){this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=i!=null?i:1,this.columns=s!=null?s:this.sprites.length}getSprite(t,e,i){var s,n,o,a,h,l,c,d,_;if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const f=t+e*this.columns,m=this.sprites[f];if(m){if(i){const p=m.clone();return p.flipHorizontal=(s=i.flipHorizontal)!=null?s:p.flipHorizontal,p.flipVertical=(n=i.flipVertical)!=null?n:p.flipVertical,p.width=(o=i.width)!=null?o:p.width,p.height=(a=i.height)!=null?a:p.height,p.rotation=(h=i.rotation)!=null?h:p.rotation,p.scale=(l=i.scale)!=null?l:p.scale,p.opacity=(c=i.opacity)!=null?c:p.opacity,p.tint=(d=i.tint)!=null?d:p.tint,p.origin=(_=i.origin)!=null?_:p.origin,p}return m}throw Error(`Invalid sprite coordinates (${t}, ${e})`)}getTiledSprite(t,e,i){if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const s=t+e*this.columns,n=this.sprites[s];if(n)return pi.fromSprite(n,i);throw Error(`Invalid sprite coordinates (${t}, ${e})`)}async getSpriteAsStandalone(t,e){if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const i=t+e*this.columns,s=this.sprites[i],n=document.createElement("canvas"),o=n.getContext("2d");if(n.width=s.width,n.height=s.height,!s)throw Error(`Invalid sprite coordinates (${t}, ${e})`);if(!o)throw Error("Unable to create canvas context");o.drawImage(s.image.image,s.sourceView.x,s.sourceView.y,s.sourceView.width,s.sourceView.height,0,0,s.sourceView.width,s.sourceView.height);const a=new Wt(n.toDataURL());return await a.load(),new zt({image:a,sourceView:{x:0,y:0,width:s.width,height:s.height},destSize:{width:s.width,height:s.height}})}async getSpriteAsImage(t,e){if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const i=t+e*this.columns,s=this.sprites[i],n=document.createElement("canvas"),o=n.getContext("2d");if(n.width=s.width,n.height=s.height,!s)throw Error(`Invalid sprite coordinates (${t}, ${e})`);if(!o)throw Error("Unable to create canvas context");o.drawImage(s.image.image,s.sourceView.x,s.sourceView.y,s.sourceView.width,s.sourceView.height,0,0,s.sourceView.width,s.sourceView.height);const a=new Image(s.width,s.height);return a.src=n.toDataURL(),await new Promise((h,l)=>{a.onload=()=>{h(a)},a.onerror=c=>{l(c)}})}static fromImageSourceWithSourceViews(t){const e=t.sourceViews.map(i=>new zt({image:t.image,sourceView:i}));return new Ae({sprites:e})}static fromImageSource(t){var e;const i=[];t.spacing=(e=t.spacing)!=null?e:{};const{image:s,grid:{rows:n,columns:o,spriteWidth:a,spriteHeight:h},spacing:{originOffset:l,margin:c}}=t;let d,_;l instanceof w?_={x:l.x,y:l.y}:l&&(_={x:l.x,y:l.y}),c instanceof w?d={x:c.x,y:c.y}:c&&(d={x:c.x,y:c.y});const f={x:0,y:0,..._},m={x:0,y:0,...d};for(let p=0;p<o;p++)for(let x=0;x<n;x++)i[p+x*o]=new zt({image:s,sourceView:{x:p*a+m.x*p+f.x,y:x*h+m.y*x+f.y,width:a,height:h},destSize:{height:h,width:a}});return new Ae({sprites:i,rows:n,columns:o})}clone(){return new Ae({sprites:this.sprites.map(t=>t.clone()),rows:this.rows,columns:this.columns})}}const $h="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADACAYAAABS3GwHAAAAAXNSR0IB2cksfwAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB+kLGhIwLEfXSw4AAAaVSURBVHja7d3BduQoDIVhas68/ytnNtOz6DPVBiEBtr9/l8RxMBVzQUiX1gAAAAC8iU/WjX5+fn5aa+3z+XxGruv9vez2RH/+6/v/dWBnu6PPOfsc+HO//qUr8Gb+vsub2qsYv4/Q0RF7VBFWK9jvzzPajurr7wIFAAU4eeS/+vrbCHg1Yr1tTm0t8f/PSQHQRIEWzllXrwF65/6jUayrOfnq/pxt/1W0K/t5q+/f2z8UANYAj5K0wTVBdP/ibnPn0TVT9XOu6q+rdlMAUIAT3+hoFChr5H5aVKR3P+H0NWH250cBQAFOfONH5/Kr5qzfdpZXPX9Wv1df3+wEA0B7X5Zlb4yfAgAAAAAAAAAAAABtUUXYroqqrAqv3uzPaEVSdUVVdf+0l/r/fOsfO8FoskETndKy8rdX5etX+eKMKuHq/lnlC5Tty5Q1I+EMB/TUA/S6IGS7JWR7aGatSZAzUo+ukUY9Wns/PwqAJgqU4LRW5X7c+8Zn+8yMRo2y5tJZUaDT3BdO+fuc4YA/rQFWvcmzUZUrH5vonDOqINVRmd5a6OznzaqZznaGy4oKUQBQgJVzxlkntqfMWXe3v2ofoDdas3o/gTMckJkLNDqHW5UbE/X2rM69OSVX6q0nxFgDAMDTfX4aXyAAAAAAAAAAAAAgwRcoK3do9f1Py2WKukJUV8BluVTscgnhCwS0CV+gX9/PeiOr3/is61fV/kazK3edWJ/9d6LKltX/FAAUYOWbeerJ9Nq/px7gyoWkuh0UABTgJLfe09szW4GVFZ26+8gf/fyjUScKAIwoQO/cf3TEqnZ7rp6LZ0dtshzgqkby7BG32oeIAgCZa4BRH5hVc9m7uxS0m0atnqYEFAAUoOdNyt75u7p/tD2nuCtX9+dVnPybE9tse66U4BS36t7npQAAAAAAAAAAAAAAAKA9+KT4U3x7Vp1ZVuVScer1VefyRrNEo6c/qggD2sJzgk/3Bdrlk/MUF4psp7mqfP5ZRzoKAOx0heALFPPHuaqXqPLoPKVibLQfKAAQUYC7V4S9rfZ298i/SgmitekUAMiIAlXP3bPcnk+Zo0fbmx3l2O30dno0jgKAArQXuRHvfo5R1+OskXS3896pnycFAAU40ffm1PtHozTZnpbZUbjRHePqqOCq+1IANNmghW+eXBycDAUAAAAAAAAA8DZ+/kVPoNkHANo7d4Lvmoe+K4cl68yvXdmeWbXFd8sAoABoskFfVHNbpSS7FS4rO7ZtPrmdAgB3qggbzS/ffe5vlQtG1jnEs897F2/OrH6Z/f+hAKAAFVGH6EhW7ZY82v5vc9tZt+TZ/smae896c+5yxMv6f6AAoADtxd6g2ecKtIdGvZ4aHaQAoABPise/3WW6WmmfpoAUABRg5c5flTt09CysXb5DVWuX6jn76LkFuxS3tx0UAMDz6y6u/t5b60AoANQDYL0X5+66CNEwCgAAAAAAAAAAzQ4rgv2bfV2zDwA09QB41rnNuyvtKAAoQIXvSm/Vf/b9s10bql0qVl9/9wq5bGc+CgAKUOm7En2DR9/ou7s2jPrjZNU+jyrJ6ufvVbRo+ygAKMAJfj6n1paujqKsUrK7tafXIY4CAE/aB9g9N101R89aC51+Us8uxf32NQUABajw7Vl97sDo2iHa/t6ReVQxen12ou2/2icZ7denKBIFACqy8mRlyoptXCEAUSDw+aEAAAAAAAAAANDOOh9gNEfjbVmGszXTu/vp6Z9X7y64fQBQAMRPTL/6/resz1NOinn7jjEFQJMLtGENcMr1WXnxV3POqE9P1ogePVd4tH6htz+z/X0oAJBZEVZd/T86AkVHntXPs6smePTnUT+gbJ+iq0q3amc7CgAKcOJIOTqnjo6s2b452ddFPVNno0yjI3S1x2d0LUcBgJ59gFmPyNmoS+8aYPS6rJ3a2X2AqDuEeL0oELBuJziau3JKnP609qzKBdq9ZqAAAAAAAAAAAAAAAAAA7dhcoOocmuzrs3JjsnKMTsthyvocRnOfstpVla0sFwhNRVggDz16umL0ZPCseoRo9uPo/UfrFaL9H72+Jbs+RGuIe38vek7zVU05BQAFyKgZrXIkm53j3sWfKOoC8dSTIGfPK3ZSPHDSKZGzc/TomiFrTbL6xPRVrhS7vUmj/lCzUSdrAGBmH6C6Nnb1PsDTPVB3nYeQve8RjS5ZAwDOB0A79NyFLOe3UV8pCgAKAJx6hlfWzr9cIAAAAAAAAAAv5R8sG/KSRHx9UQAAAABJRU5ErkJggg==",Vi=class Ct{static registerDebugConfig(t){Ct.config=t}static draw(t){this._drawCalls.push(t)}static drawPoint(t,e){Ct.draw(i=>{i.debug.drawPoint(t,e)})}static drawLine(t,e,i){Ct.draw(s=>{s.debug.drawLine(t,e,i)})}static drawLines(t,e){t.length>1&&Ct.draw(i=>{for(let s=0;s<t.length-1;s++)i.debug.drawLine(t[s],t[s+1],e)})}static drawText(t,e){Ct.draw(i=>{i.debug.drawText(t,e)})}static drawPolygon(t,e){t.length>1&&Ct.draw(i=>{const s=t[0],n=[...t,s];for(let o=0;o<n.length-1;o++)i.debug.drawLine(n[o],n[o+1],e)})}static drawCircle(t,e,i){const{color:s,strokeColor:n,width:o}={color:T.Black,strokeColor:void 0,width:void 0,...i};Ct.draw(a=>{a.debug.drawCircle(t,e,s,n,o)})}static drawBounds(t,e){Ct.draw(i=>{i.debug.drawRect(t.left,t.top,t.width,t.height,e)})}static drawRay(t,e){const{distance:i,color:s}={color:T.Blue,distance:10,...e};Ct.draw(n=>{n.z=Ct.config.settings.z.ray;const o=t.pos,a=t.pos.add(t.dir.scale(i));n.debug.drawLine(o,a,{color:s})})}static flush(t){t.save(),t.z=Ct.z;for(const e of Ct._drawCalls)e(t);t.restore(),Ct.clear()}static clear(){Ct._drawCalls.length=0}};Vi._drawCalls=[],Vi.z=1/0,Vi.config={settings:{text:{foreground:T.Black,background:T.Transparent,border:T.Transparent},z:{text:Number.POSITIVE_INFINITY,point:Number.MAX_SAFE_INTEGER-1,ray:Number.MAX_SAFE_INTEGER-1,dashed:Number.MAX_SAFE_INTEGER-2,solid:Number.MAX_SAFE_INTEGER-3}}};let It=Vi;class wn{constructor(){this.fontSheet=$h,this.size=16,this.load()}get foregroundColor(){return It.config.settings.text.foreground}get backgroundColor(){return It.config.settings.text.background}get borderColor(){return It.config.settings.text.border}load(){return this._imageSource=new Wt(this.fontSheet),this._imageSource.load().then(()=>{this._spriteSheet=Ae.fromImageSource({image:this._imageSource,grid:{rows:8,columns:16,spriteWidth:10,spriteHeight:24},spacing:{originOffset:{x:2,y:0},margin:{x:2,y:0}}}),this._spriteFont=new Wi({alphabet:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~?",caseInsensitive:!1,spriteSheet:this._spriteSheet,spacing:2})})}write(t,e,i,s,n){var o,a,h;if(this._imageSource.isLoaded()){const l=t.getTransform().getPosition();t.save(),t.resetTransform(),t.z=It.config.settings.z.text,t.translate(l.x,l.y);const c=this._spriteFont.measureText(e),d=(o=s!=null?s:this.foregroundColor)!=null?o:T.Black,_=(a=n!=null?n:this.backgroundColor)!=null?a:T.Transparent;t.save(),t.z=It.config.settings.z.solid,t.drawRectangle(i,c.width,c.height,_,(h=this.borderColor)!=null?h:T.Transparent,1),t.restore(),t.tint=d,this._spriteFont.render(t,e,null,i.x,i.y),t.restore()}}}class Yh{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 qi{constructor(t){this.antialias=!1,this.samples=1;var e,i;this._gl=t.gl,this.width=t.width,this.height=t.height,this.transparency=t.transparency,this.antialias=(e=t.antialias)!=null?e:this.antialias,this.samples=(i=t.samples)!=null?i:this._gl.getParameter(this._gl.MAX_SAMPLES);const s=this._gl;s.drawingBufferFormat?this.bufferFormat=s.drawingBufferFormat:this.transparency?this.bufferFormat=s.RGBA8:this.bufferFormat=s.RGB8,this._setupRenderBuffer(),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),this._renderBuffer&&(i.bindRenderbuffer(i.RENDERBUFFER,this._renderBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,Math.min(this.samples,i.getParameter(i.MAX_SAMPLES)),this.bufferFormat,this.width,this.height))}get renderBuffer(){return this._renderBuffer}get renderFrameBuffer(){return this._renderFrameBuffer}get frameBuffer(){return this._frameBuffer}get frameTexture(){return this._frameTexture}_setupRenderBuffer(){if(this.antialias){const t=this._gl;this._renderBuffer=t.createRenderbuffer(),this._renderFrameBuffer=t.createFramebuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this._renderBuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,Math.min(this.samples,t.getParameter(t.MAX_SAMPLES)),this.bufferFormat,this.width,this.height),t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,this._renderBuffer)}}_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 this.renderBuffer&&this.blitRenderBufferToFrameBuffer(),new Yh(this._gl,this._frameTexture)}blitToScreen(){const t=this._gl;this._renderBuffer?(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)):(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR))}blitRenderBufferToFrameBuffer(){if(this._renderBuffer){const t=this._gl;t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,this.frameBuffer),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)}}copyToTexture(t){const e=this._gl;this._renderBuffer&&this.blitRenderBufferToFrameBuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,this.width,this.height,0)}use(){const t=this._gl;this.antialias?t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer):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)}}const Zh=`#version 300 es
40
- in vec2 a_position;
41
- in vec4 a_color;
42
- in float a_lengthSoFar;
43
-
44
- out lowp vec4 v_color;
45
- out float v_lengthSoFar;
46
-
47
- uniform mat4 u_matrix;
48
-
49
- void main() {
50
- // Set the vertex position using the ortho transform matrix
51
- gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
52
-
53
- // Passthrough the color
54
- v_color = a_color;
55
-
56
- // Passthrough the line length so far
57
- v_lengthSoFar = a_lengthSoFar;
58
- }
59
- `,jh=`#version 300 es
60
- precision mediump float;
61
-
62
- // Color
63
- in lowp vec4 v_color;
64
- in float v_lengthSoFar;
65
-
66
- out vec4 fragColor;
67
-
68
- uniform bool u_dashed;
69
-
70
- void main() {
71
- fragColor = v_color;
72
- if (u_dashed) {
73
- fragColor.a = smoothstep(0.5, 0.55, fract(v_lengthSoFar / 10.0)); // 10 pixel dashes
74
- fragColor.rgb *= fragColor.a;
75
- }
76
- }
77
- `;class xn extends ot{constructor(t){super(),this.color=T.Black,this.thickness=1;const{start:e,end:i,color:s,thickness:n}=t;this.start=e,this.end=i,this.color=s!=null?s:this.color,this.thickness=n!=null?n:this.thickness,this._localBounds=this._calculateBounds();const{width:o,height:a}=this._localBounds;this.width=o,this.height=a}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 D.fromPoints(i)}_drawImage(t,e,i){t.drawLine(this.start,this.end,this.color,this.thickness)}clone(){return new xn({start:this.start,end:this.end,color:this.color,thickness:this.thickness})}}class Xi extends Rt{constructor(t,e=!0){super(),this.draw=t,this.useTransform=e}}class $i extends Rt{constructor(t){super(),this.parallaxFactor=y(1,1),this.parallaxFactor=t!=null?t:this.parallaxFactor}}const Je=class at{static measureText(t,e,i){const s=ei.getHashCode(e,t);if(at._MEASURE_CACHE.has(s))return at._MEASURE_CACHE.get(s);at._LOGGER.debug(`Font text measurement cache miss: text(${t}) font(${e.fontString}) hash(${s})`);const n=e.measureTextWithoutCache(t,i);return at._MEASURE_CACHE.set(s,n),n}static getTextInstance(t,e,i){const s=ei.getHashCode(e,t,i);let n=at._TEXT_CACHE.get(s);return n||(n=new ei(e,t,i),at._TEXT_CACHE.set(s,n),at._LOGGER.debug(`Font text instance cache miss: text(${t}) font(${e.fontString}) hash(${s})`)),at._TEXT_USAGE.set(n,performance.now()),n}static checkAndClearCache(){const t=[],e=new Set;for(const[s,n]of at._TEXT_USAGE.entries())if(n+at.FONT_TIMEOUT<performance.now())at._LOGGER.debug(`Text cache entry timed out ${s.text}`),t.push(s),s.dispose();else{const o=s.getHashCode(!1);e.add(o)}t.forEach(s=>{at._TEXT_USAGE.delete(s)}),this._TEXT_CACHE.clear();for(const[s]of this._TEXT_USAGE.entries())this._TEXT_CACHE.set(s.getHashCode(),s);const i=new Map;for(const s of e)at._MEASURE_CACHE.has(s)&&i.set(s,at._MEASURE_CACHE.get(s));this._MEASURE_CACHE.clear(),this._MEASURE_CACHE=i}static get cacheSize(){return at._TEXT_USAGE.size}static clearCache(){for(const[t]of at._TEXT_USAGE.entries())t.dispose();at._TEXT_USAGE.clear(),at._TEXT_CACHE.clear(),at._MEASURE_CACHE.clear()}};Je.FONT_TIMEOUT=500,Je._LOGGER=F.getInstance(),Je._TEXT_USAGE=new Map,Je._TEXT_CACHE=new Map,Je._MEASURE_CACHE=new Map;let Yi=Je;function Qh(r,t,e,i){if(r.parent!==t.parent){const c=r.clone(),d=r.globalPos.clone(),_=r.globalScale.clone(),f=r.globalRotation;c.parent=t.parent,c.globalPos=d,c.globalScale=_,c.globalRotation=f,r=c}let s=t.pos,n=t.scale,o=t.rotation;s=t.pos.scale(e).add(r.pos.scale(1-e)),n=t.scale.scale(e).add(r.scale.scale(1-e));const a=(1-e)*Math.cos(r.rotation)+e*Math.cos(t.rotation),h=(1-e)*Math.sin(r.rotation)+e*Math.sin(t.rotation);o=Math.atan2(h,a);const l=i!=null?i:new se;return l.setTransform(s,o,n),l}class yn extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Draw,this._token=0,this._sortedTransforms=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this._targetInterpolationTransform=new se,this.query=this.world.query([E,Z]),this.query.entityAdded$.subscribe(e=>{const i=e.get(E);this._sortedTransforms.push(i),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{const i=e.get(E);i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const s=this._sortedTransforms.indexOf(i);s>-1&&this._sortedTransforms.splice(s,1)})}get sortedTransforms(){return this._sortedTransforms}initialize(t,e){this._camera=e.camera,this._engine=e.engine}preupdate(){this._graphicsContext=this._engine.graphicsContext,this._zHasChanged&&(this._sortedTransforms.sort((t,e)=>t.globalZ-e.globalZ),this._zHasChanged=!1)}update(t){this._token++;let e;Yi.checkAndClearCache(),this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext);for(let i=0;i<this._sortedTransforms.length;i++){const s=this._sortedTransforms[i],n=s.owner;if(n.hasTag("ex.offscreen")||(e=n.get(Z),!e.isVisible))continue;e.onPreTransformDraw&&e.onPreTransformDraw(this._graphicsContext,t),n.events.emit("pretransformdraw",new Us(this._graphicsContext,t,n)),s.coordPlane===ht.Screen&&this._graphicsContext.restore(),this._graphicsContext.save(),s.coordPlane===ht.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),e.update(t,this._token);const o=n.get($i);if(o){const a=w.One.sub(o.parallaxFactor),h=this._camera.drawPos.scale(a);this._graphicsContext.translate(h.x,h.y)}this._applyTransform(n),e.material&&(this._graphicsContext.material=e.material),e.onPreDraw&&e.onPreDraw(this._graphicsContext,t),n.events.emit("predraw",new Ge(this._graphicsContext,t,n)),this._applyOpacity(n),this._drawGraphicsComponent(e,s),e.onPostDraw&&e.onPostDraw(this._graphicsContext,t),n.events.emit("postdraw",new We(this._graphicsContext,t,n)),this._graphicsContext.restore(),s.coordPlane===ht.Screen&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext)),e.onPostTransformDraw&&e.onPostTransformDraw(this._graphicsContext,t),n.events.emit("posttransformdraw",new Os(this._graphicsContext,t,n))}this._graphicsContext.restore()}_drawGraphicsComponent(t,e){var i,s;if(t.isVisible){const n=t.flipHorizontal,o=t.flipVertical,a=t.current,h=(i=t.currentOptions)!=null?i:{};if(a){let l=t.anchor,c=t.offset,d=1,_=1;h!=null&&h.anchor&&(l=h.anchor),h!=null&&h.offset&&(c=h.offset);const f=e.globalScale;d*=a.scale.x*f.x,_*=a.scale.y*f.y;const m=-a.width*l.x+c.x*d,p=-a.height*l.y+c.y*_,x=a.flipHorizontal,v=a.flipVertical;if((n||o)&&(a.flipHorizontal=n?!x:x,a.flipVertical=o?!v:v),a==null||a.draw(this._graphicsContext,m,p),(n||o)&&(a.flipHorizontal=x,a.flipVertical=v),(s=this._engine)!=null&&s.isDebug&&this._engine.debug.graphics.showBounds){this._graphicsContext.save();const g=y(m,p);if(a instanceof $e)for(const b of a.members){let S,A=w.Zero;b instanceof ot?S=b:(S=b.graphic,A=b.offset),a.useAnchor?S==null||S.localBounds.translate(g.add(A)).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0}):S==null||S.localBounds.translate(A).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0})}else a==null||a.localBounds.translate(g).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0});this._graphicsContext.restore()}}}}_applyTransform(t){const e=t.getAncestors();for(let i=0;i<e.length;i++){const s=e[i],n=s==null?void 0:s.get(E),o=s==null?void 0:s.get(U);if(n){let a=n.get();if(o&&!o.isSleeping&&this._engine.fixedUpdateTimestep&&o.__oldTransformCaptured&&o.enableFixedUpdateInterpolate){const h=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep;a=Qh(o.oldTransform,n.get(),h,this._targetInterpolationTransform)}this._graphicsContext.z=n.globalZ,this._graphicsContext.translate(a.pos.x,a.pos.y),this._graphicsContext.scale(a.scale.x,a.scale.y),this._graphicsContext.rotate(a.rotation)}}}_applyOpacity(t){var e;const i=t.getAncestors();for(let s=0;s<i.length;s++){const n=i[s],o=n==null?void 0:n.get(Z);this._graphicsContext.opacity*=(e=o==null?void 0:o.opacity)!=null?e:1}}}yn.priority=Zt.Average;class bn extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Draw,this.query=this.world.query([E,Z])}initialize(t,e){this._camera=e.camera,this._screen=e.engine.screen}update(){this._worldBounds=this._screen.getWorldBounds();let t,e,i;for(let s=0;s<this.query.entities.length;s++){const n=this.query.entities[s];e=n.get(Z),t=n.get(E),i=n.get($i);let o;if(i){const h=w.One.sub(i.parallaxFactor);o=this._camera.pos.scale(h)}const a=this._isOffscreen(t,e,o);a&&!n.hasTag("ex.offscreen")&&(n.events.emit("exitviewport",new Js(n)),n.addTag("ex.offscreen")),!a&&n.hasTag("ex.offscreen")&&(n.events.emit("enterviewport",new Ks(n)),n.removeTag("ex.offscreen"))}}_isOffscreen(t,e,i){if(e.forceOnScreen)return!1;if(t.coordPlane===ht.World){let s=e.localBounds;i&&(s=s.translate(i));const n=s.transform(t.get().matrix);return!this._worldBounds.overlaps(n)}else return!1}}bn.priority=Zt.Higher;class Zi extends je{constructor(t){var e,i,s;super(t),this._radius=0;const n=(e=t.lineWidth)!=null?e:t.strokeColor?1:0;this.padding=(i=t.padding)!=null?i:2+n/2,this.radius=t.radius,this.filtering=(s=t.filtering)!=null?s:vt.Blended,this.rasterize()}get radius(){return this._radius}set radius(t){this._radius=t,this.width=this._radius*2,this.height=this._radius*2,this.flagDirty()}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,Math.PI*2),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class mi extends je{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new mi({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 Cn extends je{constructor(t){super(t),this._points=[],this.points=t.points,this.filtering=vt.Blended,this.rasterize()}get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce((i,s)=>Math.max(s.x,i),0)-e.x,this.height=this._points.reduce((i,s)=>Math.max(s.y,i),0)-e.y,this.flagDirty()}get minPoint(){const t=this._points.reduce((i,s)=>Math.min(s.x,i),1/0),e=this._points.reduce((i,s)=>Math.min(s.y,i),1/0);return y(t,e)}clone(){return new Cn({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(s=>{t.lineTo(s.x+e.x,s.y+e.y)}),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}class ji extends je{constructor(t={}){super(t),this._options=t}get ctx(){return this._ctx}clone(){return new ji({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(e=this._options)!=null&&e.draw&&((i=this._options)==null||i.draw(t)),this._options.cache||this.flagDirty()}}var Vr=(r=>(r.Stretch="stretch",r.Tile="tile",r.TileFit="tile-fit",r))(Vr||{});class Sn extends ot{constructor(t){super(t),this._logger=F.getInstance(),this._config=t,this._imgSource=t.source,this._canvasA=document.createElement("canvas"),this._canvasB=document.createElement("canvas"),this._canvasC=document.createElement("canvas"),this._canvasD=document.createElement("canvas"),this._canvasE=document.createElement("canvas"),this._canvasF=document.createElement("canvas"),this._canvasG=document.createElement("canvas"),this._canvasH=document.createElement("canvas"),this._canvasI=document.createElement("canvas"),this._initialize(),this._imgSource.ready.then(()=>{this._initialize()})}setTargetWidth(t,e=!1){this._config.width=t,e&&this._initialize()}setTargetHeight(t,e=!1){this._config.height=t,e&&this._initialize()}setMargins(t,e,i,s,n=!1){this._config.sourceConfig.leftMargin=t,this._config.sourceConfig.topMargin=e,this._config.sourceConfig.rightMargin=i,this._config.sourceConfig.bottomMargin=s,n&&this._initialize()}setStretch(t,e,i=!1){t==="horizontal"?this._config.destinationConfig.horizontalStretch=e:t==="vertical"?this._config.destinationConfig.verticalStretch=e:(this._config.destinationConfig.horizontalStretch=e,this._config.destinationConfig.verticalStretch=e),i&&this._initialize()}getConfig(){return this._config}_drawTile(t,e,i,s,n,o,a){const h=o||0,l=a||0;let c,d,_,f;const m=this._getNumberOfTiles(e.width,i.x,s),p=this._getNumberOfTiles(e.height,i.y,n);for(let x=0;x<m;x++)for(let v=0;v<p;v++){let{tempSize:g,tempPosition:b}=this._calculateParams(x,m,e.width,i.x,this._config.destinationConfig.horizontalStretch);c=g,d=b,{tempSize:g,tempPosition:b}=this._calculateParams(v,p,e.height,i.y,this._config.destinationConfig.verticalStretch),_=g,f=b,t.drawImage(e,0,0,e.width,e.height,h+d,l+f,c,_)}}_drawImage(t,e,i){this._imgSource.isLoaded()?(this._drawTile(t,this._canvasA,new w(this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch),this._drawTile(t,this._canvasB,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,0),this._drawTile(t,this._canvasC,new w(this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,0),this._drawTile(t,this._canvasD,new w(this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.sourceConfig.topMargin),this._config.destinationConfig.drawCenter&&this._drawTile(t,this._canvasE,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasF,new w(this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasG,new w(this._config.sourceConfig.leftMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasH,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasI,new w(this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin)):this._logger.warnOnce(`NineSlice ImageSource ${this._imgSource.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.
78
-
79
- Read https://excaliburjs.com/docs/imagesource for more information.`)}_initialize(){this._sourceSprite=this._imgSource.image,this._canvasA.width=this._config.sourceConfig.leftMargin,this._canvasA.height=this._config.sourceConfig.topMargin;const t=this._canvasA.getContext("2d");t==null||t.drawImage(this._sourceSprite,0,0,this._canvasA.width,this._canvasA.height,0,0,this._canvasA.width,this._canvasA.height),this._canvasB.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasB.height=this._config.sourceConfig.topMargin;const e=this._canvasB.getContext("2d");e==null||e.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,0,this._canvasB.width,this._canvasB.height,0,0,this._canvasB.width,this._canvasB.height),this._canvasC.width=this._config.sourceConfig.rightMargin,this._canvasC.height=this._config.sourceConfig.topMargin;const i=this._canvasC.getContext("2d");i==null||i.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,0,this._canvasC.width,this._canvasC.height,0,0,this._canvasC.width,this._canvasC.height),this._canvasD.width=this._config.sourceConfig.leftMargin,this._canvasD.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const s=this._canvasD.getContext("2d");s==null||s.drawImage(this._sourceSprite,0,this._config.sourceConfig.topMargin,this._canvasD.width,this._canvasD.height,0,0,this._canvasD.width,this._canvasD.height),this._canvasE.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasE.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const n=this._canvasE.getContext("2d");n==null||n.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin,this._canvasE.width,this._canvasE.height,0,0,this._canvasE.width,this._canvasE.height),this._canvasF.width=this._config.sourceConfig.rightMargin,this._canvasF.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const o=this._canvasF.getContext("2d");o==null||o.drawImage(this._sourceSprite,this._config.sourceConfig.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin,this._canvasF.width,this._canvasF.height,0,0,this._canvasF.width,this._canvasF.height),this._canvasG.width=this._config.sourceConfig.leftMargin,this._canvasG.height=this._config.sourceConfig.bottomMargin;const a=this._canvasG.getContext("2d");a==null||a.drawImage(this._sourceSprite,0,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasG.width,this._canvasG.height,0,0,this._canvasG.width,this._canvasG.height),this._canvasH.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasH.height=this._config.sourceConfig.bottomMargin;const h=this._canvasH.getContext("2d");h==null||h.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasH.width,this._canvasH.height,0,0,this._canvasH.width,this._canvasH.height),this._canvasI.width=this._config.sourceConfig.rightMargin,this._canvasI.height=this._config.sourceConfig.bottomMargin;const l=this._canvasI.getContext("2d");l==null||l.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasI.width,this._canvasI.height,0,0,this._canvasI.width,this._canvasI.height)}clone(){return new Sn(this._config)}_getNumberOfTiles(t,e,i){switch(i){case"stretch":return 1;case"tile":return Math.ceil(e/t);case"tile-fit":return Math.ceil(e/t)}}_calculateParams(t,e,i,s,n){switch(n){case"stretch":return{tempPosition:0,tempSize:s};case"tile":return t===e-1?{tempPosition:t*i,tempSize:i-(e*i-s)}:{tempPosition:t*i,tempSize:i};case"tile-fit":const o=s/e;return{tempPosition:t*o,tempSize:o}}}}class Tn extends Gi{constructor(t){super({...t,frames:t.animation.frames.slice(),strategy:t.animation.strategy,frameDuration:t.animation.frameDuration,speed:t.animation.speed,reverse:t.animation.isReversed}),this._ready=new xt,this.ready=this._ready.promise,this._tiledWidth=0,this._tiledHeight=0,this._sourceView={},this._sourceView={...t.sourceView},this._tiledWidth=t.width,this._tiledHeight=t.height;const e=[];for(let i=0;i<this.frames.length;i++){const s=this.frames[i].graphic;if(s&&s instanceof zt){const n=new pi({image:s.image,width:t.width,height:t.height,sourceView:{...s.sourceView},wrapping:t.wrapping,filtering:t.filtering});this.frames[i].graphic=n,n.ready.then(()=>{n.sourceView={...n.sourceView,...this._sourceView}}),e.push(n.ready)}}Promise.all(e).then(()=>this._ready.resolve())}static fromAnimation(t,e){return new Tn({width:t.width,height:t.height,...e,animation:t})}_updateSourceView(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof zt&&(e.sourceView={...e.sourceView,...this._sourceView})}}get sourceView(){return Ft(this._sourceView,()=>this._updateSourceView())}set sourceView(t){this._sourceView=Ft(t,()=>this._updateSourceView()),this._updateSourceView()}_updateWidthHeight(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof zt&&(e.sourceView.height=this._tiledHeight||e.height,e.destSize.height=this._tiledHeight||e.height,e.sourceView.width=this._tiledWidth||e.width,e.destSize.width=this._tiledWidth||e.width)}}get width(){return this._tiledWidth}get height(){return this._tiledHeight}set width(t){this._tiledWidth=t,this._updateWidthHeight()}set height(t){this._tiledHeight=t,this._updateWidthHeight()}}const qr={pixelArtSampler:!1,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:vt.Blended,canvasImageRendering:"auto"},Xr={pixelArtSampler:!0,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:vt.Blended,canvasImageRendering:"auto"},Qi=class ms{static clear(){ms.DrawCallCount=0,ms.DrawnImagesCount=0,ms.RendererSwaps=0}};Qi.DrawCallCount=0,Qi.DrawnImagesCount=0,Qi.RendererSwaps=0;let Q=Qi;const J=1e-4;class Jh{constructor(t){this._ex=t,this._debugText=new wn}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~(t+J):t,this._ex.snapToPixel?~~(e+J):e,this._ex.snapToPixel?~~(i+J):i,this._ex.snapToPixel?~~(s+J):s),this._ex.__ctx.restore()}drawLine(t,e,i={color:T.Black}){var s,n;this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=(n=(s=i.color)==null?void 0:s.toString())!=null?n:"",this._ex.__ctx.moveTo(this._ex.snapToPixel?~~(t.x+J):t.x,this._ex.snapToPixel?~~(t.y+J):t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~(e.x+J):e.x,this._ex.snapToPixel?~~(e.y+J):e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:T.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+J):t.x,this._ex.snapToPixel?~~(t.y+J):t.y,e.size,0,Math.PI*2),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawCircle(t,e,i,s,n){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),s&&(this._ex.__ctx.strokeStyle=s.toString()),n&&(this._ex.__ctx.lineWidth=n),this._ex.__ctx.fillStyle=i.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+J):t.x,this._ex.snapToPixel?~~(t.y+J):t.y,e,0,Math.PI*2),this._ex.__ctx.fill(),s&&this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class Ji{constructor(t){this.useDrawSorting=!1,this.z=0,this.backgroundColor=T.ExcaliburBlue,this._state=new Wr,this.snapToPixel=!1,this.debug=new Jh(this);const{canvasElement:e,context:i,enableTransparency:s,snapToPixel:n,antialiasing:o,backgroundColor:a}=t;if(this.__ctx=i!=null?i:e.getContext("2d",{alpha:s!=null?s:!0}),!this.__ctx)throw new Error("Cannot build new ExcaliburGraphicsContext2D for some reason!");this.backgroundColor=a!=null?a:this.backgroundColor,this.snapToPixel=n!=null?n:this.snapToPixel,this.smoothing=o!=null?o:this.smoothing}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}resetTransform(){this.__ctx.resetTransform()}updateViewport(t){}drawImage(t,e,i,s,n,o,a,h,l){if(s===0||n===0)return;if(h===0||l===0)return;if(t.width===0||t.height===0)return;this.__ctx.globalAlpha=this.opacity;const c=[t,e,i,s,n,o,a,h,l].filter(d=>d!==void 0).map(d=>typeof d=="number"&&this.snapToPixel?~~d:d);this.__ctx.drawImage.apply(this.__ctx,c),Q.DrawCallCount++,Q.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+J):t.x,this.snapToPixel?~~(t.y+J):t.y),this.__ctx.lineTo(this.snapToPixel?~~(e.x+J):e.x,this.snapToPixel?~~(e.y+J):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+J):t.x,this.snapToPixel?~~(t.y+J):t.y,this.snapToPixel?~~(e+J):e,this.snapToPixel?~~(i+J):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+J):t.x,this.snapToPixel?~~(t.y+J):t.y,e,0,Math.PI*2),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+J):t,this.snapToPixel?~~(e+J):e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}getTransform(){const t=this.__ctx.getTransform(),e=new tt;return e.data[0]=t.a,e.data[1]=t.b,e.data[2]=t.c,e.data[3]=t.d,e.data[4]=t.e,e.data[5]=t.f,e}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),Q.clear()}flush(){}dispose(){this.__ctx=void 0}}class $r{constructor(t){this.type="static";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=e.createBuffer(),this._maxFloats=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)/32,!n&&!i)throw Error("Must either provide data or a size to the UniformBuffer");if(n?this.bufferData=n:this.bufferData=new Float32Array(i),this.bufferData.length>this._maxFloats)throw Error(`UniformBuffer exceeds browsers allowed number of floats ${this._maxFloats}`);this.type=s!=null?s:this.type,e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,this.buffer)}unbind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,null)}upload(t){const e=this._gl;e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),t?e.bufferSubData(e.UNIFORM_BUFFER,0,this.bufferData,0,t):e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}function An(r,t){switch(t){case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;case r.SHORT:return 2;case r.UNSIGNED_SHORT:return 2;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;default:return 1}}function Yr(r,t){const e=`(?<type>[a-z0-9]+)\\s+${t};`,s=new RegExp(e,"g").exec(r);return(s==null?void 0:s.length)>0}function Zr(r,t,e){var i;const s=`(?<type>[a-z0-9]+)\\s+${e};`,o=new RegExp(s,"g").exec(t);switch((i=o==null?void 0:o.groups)==null?void 0:i.type){case"float":case"vec2":case"vec3":case"vec4":return r.FLOAT;case"int":case"ivec2":case"ivec3":case"ivec4":return r.INT;case"uint":case"uvec2":case"uvec3":case"uvec4":return r.UNSIGNED_INT;case"bool":case"bvec2":case"bvec3":case"bvec4":return r.BOOL;case"short":return r.SHORT;case"ushort":return r.UNSIGNED_SHORT;case"ubyte":return r.UNSIGNED_BYTE;case"byte":return r.BYTE;default:return r.FLOAT}}function jr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:return 1;case r.FLOAT_VEC2:return 2;case r.FLOAT_VEC3:return 3;case r.FLOAT_VEC4:return 4;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;case r.UNSIGNED_SHORT:case r.SHORT:return 1;default:return 1}}function Qr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:case r.FLOAT_VEC2:case r.FLOAT_VEC3:case r.FLOAT_VEC4:return r.FLOAT;case r.BYTE:return r.BYTE;case r.UNSIGNED_BYTE:return r.UNSIGNED_BYTE;case r.SHORT:return r.SHORT;case r.UNSIGNED_SHORT:return r.UNSIGNED_SHORT;default:return r.FLOAT}}function Pn(r,t){const e=s=>{const n=`#version 300 es
80
- precision mediump float;
81
- out vec4 fragColor;
82
- void main() {
83
- float index = 1.01;
84
- %%complexity%%
85
- }`;let o="";for(let a=0;a<s;a++)a===0?o+=`if (index <= ${a}.5) {
86
- `:o+=` else if (index <= ${a}.5) {
87
- `,o+=` fragColor = vec4(1.0);
88
- `,o+=` }
89
- `;return n.replace("%%complexity%%",o)};let i=!1;do{const s=e(t),n=r.createShader(r.FRAGMENT_SHADER);r.shaderSource(n,s),r.compileShader(n),i=r.getShaderParameter(n,r.COMPILE_STATUS),i||(t=t/2|0)}while(!i);return t}const Kh=Object.freeze(Object.defineProperty({__proto__:null,getAttributeComponentSize:jr,getAttributePointerType:Qr,getGLTypeFromSource:Zr,getGlTypeSizeBytes:An,getMaxShaderComplexity:Pn,isAttributeInSource:Yr},Symbol.toStringTag,{value:"Module"}));function Jr(r,t){switch(t){case r.FLOAT:return"uniform1f";case r.FLOAT_VEC2:return"uniform2f";case r.FLOAT_VEC3:return"uniform3f";case r.FLOAT_VEC4:return"uniform4f";case r.INT:return"uniform1i";case r.INT_VEC2:return"uniform2i";case r.INT_VEC3:return"uniform3i";case r.INT_VEC4:return"uniform4i";case r.BOOL:return"uniform1i";case r.BOOL_VEC2:return"uniform2i";case r.BOOL_VEC3:return"uniform3i";case r.BOOL_VEC4:return"uniform4i";case r.FLOAT_MAT2:return"uniform1f";case r.FLOAT_MAT3:return"uniform1f";case r.FLOAT_MAT4:return"uniform1f";case r.SAMPLER_2D:return"uniform1f";case r.SAMPLER_CUBE:return"uniform1f";case r.UNSIGNED_INT:return"uniform1ui";case r.UNSIGNED_INT_VEC2:return"uniform2ui";case r.UNSIGNED_INT_VEC3:return"uniform3ui";case r.UNSIGNED_INT_VEC4:return"uniform4ui";case r.FLOAT_MAT2x3:return"uniformMatrix2x3fv";case r.FLOAT_MAT2x4:return"uniformMatrix2x4fv";case r.FLOAT_MAT3x2:return"uniformMatrix3x2fv";case r.FLOAT_MAT3x4:return"uniformMatrix3x4fv";case r.FLOAT_MAT4x2:return"uniformMatrix4x2fv";case r.FLOAT_MAT4x3:return"uniformMatrix4x3fv";case r.SAMPLER_2D_ARRAY:return"uniform1fv";case r.SAMPLER_2D_ARRAY_SHADOW:return"uniform1f";case r.SAMPLER_CUBE_SHADOW:return"uniform1f";case r.INT_SAMPLER_2D:return"uniform1f";case r.INT_SAMPLER_3D:return"uniform1f";case r.INT_SAMPLER_CUBE:return"uniform1f";case r.INT_SAMPLER_2D_ARRAY:return"uniform1f";case r.UNSIGNED_INT_SAMPLER_2D:return"uniform1ui";default:throw new Error(`Unknown uniform type: ${t}`)}}const Kr=class Ri{constructor(t){this.name="anonymous shader",this._logger=F.getInstance(),this._textures=new Map,this.attributes={},this._uniforms={},this._uniformBuffers={},this._compiled=!1,this._dirtyUniforms=!0,this._startingTextureSlot=0,this.uniforms=Ft({},()=>this.flagUniformsDirty()),this.images={};const{name:e,graphicsContext:i,vertexSource:s,fragmentSource:n,onPreLink:o,onPostCompile:a,uniforms:h,images:l,startingTextureSlot:c}=t;if(this.name=e!=null?e:this.name,!(i instanceof Kt))throw new Error(`ExcaliburGraphicsContext provided to a shader ${this.name} must be WebGL`);this._gl=i.__gl,this._startingTextureSlot=c!=null?c:this._startingTextureSlot,this._maxTextureSlots=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS)-this._startingTextureSlot,this.vertexSource=s,this.fragmentSource=n,this.uniforms=Ft(h!=null?h:this.uniforms,()=>this.flagUniformsDirty()),this.images=l!=null?l:this.images,Object.keys(this.images).length>=this._maxTextureSlots&&this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`),this._textureLoader=i.textureLoader,this._onPreLink=o,this._onPostCompile=a}flagUniformsDirty(){this._dirtyUniforms=!0}get compiled(){return this._compiled}dispose(){this._gl.deleteProgram(this.program),this._gl=null}use(){this._gl.useProgram(this.program),Ri._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages()}unuse(){const t=this._gl;Ri._ACTIVE_SHADER_INSTANCE=null,t.useProgram(null)}isCurrentlyBound(){return Ri._ACTIVE_SHADER_INSTANCE===this}_setUniforms(){const t=this._gl,e=Object.entries(this.uniforms);if(e.length){const i=this.getUniformDefinitions();for(const[s,n]of e)if(n instanceof Float32Array)this.setUniformBuffer(s,n);else if(Array.isArray(n)&&n[0]instanceof Float32Array&&typeof n[1]=="number")this.setUniformBuffer(s,n[0],n[1]);else if(typeof n=="number")this.trySetUniformFloat(s,n);else if(typeof n=="boolean")this.trySetUniformBoolean(s,n);else if(n instanceof w)this.trySetUniformFloatVector(s,n);else if(n instanceof T)this.trySetUniformFloatColor(s,n);else if(n instanceof tt)this.setUniformAffineMatrix(s,n);else{const o=i.find(a=>a.name===s);if(o){const a=Jr(t,o.glType);this.trySetUniform(a,s,n)}else this._logger.warnOnce(`Could not locate uniform named ${s}, this can happen if the uniform is unused in the shader code some GPUs will remove this as an optimization.`)}}}_loadImageSource(t){const e=t.image,i=e.getAttribute(N.Filtering),s=i?Ye(i):void 0,n=Gt(e.getAttribute(N.WrappingX)),o=Gt(e.getAttribute(N.WrappingY)),a=e.getAttribute("forceUpload")==="true",h=this._textureLoader.load(e,{filtering:s,wrapping:{x:n,y:o}},a);return e.removeAttribute("forceUpload"),this._textures.has(t)||this._textures.set(t,h),h}_setImages(t=!1){const e=this._gl;let i=this._startingTextureSlot;for(const[s,n]of Object.entries(this.images)){if(!n.isLoaded()){t||this._logger.warnOnce(`Image named ${s} in not loaded, nothing will be uploaded to the shader. Did you forget to add this to a loader? https://excaliburjs.com/docs/loaders/`);continue}const o=this._loadImageSource(n);o||t||this._logger.warnOnce(`Image ${s} (${n.image.src}) could not be loaded for some reason in shader ${this.name}`),e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,o),this.trySetUniformInt(s,i),i++}}compile(){if(this._compiled)return this.program;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.getAttributeDefinitions();for(const o of s)this.attributes[o.name]=o;const n=this.getUniformDefinitions();for(const o of n)this._uniforms[o.name]=o;return this._compiled=!0,this._onPostCompile&&this._onPostCompile(this),t.useProgram(this.program),Ri._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages(!0),this.unuse(),this.program}getUniformDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS),i=[];for(let s=0;s<e;s++){const n=t.getActiveUniform(this.program,s),o=t.getUniformLocation(this.program,n.name);i.push({name:n.name,glType:n.type,location:o})}return i}getAttributeDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES),i=[];for(let s=0;s<e;s++){const n=t.getActiveAttrib(this.program,s),o=t.getAttribLocation(this.program,n.name);i.push({name:n.name,glType:Qr(t,n.type),size:jr(t,n.type),location:o,normalized:!1})}return i}addImageSource(t,e){Object.keys(this.images).length<this._maxTextureSlots?this.images[t]=e:this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`)}removeImageSource(t){const e=this.images[t];e&&(this._textureLoader.delete(e.image),delete this.images[t])}setTexture(t,e){const i=this._gl;i.activeTexture(i.TEXTURE0+t),i.bindTexture(i.TEXTURE_2D,e)}setUniformBuffer(t,e,i=0){const s=this._gl,n=s.getUniformBlockIndex(this.program,t);n===s.INVALID_INDEX&&this._logger.warnOnce(`Invalid block name ${t}`);let o;this._uniformBuffers[t]?(o=this._uniformBuffers[t],o.bufferData.set(e),o.upload()):(o=new $r({gl:s,data:e}),this._uniformBuffers[t]=o),s.uniformBlockBinding(this.program,n,i),s.bindBufferBase(s.UNIFORM_BUFFER,i,o.buffer)}trySetUniformBuffer(t,e,i=0){return this._compiled?this.isCurrentlyBound()?this._gl.getUniformBlockIndex(this.program,t)?(this.setUniformBuffer(t,e,i),!0):!1:(this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1):(this._logger.warn(`Must compile shader before setting a uniform block ${t} at binding point ${i}`),!1)}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.toFloatArray())}trySetUniformFloatColor(t,e){return this.trySetUniform("uniform4f",t,...e.toFloatArray())}setUniformMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,e.data)}setUniformAffineMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,[e.data[0],e.data[1],0,0,e.data[2],e.data[3],0,0,0,0,1,0,e.data[4],e.data[5],0,1])}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 n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else 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`)}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 n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else return!1;return!0}_createProgram(t,e,i){const s=t.createProgram();if(s===null)throw Error("Could not create graphics shader program");if(t.attachShader(s,e),t.attachShader(s,i),this._onPreLink&&this._onPreLink(s),t.linkProgram(s),!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(n===null)throw Error(`Could not build shader: [${e}]`);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const a=t.getShaderInfoLog(n);throw Error(`Could not compile ${s} shader:
90
-
91
- ${a}${this._processSourceForError(e,a)}`)}return n}_processSourceForError(t,e){if(!t)return e;const i=t.split(`
92
- `),s=e.search(/\d:\d/),n=e.indexOf(" ",s),[o,a]=e.slice(s,n).split(":").map(h=>Number(h));for(let h=0;h<i.length;h++)i[h]=`${h+1}: ${i[h]}${a===h+1?" <----- ERROR!":""}`;return`
93
-
94
- Source:
95
- `+i.join(`
96
- `)}};Kr._ACTIVE_SHADER_INSTANCE=null;let Ut=Kr;const tl=`#version 300 es
97
- precision mediump float;
98
-
99
- uniform float deltaMs;
100
- uniform float maxLifeMs;
101
- uniform vec2 gravity;
102
- uniform vec2 focus;
103
- uniform float focusAccel;
104
- uniform mat4 u_matrix;
105
- uniform mat4 u_transform;
106
- uniform float startSize;
107
- uniform float endSize;
108
- // uniform sampler2D obstacle;
109
-
110
- layout(location=0)in vec2 position;
111
- layout(location=1)in vec2 velocity;
112
- layout(location=2)in float rotation;
113
- layout(location=3)in float angularVelocity;
114
- layout(location=4)in float lifeMs;
115
-
116
- // TODO z index to handle buffer wrapping?
117
-
118
- // DO NOT RE-ORDER
119
- out vec2 finalPosition;
120
- out vec2 finalVelocity;
121
- out float finalRotation;
122
- out float finalAngularVelocity;
123
- out float finalLifeMs;
124
- void main(){
125
- // Evolve particle
126
- float seconds = deltaMs / 1000.;
127
- // euler integration
128
- // Weird artifact of re-using the same buffer layout for update/draw
129
- // we need differently named variables
130
- vec2 finalGravity = gravity + normalize(focus - position) * focusAccel;
131
- finalVelocity = velocity + finalGravity * seconds;
132
- finalPosition = position + velocity * seconds + finalGravity * .5 * seconds * seconds;
133
- finalRotation = rotation + angularVelocity * seconds;
134
- finalAngularVelocity = angularVelocity;
135
- finalLifeMs = clamp(lifeMs - deltaMs, 0., maxLifeMs);
136
-
137
- // Collision mask sampling
138
- // vec2 samplePoint = finalPosition / vec2(width, height);
139
- // vec4 collides = texture(obstacle, samplePoint);
140
- // if (distance(collides,vec4(0.)) > .01) {
141
- // // non opaque means we collide! recalc final pos/vel
142
- // vec2 newVelocity = velocity * -.1;// lose energy
143
- // finalVelocity = newVelocity + gravity * seconds;
144
- // finalPosition = position + newVelocity * seconds + gravity * .5 * seconds * seconds;
145
- // }
146
-
147
- float lifePercent = finalLifeMs / maxLifeMs;
148
- vec2 transformedPos = (u_matrix * u_transform * vec4(finalPosition,0.,1.)).xy;
149
- float scale = sqrt(u_transform[0][0] * u_transform[0][0] + u_transform[1][1] * u_transform[1][1]);
150
- gl_Position = vec4(transformedPos, 1.0 - lifePercent, 1.); // use life percent to sort z
151
- gl_PointSize = mix(startSize, endSize, 1.0 - lifePercent) * scale;
152
- }`,el=`#version 300 es
153
- precision mediump float;
154
-
155
- uniform sampler2D graphic;
156
- uniform bool useTexture;
157
- uniform float maxLifeMs;
158
-
159
- uniform vec4 beginColor;
160
- uniform vec4 endColor;
161
- uniform bool fade;
162
- uniform float startOpacity;
163
-
164
- in float finalRotation;
165
- in float finalLifeMs;
166
- out vec4 fragColor;
167
-
168
- void main(){
169
-
170
- float lifePct = finalLifeMs / maxLifeMs;
171
-
172
- if (useTexture) {
173
- /** Draw texture */
174
- if (lifePct <= 0.) discard;
175
- float mid = .5;
176
- float cosine = cos(finalRotation);
177
- float sine = sin(finalRotation);
178
- vec2 rotated = vec2(cosine * (gl_PointCoord.x - mid) + sine * (gl_PointCoord.y - mid) + mid,
179
- cosine * (gl_PointCoord.y - mid) - sine * (gl_PointCoord.x - mid) + mid);
180
- vec4 color = texture(graphic, rotated);
181
- fragColor = color * (fade ? lifePct : 1.0);
182
- } else {
183
- /** Draw circle */
184
- if (lifePct <= 0.) discard;
185
- vec2 uv = gl_PointCoord.xy * 2.0 - 1.0;
186
- float dist = 1.0 - length(uv);
187
- float edge = fwidth(dot(uv, uv));
188
- float circle = smoothstep(-edge/2.0, edge/2.0, dist);
189
- vec3 color = mix(beginColor.rgb, endColor.rgb, 1.0 - lifePct);
190
- fragColor.rgb = color;
191
- fragColor.a = startOpacity * circle * (fade ? lifePct : 1.0);// * mix(beginColor.a, endColor.a, 1.0 - lifePct);
192
- fragColor.rgb *= fragColor.a;
193
- }
194
- }`,Pe=class me{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n,me._ACC)),e.vel.setTo(L(e.vel.x,-e.maxVel.x,e.maxVel.x),L(e.vel.y,-e.maxVel.y,e.maxVel.y)),t.pos.add(e.vel.scale(n,me._VEL),me._POS).addEqual(i.scale(.5*n*n,me._VEL_ACC)),e.angularVelocity+=e.torque*(1/e.inertia)*n;const o=t.rotation+e.angularVelocity*n;t.scale.add(e.scaleFactor.scale(n,this._SCALE_FACTOR),me._SCALE),t.get().setTransform(me._POS,o,me._SCALE)}};Pe._POS=new w(0,0),Pe._SCALE=new w(1,1),Pe._ACC=new w(0,0),Pe._VEL=new w(0,0),Pe._VEL_ACC=new w(0,0),Pe._SCALE_FACTOR=new w(0,0);let to=Pe;class Ki extends Tt{constructor(t){super(),this.beginColor=T.White,this.endColor=T.White,this.life=300,this.fade=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=T.White,this.size=5,this.sizeRate=0,this.visible=!0,this.isOffscreen=!1,this.paused=new Mt({canPause:!0}),this.particleTransform="global",this.name=`Particle#${this.id}`,this.addComponent(this.transform=new E),this.addComponent(this.motion=new H),this.addComponent(this.graphics=new Z),this.addComponent(this.paused),this.configure(t)}registerEmitter(t){if(this._emitter=t,this.particleTransform==="global"){const e=this._emitter.transform.globalPos;this.transform.pos=this.transform.pos.add(e),this.motion.vel=this.motion.vel.rotate(this._emitter.transform.globalRotation)}}configure(t){var e,i,s,n,o,a,h,l,c,d,_,f,m,p,x;this.particleTransform=(e=t.transform)!=null?e:this.particleTransform,this.life=(i=t.life)!=null?i:this.life,this.fade=(s=t.fade)!=null?s:this.fade,this.size=(n=t.size)!=null?n:this.size,this.endColor=(o=t.endColor)!=null?o:this.endColor.clone(),this.beginColor=(a=t.beginColor)!=null?a:this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.graphic=t.graphic,this.graphics.opacity=(h=t.opacity)!=null?h:this.graphics.opacity,this.transform.pos=(l=t.pos)!=null?l:this.transform.pos,this.transform.rotation=(c=t.rotation)!=null?c:0,this.transform.scale=y(1,1),this.transform.z=(d=t.z)!=null?d:0,this.motion.vel=(_=t.vel)!=null?_:this.motion.vel,this.motion.angularVelocity=(f=t.angularVelocity)!=null?f:0,this.motion.acc=(m=t.acc)!=null?m:this.motion.acc,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.graphics.opacity/this.life,this.startSize=(p=t.startSize)!=null?p:0,this.endSize=(x=t.endSize)!=null?x:0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.size=this.startSize),this.graphic?(this.graphics.use(this.graphic),this.graphics.onPostDraw=void 0):(this.graphics.localBounds=D.fromDimension(this.size,this.size,w.Half),this.graphics.onPostDraw=v=>{v.save(),v.debug.drawPoint(y(0,0),{color:this._currentColor,size:this.size}),v.restore()})}kill(){var t;(t=this._emitter)!=null&&t.isActive?this._emitter.removeParticle(this):super.kill()}update(t,e){this.life=this.life-e,this.life<0&&this.kill(),this.fade&&(this.graphics.opacity=L(this._aRate*this.life,1e-4,1)),this.startSize&&this.endSize&&this.startSize>0&&this.endSize>0&&(this.size=L(this.sizeRate*e+this.size,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=L(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=L(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=L(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=this.graphics.opacity;let i=this.motion.acc;this.focus&&(i=this.focus.sub(this.transform.pos).normalize().scale(this.focusAccel||0).scale(e/1e3)),to.integrate(this.transform,this.motion,i,e)}}Ki.DefaultConfig={beginColor:T.White,endColor:T.White,life:300,fade:!1,size:5,graphic:void 0,startSize:void 0,endSize:void 0};var Qt=(r=>(r.Global="global",r.Local="local",r))(Qt||{});class eo{constructor(){this.type="ex.particle",this.priority=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Ut({graphicsContext:e,vertexSource:tl,fragmentSource:el,onPreLink:i=>{t.transformFeedbackVaryings(i,["finalPosition","finalVelocity","finalRotation","finalAngularVelocity","finalLifeMs"],t.INTERLEAVED_ATTRIBS)}}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho)}_getTexture(t){const e=t.getAttribute(N.Filtering),i=e?Ye(e):void 0,s=Gt(t.getAttribute(N.WrappingX)),n=Gt(t.getAttribute(N.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);return t.removeAttribute("forceUpload"),a}draw(t,e){var i,s,n,o,a,h,l,c,d;const _=this._gl;this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho);const f=t.particle.transform===Qt.Local?this._context.getTransform():this._context.getTransform().multiply(t.emitter.transform.get().inverse);this._shader.setUniformAffineMatrix("u_transform",f),this._shader.setUniformBoolean("fade",!!t.particle.fade),this._shader.setUniformBoolean("useTexture",!!t.particle.graphic),this._shader.setUniformFloat("maxLifeMs",(i=t.particle.life)!=null?i:2e3),this._shader.setUniformFloat("deltaMs",e),this._shader.setUniformFloatVector("gravity",(s=t.particle.acc)!=null?s:y(0,0)),this._shader.setUniformFloatColor("beginColor",(n=t.particle.beginColor)!=null?n:T.Transparent),this._shader.setUniformFloatColor("endColor",(o=t.particle.endColor)!=null?o:T.Transparent);let m=(a=t.particle.startSize)!=null?a:0,p=(h=t.particle.endSize)!=null?h:0;const x=(l=t.particle.size)!=null?l:0;if(x>0&&(m=x,p=x),this._shader.setUniformFloat("startSize",m!=null?m:10),this._shader.setUniformFloat("endSize",p!=null?p:10),this._shader.setUniformFloat("startOpacity",(c=t.particle.opacity)!=null?c:1),t.particle.focus&&(this._shader.setUniformFloatVector("focus",t.particle.focus),this._shader.setUniformFloat("focusAccel",(d=t.particle.focusAccel)!=null?d:0)),t.particle.graphic){const v=t.particle.graphic,g=this._getTexture(v.image.image);_.activeTexture(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g),this._shader.setUniformInt("graphic",0)}t.draw(_)}hasPendingDraws(){return!1}flush(){}dispose(){}}class Vt{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");n?this.bufferData=n:this.bufferData=new Float32Array(i),this.type=s!=null?s:this.type,e.bindBuffer(e.ARRAY_BUFFER,this.buffer),e.bufferData(e.ARRAY_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this.buffer)}unbind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,null)}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,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}class Jt{constructor(t){this._logger=F.getInstance(),this._suppressWarnings=!1,this._layout=[],this._attributes=[],this._vertexTotalSizeBytes=0,this._initialized=!1;const{gl:e,shader:i,vertexBuffer:s,attributes:n,suppressWarnings:o}=t;this._gl=e,this._vertexBuffer=s,this._attributes=n,this._shader=i,this._suppressWarnings=o,i&&this.initialize()}get vertexBuffer(){return this._vertexBuffer}get attributes(){return this._attributes}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._initialized||!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 n of this._attributes){const o=t[n[0]];if(!o){if(!Yr(this._shader.vertexSource,n[0]))throw Error(`The attribute named: ${n[0]} size ${n[1]} not found in the shader source code:
195
- ${this._shader.vertexSource}`);this._suppressWarnings||this._logger.warn(`The attribute named: ${n[0]} size ${n[1]} not found in the compiled shader. This is possibly a bug:
196
- 1. Not a bug, but should remove unused code - attribute "${n[0]}" is unused in vertex/fragment and has been automatically removed by glsl compiler.
197
- 2. Definitely a bug, attribute "${n[0]}" in layout has been mistyped or is missing in shader, check vertex/fragment source.`);const a=Zr(this._gl,this._shader.vertexSource,n[0]);this._layout.push({name:n[0],glType:a,size:n[1],location:-1,normalized:!1})}if(o){if(o.size!==n[1])throw Error(`VertexLayout size definition for attribute: [${n[0]}, ${n[1]}], doesn't match shader source size ${o.size}:
198
- ${this._shader.vertexSource}`);this._layout.push(o)}}let e=0;for(const n of this._layout){const o=An(this._gl,n.glType);this._vertexTotalSizeBytes+=o*n.size,e+=n.size}this._vertexBuffer.bufferData.length%e!==0&&this._logger.warn(`The vertex component size (${e}) does NOT divide evenly into the specified vertex buffer (${this._vertexBuffer.bufferData.length})`);const i=this._gl;this._vao=i.createVertexArray(),i.bindVertexArray(this._vao),this._vertexBuffer.bind();let s=0;for(const n of this._layout)n.location!==-1&&(n.glType===i.INT?i.vertexAttribIPointer(n.location,n.size,n.glType,this.totalVertexSizeBytes,s):i.vertexAttribPointer(n.location,n.size,n.glType,n.normalized,this.totalVertexSizeBytes,s),i.enableVertexAttribArray(n.location)),s+=An(i,n.glType)*n.size;i.bindVertexArray(null),this._vertexBuffer.unbind(),this._initialized=!0}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),i.bindVertexArray(this._vao)}}class io{constructor(t,e){e.includes("v_texcoord")&&F.getInstance().warn(`ScreenShader: "v_texcoord" is deprecated in postprocessing fragment shaders will be removed in v1.0, use "v_uv" instead. Source [${e}]`);const i=t.__gl;this._shader=new Ut({graphicsContext:t,vertexSource:`#version 300 es
199
- in vec2 a_position;
200
- in vec2 a_uv;
201
- out vec2 v_texcoord;
202
- out vec2 v_uv;
203
-
204
- void main() {
205
- gl_Position = vec4(a_position, 0.0, 1.0);
206
- // Pass the texcoord to the fragment shader.
207
- v_texcoord = a_uv;
208
- v_uv = a_uv;
209
- }`,fragmentSource:e}),this._shader.compile(),this._buffer=new Vt({gl:i,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 Jt({gl:i,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2]]}),this._buffer.upload()}getShader(){return this._shader}getLayout(){return this._layout}}var Ke=(r=>(r.Protanope="Protanope",r.Deuteranope="Deuteranope",r.Tritanope="Tritanope",r))(Ke||{});const il=`#version 300 es
210
- precision mediump float;
211
- // our texture
212
- uniform sampler2D u_image;
213
- // the texCoords passed in from the vertex shader.
214
- in vec2 v_texcoord;
215
-
216
- // color blind type
217
- uniform int u_type;
218
-
219
- // simulation?
220
- uniform bool u_simulate;
221
-
222
- out vec4 fragColor;
223
-
224
- void main() {
225
- vec4 o = texture(u_image, v_texcoord);
226
- // RGB to LMS matrix conversion
227
- float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);
228
- float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);
229
- float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);
230
- // Simulate color blindness
231
- float l;
232
- float m;
233
- float s;
234
- //MODE CODE//
235
- if (u_type == 0) {
236
- // Protanope
237
- l = 0.0 * L + 2.02344 * M + -2.52581 * S;
238
- m = 0.0 * L + 1.0 * M + 0.0 * S;
239
- s = 0.0 * L + 0.0 * M + 1.0 * S;;
240
- } else if (u_type == 1) {
241
- // Deuteranope
242
- l = 1.0 * L + 0.0 * M + 0.0 * S;
243
- m = 0.494207 * L + 0.0 * M + 1.24827 * S;
244
- s = 0.0 * L + 0.0 * M + 1.0 * S;
245
- } else if (u_type == 2) {
246
- // Tritanope
247
- l = 1.0 * L + 0.0 * M + 0.0 * S;
248
- m = 0.0 * L + 1.0 * M + 0.0 * S;
249
- s = -0.395913 * L + 0.801109 * M + 0.0 * S;
250
- }
251
-
252
- // LMS to RGB matrix conversion
253
- vec4 error; // simulate the colors
254
- error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);
255
- error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);
256
- error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);
257
- error.a = 1.0;
258
- vec4 diff = o - error;
259
- vec4 correction; // correct the colors
260
- correction.r = 0.0;
261
- correction.g = (diff.r * 0.7) + (diff.g * 1.0);
262
- correction.b = (diff.r * 0.7) + (diff.b * 1.0);
263
- correction = o + correction;
264
- correction.a = o.a;
265
- //SIMULATE//
266
-
267
- // sim
268
- if (u_simulate) {
269
- fragColor = error.rgba;
270
- } else {
271
- fragColor = correction.rgba;
272
- }
273
- }`;class so{constructor(t,e=!1){this._colorBlindnessMode=t,this._simulate=!1,this._simulate=e}initialize(t){this._shader=new io(t,il),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 e=this._shader.getShader();e.use(),this._colorBlindnessMode===Ke.Protanope?e.setUniformInt("u_type",0):this._colorBlindnessMode===Ke.Deuteranope?e.setUniformInt("u_type",1):this._colorBlindnessMode===Ke.Tritanope&&e.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 ti{constructor(t,e,i){this._logger=F.getInstance(),this._gl=t,this.buffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer);const s=e*6;if(!i)this.bufferData=new Uint32Array(s);else{const a=Math.floor(16383.5);this.bufferGlType=t.UNSIGNED_SHORT,this.bufferData=new Uint16Array(s),e>a&&this._logger.warn(`Total quads exceeds hardware index buffer limit (uint16), max(${a}) requested quads(${e})`)}let n=0;for(let o=0;o<s;o+=6)this.bufferData[o+0]=n+0,this.bufferData[o+1]=n+1,this.bufferData[o+2]=n+2,this.bufferData[o+3]=n+2,this.bufferData[o+4]=n+1,this.bufferData[o+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)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}const sl=`#version 300 es
274
- in vec2 a_position;
275
-
276
- in vec2 a_uv;
277
- out vec2 v_uv;
278
-
279
- in vec2 a_screenuv;
280
- out vec2 v_screenuv;
281
-
282
- uniform mat4 u_matrix;
283
- uniform mat4 u_transform;
284
-
285
- void main() {
286
- // Set the vertex position using the ortho & transform matrix
287
- gl_Position = u_matrix * u_transform * vec4(a_position, 0.0, 1.0);
288
-
289
- // Pass through the UV coord to the fragment shader
290
- v_uv = a_uv;
291
- v_screenuv = a_screenuv;
292
- }
293
- `,no=class qa{constructor(t){this._logger=F.getInstance(),this._color=T.Transparent,this._initialized=!1,this._images={},this._uniforms={};const{color:e,name:i,vertexSource:s,fragmentSource:n,graphicsContext:o,images:a,uniforms:h}=t;if(this._name=i!=null?i:"anonymous material",this._vertexSource=s!=null?s:sl,this._fragmentSource=n,this._color=e!=null?e:this._color,this._uniforms=h!=null?h:this._uniforms,this._images=a!=null?a:this._images,!o)throw Error(`Material ${i} must be provided an excalibur webgl graphics context`);o instanceof Kt?this._initialize(o):this._logger.warn(`Material ${i} was created in 2D Canvas mode, currently only WebGL is supported`);{this.images.u_graphic&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_graphic, is this on purpose? If so ignore this warning.`),this.images.u_screen_texture&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_screen_texture, is this on purpose? If so ignore this warning.`);for(const l of Object.keys(this._uniforms))qa.BuiltInUniforms.includes(l)&&this._logger.warn(`Material named "${this.name}" is overriding built in uniform ${l}, is this on purpose? If so ignore this warning.`)}}_initialize(t){this._initialized||(this._shader=t.createShader({name:this._name,vertexSource:this._vertexSource,fragmentSource:this._fragmentSource,uniforms:this._uniforms,images:this._images,startingTextureSlot:this.isUsingScreenTexture?2:1}),this._initialized=!0)}get uniforms(){return this._shader.uniforms}get images(){return this._shader.images}get color(){return this._color}set color(t){this._color=t}get name(){return this._name}get isUsingScreenTexture(){return this._fragmentSource.includes("u_screen_texture")}get isOverridingGraphic(){return!!this._images.u_graphic}update(t){this._shader&&(this._shader.use(),t(this._shader))}getShader(){return this._shader}addImageSource(t,e){this._shader.addImageSource(t,e),this.images.u_graphic&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_graphic, is this on purpose? If so ignore this warning.`),this.images.u_screen_texture&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_screen_texture, is this on purpose? If so ignore this warning.`)}removeImageSource(t){this._shader.removeImageSource(t)}use(){if(this._initialized)this._shader.use(),this._shader.trySetUniformFloatColor("u_color",this._color);else throw Error(`Material ${this.name} not yet initialized, use the ExcaliburGraphicsContext.createMaterial() to work around this.`)}};no.BuiltInUniforms=["u_time_ms","u_opacity","u_resolution","u_graphic_resolution","u_size","u_matrix","u_transform","u_graphic","u_screen_texture"];let ro=no;class nl{constructor(){this.type="ex.debug-line",this.priority=0,this._maxLines=10922,this._vertexIndex=0,this._lineCount=0,this._startScratch=y(0,0),this._endScratch=y(0,0),this._lengthSoFar=0,this._currentlyDashed=!1}initialize(t,e){this._gl=t,this._context=e,this._shader=new Ut({graphicsContext:e,vertexSource:Zh,fragmentSource:jh}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._vertexBuffer=new Vt({gl:t,size:42*this._maxLines,type:"dynamic"}),this._layout=new Jt({gl:t,vertexBuffer:this._vertexBuffer,shader:this._shader,attributes:[["a_position",2],["a_color",4],["a_lengthSoFar",1]]})}dispose(){this._vertexBuffer.dispose(),this._shader.dispose(),this._context=null,this._gl=null}draw(t,e,i,s=2,n=!1){(this._isFull()||this._currentlyDashed!==n)&&(this._currentlyDashed=n,this.flush()),this._lineCount++;const o=this._context.getTransform(),a=o.multiply(t,this._startScratch),h=o.multiply(e,this._endScratch),l=h.sub(a),c=a.distance(h),d=l.normal(),_=s/2,f=this._vertexBuffer.bufferData;f[this._vertexIndex++]=a.x-d.x*_,f[this._vertexIndex++]=a.y-d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=a.x+d.x*_,f[this._vertexIndex++]=a.y+d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=h.x-d.x*_,f[this._vertexIndex++]=h.y-d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c,f[this._vertexIndex++]=h.x-d.x*_,f[this._vertexIndex++]=h.y-d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c,f[this._vertexIndex++]=a.x+d.x*_,f[this._vertexIndex++]=a.y+d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=h.x+d.x*_,f[this._vertexIndex++]=h.y+d.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c}_isFull(){return this._lineCount>=this._maxLines}hasPendingDraws(){return this._lineCount!==0}flush(){if(this._lineCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_dashed",this._currentlyDashed),t.drawArrays(t.TRIANGLES,0,this._lineCount*6),Q.DrawnImagesCount+=this._lineCount,Q.DrawCallCount++,this._vertexIndex=0,this._lineCount=0,this._lengthSoFar=0}}const rl=`#version 300 es
294
- in vec2 a_position;
295
- in vec4 a_color;
296
- in float a_size;
297
- out lowp vec4 v_color;
298
- uniform mat4 u_matrix;
299
-
300
- void main() {
301
- gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
302
- gl_PointSize = a_size * 2.0;
303
- v_color = a_color;
304
- }`,ol=`#version 300 es
305
-
306
- precision mediump float;
307
- in lowp vec4 v_color;
308
-
309
- out vec4 fragColor;
310
-
311
- void main() {
312
- float r = 0.0, delta = 0.0, alpha = 1.0;
313
- vec2 cxy = 2.0 * gl_PointCoord - 1.0;
314
- r = dot(cxy, cxy);
315
-
316
- delta = fwidth(r);
317
- alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r);
318
- // "premultiply" the color by alpha
319
- vec4 color = v_color;
320
- color.a = color.a * alpha;
321
- color.rgb = color.rgb * color.a;
322
- fragColor = color;
323
- }`;class al{constructor(){this.type="ex.debug-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 Ut({graphicsContext:e,vertexSource:rl,fragmentSource:ol}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._buffer=new Vt({gl:t,size:7*this._maxPoints,type:"dynamic"}),this._layout=new Jt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_color",4],["a_size",1]]})}dispose(){this._buffer.dispose(),this._shader.dispose(),this._context=null,this._gl=null}draw(t,e,i){this._isFull()&&this.flush(),this._pointCount++;const s=this._context.getTransform(),n=this._context.opacity,o=this._context.snapToPixel,a=s.multiply(t);o&&(a.x=~~(a.x+B),a.y=~~(a.y+B));const h=this._buffer.bufferData;h[this._vertexIndex++]=a.x,h[this._vertexIndex++]=a.y,h[this._vertexIndex++]=e.r/255,h[this._vertexIndex++]=e.g/255,h[this._vertexIndex++]=e.b/255,h[this._vertexIndex++]=e.a*n,h[this._vertexIndex++]=i}_isFull(){return this._pointCount>=this._maxPoints}hasPendingDraws(){return this._pointCount!==0}flush(){if(this._pointCount===0)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),Q.DrawnImagesCount+=this._pointCount,Q.DrawCallCount++,this._pointCount=0,this._vertexIndex=0}}const hl=`#version 300 es
324
- precision highp float;
325
-
326
- // UV coord
327
- in vec2 v_uv;
328
-
329
- // Color coord to blend with image
330
- in lowp vec4 v_color;
331
-
332
- // Stroke color if used
333
- in lowp vec4 v_strokeColor;
334
-
335
- // Stroke thickness if used
336
- in lowp float v_strokeThickness;
337
-
338
- in float v_radius;
339
-
340
- // Opacity
341
- in float v_opacity;
342
-
343
- out vec4 fragColor;
344
-
345
- void main() {
346
- // make (0, 0) the center the uv
347
- vec2 uv = v_uv * 2.0 - 1.0;
348
-
349
- vec4 color = v_color;
350
- vec4 strokeColor = v_strokeColor;
351
-
352
- float dist = 1.0 - length(uv);
353
- float radius = dist * v_radius; // 0 is the edge
354
-
355
- // Fade based on fwidth
356
- float fade = fwidth(dot(uv, uv)) / 2.0;
357
-
358
- float fill = smoothstep(-fade, fade, radius);
359
-
360
- float stroke =
361
- smoothstep(0.0, fade, radius) -
362
- smoothstep(v_strokeThickness, v_strokeThickness + fade, radius);
363
-
364
- strokeColor.a = stroke;
365
- strokeColor.rgb *= strokeColor.a;
366
-
367
- // vec4 finalColor = strokeColor;
368
-
369
- color.a *= fill * (1.0 - stroke);
370
- color.rgb *= color.a;
371
-
372
- vec4 finalColor = mix(vec4(0.0), (color + strokeColor), fill);
373
- finalColor.rgb = finalColor.rgb * v_opacity;
374
- finalColor.a = finalColor.a * v_opacity;
375
-
376
- fragColor = finalColor;
377
- }
378
- `,ll=`#version 300 es
379
- in vec2 a_position;
380
-
381
- // UV coordinate
382
- in vec2 a_uv;
383
- out vec2 v_uv;
384
-
385
- // Opacity
386
- in float a_opacity;
387
- out float v_opacity;
388
-
389
- in vec4 a_color;
390
- out vec4 v_color;
391
-
392
- in vec4 a_strokeColor;
393
- out vec4 v_strokeColor;
394
-
395
- in float a_strokeThickness;
396
- out float v_strokeThickness;
397
-
398
- in float a_radius;
399
- out float v_radius;
400
-
401
- uniform mat4 u_matrix;
402
-
403
-
404
- void main() {
405
- // Set the vertex position using the ortho transform matrix
406
- gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
407
-
408
- // Pass through UV coords
409
- v_uv = a_uv;
410
- // Pass through the Opacity to the fragment shader
411
- v_opacity = a_opacity;
412
- // Pass through the color to the fragment shader
413
- v_color = a_color;
414
- // Pass through the stroke color to the fragment shader
415
- v_strokeColor = a_strokeColor;
416
- // Pass through the stroke thickenss to the fragment shader
417
- v_strokeThickness = a_strokeThickness;
418
- v_radius = a_radius;
419
- }
420
- `;class cl{constructor(){this.type="ex.debug-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 Ut({graphicsContext:e,fragmentSource:hl,vertexSource:ll}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Vt({gl:t,size:60*this._maxCircles,type:"dynamic"}),this._layout=new Jt({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],["a_radius",1]]}),this._quads=new ti(t,this._maxCircles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=T.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const o=this._context.getTransform(),a=o.getScaleX(),h=this._context.opacity,l=this._context.snapToPixel,c=o.multiply(t.add(y(-e,-e))),d=o.multiply(t.add(y(e,-e))),_=o.multiply(t.add(y(e,e))),f=o.multiply(t.add(y(-e,e)));l&&(c.x=~~(c.x+B),c.y=~~(c.y+B),d.x=~~(d.x+B),d.y=~~(d.y+B),f.x=~~(f.x+B),f.y=~~(f.y+B),_.x=~~(_.x+B),_.y=~~(_.y+B));const m=0,p=0,x=1,v=1,g=this._layout.vertexBuffer.bufferData;g[this._vertexIndex++]=c.x,g[this._vertexIndex++]=c.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=p,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=f.x,g[this._vertexIndex++]=f.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=v,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=d.x,g[this._vertexIndex++]=d.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=p,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=_.x,g[this._vertexIndex++]=_.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=v,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a}hasPendingDraws(){return this._circleCount!==0}flush(){if(this._circleCount===0)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,this._circleCount*6,this._quads.bufferGlType,0),Q.DrawnImagesCount+=this._circleCount,Q.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}const dl=`#version 300 es
421
- in vec2 a_position;
422
-
423
- in vec2 a_texcoord;
424
- out vec2 v_texcoord;
425
-
426
- void main() {
427
- gl_Position = vec4(a_position, 0.0, 1.0);
428
-
429
- // Pass the texcoord to the fragment shader.
430
- v_texcoord = a_texcoord;
431
- }`,ul=`#version 300 es
432
- precision mediump float;
433
-
434
- // Passed in from the vertex shader.
435
- in vec2 v_texcoord;
436
-
437
- // The texture.
438
- uniform sampler2D u_texture;
439
-
440
- out vec4 fragColor;
441
-
442
- void main() {
443
- fragColor = texture(u_texture, v_texcoord);
444
- }`;class _l{constructor(t){const e=t.__gl;this._gl=e,this._shader=new Ut({graphicsContext:t,vertexSource:dl,fragmentSource:ul}),this._shader.compile(),this._buffer=new Vt({gl:e,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 Jt({gl:e,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}renderWithPostProcessor(t){const e=this._gl,i=t.getShader();i.use(),t.getLayout().use(),e.activeTexture(e.TEXTURE0),i.trySetUniformInt("u_image",0),t.onDraw&&t.onDraw(),e.drawArrays(e.TRIANGLES,0,6)}renderToScreen(){const t=this._gl;this._shader.use(),this._layout.use(),t.drawArrays(t.TRIANGLES,0,6)}}const fl=`#version 300 es
445
- precision mediump float;
446
-
447
- // UV coord
448
- in vec2 v_texcoord;
449
-
450
- // Texture index
451
- in lowp float v_textureIndex;
452
-
453
- // Textures in the current draw
454
- uniform sampler2D u_textures[%%count%%];
455
-
456
- uniform bool u_pixelart;
457
-
458
- // Opacity
459
- in float v_opacity;
460
-
461
- in vec4 v_tint;
462
-
463
- in vec2 v_res;
464
-
465
- out vec4 fragColor;
466
-
467
- // Inigo Quilez pixel art filter https://jorenjoestar.github.io/post/pixel_art_filtering/
468
- vec2 uv_iq(in vec2 uv, in vec2 texture_size) {
469
- vec2 pixel = uv * texture_size;
470
-
471
- vec2 seam=floor(pixel+.5);
472
- vec2 dudv=fwidth(pixel);
473
- pixel=seam+clamp((pixel-seam)/dudv,-.5,.5);
474
-
475
- return pixel/texture_size;
476
- }
477
-
478
- void main(){
479
- // In order to support the most efficient sprite batching, we have multiple
480
- // textures loaded into the gpu (usually 8) this picker logic skips over textures
481
- // that do not apply to a particular sprite.
482
-
483
- vec4 color=vec4(1.,0,0,1.);
484
-
485
- // GLSL is templated out to pick the right texture and set the vec4 color
486
- %%texture_picker%%
487
-
488
- color.rgb=color.rgb*v_opacity;
489
- color.a=color.a*v_opacity;
490
- fragColor=color*v_tint;
491
- }`,gl=`#version 300 es
492
- in vec2 a_position;
493
-
494
- // Opacity
495
- in float a_opacity;
496
- out float v_opacity;
497
-
498
- // UV coordinate
499
- in vec2 a_texcoord;
500
- out vec2 v_texcoord;
501
-
502
- // Texture res
503
- in vec2 a_res;
504
- out vec2 v_res;
505
-
506
- // Texture number
507
- in lowp float a_textureIndex;
508
- out lowp float v_textureIndex;
509
-
510
- in vec4 a_tint;
511
- out vec4 v_tint;
512
-
513
- uniform mat4 u_matrix;
514
-
515
- void main(){
516
- // Set the vertex position using the ortho transform matrix
517
- gl_Position=u_matrix*vec4(a_position,0.,1.);
518
-
519
- // Pass through the Opacity to the fragment shader
520
- v_opacity=a_opacity;
521
- // Pass through the UV coord to the fragment shader
522
- v_texcoord=a_texcoord;
523
-
524
- v_res = a_res;
525
-
526
- // Pass through the texture number to the fragment shader
527
- v_textureIndex=a_textureIndex;
528
- // Pass through the tint
529
- v_tint=a_tint;
530
- }`;class pl{constructor(t){this.type="ex.image",this.priority=0,this._maxImages=10922,this._maxTextures=0,this._imageCount=0,this._textures=[],this._textureIndex=0,this._textureToIndex=new Map,this._images=new Set,this._vertexIndex=0,this._imageToWidth=new Map,this._imageToHeight=new Map,this._view=[0,0,0,0],this._dest=[0,0],this._quad=[0,0,0,0,0,0,0,0],this._defaultTint=T.White,this.pixelArtSampler=t.pixelArtSampler,this.uvPadding=t.uvPadding}initialize(t,e){this._gl=t,this._context=e;const i=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),s=Pn(t,i);this._maxTextures=Math.min(i,s);const n=this._transformFragmentSource(fl,this._maxTextures);this._shader=new Ut({graphicsContext:e,fragmentSource:n,vertexSource:gl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map((o,a)=>a)),this._buffer=new Vt({gl:t,size:48*this._maxImages,type:"dynamic"}),this._layout=new Jt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_opacity",1],["a_res",2],["a_texcoord",2],["a_textureIndex",1],["a_tint",4]]}),this._quads=new ti(t,this._maxImages,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._textures.length=0,this._context=null,this._gl=null}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let n=0;n<e;n++)n===0?s+=`if (v_textureIndex <= ${n}.5) {
531
- `:s+=` else if (v_textureIndex <= ${n}.5) {
532
- `,s+=` vec2 uv = u_pixelart ? uv_iq(v_texcoord, v_res) : v_texcoord;
533
- `,s+=` color = texture(u_textures[${n}], uv);
534
- `,s+=` }
535
- `;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(N.Filtering),i=e?Ye(e):void 0,s=Gt(t.getAttribute(N.WrappingX)),n=Gt(t.getAttribute(N.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&(this._textures.push(a),this._textureToIndex.set(a,this._textureIndex++),this._images.add(t))}_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){var e;if(t){const i=this._context.textureLoader.get(t);return(e=this._textureToIndex.get(i))!=null?e:-1}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}draw(t,e,i,s,n,o,a,h,l){var c,d,_,f;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);const m=this._getImageWidth(t),p=this._getImageHeight(t);let x=m||s||0,v=p||n||0;this._view[0]=0,this._view[1]=0,this._view[2]=(c=s!=null?s:m)!=null?c:0,this._view[3]=(d=n!=null?n:p)!=null?d:0,this._dest[0]=e!=null?e:1,this._dest[1]=i!=null?i:1,o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(this._view[0]=e!=null?e:1,this._view[1]=i!=null?i:1,this._view[2]=(_=s!=null?s:m)!=null?_:0,this._view[3]=(f=n!=null?n:p)!=null?f:0,this._dest[0]=o,this._dest[1]=a,x=h,v=l),e=this._view[0],i=this._view[1];const g=this._view[2],b=this._view[3],S=this._context.getTransform(),A=this._context.opacity,M=this._context.snapToPixel;this._quad[0]=this._dest[0],this._quad[1]=this._dest[1],this._quad[2]=this._dest[0]+x,this._quad[3]=this._dest[1],this._quad[4]=this._dest[0],this._quad[5]=this._dest[1]+v,this._quad[6]=this._dest[0]+x,this._quad[7]=this._dest[1]+v,S.multiplyQuadInPlace(this._quad),M&&(this._quad[0]=~~(this._quad[0]+q(this._quad[0])*B),this._quad[1]=~~(this._quad[1]+q(this._quad[1])*B),this._quad[2]=~~(this._quad[2]+q(this._quad[2])*B),this._quad[3]=~~(this._quad[3]+q(this._quad[3])*B),this._quad[4]=~~(this._quad[4]+q(this._quad[4])*B),this._quad[5]=~~(this._quad[5]+q(this._quad[5])*B),this._quad[6]=~~(this._quad[6]+q(this._quad[6])*B),this._quad[7]=~~(this._quad[7]+q(this._quad[7])*B));const C=this._context.tint||this._defaultTint,z=this._getTextureIdForImage(t),O=m||x,st=p||v,W=(e+this.uvPadding)/O,ct=(i+this.uvPadding)/st,K=(e+g-this.uvPadding)/O,V=(i+b-this.uvPadding)/st,ut=m,ft=p,I=this._layout.vertexBuffer.bufferData;I[this._vertexIndex++]=this._quad[0],I[this._vertexIndex++]=this._quad[1],I[this._vertexIndex++]=A,I[this._vertexIndex++]=ut,I[this._vertexIndex++]=ft,I[this._vertexIndex++]=W,I[this._vertexIndex++]=ct,I[this._vertexIndex++]=z,I[this._vertexIndex++]=C.r/255,I[this._vertexIndex++]=C.g/255,I[this._vertexIndex++]=C.b/255,I[this._vertexIndex++]=C.a,I[this._vertexIndex++]=this._quad[4],I[this._vertexIndex++]=this._quad[5],I[this._vertexIndex++]=A,I[this._vertexIndex++]=ut,I[this._vertexIndex++]=ft,I[this._vertexIndex++]=W,I[this._vertexIndex++]=V,I[this._vertexIndex++]=z,I[this._vertexIndex++]=C.r/255,I[this._vertexIndex++]=C.g/255,I[this._vertexIndex++]=C.b/255,I[this._vertexIndex++]=C.a,I[this._vertexIndex++]=this._quad[2],I[this._vertexIndex++]=this._quad[3],I[this._vertexIndex++]=A,I[this._vertexIndex++]=ut,I[this._vertexIndex++]=ft,I[this._vertexIndex++]=K,I[this._vertexIndex++]=ct,I[this._vertexIndex++]=z,I[this._vertexIndex++]=C.r/255,I[this._vertexIndex++]=C.g/255,I[this._vertexIndex++]=C.b/255,I[this._vertexIndex++]=C.a,I[this._vertexIndex++]=this._quad[6],I[this._vertexIndex++]=this._quad[7],I[this._vertexIndex++]=A,I[this._vertexIndex++]=ut,I[this._vertexIndex++]=ft,I[this._vertexIndex++]=K,I[this._vertexIndex++]=V,I[this._vertexIndex++]=z,I[this._vertexIndex++]=C.r/255,I[this._vertexIndex++]=C.g/255,I[this._vertexIndex++]=C.b/255,I[this._vertexIndex++]=C.a}hasPendingDraws(){return this._imageCount!==0}flush(){if(this._imageCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0,48*this._imageCount),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_pixelart",this.pixelArtSampler),this._bindTextures(t),this._quads.bind(),t.drawElements(t.TRIANGLES,this._imageCount*6,this._quads.bufferGlType,0),Q.DrawnImagesCount+=this._imageCount,Q.DrawCallCount++,this._imageCount=0,this._vertexIndex=0,this._textures.length=0,this._textureIndex=0,this._textureToIndex.clear(),this._images.clear(),this._imageToWidth.clear(),this._imageToHeight.clear()}}const ml=`#version 300 es
536
-
537
- precision mediump float;
538
-
539
- // UV coord
540
- in vec2 v_uv;
541
-
542
- in vec2 v_size; // in pixels
543
-
544
- // Color coord to blend with image
545
- in lowp vec4 v_color;
546
-
547
- // Stroke color if used
548
- in lowp vec4 v_strokeColor;
549
-
550
- // Stroke thickness if used
551
- in lowp float v_strokeThickness; // in pixels
552
-
553
- // Opacity
554
- in float v_opacity;
555
-
556
- out vec4 fragColor;
557
-
558
- void main() {
559
- // modified from https://stackoverflow.com/questions/59197671/glsl-rounded-rectangle-with-variable-border
560
- vec2 uv = v_uv;
561
- vec2 fragCoord = uv * v_size;
562
- float maxX = v_size.x - v_strokeThickness;
563
- float minX = v_strokeThickness;
564
- float maxY = v_size.y - v_strokeThickness;
565
- float minY = v_strokeThickness;
566
-
567
- if (fragCoord.x < maxX && fragCoord.x > minX &&
568
- fragCoord.y < maxY && fragCoord.y > minY) {
569
- fragColor = v_color;
570
- } else {
571
- fragColor = v_strokeColor;
572
- }
573
- fragColor.a *= v_opacity;
574
- fragColor.rgb *= fragColor.a;
575
-
576
- // vec2 v2CenteredPos = abs(fragCoord - v_size.xy / 2.0);
577
- // vec2 v2HalfShapeSizePx = v_size.xy/2.0 - v_strokeThickness/2.0;
578
-
579
- // float fHalfBorderDist = 0.0;
580
- // float fHalfBorderThickness = 0.0;
581
-
582
- // if (fragCoord.x > max(v_radius, v_strokeThickness) &&
583
- // fragCoord.x < v_size.x - max(v_radius, v_strokeThickness))
584
- // {
585
- // fHalfBorderDist = v2CenteredPos.y - v2HalfShapeSizePx.y;
586
- // fHalfBorderThickness = v_strokeThickness / 2.0;
587
- // }
588
- // else if (fragCoord.y > max(v_radius, v_strokeThickness) &&
589
- // fragCoord.y < v_size.y - max(v_radius, v_strokeThickness))
590
- // {
591
- // fHalfBorderDist = v2CenteredPos.x - v2HalfShapeSizePx.x;
592
- // fHalfBorderThickness = v_strokeThickness / 2.0;
593
- // }
594
- // else
595
- // {
596
- // vec2 edgeVec = max(vec2(0.0), v_radius - vec2(
597
- // uv.x > 0.5 ? v_size.x - fragCoord.x : fragCoord.x,
598
- // uv.y > 0.5 ? v_size.y - fragCoord.y : fragCoord.y));
599
-
600
- // float ellipse_ab = v_radius-v_strokeThickness;
601
- // vec2 ellipse_isect = (v_strokeThickness > v_radius || v_strokeThickness > v_radius) ? vec2(0.0) :
602
- // edgeVec.xy * ellipse_ab*ellipse_ab / length(ellipse_ab*edgeVec.yx);
603
-
604
- // fHalfBorderThickness = (v_radius - length(ellipse_isect)) / 2.0;
605
- // fHalfBorderDist = length(edgeVec) - (v_radius - fHalfBorderThickness);
606
- // }
607
-
608
- // vec4 v4FromColor = v_strokeColor;
609
- // v4FromColor.rgb *= v4FromColor.a;
610
- // vec4 v4ToColor = vec4(0.0); // background color is transparent
611
- // if (fHalfBorderDist < 0.0) {
612
- // v4ToColor = v_color;
613
- // v4ToColor.rgb *= v4ToColor.a;
614
- // }
615
-
616
- // float mixPct = abs(fHalfBorderDist) - fHalfBorderThickness;
617
-
618
- // vec4 finalColor = mix(v4FromColor, v4ToColor, mixPct);
619
- // gl_FragColor = finalColor;
620
- }`,vl=`#version 300 es
621
- in vec2 a_position;
622
-
623
- // UV coordinate
624
- in vec2 a_uv;
625
- out vec2 v_uv;
626
-
627
- in vec2 a_size;
628
- out vec2 v_size;
629
-
630
- // Opacity
631
- in float a_opacity;
632
- out float v_opacity;
633
-
634
- in vec4 a_color;
635
- out vec4 v_color;
636
-
637
- in vec4 a_strokeColor;
638
- out vec4 v_strokeColor;
639
-
640
- in float a_strokeThickness;
641
- out float v_strokeThickness;
642
-
643
- uniform mat4 u_matrix;
644
-
645
-
646
- void main() {
647
- // Set the vertex position using the ortho transform matrix
648
- gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
649
-
650
- // Pass through UV coords
651
- v_uv = a_uv;
652
- // Pass through size
653
- v_size = a_size;
654
- // Pass through the Opacity to the fragment shader
655
- v_opacity = a_opacity;
656
- // Pass through the color to the fragment shader
657
- v_color = a_color;
658
- // Pass through the stroke color to the fragment shader
659
- v_strokeColor = a_strokeColor;
660
- // Pass through the stroke thickenss to the fragment shader
661
- v_strokeThickness = a_strokeThickness;
662
- }`;class wl{constructor(){this.type="ex.rectangle",this.priority=0,this._maxRectangles=10922,this._rectangleCount=0,this._vertexIndex=0,this._transparent=T.Transparent,this._scratch1=y(0,0),this._scratch2=y(0,0),this._scratch3=y(0,0),this._scratch4=y(0,0)}initialize(t,e){this._gl=t,this._context=e,this._shader=new Ut({graphicsContext:e,fragmentSource:ml,vertexSource:vl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Vt({gl:t,size:64*this._maxRectangles,type:"dynamic"}),this._layout=new Jt({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 ti(t,this._maxRectangles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._rectangleCount>=this._maxRectangles}draw(...t){t[0]instanceof w&&t[1]instanceof w?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(),o=this._context.opacity,a=this._context.snapToPixel,h=e.sub(t),l=h.magnitude,c=h.normalize().perpendicular(),d=s/2,_=n.multiply(c.scale(d,this._scratch1).add(t,this._scratch1),this._scratch1),f=n.multiply(c.scale(-d,this._scratch2).add(t,this._scratch2),this._scratch2),m=n.multiply(c.scale(d,this._scratch3).add(e,this._scratch3),this._scratch3),p=n.multiply(c.scale(-d,this._scratch4).add(e,this._scratch4),this._scratch4);a&&(_.x=~~(_.x+B),_.y=~~(_.y+B),m.x=~~(m.x+B),m.y=~~(m.y+B),f.x=~~(f.x+B),f.y=~~(f.y+B),p.x=~~(p.x+B),p.y=~~(p.y+B));const x=0,v=0,g=1,b=1,S=this._transparent,A=0,M=1,C=this._layout.vertexBuffer.bufferData;C[this._vertexIndex++]=_.x,C[this._vertexIndex++]=_.y,C[this._vertexIndex++]=x,C[this._vertexIndex++]=v,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/M,C[this._vertexIndex++]=f.x,C[this._vertexIndex++]=f.y,C[this._vertexIndex++]=x,C[this._vertexIndex++]=b,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/M,C[this._vertexIndex++]=m.x,C[this._vertexIndex++]=m.y,C[this._vertexIndex++]=g,C[this._vertexIndex++]=v,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/M,C[this._vertexIndex++]=p.x,C[this._vertexIndex++]=p.y,C[this._vertexIndex++]=g,C[this._vertexIndex++]=b,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/M}drawRectangle(t,e,i,s,n=T.Transparent,o=0){this._isFull()&&this.flush(),this._rectangleCount++;const a=this._context.getTransform(),h=this._context.opacity,l=this._context.snapToPixel,c=a.multiply(t.add(y(0,0))),d=a.multiply(t.add(y(e,0))),_=a.multiply(t.add(y(e,i))),f=a.multiply(t.add(y(0,i)));l&&(c.x=~~(c.x+B),c.y=~~(c.y+B),d.x=~~(d.x+B),d.y=~~(d.y+B),f.x=~~(f.x+B),f.y=~~(f.y+B),_.x=~~(_.x+B),_.y=~~(_.y+B));const m=0,p=0,x=1,v=1,g=this._layout.vertexBuffer.bufferData;g[this._vertexIndex++]=c.x,g[this._vertexIndex++]=c.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=p,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=f.x,g[this._vertexIndex++]=f.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=v,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=d.x,g[this._vertexIndex++]=d.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=p,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=_.x,g[this._vertexIndex++]=_.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=v,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o}hasPendingDraws(){return this._rectangleCount!==0}flush(){if(this._rectangleCount===0)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,this._rectangleCount*6,this._quads.bufferGlType,0),Q.DrawnImagesCount+=this._rectangleCount,Q.DrawCallCount++,this._rectangleCount=0,this._vertexIndex=0}}const xl=`#version 300 es
663
- precision highp float;
664
-
665
- // UV coord
666
- in vec2 v_uv;
667
-
668
- // Color coord to blend with image
669
- in lowp vec4 v_color;
670
-
671
- // Stroke color if used
672
- in lowp vec4 v_strokeColor;
673
-
674
- // Stroke thickness if used
675
- in lowp float v_strokeThickness;
676
-
677
- // Opacity
678
- in float v_opacity;
679
-
680
- out vec4 fragColor;
681
-
682
- void main() {
683
- // make (0, 0) the center the uv
684
- vec2 uv = v_uv * 2.0 - 1.0;
685
-
686
- vec4 color = v_color;
687
- vec4 strokeColor = v_strokeColor;
688
-
689
- // circle border is at radius 1.0
690
- // dist is > 0 when inside the circle
691
- float d = length(uv);
692
- float dist = 1.0 - length(uv);
693
-
694
- // Fade based on fwidth
695
- float fade = fwidth(dot(uv, uv));
696
-
697
- // if dist is greater than 0 step to 1;
698
- // when we cross this 0 threshold add a smooth fade
699
- float fill = smoothstep(-fade/2.0, fade/2.0, dist);
700
-
701
- // if dist is greater than the stroke thickness step to 1
702
- float stroke = 1.0 - smoothstep(v_strokeThickness, v_strokeThickness + fade, dist);
703
-
704
- strokeColor.a *= fill * stroke;
705
- strokeColor.rgb *= strokeColor.a;
706
-
707
- color.a *= fill * (1.0 - stroke);
708
- color.rgb *= color.a;
709
-
710
- vec4 finalColor = mix(vec4(0.0), (color + strokeColor), fill);
711
- finalColor.rgb = finalColor.rgb * v_opacity;
712
- finalColor.a = finalColor.a * v_opacity;
713
- fragColor = finalColor;
714
- }`,yl=`#version 300 es
715
- in vec2 a_position;
716
-
717
- // UV coordinate
718
- in vec2 a_uv;
719
- out vec2 v_uv;
720
-
721
- // Opacity
722
- in float a_opacity;
723
- out float v_opacity;
724
-
725
- in vec4 a_color;
726
- out vec4 v_color;
727
-
728
- in vec4 a_strokeColor;
729
- out vec4 v_strokeColor;
730
-
731
- in float a_strokeThickness;
732
- out float v_strokeThickness;
733
-
734
- uniform mat4 u_matrix;
735
-
736
-
737
- void main() {
738
- // Set the vertex position using the ortho transform matrix
739
- gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
740
-
741
- // Pass through UV coords
742
- v_uv = a_uv;
743
- // Pass through the Opacity to the fragment shader
744
- v_opacity = a_opacity;
745
- // Pass through the color to the fragment shader
746
- v_color = a_color;
747
- // Pass through the stroke color to the fragment shader
748
- v_strokeColor = a_strokeColor;
749
- // Pass through the stroke thickenss to the fragment shader
750
- v_strokeThickness = a_strokeThickness;
751
- }`;class bl{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 Ut({graphicsContext:e,fragmentSource:xl,vertexSource:yl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Vt({gl:t,size:56*this._maxCircles,type:"dynamic"}),this._layout=new Jt({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 ti(t,this._maxCircles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=T.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const o=this._context.getTransform(),a=this._context.opacity,h=this._context.snapToPixel,l=o.multiply(t.add(y(-e,-e))),c=o.multiply(t.add(y(e,-e))),d=o.multiply(t.add(y(e,e))),_=o.multiply(t.add(y(-e,e)));h&&(l.x=~~(l.x+B),l.y=~~(l.y+B),c.x=~~(c.x+B),c.y=~~(c.y+B),_.x=~~(_.x+B),_.y=~~(_.y+B),d.x=~~(d.x+B),d.y=~~(d.y+B));const f=0,m=0,p=1,x=1,v=this._layout.vertexBuffer.bufferData;v[this._vertexIndex++]=l.x,v[this._vertexIndex++]=l.y,v[this._vertexIndex++]=f,v[this._vertexIndex++]=m,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=_.x,v[this._vertexIndex++]=_.y,v[this._vertexIndex++]=f,v[this._vertexIndex++]=x,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=c.x,v[this._vertexIndex++]=c.y,v[this._vertexIndex++]=p,v[this._vertexIndex++]=m,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=d.x,v[this._vertexIndex++]=d.y,v[this._vertexIndex++]=p,v[this._vertexIndex++]=x,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e}hasPendingDraws(){return this._circleCount!==0}flush(){if(this._circleCount===0)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,this._circleCount*6,this._quads.bufferGlType,0),Q.DrawnImagesCount+=this._circleCount,Q.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}class Cl{constructor(){this.z=0,this.priority=0,this.renderer="",this.transform=tt.identity(),this.state={z:0,opacity:1,tint:T.White,material:null},this.args=new Array(10)}}class oo{constructor(){this.type="ex.material",this.priority=0,this._textures=[]}initialize(t,e){this._gl=t,this._context=e,this._buffer=new Vt({gl:t,size:24,type:"dynamic"}),this._layout=new Jt({gl:t,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_screenuv",2]],suppressWarnings:!0}),this._quads=new ti(t,1,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._textures.length=0,this._context=null,this._gl=null}draw(t,e,i,s,n,o,a,h,l){var c,d,_,f,m;const p=this._gl,x=this._context.material;if(!x)return;const v=this._context.getTransform(),g=this._context.opacity,b=x.getShader(),S=this._layout.vertexBuffer.bufferData;let A=0,M=(t==null?void 0:t.width)||s||0,C=(t==null?void 0:t.height)||n||0,z=[0,0,(c=s!=null?s:t==null?void 0:t.width)!=null?c:0,(d=n!=null?n:t==null?void 0:t.height)!=null?d:0],O=[e!=null?e:1,i!=null?i:1];o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(z=[e!=null?e:1,i!=null?i:1,(_=s!=null?s:t==null?void 0:t.width)!=null?_:0,(f=n!=null?n:t==null?void 0:t.height)!=null?f:0],O=[o,a],M=h,C=l),e=z[0],i=z[1];const st=z[2],W=z[3],ct=y(O[0],O[1]),K=y(O[0]+M,O[1]),V=y(O[0],O[1]+C),ut=y(O[0]+M,O[1]+C),ft=t.width||M,I=t.height||C,Be=e/ft,Le=i/I,ke=(e+st-.01)/ft,Ii=(i+W-.01)/I,or=v.getPosition(),ka=or.add(ut),za=or.x/this._context.width,Ua=or.y/this._context.height,Oa=ka.x/this._context.width,Na=ka.y/this._context.height;S[A++]=ct.x,S[A++]=ct.y,S[A++]=Be,S[A++]=Le,S[A++]=za,S[A++]=Ua,S[A++]=V.x,S[A++]=V.y,S[A++]=Be,S[A++]=Ii,S[A++]=za,S[A++]=Na,S[A++]=K.x,S[A++]=K.y,S[A++]=ke,S[A++]=Le,S[A++]=Oa,S[A++]=Ua,S[A++]=ut.x,S[A++]=ut.y,S[A++]=ke,S[A++]=Ii,S[A++]=Oa,S[A++]=Na;let Ha=this._addImageAsTexture(t);x.use(),this._layout.shader=b,this._layout.use(!0),b.trySetUniformFloat("u_time_ms",performance.now()),b.trySetUniformFloat("u_opacity",g),b.trySetUniformFloatVector("u_resolution",y(this._context.width,this._context.height)),b.trySetUniformFloatVector("u_graphic_resolution",y(ft,I)),b.trySetUniformFloatVector("u_size",y(st,W)),b.trySetUniformMatrix("u_matrix",this._context.ortho),b.trySetUniformMatrix("u_transform",v.to4x4()),x.isOverridingGraphic&&(m=x.images.u_graphic)!=null&&m.image&&(Ha=this._addImageAsTexture(x.images.u_graphic.image)),p.activeTexture(p.TEXTURE0+0),p.bindTexture(p.TEXTURE_2D,Ha),b.trySetUniformInt("u_graphic",0),x.isUsingScreenTexture&&(p.activeTexture(p.TEXTURE0+1),p.bindTexture(p.TEXTURE_2D,this._context.materialScreenTexture),b.trySetUniformInt("u_screen_texture",1)),this._quads.bind(),p.drawElements(p.TRIANGLES,6,this._quads.bufferGlType,0),Q.DrawnImagesCount++,Q.DrawCallCount++}_addImageAsTexture(t){const e=t.getAttribute(N.Filtering),i=e?Ye(e):void 0,s=Gt(t.getAttribute(N.WrappingX)),n=Gt(t.getAttribute(N.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);return t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&this._textures.push(a),a}hasPendingDraws(){return!1}flush(){}}const Sl=`#version 300 es
752
- precision mediump float;
753
-
754
- // UV coord
755
- in vec2 v_texcoord;
756
-
757
- // Textures in the current draw
758
- uniform sampler2D u_textures[%%count%%];
759
-
760
- uniform bool u_pixelart;
761
-
762
- in float v_texture_index;
763
-
764
- in float v_opacity;
765
-
766
- in vec4 v_tint;
767
-
768
- // texture resolution
769
- in vec2 v_res;
770
-
771
- in vec2 v_size;
772
-
773
- in vec2 v_uv_min;
774
- in vec2 v_uv_max;
775
-
776
- out vec4 fragColor;
777
-
778
- // Inigo Quilez pixel art filter https://jorenjoestar.github.io/post/pixel_art_filtering/
779
- vec2 uv_iq(in vec2 uv, in vec2 texture_size) {
780
- vec2 pixel = uv * texture_size;
781
-
782
- vec2 seam=floor(pixel+.5);
783
- vec2 dudv=fwidth(pixel);
784
- pixel=seam+clamp((pixel-seam)/dudv,-.5,.5);
785
-
786
- return pixel/texture_size;
787
- }
788
-
789
- float lerp(float from, float to, float rel){
790
- return ((1. - rel) * from) + (rel * to);
791
- }
792
-
793
- float invLerp(float from, float to, float value){
794
- return (value - from) / (to - from);
795
- }
796
-
797
- float remap(float origFrom, float origTo, float targetFrom, float targetTo, float value){
798
- float rel = invLerp(origFrom, origTo, value);
799
- return lerp(targetFrom, targetTo, rel);
800
- }
801
-
802
- void main(){
803
- // In order to support the most efficient sprite batching, we have multiple
804
- // textures loaded into the gpu (usually 8) this picker logic skips over textures
805
- // that do not apply to a particular sprite.
806
-
807
- vec4 color=vec4(1.,0,0,1.);
808
- vec2 remapped_uv = v_texcoord;
809
- remapped_uv.x = remap(0.,1., v_uv_min.x, v_uv_max.x, v_texcoord.x);
810
- remapped_uv.y = remap(0.,1., v_uv_min.y, v_uv_max.y, v_texcoord.y);
811
- vec2 uv = u_pixelart ? uv_iq(remapped_uv, v_size) : remapped_uv;
812
-
813
- // GLSL is templated out to pick the right texture and set the vec4 color
814
- %%texture_picker%%
815
-
816
- color.rgb = color.rgb * v_opacity;
817
- color.a = color.a * v_opacity;
818
- fragColor = color * v_tint;
819
- }`,Tl=`#version 300 es
820
- layout(location=0) in vec2 pos;
821
- layout(location=1) in vec2 a_texcoord;
822
- out vec2 v_texcoord;
823
-
824
- layout(location=2) in vec2 a_offset;
825
- layout(location=3) in vec2 a_mat_column1;
826
- layout(location=4) in vec2 a_mat_column2;
827
- layout(location=5) in vec2 a_mat_column3;
828
-
829
- layout(location=6) in float a_opacity;
830
- out float v_opacity;
831
-
832
- // Texture resolution (could be bigger than a_size)
833
- layout(location=7) in vec2 a_res;
834
- out vec2 v_res;
835
-
836
- // Final size of graphic
837
- layout(location=8) in vec2 a_size;
838
- out vec2 v_size;
839
-
840
- layout(location=9) in lowp float a_texture_index;
841
- out lowp float v_texture_index;
842
-
843
- layout(location=10) in vec2 a_uv_min;
844
- out vec2 v_uv_min;
845
-
846
- layout(location=11) in vec2 a_uv_max;
847
- out vec2 v_uv_max;
848
-
849
- layout(location=12) in vec4 a_tint;
850
- out vec4 v_tint;
851
-
852
- uniform mat4 u_matrix;
853
-
854
- void main(){
855
- mat4 world_mat = mat4(
856
- a_mat_column1.x, a_mat_column1.y, 0., 0.,
857
- a_mat_column2.x, a_mat_column2.y, 0., 0.,
858
- 0. , 0. , 1., 0.,
859
- a_mat_column3.x, a_mat_column3.y, 0., 1.
860
- );
861
-
862
- vec2 newPos = vec2(pos.x * a_res.x, pos.y * a_res.y);
863
- gl_Position = u_matrix * world_mat * vec4(newPos + a_offset, 0., 1.);
864
-
865
- v_opacity = a_opacity;
866
- v_texcoord = a_texcoord;
867
- v_uv_min = a_uv_min;
868
- v_uv_max = a_uv_max;
869
- v_res = a_res;
870
- v_size = a_size;
871
- v_texture_index = a_texture_index;
872
- v_tint = a_tint;
873
- }`;class Al{constructor(t){this.type="ex.image-v2",this.priority=0,this._maxImages=2e4,this._maxTextures=0,this._components=22,this._imageCount=0,this._textures=[],this._textureIndex=0,this._textureToIndex=new Map,this._images=new Set,this._vertexIndex=0,this._imageToWidth=new Map,this._imageToHeight=new Map,this._view=[0,0,0,0],this._dest=[0,0],this._defaultTint=T.White,this.pixelArtSampler=t.pixelArtSampler,this.uvPadding=t.uvPadding}initialize(t,e){this._gl=t,this._context=e;const i=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),s=Pn(t,i);this._maxTextures=Math.min(i,s);const n=this._transformFragmentSource(Sl,this._maxTextures);this._shader=new Ut({graphicsContext:e,fragmentSource:n,vertexSource:Tl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map((d,_)=>_)),this._vao=t.createVertexArray(),t.bindVertexArray(this._vao),this._quadMesh=new Float32Array([0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1]),this._meshBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._meshBuffer),t.bufferData(t.ARRAY_BUFFER,this._quadMesh,t.STATIC_DRAW),t.vertexAttribPointer(0,2,t.FLOAT,!1,16,0),t.enableVertexAttribArray(0),t.vertexAttribPointer(1,2,t.FLOAT,!1,16,8),t.enableVertexAttribArray(1),t.bindBuffer(t.ARRAY_BUFFER,null);const o=this._components;this._transformData=new Vt({gl:t,size:o*this._maxImages,type:"dynamic"}),this._transformData.bind();let a=0,h=2;const l=4,c=o*4;t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(2),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(3),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(4),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(5),a+=2*l,t.vertexAttribPointer(h++,1,t.FLOAT,!1,c,a),t.enableVertexAttribArray(6),a+=1*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(7),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(8),a+=2*l,t.vertexAttribPointer(h++,1,t.FLOAT,!1,c,a),t.enableVertexAttribArray(9),a+=1*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(10),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(11),a+=2*l,t.vertexAttribPointer(h++,4,t.FLOAT,!1,c,a),t.enableVertexAttribArray(12),a+=4*l,t.vertexAttribDivisor(2,1),t.vertexAttribDivisor(3,1),t.vertexAttribDivisor(4,1),t.vertexAttribDivisor(5,1),t.vertexAttribDivisor(6,1),t.vertexAttribDivisor(7,1),t.vertexAttribDivisor(8,1),t.vertexAttribDivisor(9,1),t.vertexAttribDivisor(10,1),t.vertexAttribDivisor(11,1),t.vertexAttribDivisor(12,1),t.bindVertexArray(null)}_bindData(t){const e=this._components;this._transformData.bind(),this._transformData.upload(e*this._imageCount),t.bindVertexArray(this._vao)}dispose(){this._transformData.dispose(),this._shader.dispose(),this._textures.length=0,this._context=null,this._gl=null}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let n=0;n<e;n++)n===0?s+=`if (v_texture_index <= ${n}.5) {
874
- `:s+=` else if (v_texture_index <= ${n}.5) {
875
- `,s+=` color = texture(u_textures[${n}], uv);
876
- `,s+=` }
877
- `;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(N.Filtering),i=e?Ye(e):void 0,s=Gt(t.getAttribute(N.WrappingX)),n=Gt(t.getAttribute(N.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&(this._textures.push(a),this._textureToIndex.set(a,this._textureIndex++),this._images.add(t))}_bindTextures(t){const e=Math.min(this._textureIndex,this._maxTextures);for(let i=0;i<e;i++)t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,this._textures[i]||this._textures[0])}_getTextureIdForImage(t){var e;if(t){const i=this._context.textureLoader.get(t);return(e=this._textureToIndex.get(i))!=null?e:-1}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}draw(t,e,i,s,n,o,a,h,l){var c,d,_,f;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);const m=this._getImageWidth(t),p=this._getImageHeight(t);let x=m||s||0,v=p||n||0;this._view[0]=0,this._view[1]=0,this._view[2]=(c=s!=null?s:m)!=null?c:0,this._view[3]=(d=n!=null?n:p)!=null?d:0,this._dest[0]=e!=null?e:1,this._dest[1]=i!=null?i:1,o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(this._view[0]=e!=null?e:1,this._view[1]=i!=null?i:1,this._view[2]=(_=s!=null?s:m)!=null?_:0,this._view[3]=(f=n!=null?n:p)!=null?f:0,this._dest[0]=o,this._dest[1]=a,x=h,v=l),e=this._view[0],i=this._view[1];const g=this._view[2],b=this._view[3],S=this._context.getTransform(),A=this._context.opacity;this._context.snapToPixel&&(this._dest[0]=~~(this._dest[0]+B),this._dest[1]=~~(this._dest[1]+B));const C=this._context.tint||this._defaultTint,z=this._getTextureIdForImage(t),O=m||x,st=p||v,W=(e+this.uvPadding)/O,ct=(i+this.uvPadding)/st,K=(e+g-this.uvPadding)/O,V=(i+b-this.uvPadding)/st,ut=m,ft=p,I=this._transformData.bufferData;I[this._vertexIndex++]=this._dest[0],I[this._vertexIndex++]=this._dest[1],I[this._vertexIndex++]=S.data[0],I[this._vertexIndex++]=S.data[1],I[this._vertexIndex++]=S.data[2],I[this._vertexIndex++]=S.data[3],I[this._vertexIndex++]=S.data[4],I[this._vertexIndex++]=S.data[5],I[this._vertexIndex++]=A,I[this._vertexIndex++]=x,I[this._vertexIndex++]=v,I[this._vertexIndex++]=ut,I[this._vertexIndex++]=ft,I[this._vertexIndex++]=z,I[this._vertexIndex++]=W,I[this._vertexIndex++]=ct,I[this._vertexIndex++]=K,I[this._vertexIndex++]=V,I[this._vertexIndex++]=C.r/255,I[this._vertexIndex++]=C.g/255,I[this._vertexIndex++]=C.b/255,I[this._vertexIndex++]=C.a}hasPendingDraws(){return this._imageCount!==0}flush(){if(this._imageCount===0)return;const t=this._gl;this._shader.use(),this._bindData(t),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_pixelart",this.pixelArtSampler),this._bindTextures(t),t.drawArraysInstanced(t.TRIANGLES,0,6,this._imageCount),Q.DrawnImagesCount+=this._imageCount,Q.DrawCallCount++,t.bindVertexArray(null),this._imageCount=0,this._vertexIndex=0,this._textures.length=0,this._textureIndex=0,this._textureToIndex.clear(),this._images.clear(),this._imageToWidth.clear(),this._imageToHeight.clear()}}const B=1e-4;class Pl{constructor(t){this._webglCtx=t,this._debugText=new wn}drawRect(t,e,i,s,n={color:T.Black}){this.drawLine(y(t,e),y(t+i,e),{...n}),this.drawLine(y(t+i,e),y(t+i,e+s),{...n}),this.drawLine(y(t+i,e+s),y(t,e+s),{...n}),this.drawLine(y(t,e+s),y(t,e),{...n})}drawLine(t,e,i){var s;this._webglCtx.save(),this._webglCtx.z=i!=null&&i.dashed?It.config.settings.z.dashed:It.config.settings.z.solid,this._webglCtx.draw("ex.debug-line",t,e,(s=i==null?void 0:i.color)!=null?s:T.Black,i==null?void 0:i.lineWidth,i==null?void 0:i.dashed),this._webglCtx.restore()}drawPoint(t,e={color:T.Black,size:5}){this._webglCtx.save(),this._webglCtx.z=It.config.settings.z.point,this._webglCtx.draw("ex.debug-point",t,e.color,e.size),this._webglCtx.restore()}drawCircle(t,e,i,s,n){this._webglCtx.save(),this._webglCtx.z=It.config.settings.z.solid,this._webglCtx.draw("ex.debug-circle",t,e,i,s,n),this._webglCtx.restore()}drawText(t,e){this._webglCtx.save(),this._webglCtx.z=It.config.settings.z.text,this._debugText.write(this._webglCtx,t,e),this._webglCtx.restore()}}class Kt{constructor(t){this._logger=F.getInstance(),this._renderers=new Map,this._lazyRenderersFactory=new Map,this.imageRenderer=Ue.isEnabled("use-legacy-image-renderer")?"ex.image":"ex.image-v2",this._isDrawLifecycle=!1,this.useDrawSorting=!0,this._drawCallPool=new Hi(()=>new Cl,void 0,4e3),this._drawCallIndex=0,this._drawCalls=new Array(4e3).fill(null),this._postProcessTargets=[],this._postprocessors=[],this._transform=new qh,this._state=new Wr,this.snapToPixel=!1,this.smoothing=!1,this.pixelArtSampler=!1,this.uvPadding=.01,this.backgroundColor=T.ExcaliburBlue,this.multiSampleAntialiasing=!0,this.transparency=!0,this._isContextLost=!1,this._disposed=!1,this._imageToWidth=new Map,this._imageToHeight=new Map,this._totalPostProcessorTime=0;const{canvasElement:e,context:i,enableTransparency:s,antialiasing:n,uvPadding:o,multiSampleAntialiasing:a,pixelArtSampler:h,powerPreference:l,snapToPixel:c,backgroundColor:d,useDrawSorting:_,garbageCollector:f,handleContextLost:m,handleContextRestored:p}=t;if(this.__gl=i!=null?i:e.getContext("webgl2",{antialias:n!=null?n:this.smoothing,premultipliedAlpha:!1,alpha:s!=null?s:this.transparency,depth:!1,powerPreference:l!=null?l:"high-performance"}),!this.__gl)throw Error("Failed to retrieve webgl context from browser");m&&this.__gl.canvas.addEventListener("webglcontextlost",m,!1),p&&this.__gl.canvas.addEventListener("webglcontextrestored",p,!1),this.__gl.canvas.addEventListener("webglcontextlost",()=>{this._isContextLost=!0}),this.__gl.canvas.addEventListener("webglcontextrestored",()=>{this._isContextLost=!1}),this.textureLoader=new Ze(this.__gl,f),this.snapToPixel=c!=null?c:this.snapToPixel,this.smoothing=n!=null?n:this.smoothing,this.transparency=s!=null?s:this.transparency,this.pixelArtSampler=h!=null?h:this.pixelArtSampler,this.uvPadding=o!=null?o:this.uvPadding,this.multiSampleAntialiasing=typeof a=="boolean"?a:this.multiSampleAntialiasing,this.samples=typeof a=="object"?a.samples:void 0,this.backgroundColor=d!=null?d:this.backgroundColor,this.useDrawSorting=_!=null?_:this.useDrawSorting,this._drawCallPool.disableWarnings=!0,this._drawCallPool.preallocate(),this._init()}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}dispose(){if(!this._disposed){this._disposed=!0,this.textureLoader.dispose();for(const t of this._renderers.values())t.dispose();this._renderers.clear(),this._drawCallPool.dispose(),this._drawCalls.length=0,this.__gl=null}}_init(){const t=this.__gl;if(this._ortho=St.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.toFloatArray()),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),t.depthMask(!1),this.register(new pl({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.register(new oo),this.register(new wl),this.register(new bl),this.lazyRegister("ex.debug-circle",()=>new cl),this.lazyRegister("ex.debug-point",()=>new al),this.lazyRegister("ex.debug-line",()=>new nl),this.lazyRegister("ex.particle",()=>new eo),this.register(new Al({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.materialScreenTexture=t.createTexture(),!this.materialScreenTexture)throw new Error("Could not create screen texture!");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 _l(this),this._renderTarget=new qi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),this._postProcessTargets=[new qi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),new qi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height})],this._msaaTarget=new qi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height,antialias:this.multiSampleAntialiasing,samples:this.samples}),this.debug=new Pl(this)}register(t){this._renderers.set(t.type,t),t.initialize(this.__gl,this)}lazyRegister(t,e){this._lazyRenderersFactory.set(t,e)}get(t){let e=this._renderers.get(t);if(!e){const i=this._lazyRenderersFactory.get(t);i&&(this._logger.debug("lazy init renderer:",t),e=i(),this.register(e))}return e}_isCurrentRenderer(t){return!this._currentRenderer||this._currentRenderer===t}beginDrawLifecycle(){this._isDrawLifecycle=!0}endDrawLifecycle(){this._isDrawLifecycle=!1}draw(t,...e){if(e.length>9)throw new Error("Only 10 or less renderer arguments are supported!;");if(this._isDrawLifecycle||this._logger.warnOnce(`Attempting to draw outside the the drawing lifecycle (preDraw/postDraw) is not supported and is a source of bugs/errors.
878
- If you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPostDraw handler.`),this._isContextLost){this._logger.errorOnce(`Unable to draw ${t}, the webgl context is lost`);return}const i=this.get(t);if(i)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[0]=e[0],s.args[1]=e[1],s.args[2]=e[2],s.args[3]=e[3],s.args[4]=e[4],s.args[5]=e[5],s.args[6]=e[6],s.args[7]=e[7],s.args[8]=e[8],s.args[9]=e[9],this._drawCalls[this._drawCallIndex++]=s}else this._currentRenderer||(this._currentRenderer=i),this._isCurrentRenderer(i)||this._currentRenderer.flush(),i.draw(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9]),this._currentRenderer=i;else throw Error(`No renderer with name ${t} has been registered`)}resetTransform(){this._transform.reset()}updateViewport(t){const e=this.__gl;this._ortho=this._ortho=St.ortho(0,t.width,t.height,0,400,-400),this._renderTarget.setResolution(e.canvas.width,e.canvas.height),this._msaaTarget.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)}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}drawImage(t,e,i,s,n,o,a,h,l){if(!(s===0||n===0)){{if(h===0||l===0)return;if(this._getImageWidth(t)===0||this._getImageHeight(t)===0)return}if(!t){F.getInstance().warn("Cannot draw a null or undefined image"),console.trace&&console.trace();return}this._state.current.material?this.draw("ex.material",t,e,i,s,n,o,a,h,l):this.imageRenderer==="ex.image"?this.draw(this.imageRenderer,t,e,i,s,n,o,a,h,l):this.draw(this.imageRenderer,t,e,i,s,n,o,a,h,l)}}drawLine(t,e,i,s=1){this.draw("ex.rectangle",t,e,i,s)}drawRectangle(t,e,i,s,n,o){this.draw("ex.rectangle",t,e,i,s,n,o)}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+B):t,this.snapToPixel?~~(e+B):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)}removePostProcessor(t){const e=this._postprocessors.indexOf(t);e!==-1&&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.getUniformDefinitions();this._totalPostProcessorTime+=t,s.find(n=>n.name==="u_time_ms")&&i.setUniformFloat("u_time_ms",this._totalPostProcessorTime),s.find(n=>n.name==="u_elapsed_ms")&&i.setUniformFloat("u_elapsed_ms",t),s.find(n=>n.name==="u_resolution")&&i.setUniformFloatVector("u_resolution",y(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){return new ro({...t,graphicsContext:this})}createShader(t){const{name:e,vertexSource:i,fragmentSource:s,uniforms:n,images:o,startingTextureSlot:a}=t,h=new Ut({name:e,graphicsContext:this,vertexSource:i,fragmentSource:s,uniforms:n,images:o,startingTextureSlot:a});return h.compile(),h}clear(){const t=this.__gl;(this.multiSampleAntialiasing?this._msaaTarget:this._renderTarget).use(),t.clearColor(...this.backgroundColor.toFloatArray()),t.clear(t.COLOR_BUFFER_BIT)}flush(){var t;if(this._isContextLost){this._logger.errorOnce("Unable to flush the webgl context is lost");return}let e=this.multiSampleAntialiasing?this._msaaTarget:this._renderTarget;if(e.use(),this.useDrawSorting){for(let o=this._drawCallIndex;o<this._drawCalls.length;o++)this._drawCalls[o]=null;const i=new Map;for(const[o]of this._renderers){let a=0;for(a=0;a<this._drawCallIndex&&this._drawCalls[a].renderer!==o;a++);i.set(o,a)}this._drawCalls.sort((o,a)=>{if(o===null||a===null)return 0;const h=o.z-a.z,l=i.get(o.renderer)-i.get(a.renderer),c=o.priority-a.priority;return h===0?c===0?l:c:h});const s=this._transform.current,n=this._state.current;if(this._drawCalls.length&&this._drawCallIndex){let o=this._drawCalls[0].renderer,a=this.get(o);for(let h=0;h<this._drawCallIndex;h++)this._transform.current=this._drawCalls[h].transform,this._state.current=this._drawCalls[h].state,this._drawCalls[h].renderer!==o&&(a.flush(),o=this._drawCalls[h].renderer,a=this.get(o),Q.RendererSwaps++),a instanceof oo&&((t=this.material)!=null&&t.isUsingScreenTexture)&&(e.copyToTexture(this.materialScreenTexture),e.use()),a.draw(...this._drawCalls[h].args);a.hasPendingDraws()&&a.flush()}this._transform.current=s,this._state.current=n,this._drawCallPool.done(),this._drawCallIndex=0,this._imageToHeight.clear(),this._imageToWidth.clear()}else for(const i of this._renderers.values())i.hasPendingDraws()&&i.flush();e.disable(),this._postprocessors.length>0&&e.toRenderSource().use();for(let i=0;i<this._postprocessors.length;i++)e=this._postProcessTargets[i%2],this._postProcessTargets[i%2].use(),this._screenRenderer.renderWithPostProcessor(this._postprocessors[i]),this._postProcessTargets[i%2].toRenderSource().use();e.blitToScreen()}}function vi(r){let t=2166136261;for(let e=0;e<r.length;++e)t^=r.charCodeAt(e),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function ao(...r){let t=0;for(const e of r)t=(t<<5)+t^e;return t|0}class ei{constructor(t,e,i,s){this.font=t,this.text=e,this.color=i,this.maxWidth=s,this._textFragments=[],this.disposed=!1,this._maxAscent=0,this._totalHeight=0,this._dirty=!0,this.canvas=document.createElement("canvas");const n=this.canvas.getContext("2d");if(!n)throw new Error("Unable to create FontTextInstance, internal canvas failed to create");this.ctx=n,this.canvas.dataset.originalSrc=`text(${e}) font(${t.fontString}`,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;e!=null?i=this._getLinesFromText(t,e):i=t.split(`
879
- `),this._applyFont(this.ctx);let s=0,n=0,o=0;const a=this.font.padding/this.font.quality;for(let c=0;c<i.length;c++){const d=this.ctx.measureText(i[c]),_=d.width+a*2;s=Math.max(s,_),n=Math.max(n,d.actualBoundingBoxAscent),o=Math.max(o,d.actualBoundingBoxDescent)}const l=(Math.abs(n)+Math.abs(o))*i.length+a*2;return this._maxAscent=n,this._totalHeight=l,D.fromDimension(s,this._totalHeight,y(this._xAnchorFromAlignment(),this._yAnchorFromBaseline()),w.Zero)}_setDimension(t,e){let i=1;this.font.lineHeight&&(i=this.font.lineHeight/this.font.size),e.canvas.width=(t.width+this.font.padding*2)*this.font.quality,e.canvas.height=(t.height+this.font.padding*2)*this.font.quality*i}static getHashCode(t,e,i){var s;return ao(vi(e),t.hashCode,(s=i==null?void 0:i.hashCode)!=null?s:0)}getHashCode(t=!0){return ei.getHashCode(this.font,this.text,t?this.color:void 0)}_xAnchorFromAlignment(){let t;const e=this.font.direction==="ltr";switch(this.font.textAlign){case"left":case"start":t=e?0:1;break;case"center":t=.5;break;case"right":case"end":t=e?1:0;break;default:t=0}return t}_xFromAlignment(){let t;const e=this.font.direction==="ltr";switch(this.font.textAlign){case"left":case"start":t=e?0:this.canvas.width;break;case"center":t=this.canvas.width/2;break;case"right":case"end":t=e?this.canvas.width:0;break;default:t=0}return t/this.font.quality}_yAnchorFromBaseline(){let t;switch(this.font.baseAlign){case"top":case"hanging":t=0;break;case"middle":t=.5;break;case"bottom":case"ideographic":t=1;break;case"alphabetic":default:t=this._maxAscent/this._totalHeight;break}return t}_applyRasterProperties(t){var e,i,s;t.imageSmoothingEnabled=this.font.smoothing,t.lineWidth=this.font.lineWidth,t.setLineDash((e=this.font.lineDash)!=null?e:t.getLineDash()),t.strokeStyle=(s=(i=this.font.strokeColor)==null?void 0:i.toString())!=null?s:"",t.fillStyle=this.color.toString()}_applyFont(t){t.resetTransform(),t.scale(this.font.quality,this.font.quality),t.translate(this.font.padding,this.font.padding),t.textAlign=this.font.textAlign,t.textBaseline=this.font.baseAlign,t.font=this.font.fontString,t.direction=this.font.direction,this.font.shadow&&(this.font.shadow.color&&(t.shadowColor=this.font.shadow.color.toString()),this.font.shadow.blur&&(t.shadowBlur=this.font.shadow.blur),this.font.shadow.offset&&(t.shadowOffsetX=this.font.shadow.offset.x,t.shadowOffsetY=this.font.shadow.offset.y))}_drawText(t,e,i){this._applyRasterProperties(t),this._applyFont(t);const s=this._xFromAlignment(),n=this._maxAscent;for(let o=0;o<e.length;o++){const a=e[o];this.color&&t.fillText(a,s,n+o*i),this.font.strokeColor&&t.strokeText(a,s,n+o*i)}}_splitTextBitmap(t){const e=[];let i=0,s=0;const n=Math.min(4096,t.canvas.width),o=Math.min(4096,t.canvas.height);for(;i<t.canvas.width;){for(;s<t.canvas.height;){const a=document.createElement("canvas");a.dataset.originalSrc=`fragment(${i},${s}): text(${this.text}) font(${this.font.fontString}`,a.width=n,a.height=o;const h=a.getContext("2d");if(!h)throw new Error("Unable to split internal FontTextInstance bitmap, failed to create internal canvas");h.drawImage(t.canvas,i,s,n,o,0,0,n,o),e.push({x:i,y:s,canvas:a}),s+=o}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 d=this._getLinesFromText(this.text,s),_=this.font.lineHeight?this.font.lineHeight:(this.dimensions.height-this._maxAscent)/d.length;if(this._drawText(this.ctx,d,_),t instanceof Kt)for(const f of this._textFragments)t.textureLoader.delete(f.canvas);if(this._textFragments=this._splitTextBitmap(this.ctx),t instanceof Kt)for(const f of this._textFragments)t.textureLoader.load(f.canvas,{filtering:this.font.filtering},!0);this._lastHashCode=n,this._dirty=!1}const o=this.font.padding/this.font.quality,a=this.canvas.width/this.font.quality-o,h=this._totalHeight,l=this._xAnchorFromAlignment()*a+o,c=this._yAnchorFromBaseline()*h+o;for(const d of this._textFragments)t.drawImage(d.canvas,0,0,d.canvas.width,d.canvas.height,d.x/this.font.quality+e-l,d.y/this.font.quality+i-c,d.canvas.width/this.font.quality,d.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 Kt)for(const t of this._textFragments)this._ex.textureLoader.delete(t.canvas);this._textFragments.length=0}_getLinesFromText(t,e){var i;if(this._cachedText===t&&this._cachedRenderWidth===e&&((i=this._cachedLines)!=null&&i.length))return this._cachedLines;const s=t.split(`
880
- `);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class Ee extends ot{constructor(t={}){var e,i,s,n,o,a,h,l,c,d,_,f,m,p,x,v,g,b,S,A;super(t),this.filtering=vt.Blended,this.quality=2,this.padding=2,this.smoothing=!1,this.lineWidth=1,this.lineDash=[],this.color=T.Black,this.family="sans-serif",this.style=mn.Normal,this.bold=!1,this.unit=fn.Px,this.textAlign=gn.Left,this.baseAlign=pn.Top,this.direction=vn.LeftToRight,this.lineHeight=void 0,this.size=10,this._textBounds=new D,this.smoothing=(e=t==null?void 0:t.smoothing)!=null?e:this.smoothing,this.padding=(i=t==null?void 0:t.padding)!=null?i:this.padding,this.color=(s=t==null?void 0:t.color)!=null?s:this.color,this.strokeColor=(n=t==null?void 0:t.strokeColor)!=null?n:this.strokeColor,this.lineDash=(o=t==null?void 0:t.lineDash)!=null?o:this.lineDash,this.lineWidth=(a=t==null?void 0:t.lineWidth)!=null?a:this.lineWidth,this.filtering=(h=t==null?void 0:t.filtering)!=null?h:this.filtering,this.family=(l=t==null?void 0:t.family)!=null?l:this.family,this.style=(c=t==null?void 0:t.style)!=null?c:this.style,this.bold=(d=t==null?void 0:t.bold)!=null?d:this.bold,this.size=(_=t==null?void 0:t.size)!=null?_:this.size,this.unit=(f=t==null?void 0:t.unit)!=null?f:this.unit,this.textAlign=(m=t==null?void 0:t.textAlign)!=null?m:this.textAlign,this.baseAlign=(p=t==null?void 0:t.baseAlign)!=null?p:this.baseAlign,this.direction=(x=t==null?void 0:t.direction)!=null?x:this.direction,this.lineHeight=(v=t==null?void 0:t.lineHeight)!=null?v:this.lineHeight,this.quality=(g=t==null?void 0:t.quality)!=null?g:this.quality,t!=null&&t.shadow&&(this.shadow={},this.shadow.blur=(b=t.shadow.blur)!=null?b:this.shadow.blur,this.shadow.offset=(S=t.shadow.offset)!=null?S:this.shadow.offset,this.shadow.color=(A=t.shadow.color)!=null?A:this.shadow.color),this._textMeasurement=new ei(this,"",T.Black)}get hashCode(){var t,e,i,s,n,o,a,h,l,c,d,_,f,m;return ao(vi(this.fontString),+this.showDebug,vi(this.textAlign),vi(this.baseAlign),vi(this.direction),+((t=this.lineHeight)!=null?t:0),+((i=(e=this.shadow)==null?void 0:e.blur)!=null?i:0),+((o=(n=(s=this.shadow)==null?void 0:s.color)==null?void 0:n.hashCode)!=null?o:0),+((l=(h=(a=this.shadow)==null?void 0:a.offset)==null?void 0:h.x)!=null?l:0),+((_=(d=(c=this.shadow)==null?void 0:c.offset)==null?void 0:d.y)!=null?_:0),+this.padding,+this.smoothing,+this.lineWidth,+this.lineDash.reduce((p,x)=>p+x,0),+((m=(f=this.strokeColor)==null?void 0:f.hashCode)!=null?m:0),this.color.hashCode)}clone(){return new Ee({...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}:void 0})}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=(e=this.origin)!=null?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 Yi.measureText(t,this,e)}_postDraw(t){t.restore()}render(t,e,i,s,n,o){const a=Yi.getTextInstance(e,this,i);this._textBounds=a.dimensions,this._preDraw(t,s,n),a.render(t,s,n,o),this._postDraw(t)}}class wi extends ot{constructor(t){var e,i;super(t),this._text="",this._textWidth=0,this._textHeight=0,this.font=(e=t.font)!=null?e:new Ee,this.color=(i=t.color)!=null?i:this.color,this.text=t.text,this.maxWidth=t.maxWidth}clone(){var t,e;return new wi({text:this.text.slice(),color:(e=(t=this.color)==null?void 0:t.clone())!=null?e:T.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 this._textWidth===0&&this._calculateDimension(),this._textWidth*this.scale.x}get height(){return this._textHeight===0&&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=T.Black;this.font instanceof Ee&&(n=(s=this.color)!=null?s:this.font.color);const{width:o,height:a}=this.font.measureText(this._text,this.maxWidth);this._textWidth=o,this._textHeight=a,this.font.render(t,this._text,n,e,i,this.maxWidth),this.font.showDebug&&(t.debug.drawRect(e-o,i-a,o*2,a*2),this.maxWidth!=null&&t.debug.drawRect(e,i,this.maxWidth,this.height,{color:T.Yellow}))}}function En(r){return!!r.tick}class Z extends Rt{constructor(t){super(),this._logger=F.getInstance(),this._current="default",this._graphics={},this._options={},this.material=null,this.isVisible=!0,this.forceOnScreen=!1,this.opacity=1,this._offset=new ce(w.Zero,()=>this.recalculateBounds()),this._anchor=new ce(w.Half,()=>this.recalculateBounds()),this.flipHorizontal=!1,this.flipVertical=!1,this.copyGraphics=!1,t={visible:this.isVisible,graphics:{},...t};const{current:e,anchor:i,color:s,opacity:n,visible:o,graphics:a,offset:h,copyGraphics:l,onPreDraw:c,onPostDraw:d,onPreTransformDraw:_,onPostTransformDraw:f}=t;for(const[m,p]of Object.entries(a))p instanceof ot?this._graphics[m]=p:(this._graphics[m]=p.graphic,this._options[m]=p.options);this.offset=h!=null?h:this.offset,this.opacity=n!=null?n:this.opacity,this.anchor=i!=null?i:this.anchor,this.color=s!=null?s:this.color,this.copyGraphics=l!=null?l:this.copyGraphics,this.onPreDraw=c!=null?c:this.onPreDraw,this.onPostDraw=d!=null?d:this.onPostDraw,this.onPreDraw=_!=null?_:this.onPreTransformDraw,this.onPostTransformDraw=f!=null?f:this.onPostTransformDraw,this.isVisible=!!o,this._current=e!=null?e:this._current,e&&this._graphics[e]&&this.use(e)}get visible(){return this.isVisible}set visible(t){this.isVisible=t}get offset(){return this._offset}set offset(t){this._offset=new ce(t,()=>this.recalculateBounds()),this.recalculateBounds()}get anchor(){return this._anchor}set anchor(t){this._anchor=new ce(t,()=>this.recalculateBounds()),this.recalculateBounds()}get color(){return this._color}set color(t){if(t){this._color=t.clone();const e=this.current;(e instanceof je||e instanceof wi)&&(e.color=this._color)}}getGraphic(t){return this._graphics[t]}getOptions(t){return this._options[t]}getNames(){return Object.keys(this._graphics)}get current(){return this._graphics[this._current]}get currentOptions(){return this._options[this._current]}get graphics(){return this._graphics}get options(){return this._options}add(t,e,i){let s="default",n=null,o;if(typeof t=="string"&&e instanceof ot&&(s=t,n=e,o=i),t instanceof ot&&!(e instanceof ot)&&(n=t,o=e),!n)throw new Error("Need to provide a graphic or valid graphic string");return this._graphics[s]=this.copyGraphics?n.clone():n,this._options[s]=this.copyGraphics?{...o}:o,s==="default"&&this.use("default"),n}remove(t){delete this._graphics[t],delete this._options[t],this._current===t&&(this._current="default",this.recalculateBounds())}use(t,e){var i;if(t instanceof ot){let s=t;this.copyGraphics&&(s=t.clone()),this._current="default",this._graphics[this._current]=s,this._options[this._current]=e}else this._current=t,this._options[this._current]=e,this._current in this._graphics||this._logger.warn(`Graphic ${this._current} is not registered with the graphics component owned by ${(i=this.owner)==null?void 0:i.name}. Nothing will be drawn.`);return this.recalculateBounds(),this.current}hide(){this._current="ex.none"}set localBounds(t){this._localBounds=t}recalculateBounds(){let t=new D;const e=this._graphics[this._current],i=this._options[this._current];if(!e){this._localBounds=t;return}let s=this.anchor,n=this.offset;i!=null&&i.anchor&&(s=i.anchor),i!=null&&i.offset&&(n=i.offset);const o=e.localBounds,a=-o.width*s.x+n.x,h=-o.height*s.y+n.y;e instanceof $e&&!e.useAnchor?t=e==null?void 0:e.localBounds.combine(t):t=e==null?void 0:e.localBounds.translate(y(a,h)).combine(t),this._localBounds=t}get localBounds(){return(!this._localBounds||this._localBounds.hasZeroDimensions())&&this.recalculateBounds(),this._localBounds}get bounds(){let t=this.localBounds;if(this.owner){const e=this.owner.get(E);e&&(t=t.transform(e.get().matrix))}return t}update(t,e=0){const i=this.current;i&&En(i)&&i.tick(t,e)}clone(){const t=new Z;return t._graphics={...this._graphics},t._options={...this._options},t.offset=this.offset.clone(),this.color&&(t.color=this.color.clone()),t.opacity=this.opacity,t.anchor=this.anchor.clone(),t.copyGraphics=this.copyGraphics,t.onPreDraw=this.onPreDraw,t.onPostDraw=this.onPostDraw,t.isVisible=this.isVisible,t}serialize(){var t;const i={type:this.constructor.name,current:this._current,graphicRefs:[],options:{},isVisible:this.isVisible,opacity:this.opacity,offset:{x:this._offset.x,y:this._offset.y},anchor:{x:this._anchor.x,y:this._anchor.y},flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,copyGraphics:this.copyGraphics,forceOnScreen:this.forceOnScreen,tint:void 0};i.graphicRefs=Object.keys(this._graphics);for(const[s,n]of Object.entries(this._options))n?i.options[s]={offset:n.offset?{x:n.offset.x,y:n.offset.y}:void 0,anchor:n.anchor?{x:n.anchor.x,y:n.anchor.y}:void 0}:i.options[s]=void 0;return this._color&&(i.color={r:this._color.r,g:this._color.g,b:this._color.b,a:this._color.a}),(t=this.current)!=null&&t.tint&&(i.tint={r:this.current.tint.r,g:this.current.tint.g,b:this.current.tint.b,a:this.current.tint.a}),i}deserialize(t){var e,i,s,n,o,a,h;this._current=(e=t.current)!=null?e:"default",this.isVisible=(i=t.isVisible)!=null?i:!0,this.opacity=(s=t.opacity)!=null?s:1,this.flipHorizontal=(n=t.flipHorizontal)!=null?n:!1,this.flipVertical=(o=t.flipVertical)!=null?o:!1,this.copyGraphics=(a=t.copyGraphics)!=null?a:!1,this.forceOnScreen=(h=t.forceOnScreen)!=null?h:!1,this._offset={x:t.offset.x,y:t.offset.y},this._anchor={x:t.anchor.x,y:t.anchor.y},t.color&&(this._color=T.fromRGB(t.color.r,t.color.g,t.color.b,t.color.a)),this._options={};for(const[l,c]of Object.entries(t.options))c?this._options[l]={offset:c.offset?{x:c.offset.x,y:c.offset.y}:void 0,anchor:c.anchor?{x:c.anchor.x,y:c.anchor.y}:void 0}:this._options[l]=void 0}}class qt extends Rt{constructor(t){var e,i;super(),this.useColliderShape=!0,this.useGraphicsBounds=!0,this.useColliderShape=(e=t==null?void 0:t.useColliderShape)!=null?e:this.useColliderShape,this.useGraphicsBounds=(i=t==null?void 0:t.useGraphicsBounds)!=null?i:this.useGraphicsBounds,this.localBounds=t==null?void 0:t.localBounds}}function Ie(r){return!!r&&r.length===4}const bt=class{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 w(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}};bt.Linear=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,e*r/i+t)),bt.EaseInQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r+t)),bt.EaseOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,-e*r*(r-2)+t)),bt.EaseInOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r+t:(r--,-e/2*(r*(r-2)-1)+t))),bt.EaseInCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r*r+t)),bt.EaseOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,r--,e*(r*r*r+1)+t)),bt.EaseInOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r*r+t:(r-=2,e/2*(r*r*r+2)+t)));let Dt=bt;class ho{constructor(t){this._actions=[],this._currentAction=null,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)}getIncompleteActions(){return this._actions}getCurrentAction(){return this._currentAction}hasNext(){return this._actions.length>0}isComplete(){return this._actions.length===0}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){if(this._actions.length>0&&(this._currentAction!==this._actions[0]&&(this._currentAction=this._actions[0],this._entity.emit("actionstart",new sn(this._currentAction,this._entity))),this._currentAction.update(t),this._currentAction.isComplete(this._entity))){this._entity.emit("actioncomplete",new nn(this._currentAction,this._entity));const e=this._actions.shift();e&&this._completedActions.push(e)}}}let El=0;function G(){return El++}class lo{constructor(t,e,i){this.id=G(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new xi(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 co{constructor(t,e){this.id=G(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new xi(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(){}}function uo(r){return r.offset instanceof w&&typeof r.duration=="number"}class _o{constructor(t,e){this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._legacyEasing=Dt.Linear,this._easing=Mi,this._useLegacyEasing=!1;var i;if(this._offset=e.offset,this._easing=(i=e.easing)!=null?i:this._easing,Ie(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only MoveBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._end=this._start.add(this._offset),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=X(this._start.x,this._end.x,this._easing(e)),n=X(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=y(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class In{constructor(t,e,i,s){if(this.id=G(),this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(E),this._motion=t.get(H),this._speed=s,this._offset=new w(e,i),s<=0)throw F.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 w(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.magnitude,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(E);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=y(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function fo(r){return r.pos instanceof w&&typeof r.duration=="number"}class go{constructor(t,e){this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._easing=Mi,this._legacyEasing=Dt.Linear,this._useLegacyEasing=!1;var i;if(this._end=e.pos,this._easing=(i=e.easing)!=null?i:this._easing,Ie(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only moveTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=X(this._start.x,this._end.x,this._easing(e)),n=X(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=y(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class Rn{constructor(t,e,i,s){this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._end=new w(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new w(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=y(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0))}isComplete(t){const e=t.get(E);return this._stopped||new w(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=y(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function Il(r){return typeof r.angle=="number"&&typeof r.duration=="number"}class po{constructor(t,e){this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._endAngle=0,this._startAngle=0;var i;if(this._endAngle=e.angle,this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:et.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=Cs(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete(this.entity)&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class mo{constructor(t,e,i,s){this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._end=e,this._speed=i,this._rotationType=s||et.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const e=Math.abs(this._end-this._start),i=gt-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+gt)%gt>=Math.PI,this._rotationType){case et.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case et.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case et.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case et.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance;break}}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}}function Rl(r){return typeof r.angleRadiansOffset=="number"&&typeof r.duration=="number"}class vo{constructor(t,e){this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._offset=0,this._startAngle=0,this._endAngle=0;var i;if(this._offset=e.angleRadiansOffset,this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:et.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._endAngle=Ot(this._startAngle+this._offset),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=Cs(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete()&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class wo{constructor(t,e,i,s){this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._speed=i,this._offset=e,this._rotationType=s||et.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 e=Math.abs(this._end-this._start),i=gt-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+gt)%gt>=Math.PI,this._rotationType){case et.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case et.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case et.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case et.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance;break}}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}}function xo(r){return typeof r.scale=="object"&&typeof r.duration=="number"}class yo{constructor(t,e){if(this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._endScale=y(1,1),this._startScale=y(1,1),this._endScale=e.scale,this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=oi(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=w.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class bo{constructor(t,e,i,s,n){this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),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 e=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*e}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const e=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*e}this.isComplete()&&(this._tx.scale=y(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}}function Co(r){return typeof r.scaleOffset=="object"&&typeof r.duration=="number"}class So{constructor(t,e){if(this.entity=t,this.id=G(),this._started=!1,this._stopped=!1,this._endScale=y(1,1),this._scaleOffset=y(0,0),this._startScale=y(1,1),this._scaleOffset=e.scaleOffset,this._tx=t.get(E),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._endScale=this._startScale.add(this._scaleOffset),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=oi(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=w.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class To{constructor(t,e,i,s){this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._offset=new w(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 Ao{constructor(t){this.id=G(),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 Po{constructor(t,e,i,s,n){this.easingFcn=n,this.id=G(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new w(0,0),this._lerpEnd=new w(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._lerpDuration=s,this._lerpEnd=new w(e,i)}_initialize(){this._lerpStart=new w(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;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=y(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=y(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=w.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=y(0,0),this._stopped=!0}}class Eo{constructor(t,e,i,s,n){this.easingFcn=n,this.id=G(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new w(0,0),this._lerpEnd=new w(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._lerpDuration=s,this._offset=new w(e,i)}_initialize(){this._lerpStart=new w(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;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=y(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=y(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=w.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=y(0,0),this._stopped=!0}}class Io{constructor(t,e,i,s=1){this.id=G(),this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(Z),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.isVisible&&this._elapsedTime>=this._timeVisible&&(this._graphics.isVisible=!1,this._elapsedTime=0),!this._graphics.isVisible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.isVisible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.isVisible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._elapsedTime=0,this._totalTime=0}}class Ro{constructor(t,e,i){this.id=G(),this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(Z),this._endOpacity=e,this._remainingTime=this._originalTime=i}update(t){this._graphics&&(this._started||(this._started=!0,this._remainingTime=this._originalTime,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._remainingTime>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._remainingTime),this._remainingTime-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),F.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||this._remainingTime<=0}stop(){this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._remainingTime=this._originalTime}}class Mo{constructor(t){this.id=G(),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 Fo{constructor(t){this.id=G(),this._stopped=!1,this._entity=t}update(t){this._entity.get(re).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class Mn{constructor(t,e,i){this.id=G(),this._started=!1,this._stopped=!1,this._tx=t.get(E),this._motion=t.get(H),this._followTx=e.get(E),this._followMotion=e.get(H),this._current=new w(this._tx.pos.x,this._tx.pos.y),this._end=new w(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=i!==void 0?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(e!==0&&(this._speed=e),this._current=y(this._tx.pos.x,this._tx.pos.y),this._end=y(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 i=this._dir.scale(this._speed);this._motion.vel=y(i.x,i.y)}else this._motion.vel=y(0,0);this.isComplete()&&(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0))}stop(){this._motion.vel=y(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1,this._stopped=!1}}class ts{constructor(t,e,i,s){this.id=G(),this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tolerance=1,this._tx=t.get(E),this._motion=t.get(H),this._meetTx=e.get(E),this._meetMotion=e.get(H),this._current=new w(this._tx.pos.x,this._tx.pos.y),this._end=new w(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,i!==void 0&&(this._speedWasSpecified=!0),s!==void 0&&(this._tolerance=s)}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));e!==0&&!this._speedWasSpecified&&(this._speed=e),this._current=y(this._tx.pos.x,this._tx.pos.y),this._end=y(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=y(i.x,i.y),this.isComplete()&&(this._tx.pos=y(this._end.x,this._end.y),this._motion.vel=y(0,0))}isComplete(){return this._stopped||this._distanceBetween<=this._tolerance}stop(){this._motion.vel=y(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._distanceBetween=1/0}}class Do{constructor(t,e,i=1e3){this.id=G(),this._stopped=!1,this._started=!1,this._total=0,this._currentDuration=0;var s;this._graphics=t.get(Z),this._duration=i,this._entity=t,this._material=(s=t.scene)==null?void 0:s.engine.graphicsContext.createMaterial({name:"flash-material",color:e,fragmentSource:`#version 300 es
881
-
882
- precision mediump float;
883
- uniform float u_blend;
884
- uniform sampler2D u_graphic;
885
- uniform vec4 u_color;
886
-
887
- in vec2 v_uv;
888
- out vec4 color;
889
-
890
- void main() {
891
- vec4 textureColor = texture(u_graphic, v_uv);
892
- color = mix(textureColor, u_color, u_blend * textureColor.a);
893
- color.rgb = color.rgb * color.a;
894
- }`}),this._total=i}update(t){var e;this._started||(this._started=!0,this._total=this._duration,this._currentDuration=this._duration,this._entity.graphics.material=this._material),this._graphics&&(this._currentDuration-=t,this._graphics&&((e=this._material)==null||e.update(i=>{i.trySetUniformFloat("u_blend",this._currentDuration/this._total)})),this.isComplete()&&(this._entity.graphics.material=null))}isComplete(){return this._stopped||this._currentDuration<=0}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class Bo{constructor(t,e){this.id=G(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(E),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=new ai({controlPoints:[y(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos.clone()),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0,this._currentMs=0}}class Lo{constructor(t,e){this.id=G(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(E),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=this._curve=new ai({controlPoints:[y(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos),this._curve.setControlPoint(1,this._curve.controlPoints[1].add(this._tx.globalPos)),this._curve.setControlPoint(2,this._curve.controlPoints[2].add(this._tx.globalPos)),this._curve.setControlPoint(3,this._curve.controlPoints[3].add(this._tx.globalPos)),this._started=!0),this._currentMs-=t;const e=L($t(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0}}class xi{constructor(t){this._entity=t,this._queue=new ho(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}curveBy(t){return this._queue.add(new Lo(this._entity,t)),this}curveTo(t){return this._queue.add(new Bo(this._entity,t)),this}easeTo(...t){var e,i;let s=0,n=0,o=0,a=Dt.Linear;return t[0]instanceof w?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new Po(this._entity,s,n,o,a)),this}easeBy(...t){var e,i;let s=0,n=0,o=0,a=Dt.Linear;return t[0]instanceof w?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new Eo(this._entity,s,n,o,a)),this}moveTo(t,e,i){let s=0,n=0,o=0;return t instanceof w?(s=t.x,n=t.y,o=+(e!=null?e:0),this._queue.add(new Rn(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new Rn(this._entity,s,n,o))):fo(t)&&this._queue.add(new go(this._entity,t)),this}moveBy(t,e,i){let s=0,n=0,o=0;return t instanceof w&&typeof e=="number"?(s=t.x,n=t.y,o=e,this._queue.add(new In(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new In(this._entity,s,n,o))):uo(t)&&this._queue.add(new _o(this._entity,t)),this}rotateTo(t,e,i){return typeof t=="number"&&typeof e=="number"?this._queue.add(new mo(this._entity,t,e,i)):typeof t=="object"&&this._queue.add(new po(this._entity,t)),this}rotateBy(t,e,i){return typeof t=="object"?this._queue.add(new vo(this._entity,t)):this._queue.add(new wo(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,o=1,a=0,h=0;return xo(t)?(this._queue.add(new yo(this._entity,t)),this):(t instanceof w&&e instanceof w&&(n=t.x,o=t.y,a=e.x,h=e.y),typeof t=="number"&&typeof e=="number"&&(n=t,o=e,a=i,h=s),this._queue.add(new bo(this._entity,n,o,a,h)),this)}scaleBy(t,e,i){if(Co(t))return this._queue.add(new So(this._entity,t)),this;let s=1,n=1;return t instanceof w&&(s=t.x,n=t.y,i=e),typeof t=="number"&&typeof e=="number"&&(s=t,n=e),this._queue.add(new To(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new Io(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new Ro(this._entity,t,e)),this}flash(t,e=1e3){return this._queue.add(new Do(this._entity,t,e)),this}delay(t){return this._queue.add(new Mo(t)),this}die(){return this._queue.add(new Fo(this._entity)),this}callMethod(t){return this._queue.add(new Ao(t)),this}repeat(t,e){return e?(this._queue.add(new lo(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new co(this._entity,t)),this}follow(t,e){return e===void 0?this._queue.add(new Mn(this._entity,t)):this._queue.add(new Mn(this._entity,t,e)),this}meet(t,e,i){return e===void 0&&i===void 0?this._queue.add(new ts(this._entity,t)):i===void 0?this._queue.add(new ts(this._entity,t,e)):this._queue.add(new ts(this._entity,t,e,i)),this}toPromise(){return new Promise(e=>{this._queue.add(new Ao(()=>{e()}))})}}class re extends Rt{constructor(){super(...arguments),this.dependencies=[E,H],this._ctx=null}onAdd(t){this._ctx=new xi(t)}onRemove(){this._ctx=null}_getCtx(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no context available");return this._ctx}getQueue(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no queue available");return this._ctx.getQueue()}runAction(t){if(!this._ctx)throw new Error("Actions component not attached to an entity, cannot run action");return this._ctx.runAction(t)}update(t){var e;return(e=this._ctx)==null?void 0:e.update(t)}clearActions(){var t;(t=this._ctx)==null||t.clearActions()}curveBy(t){return this._getCtx().curveBy.apply(this._ctx,[t])}curveTo(t){return this._getCtx().curveTo.apply(this._ctx,[t])}easeTo(...t){return this._getCtx().easeTo.apply(this._ctx,t)}easeBy(...t){return this._getCtx().easeBy.apply(this._ctx,t)}moveTo(t,e,i){return this._getCtx().moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._getCtx().moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._getCtx().rotateTo.apply(this._ctx,[t,e,i])}rotateBy(t,e,i){return this._getCtx().rotateBy.apply(this._ctx,[t,e,i])}scaleTo(t,e,i,s){return this._getCtx().scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._getCtx().scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._getCtx().blink(t,e,i)}fade(t,e){return this._getCtx().fade(t,e)}flash(t,e=1e3){return this._getCtx().flash(t,e)}delay(t){return this._getCtx().delay(t)}die(){return this._getCtx().die()}callMethod(t){return this._getCtx().callMethod(t)}repeat(t,e){return this._getCtx().repeat(t,e)}repeatForever(t){return this._getCtx().repeatForever(t)}follow(t,e){return this._getCtx().follow(t,e)}meet(t,e){return this._getCtx().meet(t,e)}toPromise(){return this._getCtx().toPromise()}}function Ml(r){return r instanceof Bt}const Fl={CollisionStart:"collisionstart",CollisionEnd:"collisionend",PreCollision:"precollision",PostCollision:"postcollision",Kill:"kill",PreKill:"prekill",PostKill:"postkill",PreDraw:"predraw",PostDraw:"postdraw",PreTransformDraw:"pretransformdraw",PostTransformDraw:"posttransformdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerEnter:"pointerenter",PointerLeave:"pointerleave",PointerMove:"pointermove",PointerCancel:"pointercancel",Wheel:"pointerwheel",PointerDrag:"pointerdragstart",PointerDragEnd:"pointerdragend",PointerDragEnter:"pointerdragenter",PointerDragLeave:"pointerdragleave",PointerDragMove:"pointerdragmove",EnterViewPort:"enterviewport",ExitViewPort:"exitviewport",ActionStart:"actionstart",ActionComplete:"actioncomplete"},ko=class lr extends Tt{constructor(t){super(),this.events=new Y,this._anchor=Ft(w.Half,W=>this._handleAnchorChange(W)),this._offset=Ft(w.Zero,W=>this._handleOffsetChange(W)),this.logger=F.getInstance(),this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=W=>{this._dragging&&(this.pos=W.worldPos)},this._pointerDragLeaveHandler=W=>{this._dragging&&(this.pos=W.worldPos)};const{name:e,x:i,y:s,pos:n,coordPlane:o,scale:a,width:h,height:l,radius:c,collider:d,vel:_,acc:f,rotation:m,angularVelocity:p,z:x,color:v,visible:g,opacity:b,anchor:S,offset:A,collisionType:M,collisionGroup:C,graphic:z,material:O,canPause:st}={...t};this.name=e!=null?e:this.name,this.anchor=S!=null?S:lr.defaults.anchor.clone(),this.offset=A!=null?A:w.Zero,this.transform=new E,this.addComponent(this.transform),this.pos=n!=null?n:y(i!=null?i:0,s!=null?s:0),this.rotation=m!=null?m:0,this.scale=a!=null?a:y(1,1),this.z=x!=null?x:0,this.transform.coordPlane=o!=null?o:ht.World,this.pointer=new qt,this.addComponent(this.pointer),this.graphics=new Z({anchor:this.anchor,offset:this.offset,opacity:b}),this.addComponent(this.graphics),this.motion=new H,this.addComponent(this.motion),this.vel=_!=null?_:w.Zero,this.acc=f!=null?f:w.Zero,this.angularVelocity=p!=null?p:0,this.actions=new re,this.addComponent(this.actions),this.body=new U,this.addComponent(this.body),this.body.collisionType=M!=null?M:R.Passive,C&&(this.body.group=C),this.paused=new Mt({canPause:st}),this.addComponent(this.paused),v&&(this.color=v),d?(this.collider=new j(d),this.addComponent(this.collider)):c?(this.collider=new j(rt.Circle(c)),this.addComponent(this.collider),v&&this.graphics.add(new Zi({color:v,radius:c}))):h>0&&l>0?(this.collider=new j(rt.Box(h,l,this.anchor)),this.addComponent(this.collider),v&&h&&l&&this.graphics.add(new mi({color:v,width:h,height:l}))):(this.collider=new j,this.addComponent(this.collider)),this.graphics.isVisible=g!=null?g:!0,z&&this.graphics.use(z),O&&(this.graphics.material=O)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}get oldGlobalPos(){return this.body.oldGlobalPos}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(E).scale}set scale(t){this.get(E).scale=t}get canPause(){return this.paused.canPause}set canPause(t){this.paused.canPause=t}get isPaused(){return this.paused.paused}get anchor(){return this._anchor}set anchor(t){this._anchor=Ft(t,e=>this._handleAnchorChange(e)),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get offset(){return this._offset}set offset(t){this._offset=Ft(t,e=>this._handleOffsetChange(e)),this._handleOffsetChange(t)}_handleOffsetChange(t){this.graphics&&(this.graphics.offset=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.graphics.color}set color(t){this.graphics.color=t}clone(){const t=new lr({color:this.color.clone(),anchor:this.anchor.clone(),offset:this.offset.clone()});t.clearComponents(),t.processComponentRemoval(),t.addComponent(t.transform=this.transform.clone(),!0),t.addComponent(t.pointer=this.pointer.clone(),!0),t.addComponent(t.graphics=this.graphics.clone(),!0),t.addComponent(t.motion=this.motion.clone(),!0),t.addComponent(t.actions=this.actions.clone(),!0),t.addComponent(t.body=this.body.clone(),!0),this.collider.get()&&t.addComponent(t.collider=this.collider.clone(),!0);const e=[this.transform,this.pointer,this.graphics,this.motion,this.actions,this.body,this.collider],i=this.getComponents();for(const s of i)e.includes(s)||t.addComponent(s.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 Bs(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){this.events.emit("postkill",new Ls(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),super.kill(),this._postkill(this.scene)):this.logger.warn(`Cannot kill actor named "${this.name}", it was never added to the Scene`)}unkill(){this.isActive=!0}isKilled(){return!this.isActive}get z(){return this.get(E).z}set z(t){this.get(E).z=t}get center(){const t=this.getGlobalPos();return new w(t.x+this.width/2-this.anchor.x*this.width,t.y+this.height/2-this.anchor.y*this.height)}get localCenter(){return new w(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(E).globalRotation}get globalRotation(){return this.get(E).globalRotation}getGlobalPos(){return this.get(E).globalPos}get globalPos(){return this.get(E).globalPos}getGlobalScale(){return this.get(E).globalScale}get globalScale(){return this.get(E).globalScale}get globalZ(){return this.get(E).globalZ}contains(t,e,i=!1){const s=y(t,e),n=this.get(j);n.update();const o=n.get();if(!o)return!1;const a=o.contains(s);return i?a||this.children.some(h=>h.contains(t,e,!0)):a}within(t,e){const i=this.get(j),s=t.get(j),n=i.get(),o=s.get();return n&&o?n.getClosestLineBetween(o).getLength()<=e:!1}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e),this._postupdate(t,e),this._remove(t)}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreCollisionResolve(t,e,i,s){}onPostCollisionResolve(t,e,i,s){}onCollisionStart(t,e,i,s){}onCollisionEnd(t,e,i,s){}_preupdate(t,e){this.events.emit("preupdate",new de(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new ue(t,e,this)),this.onPostUpdate(t,e)}};ko.defaults={anchor:w.Half};let Bt=ko;class j extends Rt{constructor(t){super(),this.events=new Y,this.$colliderAdded=new pt,this.$colliderRemoved=new pt,this._collidersToRemove=[],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._collidersToRemove.push(this._collider),this._collider=null)}processColliderRemoval(){for(const t of this._collidersToRemove)t.events.unpipe(this.events),this.$colliderRemoved.notifyAll(t),t.owner=null}clone(){return new j(this._collider.clone())}get bounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.bounds)!=null?e:new D}get localBounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.localBounds)!=null?e:new D}update(){var t;const e=(t=this.owner)==null?void 0:t.get(E);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 nt&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach(o=>{o.mtv=o.mtv.negate(),o.normal=o.normal.negate(),o.tangent=o.normal.perpendicular(),o.colliderA=this._collider,o.colliderB=t._collider}),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",e=>{const i=e;t.events.emit("precollision",new be(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof Bt&&t.onPreCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("postcollision",e=>{const i=e;t.events.emit("postcollision",new Ce(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof Bt&&t.onPostCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("collisionstart",e=>{const i=e;t.events.emit("collisionstart",new hi(i.self,i.other,i.side,i.contact)),t instanceof Bt&&t.onCollisionStart(i.self,i.other,i.side,i.contact)}),this.events.on("collisionend",e=>{const i=e;t.events.emit("collisionend",new li(i.self,i.other,i.side,i.lastContact)),t instanceof Bt&&t.onCollisionEnd(i.self,i.other,i.side,i.lastContact)})}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=w.Half,s=w.Zero){const n=rt.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=w.Zero){const i=rt.Polygon(t,e);return this.set(i)}useCircleCollider(t,e=w.Zero){const i=rt.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=rt.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new nt(t))}serialize(){const t=this.constructor.name,e=this._collider,i={type:t,colliderType:null,colliderData:null};if(e instanceof lt){i.colliderType="polygon";const s=e.points;i.colliderData={points:s.map(n=>({x:n.x,y:n.y})),offset:{x:e.offset.x,y:e.offset.y}}}else if(e instanceof dt)i.colliderType="circle",i.colliderData={radius:e.radius,offset:{x:e.offset.x,y:e.offset.y}};else if(e instanceof nt){i.colliderType="composite";const s=[];for(const n of e.getColliders()){const a=new j(n).serialize();s.push(a.colliderData)}i.colliderData={parts:s}}return i}deserialize(t){var e,i,s,n,o,a,h,l;if(t.colliderType==="polygon"){const c=t.colliderData,d=c.points.map(_=>new w(_.x,_.y));this.usePolygonCollider(d,w.Zero).offset=new w((i=(e=c.offset)==null?void 0:e.x)!=null?i:0,(n=(s=c.offset)==null?void 0:s.y)!=null?n:0)}else if(t.colliderType==="circle"){const c=t.colliderData;this.useCircleCollider(c.radius,w.Zero).offset=new w((a=(o=c.offset)==null?void 0:o.x)!=null?a:0,(l=(h=c.offset)==null?void 0:h.y)!=null?l:0)}else if(t.colliderType==="composite"){const c=t.colliderData,d=[];for(const _ of c.parts){const f=this._createColliderFromData(_);d.push(f)}this.useCompositeCollider(d)}}_createColliderFromData(t){var e,i,s,n,o,a,h,l,c,d,_,f,m,p,x,v;if(t.width!==void 0&&t.height!==void 0){const g=t;return rt.Box(g.width,g.height,new w((i=(e=g.anchor)==null?void 0:e.x)!=null?i:.5,(n=(s=g.anchor)==null?void 0:s.y)!=null?n:.5),new w((a=(o=g.offset)==null?void 0:o.x)!=null?a:0,(l=(h=g.offset)==null?void 0:h.y)!=null?l:0))}else if(t.radius!==void 0){const g=t;return rt.Circle(g.radius,new w((d=(c=g.offset)==null?void 0:c.x)!=null?d:0,(f=(_=g.offset)==null?void 0:_.y)!=null?f:0))}else if(t.points!==void 0){const g=t,b=g.points.map(S=>new w(S.x,S.y));return rt.Polygon(b,new w((p=(m=g.offset)==null?void 0:m.x)!=null?p:0,(v=(x=g.offset)==null?void 0:x.y)!=null?v:0))}else if(t.start!==void 0&&t.end!==void 0){const g=t;return rt.Edge(new w(g.start.x,g.start.y),new w(g.end.x,g.end.y))}else if(t.parts!==void 0){const g=t,b=[];for(const S of g.parts){const A=this._createColliderFromData(S);b.push(A)}return new nt(b)}return null}}var oe=(r=>(r.Rotation="rotation",r.X="x",r.Y="y",r))(oe||{});const Fn=class vs extends Rt{constructor(t){var e,i,s;super(),this.dependencies=[E,H],this.id=we("body",vs._ID++),this.events=new Y,this.island=null,this.oldTransform=new se,this.__oldTransformCaptured=!1,this.enableFixedUpdateInterpolate=!0,this.sleepTime=0,this.collisionType=R.PreventCollision,this.group=Yt.All,this.canSleep=this.collisionType===R.Active,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this._oldGlobalPos=w.Zero,this.oldVel=new w(0,0),this.oldAcc=w.Zero,this._impulseScratch=y(0,0),this._distanceFromCenterScratch=y(0,0),t?(this.collisionType=(e=t.type)!=null?e:this.collisionType,this.group=(i=t.group)!=null?i:this.group,this.useGravity=(s=t.useGravity)!=null?s:this.useGravity,this._bodyConfig={...ne().bodies,...t.config}):this._bodyConfig={...ne().bodies},this.updatePhysicsConfig(this._bodyConfig),this._mass=vs._DEFAULT_CONFIG.defaultMass}get matrix(){return this.transform.get().matrix}updatePhysicsConfig(t){this._bodyConfig={...ne().bodies,...t},this.canSleep=this._bodyConfig.canSleepByDefault,this.sleepMotion=this._bodyConfig.sleepEpsilon*5,this.wakeThreshold=this._bodyConfig.wakeThreshold}get canFallAsleep(){return this.canSleep&&this.collisionType===R.Active&&this.sleepMotion<this._bodyConfig.sleepEpsilon}get canWakeUp(){return this.collisionType===R.Active&&this.sleepMotion>this.wakeThreshold}static updateDefaultPhysicsConfig(t){vs._DEFAULT_CONFIG=t}get mass(){return this._mass}set mass(t){this._mass=t,this._cachedInertia=void 0,this._cachedInverseInertia=void 0}get inverseMass(){return this.collisionType===R.Fixed?0:1/this.mass}get sleeping(){return this.isSleeping}get isSleeping(){return this.canSleep&&this._sleeping}setSleeping(t){this.isSleeping=t}wake(){var t;this._sleeping&&this.collisionType===R.Active&&(this._sleeping=!1,(t=this.owner)==null||t.removeTag("ex.is_sleeping"),this.sleepMotion=this._bodyConfig.sleepEpsilon*2,this.sleepTime=0)}sleep(){var t;!this._sleeping&&this.canSleep&&(this._sleeping=!0,(t=this.owner)==null||t.addTag("ex.is_sleeping"),this.vel=w.Zero,this.acc=w.Zero,this.angularVelocity=0,this.sleepMotion=0)}set isSleeping(t){t?this.sleep():this.wake()}updateMotion(t){if(this.collisionType!==R.Active)return;const e=this.pos.sub(this.oldPos),i=dr(Ot(this.rotation),Ot(this.oldRotation)),s=e.magnitude,n=i,o=s*s+n*n,a=Math.pow(this._bodyConfig.sleepBias,t/1e3),h=this.sleepMotion;this.sleepMotion=a*h+(1-a)*o,this.sleepMotion=L(this.sleepMotion,0,10*this._bodyConfig.sleepEpsilon),this.canFallAsleep&&(this.sleepTime+=t)}get inertia(){if(this._cachedInertia)return this._cachedInertia;const t=this.owner.get(j);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===R.Fixed?0:1/this.inertia}get active(){var t;return!!((t=this.owner)!=null&&t.isActive)}get isActive(){var t;return!!((t=this.owner)!=null&&t.isActive)}get center(){return this.globalPos}onAdd(t){var e,i;this.transform=(e=this.owner)==null?void 0:e.get(E),this.motion=(i=this.owner)==null?void 0:i.get(H)}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 oldGlobalPos(){return this._oldGlobalPos}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!==R.Active)return;const i=e.scale(this.inverseMass,this._impulseScratch);if(this.limitDegreeOfFreedom.indexOf("x")>-1&&(i.x=0),this.limitDegreeOfFreedom.indexOf("y")>-1&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes("rotation")){const s=t.sub(this.globalPos,this._distanceFromCenterScratch);this.angularVelocity+=this.inverseInertia*s.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==R.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes("x")&&(e.x=0),this.limitDegreeOfFreedom.includes("y")&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===R.Active&&!this.limitDegreeOfFreedom.includes("rotation")){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.__oldTransformCaptured=!0;const t=this.transform.get();t.clone(this.oldTransform),this.oldTransform.parent=t.parent,this.oldVel.setTo(this.vel.x,this.vel.y),this.oldAcc.setTo(this.acc.x,this.acc.y),this.oldGlobalPos.setTo(this.globalPos.x,this.globalPos.y)}clone(){return super.clone()}serialize(){return{type:this.constructor.name,collisionType:R[this.collisionType],mass:this._mass,bounciness:this.bounciness,friction:this.friction,useGravity:this.useGravity,collisionGroup:this._serializeCollisionGroup(this.group),canSleep:this.canSleep,isSleeping:this._sleeping,limitDegreeOfFreedom:this.limitDegreeOfFreedom.map(e=>e.toString()),enableFixedUpdateInterpolate:this.enableFixedUpdateInterpolate}}deserialize(t){var e,i,s,n,o,a,h;this.collisionType=R[t.collisionType],this._mass=t.mass,this.bounciness=(e=t.bounciness)!=null?e:.2,this.friction=(i=t.friction)!=null?i:.99,this.useGravity=(s=t.useGravity)!=null?s:!0,t.collisionGroup&&(this.group=this._deserializeCollisionGroup(t.collisionGroup)),this.canSleep=(n=t.canSleep)!=null?n:!1,this._sleeping=(o=t.isSleeping)!=null?o:!1,this.limitDegreeOfFreedom=((a=t.limitDegreeOfFreedom)!=null?a:[]).map(l=>oe[l]),this.enableFixedUpdateInterpolate=(h=t.enableFixedUpdateInterpolate)!=null?h:!0}_serializeCollisionGroup(t){var e;return t===Yt.All?"All":(e=t.name)!=null?e:"Custom"}_deserializeCollisionGroup(t){return Yt.All}};Fn._ID=0,Fn._DEFAULT_CONFIG={...ne().bodies};let U=Fn;class Dn{constructor(t,e){this.object=t,this.id=-1,this.cells=[],this.hasZeroBounds=!1,this.gridSize=e,this.bounds=t.bounds,this.hasZeroBounds=this.bounds.hasZeroDimensions(),this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize)}hasChanged(){const t=this.object.bounds,e=Math.floor(t.left/this.gridSize),i=Math.floor(t.right/this.gridSize),s=Math.floor(t.bottom/this.gridSize),n=Math.floor(t.top/this.gridSize);return this.leftX!==e||this.rightX!==i||this.bottomY!==s||this.topY!==n}clear(){for(const t of this.cells){const e=t.proxies.indexOf(this);e>-1&&t.proxies.splice(e,1)}}updateBounds(){this.bounds=this.object.bounds}update(){this.bounds=this.object.bounds,this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize),this.hasZeroBounds=this.object.bounds.hasZeroDimensions()}}class te{constructor(){this.proxies=[]}configure(t,e){this.x=t,this.y=e,this.key=te.calculateHashKey(t,e)}static calculateHashKey(t,e){return`${t}+${e}`}}class Bn{constructor(t){this.bounds=new D,this._hashGridCellPool=new Qe(()=>new te,e=>(e.configure(0,0),e.proxies.length=0,e),1e3),this.gridSize=t.size,this.sparseHashGrid=new Map,this.objectToProxy=new Map,t.proxyFactory?this._buildProxy=e=>t.proxyFactory(e,this.gridSize):this._buildProxy=e=>new Dn(e,this.gridSize)}query(t){const e=new Set;if(t instanceof D){const i=t,s=Math.floor(i.left/this.gridSize),n=Math.floor(i.right/this.gridSize),o=Math.floor(i.bottom/this.gridSize),a=Math.floor(i.top/this.gridSize);for(let h=s;h<=n;h++)for(let l=a;l<=o;l++){const c=te.calculateHashKey(h,l),d=this.sparseHashGrid.get(c);if(d)for(let _=0;_<d.proxies.length;_++)d.proxies[_].updateBounds(),d.proxies[_].bounds.intersect(i)&&e.add(d.proxies[_].object)}}else{const i=t,s=te.calculateHashKey(Math.floor(i.x/this.gridSize),Math.floor(i.y/this.gridSize)),n=this.sparseHashGrid.get(s);if(n)for(let o=0;o<n.proxies.length;o++)n.proxies[o].updateBounds(),n.proxies[o].bounds.contains(i)&&e.add(n.proxies[o].object)}return Array.from(e)}get(t,e){const i=te.calculateHashKey(t,e);return this.sparseHashGrid.get(i)}_insert(t,e,i){const s=te.calculateHashKey(t,e);let n=this.sparseHashGrid.get(s);n||(n=this._hashGridCellPool.rent(),n.configure(t,e),this.sparseHashGrid.set(n.key,n)),n.proxies.push(i),i.cells.push(n),this.bounds.combine(i.bounds,this.bounds)}_remove(t,e,i){const s=te.calculateHashKey(t,e),n=this.sparseHashGrid.get(s);if(n){const o=n.proxies.indexOf(i);o>-1&&n.proxies.splice(o,1);const a=i.cells.indexOf(n);a>-1&&i.cells.splice(a,1),n.proxies.length===0&&(this._hashGridCellPool.return(n),this.sparseHashGrid.delete(s))}}track(t){const e=this._buildProxy(t);this.objectToProxy.set(t,e);for(let i=e.leftX;i<=e.rightX;i++)for(let s=e.topY;s<=e.bottomY;s++)this._insert(i,s,e)}untrack(t){const e=this.objectToProxy.get(t);e&&(e.clear(),this.objectToProxy.delete(t))}update(t){let e=0;for(const i of t){const s=this.objectToProxy.get(i);if(s&&s.hasChanged()){for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._remove(n,o,s);s.update();for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._insert(n,o,s);e++}}return e}debug(t,e){const i=T.White;for(const s of this.sparseHashGrid.values())t.debug.drawRect(s.x*this.gridSize,s.y*this.gridSize,this.gridSize,this.gridSize,{color:i,lineWidth:2})}}class zo extends Dn{constructor(t,e){var i,s,n;super(t,e),this.collider=t,this.id=-1,this.hasZeroBounds=!1,this.cells=[],this.gridSize=e;const o=t.bounds;this.hasZeroBounds=o.hasZeroDimensions(),this.leftX=Math.floor(o.left/this.gridSize),this.rightX=Math.floor(o.right/this.gridSize),this.bottomY=Math.floor(o.bottom/this.gridSize),this.topY=Math.floor(o.top/this.gridSize),this.owner=t.owner,this.body=(i=this.owner)==null?void 0:i.get(U),this.collisionType=(n=(s=this.body)==null?void 0:s.collisionType)!=null?n:R.PreventCollision}update(){var t,e,i;super.update(),this.body=(t=this.owner)==null?void 0:t.get(U),this.collisionType=(i=(e=this.body)==null?void 0:e.collisionType)!=null?i:R.PreventCollision,this.hasZeroBounds=this.collider.localBounds.hasZeroDimensions()}}class Ln{constructor(t){this._pairs=new Set,this._nonPairs=new Set,this._pairPool=new Hi(()=>new mt({id:we("collider",0)},{id:we("collider",0)}),e=>(e.colliderA=null,e.colliderB=null,e),200),this.gridSize=t.size,this.hashGrid=new Bn({size:this.gridSize,proxyFactory:(e,i)=>new zo(e,i)}),this._pairPool.disableWarnings=!0}getColliders(){return Array.from(this.hashGrid.objectToProxy.keys())}query(t){return this.hashGrid.query(t)}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:Yt.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1,d=t.dir.normalize(),_=d.y/d.x,f=d.x/d.y,m=Math.sqrt(1+_*_)*this.gridSize,p=Math.sqrt(1+f*f)*this.gridSize,x=t.pos.x/this.gridSize,v=t.pos.y/this.gridSize,g=y(1,1);let b=~~x,S=~~v,A=0,M=0;d.x<0?(g.x=-1,A=(x-b)*m):(g.x=1,A=(b+1-x)*m),d.y<0?(g.y=-1,M=(v-S)*p):(g.y=1,M=(S+1-v)*p);const C=new Set;let z=!1,O=9999;for(;!z&&O>0&&(O--,!!this.hashGrid.bounds.contains(y(b*this.gridSize,S*this.gridSize)));){const st=te.calculateHashKey(b,S),W=this.hashGrid.sparseHashGrid.get(st);if(W){const ct=[];for(let K=0;K<W.proxies.length;K++){const V=W.proxies[K];if(!C.has(V.collider.id.value)){if(C.add(V.collider.id.value),V.body){if(e!=null&&e.ignoreCollisionGroupAll&&V.body.group===Yt.All)continue;const ft=(l&V.body.group.category)!==0;if(V.body.group&&!ft)continue}const ut=V.collider.rayCast(t,a);ut&&ct.push(ut)}}ct.sort((K,V)=>K.distance-V.distance);for(let K=0;K<ct.length;K++){const V=ct[K];if(e!=null&&e.filter){if(e.filter(V)&&(o.push(V),!c)){z=!0;break}}else if(o.push(V),!c){z=!0;break}}}A<M?(b+=g.x,A+=m):(S+=g.y,M+=p)}return o.sort((st,W)=>st.distance-W.distance),!c&&o.length?[o[0]]:o}track(t){let e=[t];if(t instanceof nt){const i=t.getColliders();for(const s of i)s.owner=t.owner;e=i}for(const i of e)this.hashGrid.track(i)}untrack(t){let e=[t];t instanceof nt&&(e=t.getColliders());for(const i of e)this.hashGrid.untrack(i)}_canCollide(t,e){return!(t.collider.id===e.collider.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.hasZeroBounds||e.hasZeroBounds||t.body&&e.body&&!t.body.group.canCollide(e.body.group)||t.collisionType===R.Fixed&&e.collisionType===R.Fixed||t.collisionType===R.PreventCollision||e.collisionType===R.PreventCollision||!t.owner.isActive||!e.owner.isActive)}broadphase(t,e){const i=[];this._pairs.clear(),this._nonPairs.clear();let s=0;for(const n of this.hashGrid.objectToProxy.values())if(n.id=s++,!(!n.owner.isActive||n.collisionType===R.PreventCollision))for(let o=0;o<n.cells.length;o++){const a=n.cells[o];for(let h=0;h<a.proxies.length;h++){const l=a.proxies[h];if(l.id===n.id)continue;const c=mt.calculatePairHash(n.collider.id,l.collider.id);if(!this._nonPairs.has(c))if(!this._pairs.has(c)&&this._canCollide(n,l)&&n.object.bounds.overlaps(l.object.bounds)){const d=this._pairPool.get();d.colliderA=n.collider,d.colliderB=l.collider,d.id=c,this._pairs.add(c),i.push(d)}else this._nonPairs.add(c)}}return i}narrowphase(t,e){const i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();for(let o=0;o<n.length;o++){const a=n[o];i.push(a),e&&e.physics.contacts.set(a.id,a)}}return this._pairPool.done(),e&&(e.physics.collisions+=i.length),i}update(t,e){return this.hashGrid.update(t)}debug(t,e){this.hashGrid.debug(t,e)}}class ii{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 ii(new D({left:this.bounds.left,top:this.bounds.top,right:this.bounds.left+this.halfWidth,bottom:this.bounds.top+this.halfHeight}),t),this.topRight=new ii(new D({left:this.bounds.left+this.halfWidth,top:this.bounds.top,right:this.bounds.right,bottom:this.bounds.top+this.halfHeight}),t),this.bottomLeft=new ii(new D({left:this.bounds.left,top:this.bounds.top+this.halfHeight,right:this.bounds.left+this.halfWidth,bottom:this.bounds.bottom}),t),this.bottomRight=new ii(new D({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;(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.insert(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.insert(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.insert(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.insert(t)}insert(t){if(this._isDivided){this._insertIntoSubNodes(t);return}if(this.items.push(t),this.items.length>this.options.capacity&&this.options.level<this.options.maxDepth){this._isDivided||this._split();for(const e of this.items)this._insertIntoSubNodes(e);this.items.length=0}}remove(t){var e,i,s,n;if(this.bounds.overlaps(t.bounds)){if(!this._isDivided){const o=this.items.indexOf(t);o>-1&&this.items.splice(o,1);return}(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.remove(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.remove(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.remove(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.remove(t)}}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((i,s)=>e.indexOf(i)>=s),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.debug(t,{color:T.Yellow}),this._isDivided&&(this.topLeft.bounds.debug(t,{color:T.Yellow}),this.topRight.bounds.debug(t,{color:T.Yellow}),this.bottomLeft.bounds.debug(t,{color:T.Yellow}),this.bottomRight.bounds.debug(t,{color:T.Yellow}))}}class kn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this._compositeContactsIds=new Set}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case _e.HorizontalFirst:{e=un;break}case _e.VerticalFirst:{e=dn;break}default:e=_n}t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h});for(const i of t)this.solvePosition(i),this.solveVelocity(i);return this.postSolve(t),t}preSolve(t){for(let i=0;i<t.length;i++){const s=t[i],n=s.id.indexOf("|");if(n>0){const l=s.id.substring(n+1);if(this._compositeContactsIds.has(l)){s.cancel();continue}this._compositeContactsIds.add(l)}if(Math.abs(s.mtv.x)<1e-4&&Math.abs(s.mtv.y)<1e-4){s.cancel();continue}const o=u.Side.fromDirection(s.mtv),a=s.mtv.negate(),h=Math.abs(s.info.separation);this.distanceMap.set(s.id,h),this.directionMap.set(s.id,o===u.Side.Left||o===u.Side.Right?"horizontal":"vertical"),s.colliderA.events.emit("precollision",new be(s.colliderA,s.colliderB,o,a,s)),s.colliderB.events.emit("precollision",new be(s.colliderB,s.colliderA,u.Side.getOpposite(o),a.negate(),s))}this._compositeContactsIds.clear()}postSolve(t){var e,i;for(let s=0;s<t.length;s++){const n=t[s];if(n.isCanceled())continue;const o=n.colliderA,a=n.colliderB,h=(e=o.owner)==null?void 0:e.get(U),l=(i=a.owner)==null?void 0:i.get(U);if(h&&l&&(h.collisionType===R.Passive||l.collisionType===R.Passive))continue;const c=u.Side.fromDirection(n.mtv),d=n.mtv.negate();n.colliderA.events.emit("postcollision",new Ce(n.colliderA,n.colliderB,c,d,n)),n.colliderB.events.emit("postcollision",new Ce(n.colliderB,n.colliderA,u.Side.getOpposite(c),d.negate(),n))}}solvePosition(t){var e,i;if(!t.colliderA.bounds.overlaps(t.colliderB.bounds,1e-4)){t.cancel();return}if(Math.abs(t.mtv.x)<1e-4&&Math.abs(t.mtv.y)<1e-4){t.cancel();return}let n=t.mtv;const o=t.colliderA,a=t.colliderB,h=(e=o.owner)==null?void 0:e.get(U),l=(i=a.owner)==null?void 0:i.get(U);if(h&&l){if(h.collisionType===R.Passive||l.collisionType===R.Passive)return;h.collisionType===R.Active&&l.collisionType===R.Active&&(n=n.scale(.5)),h.collisionType===R.Active&&(h.globalPos.x-=n.x,h.globalPos.y-=n.y,o.update(h.transform.get())),l.collisionType===R.Active&&(l.globalPos.x+=n.x,l.globalPos.y+=n.y,a.update(l.transform.get()))}}solveVelocity(t){var e,i;if(t.isCanceled())return;const s=t.colliderA,n=t.colliderB,o=(e=s.owner)==null?void 0:e.get(U),a=(i=n.owner)==null?void 0:i.get(U);if(o&&a){if(o.collisionType===R.Passive||a.collisionType===R.Passive)return;const h=t.normal,l=h.negate();if(o.collisionType===R.Active&&o.vel.normalize().dot(l)<0){const c=h.scale(h.dot(o.vel.negate()));o.vel=o.vel.add(c)}if(a.collisionType===R.Active&&a.vel.normalize().dot(h)<0){const c=l.scale(l.dot(a.vel.negate()));a.vel=a.vel.add(c)}}}}class Uo{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 w(0,0),this.bToContact=new w(0,0),this.originalVelocityAndRestitution=0,this.update()}update(){const t=this.contact.bodyA,e=this.contact.colliderA,i=this.contact.bodyB,s=this.contact.colliderB;if(t&&i){const n=this.contact.normal,o=this.contact.tangent;this.aToContact=this.point.sub(e.center),this.bToContact=this.point.sub(s.center);const a=this.aToContact.cross(n),h=this.bToContact.cross(n);this.normalMass=t.inverseMass+i.inverseMass+t.inverseInertia*a*a+i.inverseInertia*h*h;const l=this.aToContact.cross(o),c=this.bToContact.cross(o);this.tangentMass=t.inverseMass+i.inverseMass+t.inverseInertia*l*l+i.inverseInertia*c*c}return this}getRelativeVelocity(){const t=this.contact.bodyA,e=this.contact.bodyB;if(t&&e){const i=t.vel.add(w.cross(t.angularVelocity,this.aToContact));return e.vel.add(w.cross(e.angularVelocity,this.bToContact)).sub(i)}return w.Zero}}class zn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return(e=this.idToContactConstraint.get(t))!=null?e:[]}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case _e.HorizontalFirst:{e=un;break}case _e.VerticalFirst:{e=dn;break}default:e=_n}return t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h}),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}preSolve(t){var e,i,s,n;for(let h=0;h<t.length;h++){const l=t[h];if(Math.abs(l.mtv.x)<1e-4&&Math.abs(l.mtv.y)<1e-4){l.cancel();continue}const c=u.Side.fromDirection(l.mtv),d=Math.abs(((e=l==null?void 0:l.info)==null?void 0:e.separation)||0);this.distanceMap.set(l.id,d),this.directionMap.set(l.id,c===u.Side.Left||c===u.Side.Right?"horizontal":"vertical"),l.colliderA.events.emit("precollision",new be(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderA.events.emit("beforecollisionresolve",new Li(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderB.events.emit("precollision",new be(l.colliderB,l.colliderA,u.Side.getOpposite(c),l.mtv.negate(),l)),l.colliderB.events.emit("beforecollisionresolve",new Li(l.colliderB,l.colliderA,u.Side.getOpposite(c),l.mtv.negate(),l))}const a=Array.from(this.idToContactConstraint.keys());for(let h=0;h<t.length;h++){const l=t[h],c=a.indexOf(l.id);c>-1&&a.splice(c,1);const d=(i=this.idToContactConstraint.get(l.id))!=null?i:[];let _=0;const f=l.bodyA,m=l.colliderA,p=l.bodyB,x=l.colliderB;if(f&&p&&(!f.isSleeping||!p.isSleeping))for(let v=0;v<l.points.length;v++){const g=l.points[v],b=l.normal,S=l.tangent,A=g.sub(m.center),M=g.sub(x.center),C=A.cross(b),z=M.cross(b),O=f.inverseMass+p.inverseMass+f.inverseInertia*C*C+p.inverseInertia*z*z,st=A.cross(S),W=M.cross(S),ct=f.inverseMass+p.inverseMass+f.inverseInertia*st*st+p.inverseInertia*W*W;d[_]&&((n=(s=d[_])==null?void 0:s.point)==null?void 0:n.squareDistance(g))<4?(d[_].point=g,d[_].local=l.localPoints[_]):d[_]=new Uo(g,l.localPoints[_],l),d[_].aToContact=A,d[_].bToContact=M,d[_].normalMass=1/O,d[_].tangentMass=1/ct;const K=f.bounciness>p.bounciness?f.bounciness:p.bounciness,V=l.normal.dot(d[_].getRelativeVelocity());d[_].originalVelocityAndRestitution=0,V<-.1&&(d[_].originalVelocityAndRestitution=-K*V),_++}this.idToContactConstraint.set(l.id,d)}for(const h of a)this.idToContactConstraint.delete(h);if(this.config.warmStart)this.warmStart(t);else for(let h=0;h<t.length;h++){const l=t[h],c=this.getContactConstraints(l.id);for(const d of c)d.normalImpulse=0,d.tangentImpulse=0}}postSolve(t){for(let e=0;e<t.length;e++){const i=t[e],s=i.bodyA,n=i.bodyB;if(s&&n&&(s.collisionType===R.Passive||n.collisionType===R.Passive))continue;const o=u.Side.fromDirection(i.mtv);i.colliderA.events.emit("postcollision",new Ce(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderA.events.emit("aftercollisionresolve",new ki(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderB.events.emit("postcollision",new Ce(i.colliderB,i.colliderA,u.Side.getOpposite(o),i.mtv.negate(),i)),i.colliderB.events.emit("aftercollisionresolve",new ki(i.colliderB,i.colliderA,u.Side.getOpposite(o),i.mtv.negate(),i))}this.lastFrameContacts.clear();for(let e=0;e<t.length;e++){const i=t[e];this.lastFrameContacts.set(i.id,i)}}warmStart(t){var e;for(let i=0;i<t.length;i++){const s=t[i],n=s.bodyA,o=s.bodyB;if(!(n.isSleeping&&o.isSleeping)&&n&&o){const a=(e=this.idToContactConstraint.get(s.id))!=null?e:[];for(const h of a)if(this.config.warmStart){const l=s.normal.scale(h.normalImpulse),c=s.tangent.scale(h.tangentImpulse),d=l.add(c);n.applyImpulse(h.point,d.negate()),o.applyImpulse(h.point,d)}else h.normalImpulse=0,h.tangentImpulse=0}}}solvePosition(t){var e;for(let i=0;i<this.config.positionIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(!(o.isSleeping&&a.isSleeping)&&o&&a){if(o.collisionType===R.Passive||a.collisionType===R.Passive)continue;const h=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const l of h){const c=n.normal,d=Ht.FindContactSeparation(n,l.local),_=this.config.steeringFactor,f=-5,m=this.config.slop,p=L(_*(d+m),f,0),x=c.scale(-p*l.normalMass);if(o.collisionType===R.Active){const v=x.negate().scale(o.inverseMass);o.limitDegreeOfFreedom.includes(oe.X)&&(v.x=0),o.limitDegreeOfFreedom.includes(oe.Y)&&(v.y=0),o.globalPos=o.globalPos.add(v),o.limitDegreeOfFreedom.includes(oe.Rotation)||(o.rotation-=l.aToContact.cross(x)*o.inverseInertia)}if(a.collisionType===R.Active){const v=x.scale(a.inverseMass);a.limitDegreeOfFreedom.includes(oe.X)&&(v.x=0),a.limitDegreeOfFreedom.includes(oe.Y)&&(v.y=0),a.globalPos=a.globalPos.add(v),a.limitDegreeOfFreedom.includes(oe.Rotation)||(a.rotation+=l.bToContact.cross(x)*a.inverseInertia)}}}}}solveVelocity(t){var e;for(let i=0;i<this.config.velocityIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(!(o.isSleeping&&a.isSleeping)&&o&&a){if(o.collisionType===R.Passive||a.collisionType===R.Passive)continue;const h=Math.min(o.friction,a.friction),l=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const c of l){let f=-c.getRelativeVelocity().dot(n.tangent)*c.tangentMass;const m=h*c.normalImpulse,p=L(c.tangentImpulse+f,-m,m);f=p-c.tangentImpulse,c.tangentImpulse=p;const x=n.tangent.scale(f);o.applyImpulse(c.point,x.negate()),a.applyImpulse(c.point,x)}for(const c of l){const _=c.getRelativeVelocity().dot(n.normal);let f=-c.normalMass*(_-c.originalVelocityAndRestitution);const m=Math.max(c.normalImpulse+f,0);f=m-c.normalImpulse,c.normalImpulse=m;const p=n.normal.scale(f);o.applyImpulse(c.point,p.negate()),a.applyImpulse(c.point,p)}}}}}class es extends Pt{constructor(t,e){super(),this.world=t,this.physics=e,this.systemType=At.Update,this._physicsConfigDirty=!1,this.query=this._createPhysicsQuery(t,e),e.$configUpdate.subscribe(()=>{this._physicsConfigDirty=!0})}_createPhysicsQuery(t,e){return t.query({components:{all:[E,H,Mt]},tags:{not:e.config.integration.onScreenOnly?["ex.offscreen","ex.is_sleeping"]:["ex.is_sleeping"]}})}update(t){let e,i,s;const n=this.query.entities,a=this.physics.config.substep;for(let h=0;h<n.length;h++){if(e=n[h].get(E),i=n[h].get(H),s=n[h].get(Mt),s.paused||i.integration.onScreenOnly&&n[h].hasTag("ex.offscreen"))continue;const l=n[h].get(U);if(this._physicsConfigDirty&&l&&l.updatePhysicsConfig(this.physics.config.bodies),l!=null&&l.isSleeping)continue;const c=i.acc.clone();(l==null?void 0:l.collisionType)===R.Active&&(l!=null&&l.useGravity)&&c.addEqual(this.physics.config.gravity),n[h].parent||this.captureOldTransformWithChildren(n[h]),to.integrate(e,i,c,t/a)}this._physicsConfigDirty&&(this._physicsConfigDirty=!1,this.query=this._createPhysicsQuery(this.world,this.physics))}captureOldTransformWithChildren(t){var e;(e=t.get(U))==null||e.captureOldTransform();for(let i=0;i<t.children.length;i++)this.captureOldTransformWithChildren(t.children[i])}}es.priority=Zt.Higher;class Dl{constructor(t){this.config=t,this.bodies=[],this.contacts=[],this.isSleeping=!1}wake(){this.isSleeping=!1;for(const t of this.bodies)t.wake()}sleep(){this.isSleeping=!0;for(const t of this.bodies)t.sleep()}updateSleepState(t){let e=!1,i=!0;for(const s of this.bodies)s.updateMotion(t),s.canFallAsleep||i&&(i=!1),s.canWakeUp&&(e||(e=!0));if(e)this.wake();else if(i){let s=1/0;for(const n of this.bodies)s=Math.min(s,n.sleepTime);s>this.config.sleepTimeThreshold&&this.sleep()}}}function Bl(r,t,e){const i=new Map;function s(h){return i.has(h)||i.set(h,h),i.get(h)!==h&&i.set(h,s(i.get(h))),i.get(h)}function n(h,l){const c=s(h),d=s(l);c!==d&&i.set(c,d)}const o=new Map;for(const h of e)h.bodyA.collisionType===R.Active&&h.bodyB.collisionType===R.Active&&n(h.bodyA,h.bodyB),o.has(h.bodyA)||o.set(h.bodyA,[]),o.has(h.bodyB)||o.set(h.bodyB,[]),h.bodyA.collisionType===R.Active&&o.get(h.bodyA).push(h),h.bodyB.collisionType===R.Active&&o.get(h.bodyB).push(h);const a=new Map;for(const h of t){if(h.collisionType!==R.Active)continue;const l=s(h);a.has(l)||a.set(l,[]),a.get(l).push(h)}return Array.from(a.values()).map(h=>{const l=new Dl(r);return l.bodies=h,h.forEach(c=>c.island=l),l.contacts=Array.from(new Set(h.flatMap(c=>o.get(c)))),l})}class is extends Pt{constructor(t,e){super(),this._physics=e,this.systemType=At.Update,this._configDirty=!1,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._bodies=[],this._arcadeSolver=new kn(e.config.arcade),this._realisticSolver=new zn(e.config.realistic),this._physics.$configUpdate.subscribe(()=>this._configDirty=!0),this._trackCollider=i=>this._processor.track(i),this._untrackCollider=i=>this._processor.untrack(i),this.query=t.query([E,j,Mt]),this.query.entityAdded$.subscribe(i=>{const s=i.get(j);s.$colliderAdded.subscribe(this._trackCollider),s.$colliderRemoved.subscribe(this._untrackCollider);const n=s.get();n&&this._processor.track(n)}),this.query.entityRemoved$.subscribe(i=>{const s=i.get(j),n=s.get();s&&n&&this._processor.untrack(n)}),this._motionSystem=t.get(es),this.bodyQuery=t.query([U]),this.bodyQuery.entityAdded$.subscribe(i=>{this._bodies.push(i.get(U))}),this.bodyQuery.entityRemoved$.subscribe(i=>{const s=i.get(U),n=this._bodies.indexOf(s);n>-1&&this._bodies.splice(n,1)})}get _processor(){return this._physics.collisionProcessor}initialize(t,e){this._engine=e.engine}update(t){var e,i,s,n;if(!this._physics.config.enabled)return;let o=[];for(let d=0;d<this.query.entities.length;d++){const _=this.query.entities[d],f=_.get(j);if(_.get(Mt).paused)continue;const p=f==null?void 0:f.get();if(f&&((e=f.owner)!=null&&e.isActive)&&p)if(f.update(),p instanceof nt){const x=p.getColliders();p.compositeStrategy||(p.compositeStrategy=this._physics.config.colliders.compositeStrategy),o=o.concat(x)}else o.push(p)}this._processor.update(o,t);let a=this._processor.broadphase(o,t);this._currentFrameContacts.clear();let h=[];const l=this.getSolver(),c=this._physics.config.substep;for(let d=0;d<c;d++)if(d>0&&this._motionSystem.update(t),h.length&&(a=h.map(_=>new mt(_.colliderA,_.colliderB))),a.length){if(h=this._processor.narrowphase(a,(n=(s=(i=this._engine)==null?void 0:i.debug)==null?void 0:s.stats)==null?void 0:n.currFrame),this._physics.config.solver===ui.Realistic){const _=Bl(this._physics.config.bodies,this._bodies,h);for(const f of _)f.updateSleepState(t/c)}h=l.solve(h,t/c);for(const _ of h){if(_.isCanceled())continue;const f=_.id.indexOf("|");if(f>0){const m=_.id.substring(f+1);this._currentFrameContacts.set(m,_)}else this._currentFrameContacts.set(_.id,_)}}this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts);for(const d of this.query.entities){const _=d.get(j);_&&_.processColliderRemoval()}}postupdate(){Xe.SeparationPool.done()}getSolver(){return this._configDirty&&(this._configDirty=!1,this._arcadeSolver=new kn(this._physics.config.arcade),this._realisticSolver=new zn(this._physics.config.realistic)),this._physics.config.solver===ui.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t,0)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB,n=u.Side.fromDirection(e.mtv),o=u.Side.getOpposite(n);i.events.emit("collisionstart",new hi(i,s,n,e)),i.events.emit("contactstart",new Di(i,s,n,e)),s.events.emit("collisionstart",new hi(s,i,o,e)),s.events.emit("contactstart",new Di(s,i,o,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB;e.bodyA.isSleeping=!1,e.bodyB.isSleeping=!1;const n=u.Side.fromDirection(e.mtv),o=u.Side.getOpposite(n);i.events.emit("collisionend",new li(i,s,n,e)),i.events.emit("contactend",new Bi(i,s,n,e)),s.events.emit("collisionend",new li(s,i,o,e)),s.events.emit("contactend",new Bi(s,i,o,e))}}}is.priority=Zt.Higher;class Oo{constructor(t){this.$configUpdate=new pt,this._configDirty=!1,this.config=t,this.$configUpdate.subscribe(e=>{this._configDirty=!0,U.updateDefaultPhysicsConfig(e.bodies)}),this._config.spatialPartition===_i.SparseHashGrid?this._collisionProcessor=new Ln(this._config.sparseHashGrid):this._collisionProcessor=new Ni(this._config)}get config(){return Gh(this._config,t=>{this.$configUpdate.notifyAll(t)})}set config(t){this._config=t,this.$configUpdate.notifyAll(t)}get collisionProcessor(){if(this._configDirty){this._configDirty=!1;const t=this._collisionProcessor.getColliders();this._config.spatialPartition===_i.SparseHashGrid?this._collisionProcessor=new Ln(this._config.sparseHashGrid):this._collisionProcessor=new Ni(this._config);for(const e of t)this._collisionProcessor.track(e)}return this._collisionProcessor}rayCast(t,e){return this.collisionProcessor.rayCast(t,e)}query(t){return this._collisionProcessor.query(t)}}var yi=(r=>(r.Fixed="Fixed",r.FitContainerAndFill="FitContainerAndFill",r.FitScreenAndFill="FitScreenAndFill",r.FitContainerAndZoom="FitContainerAndZoom",r.FitScreenAndZoom="FitScreenAndZoom",r.FitScreen="FitScreen",r.FillScreen="FillScreen",r.FitContainer="FitContainer",r.FillContainer="FillContainer",r))(yi||{});class Un{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 Ll={ScreenResize:"resize",PixelRatioChange:"pixelratio",FullScreenChange:"fullscreen"};class On{constructor(t){this.events=new Y,this._antialiasing=!0,this._canvasImageRendering="auto",this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullscreen=!1,this._isDisposed=!1,this._logger=F.getInstance(),this._fullscreenChangeHandler=()=>{this._isDisposed||(this._isFullscreen=!this._isFullscreen,this._logger.debug("Fullscreen Change",this._isFullscreen),this.events.emit("fullscreen",{fullscreen:this.isFullscreen}))},this._pixelRatioChangeHandler=()=>{this._isDisposed||(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=()=>{if(this._isDisposed)return;const o=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(o),this.applyResolutionAndViewport(),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._contentArea=new D,this._unsafeArea=new D;var e,i,s,n;this.viewport=t.viewport,this.resolution=(e=t.resolution)!=null?e:{...this.viewport},this._contentResolution=this.resolution,this._displayMode=(i=t.displayMode)!=null?i:"Fixed",this._canvas=t.canvas,this.graphicsContext=t.context,this._antialiasing=(s=t.antialiasing)!=null?s:this._antialiasing,this._canvasImageRendering=(n=t.canvasImageRendering)!=null?n:this._canvasImageRendering,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.events.clear(),this._browser.window.off("resize",this._resizeHandler),this._browser.window.clear(),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),this._canvas=null)}_calculateDevicePixelRatio(){return window.devicePixelRatio<1?1:window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get worldToPagePixelRatio(){if(this._canvas){const t=this.worldToPageCoordinates(w.Zero);return this.worldToPageCoordinates(y(1,0)).sub(t).x}else return 1}get pixelRatioOverride(){return this._pixelRatioOverride}set pixelRatioOverride(t){this._pixelRatioOverride=t}get isHiDpi(){return this.pixelRatio!==1}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){switch(this.displayMode){case"FillContainer":case"FitContainer":case"FitContainerAndFill":case"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._resolutionStack.length&&this._viewportStack.length&&(this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop())}applyResolutionAndViewport(){if(this.graphicsContext instanceof Kt&&!this.graphicsContext.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})&&(this._logger.warnOnce(`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.pixelRatioOverride)){let s=Math.max(1,this.pixelRatio-.5),n=!1;for(;s>1&&!n;){s=Math.max(1,s-.5);const o=this._resolution.width*s,a=this._resolution.height*s;n=this.graphicsContext.checkIfResolutionSupported({width:o,height:a})}this.pixelRatioOverride=s,this._logger.warnOnce(`Scaled resolution too big attempted recovery! Pixel ratio was automatically reduced to (${this.pixelRatio}) to avoid 4k texture limit. Setting \`ex.Engine({pixelRatio: ...}) will override any automatic recalculation, do so at your own risk.\` (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`)}this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this._canvasImageRendering==="auto"?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",this._canvas.style.imageRendering===""&&(this._canvas.style.imageRendering="crisp-edges"));const t=this.viewport.widthUnit==="percent"?"%":"px",e=this.viewport.heightUnit==="percent"?"%":"px";this._canvas.style.width=this.viewport.width+t,this._canvas.style.height=this.viewport.height+e,this.graphicsContext.updateViewport(this.resolution),this.graphicsContext.resetTransform(),this.graphicsContext.smoothing=this._antialiasing,this.graphicsContext instanceof Ji&&this.graphicsContext.scale(this.pixelRatio,this.pixelRatio),document.documentElement.style.setProperty("--ex-pixel-ratio",this.worldToPagePixelRatio.toString())}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this.graphicsContext.smoothing=this._antialiasing}get isFullScreen(){return this._isFullscreen}get isFullscreen(){return this._isFullscreen}goFullScreen(t){return this.enterFullscreen(t)}enterFullscreen(t){var e,i,s,n,o,a;if(t){const h=document.getElementById(t);if(h!=null&&h.requestFullscreen||h!=null&&h.webkitRequestFullscreen){if(h.getAttribute("ex-fullscreen-listener")||(h.setAttribute("ex-fullscreen-listener","true"),h.addEventListener("fullscreenchange",this._fullscreenChangeHandler)),h.requestFullscreen)return(e=h.requestFullscreen())!=null?e:Promise.resolve();if(h.webkitRequestFullscreen)return(i=h.webkitRequestFullscreen())!=null?i:Promise.resolve()}}return(s=this._canvas)!=null&&s.requestFullscreen?(o=(n=this._canvas)==null?void 0:n.requestFullscreen())!=null?o:Promise.resolve():this._canvas.webkitRequestFullscreen?(a=this._canvas.webkitRequestFullscreen())!=null?a:Promise.resolve():(this._logger.warnOnce("Could not go fullscreen, is this an iPhone? Currently Apple does not support fullscreen on iPhones"),Promise.resolve())}exitFullScreen(){return this.exitFullscreen()}exitFullscreen(){return document.exitFullscreen()}_viewportToPixels(t){return{width:t.widthUnit==="percent"?this.canvas.offsetWidth:t.width,height:t.heightUnit==="percent"?this.canvas.offsetHeight:t.height}}pageToScreenCoordinates(t){let e=t.x,i=t.y;this._isFullscreen||(e-=ci(this._canvas).x,i-=ci(this._canvas).y);const s=this._viewportToPixels(this.viewport);if(this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=(i-o)/n*s.height,e=e/window.innerWidth*s.width}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=(e-o)/n*s.width,i=i/window.innerHeight*s.height}return e=e/s.width*this.resolution.width,i=i/s.height*this.resolution.height,e=e-this.contentArea.left,i=i-this.contentArea.top,new w(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;const s=this._viewportToPixels(this.viewport);if(e=e/this.resolution.width*s.width,i=i/this.resolution.height*s.height,this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=i/s.height*n+o,e=e/s.width*window.innerWidth}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=e/s.width*n+o,i=i/s.height*window.innerHeight}return this._isFullscreen||(e+=ci(this._canvas).x,i+=ci(this._canvas).y),new w(e,i)}screenToWorldCoordinates(t){return t=t.add(y(this.contentArea.left,this.contentArea.top)),this._camera?this._camera.inverse.multiply(t):t.sub(y(this.resolution.width/2,this.resolution.height/2))}worldToScreenCoordinates(t){return this._camera?this._camera.transform.multiply(t):t.add(y(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 D.fromDimension(this.resolution.width,this.resolution.height,w.Half).scale(y(1/this._camera.zoom,1/this._camera.zoom)).rotate(this._camera.rotation).translate(this._camera.drawPos)}getScreenBounds(){return D.fromDimension(this.resolution.width,this.resolution.height,w.Zero,w.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 width(){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 height(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return y(this.halfDrawWidth,this.halfDrawHeight)}get contentArea(){return this._contentArea}get unsafeArea(){return this._unsafeArea}_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=D.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this._unsafeArea=D.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitScreenAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndFill(t,e),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndFill(){this.canvas.style.width="100%",this.canvas.style.height="100%",this._computeFitAndFill(this.canvas.offsetWidth,this.canvas.offsetHeight,{width:100,widthUnit:"percent",height:100,heightUnit:"percent"}),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitAndFill(t,e,i){if(this.viewport=i!=null?i:{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 s=(this.resolution.height-this._contentResolution.height)/2;this._contentArea=new D({top:s,left:0,right:this._contentResolution.width,bottom:this.resolution.height-s}),this._unsafeArea=new D({top:-s,left:0,right:this._contentResolution.width,bottom:this.resolution.height+s})}else{this.resolution={width:e*this._contentResolution.height/e*t/e,height:e*this._contentResolution.height/e};const s=(this.resolution.width-this._contentResolution.width)/2;this._contentArea=new D({top:0,left:s,right:this.resolution.width-s,bottom:this._contentResolution.height}),this._unsafeArea=new D({top:0,left:-s,right:this.resolution.width+s,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),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndZoom(){this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.position="relative";const t=this.canvas.parentElement;t.style.overflow="hidden";const{offsetWidth:e,offsetHeight:i}=this.canvas;this._computeFitAndZoom(e,i),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_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 o=t/s,a=e/n,h=Math.max(o,a),l=s*h,c=n*h;l>t?this.canvas.style.left=-(l-t)/2+"px":this.canvas.style.left="",c>e?this.canvas.style.top=-(c-e)/2+"px":this.canvas.style.top="",this.viewport={width:l,height:c};const d=D.fromDimension(this.viewport.width,this.viewport.height,w.Zero);if(this.viewport.width>t){const _=(this.viewport.width-t)/this.viewport.width*this.resolution.width;d.top=0,d.left=_/2,d.right=this.resolution.width-_/2,d.bottom=this.resolution.height}if(this.viewport.height>e){const _=(this.viewport.height-e)/this.viewport.height*this.resolution.height;d.top=_/2,d.left=0,d.bottom=this.resolution.height-_/2,d.right=this.resolution.width}this._contentArea=d}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0,s="pixel",n="pixel";const o=this.canvas.parentElement;o.clientWidth/t<o.clientHeight?(this.canvas.style.width="100%",e=100,s="percent",i=this.canvas.offsetWidth/t):(this.canvas.style.height="100%",i=100,n="percent",e=this.canvas.offsetHeight*t),this.viewport={width:e,widthUnit:s,height:i,heightUnit:n},this._contentArea=D.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_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==="FillContainer"&&(this.canvas.style.width="100%",this.canvas.style.height="100%",this.viewport={width:100,widthUnit:"percent",height:100,heightUnit:"percent"},this.resolution={width:this.canvas.offsetWidth,height:this.canvas.offsetHeight}),this.displayMode==="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=D.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.displayMode==="FitScreen"&&this._computeFit(),this.displayMode==="FitContainer"&&this._computeFitContainer(),this.displayMode==="FitScreenAndFill"&&this._computeFitScreenAndFill(),this.displayMode==="FitContainerAndFill"&&this._computeFitContainerAndFill(),this.displayMode==="FitScreenAndZoom"&&this._computeFitScreenAndZoom(),this.displayMode==="FitContainerAndZoom"&&this._computeFitContainerAndZoom()}}class fe{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}static currentTime(){return fe.create().currentTime*1e3}}function kl(r){return!!r.playbackState}const No=class ws{static unlock(){return new Promise((e,i)=>{if(ws._UNLOCKED||!fe.create())return e(!0);const s=setTimeout(()=>{F.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),e(!1)},200),n=fe.create();n.resume().then(()=>{const o=n.createBuffer(1,1,22050),a=n.createBufferSource();let h=!1;a.buffer=o,a.connect(n.destination),a.onended=()=>h=!0,a.start(0),setTimeout(()=>{kl(a)?(a.playbackState===a.PLAYING_STATE||a.playbackState===a.FINISHED_STATE)&&(ws._UNLOCKED=!0):(n.currentTime>0||h)&&(ws._UNLOCKED=!0)},0),clearTimeout(s),e(!0)},()=>{i()})})}static isUnlocked(){return this._UNLOCKED}};No._UNLOCKED=!1;let Ho=No;class Nn{}Nn.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class ss{constructor(){this.states=new Map}get currentState(){return this._currentState}set currentState(t){this._currentState=t}static create(t,e){const i=new ss;i.data=e;for(const s in t.states)i.states.set(s,{name:s,...t.states[s]});for(const s of i.states.values())for(const n of s.transitions)if(n!=="*"&&!i.states.has(n))throw Error(`Invalid state machine, state [${s.name}] has a transition to another state that doesn't exist [${n}]`);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);return this.currentState.onExit&&((i=this.currentState)==null?void 0:i.onExit({to:n.name,data:this.data}))===!1||n!=null&&n.onEnter&&(n==null?void 0:n.onEnter({from:this.currentState.name,eventData:e,data:this.data}))===!1?!1:(this.currentState=n,(s=this.currentState)!=null&&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 Go{constructor(t){this._src=t,this._audioContext=fe.create(),this._volumeNode=this._audioContext.createGain(),this._playingFuture=new xt,this._stateMachine=ss.create({start:"STOPPED",states:{PLAYING:{onEnter:({data:e})=>{this._createNewBufferSource(),this._handleEnd(),this.loop?this._instance.start(this.scheduledStartTime,e.pausedAt*this._playbackRate):this._instance.start(this.scheduledStartTime,e.pausedAt*this._playbackRate,this.duration),e.startedAt=this._audioContext.currentTime-e.pausedAt,e.pausedAt=0},onState:()=>this._playStarted(),onExit:({to:e})=>{e==="STOPPED"&&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:e,data:i})=>{i.pausedAt=(e!=null?e:0)/this._playbackRate,i.startedAt=0},transitions:["*"]},STOPPED:{onEnter:({data:e})=>{e.pausedAt=0,e.startedAt=0,this._playingFuture.resolve(!0)},transitions:["PLAYING","PAUSED","SEEK"]},PAUSED:{onEnter:({data:e})=>{e.pausedAt=this._audioContext.currentTime-e.startedAt},transitions:["PLAYING","STOPPED","SEEK"]}}},{startedAt:0,pausedAt:0}),this._volume=1,this._loop=!1,this._playStarted=()=>{},this._playbackRate=1,this.scheduledStartTime=0,this._createNewBufferSource()}_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=L(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(t=this._duration)!=null?t:this.getTotalPlaybackDuration()}set duration(t){this._duration=t}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 Hn extends k{constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}stopPropagation(){}action(){}propagate(){}layPath(t){}}class Re extends Hn{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class Wo extends Hn{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}function zl(r){try{const t=new Audio,e=/.*\.([A-Za-z0-9]+)(?=[?#]|$)/,i=r.match(e)[1];return!!t.canPlayType("audio/"+i)}catch(t){return F.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}function Ul(r){try{const t=new Audio,e=/.*audio\/([A-Za-z0-9]+);?/,i=r.match(e)[1];return!!t.canPlayType(`audio/${i}`)}catch(t){return F.getInstance().warn("Cannot determine audio support via blob mime type.",t),!1}}const Ol={VolumeChange:"volumechange",Processed:"processed",Pause:"pause",Stop:"stop",PlaybackEnd:"playbackend",Resume:"resume",PlaybackStart:"playbackstart"};function Nl(r){var t;return!!((t=r[0])!=null&&t.paths)}class bi{constructor(...t){this.events=new Y,this.logger=F.getInstance(),this.scheduledStartTime=0,this._loop=!1,this._volume=1,this._isStopped=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._playbackRate=1,this._audioContext=fe.create();let e;Nl(t)?e=t[0]:e={paths:t},this._resource=new fi("",Nn.type.arraybuffer);const{volume:i,position:s,playbackRate:n,loop:o,bustCache:a,duration:h}=e;this.volume=i!=null?i:this.volume,this.playbackRate=n!=null?n:this.playbackRate,this.loop=o!=null?o:this.loop,this.duration=h!=null?h:this.duration,this.bustCache=a!=null?a:this.bustCache,this.position=s!=null?s:this.position;for(const l of e.paths)if(zl(l)){this.path=l;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",e.paths.join(", ")),this.logger.warn("Attempting to use",e.paths[0]),this.path=e.paths[0])}set loop(t){this._loop=t;for(const e of this._tracks)e.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 e of this._tracks)e.volume=this._volume;this.events.emit("volumechange",new Re(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}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=(e=(t=this._duration)!=null?t:s==null?void 0:s.duration)!=null?e:void 0,this.events.emit("processed",new Wo(this,s)),this.data=s}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(e){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){if(!this.isLoaded())return this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0);if(this._isStopped)return this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1);let e=0;if(t instanceof Object){const{volume:i,scheduledStartTime:s}=t;e=(s!=null?s:0)/1e3||e,this.volume=i!=null?i:this.volume}else this.volume=t!=null?t:this.volume;return this.isPaused()?this._resumePlayback():(this.position&&this.seek(this.position),this._startPlayback(e))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this.events.emit("pause",new Re(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 Re(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(e=>{e.playbackRate=this._playbackRate})}seek(t,e=0){this._tracks.length===0&&this._getTrackInstance(this.data),this._tracks[e].seek(t)}getTotalPlaybackDuration(){return this.isLoaded()?this.data.duration:(this.logger.warnOnce(`Sound from ${this.path} is not loaded, cannot return total playback duration.Did you forget to add Sound to a loader? https://excaliburjs.com/docs/loaders/`),0)}getPlaybackPosition(t=0){return this._tracks.length?this._tracks[t].getPlaybackPosition():0}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(t=0){if(this.isPaused()){const e=[];for(const i of this._tracks)i.scheduledStartTime=t,e.push(i.play().then(()=>(this._tracks.splice(this.getTrackId(i),1),!0)));this.events.emit("resume",new Re(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(e)}return!0}async _startPlayback(t=0){const e=this._getTrackInstance(this.data);e.scheduledStartTime=t;const i=await e.play(()=>{this.events.emit("playbackstart",new Re(this,e)),this.logger.debug("Playing new instance for sound",this.path)});this.events.emit("playbackend",new Re(this,e));const s=this.getTrackId(e);return s!==-1&&this._tracks.splice(s,1),i}_getTrackInstance(t){var e;const i=new Go(t);return i.loop=this.loop,i.volume=this.volume,i.duration=(e=this.duration)!=null?e:0,i.playbackRate=this._playbackRate,this._tracks.push(i),i}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)}static async fromBlob(t){Ul(t.type)||F.getInstance().warn("Blob mime type is unsupported.");const e=new bi,i=await t.arrayBuffer(),s=await fe.create().decodeAudioData(i);return e.data=s,e._duration=s.duration,e}}const Hl={BeforeLoad:"beforeload",AfterLoad:"afterload",UserAction:"useraction",LoadResourceStart:"loadresourcestart",LoadResourceEnd:"loadresourceend"};function Gn(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Ci{constructor(t){this.events=new Y,this.canvas=new ji({filtering:vt.Blended,smoothing:!0,cache:!1,draw:this.onDraw.bind(this)}),this._resources=[],this._numLoaded=0,this._loaded=!1,this._isLoading=!1,this._totalTimeMs=0,this._resourcesLoadedFuture=new xt,this._loaderCompleteFuture=new xt;var e;t&&((e=t.loadables)!=null&&e.length)&&this.addResources(t.loadables)}get resources(){return this._resources}onInitialize(t){this.engine=t,this.canvas.width=this.engine.screen.resolution.width,this.canvas.height=this.engine.screen.resolution.height}async onUserAction(){return await Promise.resolve()}async onBeforeLoad(){}async onAfterLoad(){await zi(500,this.engine.clock)}addResource(t){this._resources.push(t),this._loaded=!1}addResources(t){let e=0;const i=t.length;for(e;e<i;e++)this.addResource(t[e]);this._loaded=!1}markResourceComplete(){this._numLoaded++}get progress(){const t=this._resources.length;return t>0?L(this._numLoaded,0,t)/t:1}isLoaded(){return this._loaded||this._resources.length===0}onUpdate(t,e){this._totalTimeMs+=e}onDraw(t){const e=this._totalTimeMs/1e3;t.fillStyle=T.Black.toRGBA(),t.fillRect(0,0,this.engine.screen.resolution.width,this.engine.screen.resolution.height),t.save(),t.translate(this.engine.screen.resolution.width/2,this.engine.screen.resolution.height/2);const i=e*10;t.strokeStyle="white",t.lineWidth=10,t.lineCap="round",t.arc(0,0,40,i,i+Math.PI*3/2),t.stroke(),t.fillStyle="white",t.font="16px sans-serif";const s=(this.progress*100).toFixed(0)+"%",n=t.measureText(s),o=Math.abs(n.actualBoundingBoxLeft)+Math.abs(n.actualBoundingBoxRight),a=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);t.fillText(s,-o/2,a/2),t.restore()}areResourcesLoaded(){return this._resources.length===0?Promise.resolve():this._resourcesLoadedFuture.promise}async load(){if(this._isLoading)return this._loaderCompleteFuture.promise;if(this.isLoaded())return this.data=this._resources;this._isLoading=!0,this._loaderCompleteFuture=new xt,await this.onBeforeLoad(),this.events.emit("beforeload"),this.canvas.flagDirty(),await Promise.all(this._resources.filter(t=>!t.isLoaded()).map(async t=>{this.events.emit("loadresourcestart",t),await t.load().finally(()=>{this._numLoaded++,this.canvas.flagDirty(),this.events.emit("loadresourceend",t)})}));for(const t of this._resources)t instanceof bi&&t.wireEngine(this.engine);return this._resourcesLoadedFuture.resolve(),this.canvas.flagDirty(),await this.onUserAction(),this.events.emit("useraction"),await Ho.unlock(),await this.onAfterLoad(),this.events.emit("afterload"),this._isLoading=!1,this._loaded=!0,this._loaderCompleteFuture.resolve(this._resources),this.data=this._resources}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 Gl(r,t=T.Red,e,i,s,n,o=1,a="butt"){r.save(),r.beginPath(),r.lineWidth=o,r.lineCap=a,r.strokeStyle=t.toString(),r.moveTo(e,i),r.lineTo(s,n),r.closePath(),r.stroke(),r.restore()}function Wl(r,t=T.Red,e){r.beginPath(),r.strokeStyle=t.toString(),r.arc(e.x,e.y,5,0,Math.PI*2),r.closePath(),r.stroke()}function Vl(r,t,e,i,s=1){const n=t?t.toString():"blue",o=i.scale(s);r.beginPath(),r.strokeStyle=n,r.moveTo(e.x,e.y),r.lineTo(e.x+o.x,e.y+o.y),r.closePath(),r.stroke()}function Wn(r,t,e,i,s,n=5,o=T.White,a=null){let h;if(typeof n=="number")h={tl:n,tr:n,br:n,bl:n};else{const l={tl:0,tr:0,br:0,bl:0};for(const c in l)if(l.hasOwnProperty(c)){const d=c;h[d]=n[d]||l[d]}}r.beginPath(),r.moveTo(t+h.tl,e),r.lineTo(t+i-h.tr,e),r.quadraticCurveTo(t+i,e,t+i,e+h.tr),r.lineTo(t+i,e+s-h.br),r.quadraticCurveTo(t+i,e+s,t+i-h.br,e+s),r.lineTo(t+h.bl,e+s),r.quadraticCurveTo(t,e+s,t,e+s-h.bl),r.lineTo(t,e+h.tl),r.quadraticCurveTo(t,e,t+h.tl,e),r.closePath(),a&&(r.fillStyle=a.toString(),r.fill()),o&&(r.strokeStyle=o.toString(),r.stroke())}function ql(r,t,e,i,s=T.White,n=null){r.beginPath(),r.arc(t,e,i,0,Math.PI*2),r.closePath(),n&&(r.fillStyle=n.toString(),r.fill()),s&&(r.strokeStyle=s.toString(),r.stroke())}const Xl=Object.freeze(Object.defineProperty({__proto__:null,circle:ql,line:Gl,point:Wl,roundRect:Wn,vector:Vl},Symbol.toStringTag,{value:"Module"})),$l="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=",Yl='button#excalibur-play{display:none}button#excalibur-play{box-sizing:border-box;display:flex;gap:.25rem;justify-content:center;position:relative;z-index:999;border-radius:6px;border:none;padding:1rem;margin:0;text-decoration:none;background:#00b233;color:#fff;font-family:sans-serif;font-size:2rem;white-space:nowrap;line-height:1;cursor:pointer;text-align:center;transition:background .25s ease-in-out,transform .15s ease;-webkit-appearance:none;-moz-appearance:none;-webkit-animation:excalibur-button-fadein .2s;-moz-animation:excalibur-button-fadein .2s;-ms-animation:excalibur-button-fadein .2s;-o-animation:excalibur-button-fadein .2s;animation:excalibur-button-fadein .2s}span#excalibur-play-icon{content:"";display:inline-block;position:relative;width:2rem;height:2rem}span#excalibur-play-icon:after{box-sizing:border-box;position:absolute;content:"";border:.5rem solid;border-color:transparent transparent transparent white;left:calc(50% - .1rem);top:calc(30% - .1rem);width:0;height:0}span#excalibur-play-icon:before{box-sizing:border-box;left:50%;top:50%;transform:translate(-50%,-50%);position:absolute;content:"";border:3px solid;border-radius:1rem;width:2rem;height:2rem}button#excalibur-play:focus{outline:1px solid #fff;outline-offset:-4px}button#excalibur-play:active{transform:scale(.99)}@keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-moz-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-webkit-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-ms-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-o-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}',Vo=class Xa extends Ci{constructor(t){const e=Array.isArray(t)?{loadables:t}:t;super(e),this._logger=F.getInstance(),this._originalOptions={loadables:[]},this.events=new Y,this._playButtonShown=!1,this.logo=$l,this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=T.White,this.backgroundColor="#176BAA",this._imageLoaded=new xt,this.suppressPlayButton=!1,this._playButtonStyles=Yl,this.playButtonText="Play game",this.startButtonFactory=()=>{let i=document.getElementById("excalibur-play");if(i||(i=document.createElement("button")),i.id="excalibur-play",i.style.display="none",i){let[s,n]=i.getElementsByTagName("span");s||(s!=null||(s=document.createElement("span")),i.appendChild(s)),s.id="excalibur-play-icon",n||(n!=null||(n=document.createElement("span")),i.appendChild(n)),n.id="excalibur-play-text",n.textContent=this.playButtonText}return i},this._originalOptions={...Xa._DEFAULT_LOADER_OPTIONS,...e}}get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.onload=()=>this._imageLoaded.resolve(),this._imageElement.src=this.logo),this._imageElement}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");return t&&(this._playButtonRootElement=t),this._playButtonRootElement||(this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute",document.body.appendChild(this._playButtonRootElement)),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}onInitialize(t){this.engine=t,this.screen=t.screen,this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height,this.screen.events.on("resize",()=>{this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height})}async showPlayButton(){var t,e;if(this.suppressPlayButton)this.hidePlayButton(),await zi(500,(t=this.engine)==null?void 0:t.clock);else{const i=()=>{try{this._positionPlayButton()}catch(n){}};return(e=this.engine)!=null&&e.browser&&this.engine.browser.window.on("resize",i),this._playButtonShown=!0,this._playButton.style.display="flex",document.body.addEventListener("keyup",n=>{n.key==="Enter"&&this._playButton.click()}),this._positionPlayButton(),await new Promise(n=>{const o=a=>{var h;if(a.stopPropagation(),this.hidePlayButton(),(h=this.engine)!=null&&h.browser&&this.engine.browser.window.off("resize",i),this._originalOptions.fullscreenAfterLoad)try{this._logger.info("requesting fullscreen"),this._originalOptions.fullscreenContainer instanceof HTMLElement?this._originalOptions.fullscreenContainer.requestFullscreen():this.engine.screen.enterFullscreen(this._originalOptions.fullscreenContainer)}catch(l){this._logger.error("could not go fullscreen",l)}n()};this._playButton.addEventListener("click",o),this._playButton.addEventListener("touchend",o),this._playButton.addEventListener("pointerup",o),this.engine&&this.engine.input.gamepads.once("button",()=>o(new Event("button")))})}}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)}async onUserAction(){var t;await zi(200,(t=this.engine)==null?void 0:t.clock),this.canvas.flagDirty(),await this.showPlayButton()}async onBeforeLoad(){this.screen.pushResolutionAndViewport(),this.screen.resolution={width:this.screen.resolution.width,height:this.screen.resolution.height},this.screen.applyResolutionAndViewport();const t=this._image;await this._imageLoaded.promise,await(t==null?void 0:t.decode())}async onAfterLoad(){this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport(),this.dispose()}_positionPlayButton(){if(this.engine){const{x:t,y:e,width:i,height:s}=this.engine.canvas.getBoundingClientRect();if(this._playButtonRootElement&&this._playButtonElement){const n=this._playButtonElement.querySelector("#excalibur-play-text");i<450?n.style.display="none":n.style.display="inline-block";const o=this._playButton.clientWidth,a=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=`${t+i/2-o/2}px`,this._playButtonRootElement.style.top=`${e+s/2-a/2+100}px`),i<450&&(this._playButtonRootElement.style.left=`${t+i/2-o/2}px`,this._playButtonRootElement.style.top=`${e+s/2-a/2+25}px`)}}}onDraw(t){const e=this.engine.canvasHeight/this.engine.pixelRatio,i=this.engine.canvasWidth/this.engine.pixelRatio;t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,i*.75);let o=i/2-n/2;this.logoPosition&&(o=this.logoPosition.x,s=this.logoPosition.y);const a=Math.floor(n*(this.logoHeight/this.logoWidth)),h=this.engine.screen.antialiasing;if(this.engine.screen.antialiasing=!0,this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s,n,a):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s-a-20,n,a),!this.suppressPlayButton&&this._playButtonShown){this.engine.screen.antialiasing=h;return}let l=o,c=s;this.loadingBarPosition&&(l=this.loadingBarPosition.x,c=this.loadingBarPosition.y),t.lineWidth=2,Wn(t,l,c,n,20,10,this.loadingBarColor);const d=n*this.progress,_=5,f=d-_*2,m=20-_*2;Wn(t,l+_,c+_,f>10?f:10,m,5,null,this.loadingBarColor),this.engine.screen.antialiasing=h}};Vo._DEFAULT_LOADER_OPTIONS={loadables:[],fullscreenAfterLoad:!1,fullscreenContainer:void 0};let ns=Vo;const qo={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class Xo{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(e){return!1}return t.responseType==="arraybuffer"},dataUrlSupport:function(){return document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")===0},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 this._features===null&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t=`%cSUPPORTED BROWSER FEATURES
895
- ==========================%c
896
- `;const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(qo))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+=" "+qo[s]+`
897
- `;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),F.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const e in this._warningTest)this._warningTest[e]()||F.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",e);return!0}}function $o(r){return r instanceof Vn}class Vn extends Bt{constructor(t){var e,i;super({...t}),this.get(E).coordPlane=ht.Screen,this.anchor=(e=t==null?void 0:t.anchor)!=null?e:y(0,0),this.body.collisionType=(i=t==null?void 0:t.collisionType)!=null?i:R.PreventCollision,this.pointer.useGraphicsBounds=!0,this.pointer.useColliderShape=!1,!(t!=null&&t.collider)&&(t==null?void 0:t.width)>0&&(t==null?void 0:t.height)>0&&this.collider.useBoxCollider(t.width,t.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 w(t,e));return super.contains(s.x,s.y)}}const Zl={Start:"start",Stop:"stop",Pause:"pause",Resume:"resume",Cancel:"cancel",Action:"action",Complete:"complete"},Yo=class $a{constructor(t){this._logger=F.getInstance(),this.id=0,this.events=new Y,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._onComplete=()=>{},this._complete=!1,this.scene=null;var e,i;const s=(e=t.action)!=null?e:t.fcn,n=t.interval,o=t.repeats,a=t.numberOfRepeats,h=t.randomRange,l=t.random;if(this._onComplete=(i=t.onComplete)!=null?i:this._onComplete,a&&a>=0&&(this.maxNumberOfRepeats=a,!o))throw new Error("repeats must be set to true if numberOfRepeats is set");if(this.id=$a._MAX_ID++,this._callbacks=[],this._baseInterval=this.interval=n,h){if(h[0]>h[1])throw new Error("min value must be lower than max value for range");this.random=l!=null?l:new le,this.randomRange=h,this.interval=this._generateRandomInterval(),this.on(()=>{this.interval=this._generateRandomInterval()})}this.repeats=o||this.repeats,s&&this.on(s)}get complete(){return this._complete}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._onComplete(),this.events.emit("complete")),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach(e=>{e.call(this)}),this._numberOfTicks++,this.events.emit("action"),this.repeats?this._elapsedTime=0:(this._complete=!0,this._running=!1,this._elapsedTime=0,this._onComplete(),this.events.emit("complete"))))}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.events.emit("pause"),this}resume(){return this._running=!0,this.events.emit("resume"),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.events.emit("start"),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this.events.emit("stop"),this}cancel(){this.pause(),this.scene&&(this.scene.cancelTimer(this),this.events.emit("cancel"))}};Yo._MAX_ID=0;let rs=Yo;function Zo(r){return r&&r._dispatchPointerEvents&&r._processPointerToObject}class jl{get events(){return this.object.events}init(t,e,i){this.object=t,this.contains=e,this.active=i}}class qn{constructor(){this._proxyPool=new Qe(()=>new jl,t=>t,100),this._objectToProxy=new Map,this._proxies=[],this._lastFrameObjectToPointers=new Map,this._currentFrameObjectToPointers=new Map}addObject(t,e,i){const s=this._proxyPool.rent(!1);s.init(t,e,i),this._proxies.push(s),this._objectToProxy.set(t,s)}_getProxy(t){const e=this._objectToProxy.get(t);if(e)return e;throw new Error("No PointerTargetProxy for object")}removeObject(t){const e=this._objectToProxy.get(t);if(e){const i=this._proxies.indexOf(e);this._objectToProxy.delete(t),i>-1&&this._proxies.splice(i,1),this._proxyPool.return(e)}}_objectCurrentlyUnderPointer(t,e){return!!(this._currentFrameObjectToPointers.has(t)&&this._currentFrameObjectToPointers.get(t).includes(e))}_objectWasUnderPointer(t,e){return!!(this._lastFrameObjectToPointers.has(t)&&this._lastFrameObjectToPointers.get(t).includes(e))}_entered(t,e){return this._objectCurrentlyUnderPointer(t,e)&&!this._lastFrameObjectToPointers.has(t)}_left(t,e){return!this._currentFrameObjectToPointers.has(t)&&this._objectWasUnderPointer(t,e)}addPointerToObject(t,e){const i=this._objectToProxy.get(t);i&&this._addPointerToProxy(i,e)}_addPointerToProxy(t,e){if(!this._currentFrameObjectToPointers.has(t)){this._currentFrameObjectToPointers.set(t,[e]);return}const i=this._currentFrameObjectToPointers.get(t);this._currentFrameObjectToPointers.set(t,i.concat(e))}dispatchEvents(t,e){const i=new Set(this._lastFrameObjectToPointers.keys()),s=new Set(this._currentFrameObjectToPointers.keys());let n,o,a,h=[];if(e)for(let l=0;l<e.length;l++){const c=e[l],d=this._getProxy(c);h.push(d)}else{const l=new Set(i);for(const c of s)l.add(c);h=Array.from(l)}for(let l=0;l<h.length;l++){const c=h[l];if(Zo(c.object)&&c.object._dispatchPointerEvents(t),i.has(c)||s.has(c)){a=this._processDownAndEmit(t,c),o=this._processUpAndEmit(t,c),n=this._processMoveAndEmit(t,c);const d=[...n.values(),...a.values(),...o.values()];this._processEnterLeaveAndEmit(t,c,d),this._processCancelAndEmit(t,c),this._processWheelAndEmit(t,c)}}}processPointerToObject(t,e){for(let i=0;i<e.length;i++){const s=e[i],n=this._getProxy(s);Zo(s)&&s._processPointerToObject(t);for(const[o,a]of t.currentFramePointerCoords.entries())n.contains(a)&&this._addPointerToProxy(n,o)}}clear(){this._lastFrameObjectToPointers.clear(),this._lastFrameObjectToPointers=new Map(this._currentFrameObjectToPointers),this._currentFrameObjectToPointers.clear()}_processDownAndEmit(t,e){const i=new Map;for(const s of t.currentFrameDown)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerdown",s),t.isDragStart(s.pointerId)&&e.events.emit("pointerdragstart",s)),i.set(s.pointerId,s);return i}_processUpAndEmit(t,e){const i=new Map;for(const s of t.currentFrameUp)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerup",s),t.isDragEnd(s.pointerId)&&e.events.emit("pointerdragend",s)),i.set(s.pointerId,s);return i}_processMoveAndEmit(t,e){const i=new Map;for(const s of t.currentFrameMove)s.active&&e.active()&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointermove",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragmove",s)),i.set(s.pointerId,s);return i}_processEnterLeaveAndEmit(t,e,i){for(const s of i){if(s.active&&e.active()&&this._entered(e,s.pointerId)){e.events.emit("pointerenter",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragenter",s);break}if(s.active&&e.active()&&(this._left(e,s.pointerId)||this._objectCurrentlyUnderPointer(e,s.pointerId)&&s.type==="up")){e.events.emit("pointerleave",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragleave",s);break}}}_processCancelAndEmit(t,e){for(const i of t.currentFrameCancel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,i.pointerId)&&e.events.emit("pointercancel",i)}_processWheelAndEmit(t,e){for(const i of t.currentFrameWheel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,0)&&e.events.emit("pointerwheel",i)}}const Ql={PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerMove:"pointermove",PointerCancel:"pointercancel"};class jo extends Tt{constructor(t){var e,i,s,n;super([],t.name),this.events=new Y,this._token=0,this.logger=F.getInstance(),this.tiles=[],this._rows=[],this._cols=[],this.renderFromTopOfGraphic=!1,this.meshingLookBehind=10,this._collidersDirty=!0,this._oldRotation=0,this._originalOffsets=new WeakMap,this.meshingLookBehind=(e=t.meshingLookBehind)!=null?e:this.meshingLookBehind,this.addComponent(new E),this.addComponent(new H),this.addComponent(new U({type:R.Fixed})),this.addComponent(new Z({onPostDraw:(a,h)=>this.draw(a,h)})),this.addComponent(new Xi((a,h)=>this.debug(a,h),!1)),this.addComponent(new j),this.addComponent(new qt),this.pointer=this.get(qt),this._graphics=this.get(Z),this.transform=this.get(E),this._motion=this.get(H),this.collider=this.get(j),this._composite=this.collider.useCompositeCollider([]),this._composite.compositeStrategy=(i=t.compositeStrategy)!=null?i:"separate",this.transform.pos=(s=t.pos)!=null?s:w.Zero,this._oldPos=this.transform.pos.clone(),this._oldScale=this.transform.scale.clone(),this.renderFromTopOfGraphic=(n=t.renderFromTopOfGraphic)!=null?n:this.renderFromTopOfGraphic,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.rows=t.rows,this.columns=t.columns,this._pointerEventDispatcher=new qn,this.tiles=new Array(this.rows*this.columns),this._rows=new Array(this.rows),this._cols=new Array(this.columns);let o=[];for(let a=0;a<this.columns;a++){for(let h=0;h<this.rows;h++){const l=new Qo({x:a,y:h,map:this});l.map=this,this.tiles[a+h*this.columns]=l,this._pointerEventDispatcher.addObject(l,c=>l.bounds.contains(c.worldPos),()=>!0),o.push(l),this._rows[h]||(this._rows[h]=[]),this._rows[h].push(l)}this._cols[a]=o,o=[]}this._graphics.localBounds=new D({left:0,top:0,right:this.columns*this.tileWidth*this.scale.x,bottom:this.rows*this.tileHeight*this.scale.y})}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(t=this.transform.pos.x)!=null?t:0}set x(t){var e;(e=this.transform)!=null&&e.pos&&(this.get(E).pos=y(t,this.y))}get y(){var t,e;return(e=(t=this.transform)==null?void 0:t.pos.y)!=null?e:0}set y(t){var e;(e=this.transform)!=null&&e.pos&&(this.transform.pos=y(this.x,t))}get z(){var t;return(t=this.transform.z)!=null?t:0}set z(t){this.transform&&(this.transform.z=t)}get rotation(){var t,e;return(e=(t=this.transform)==null?void 0:t.rotation)!=null?e:0}set rotation(t){this.transform&&(t!==this.transform.rotation&&(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.rotation=t)}get scale(){var t,e;return(e=(t=this.transform)==null?void 0:t.scale)!=null?e:w.One}set scale(t){this.transform&&(t!=null&&t.equals(this.transform.scale)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.scale=t)}get pos(){return this.transform.pos}set pos(t){this.transform&&(t!=null&&t.equals(this.transform.pos)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.pos=t)}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}get width(){return this.tileWidth*this.columns*this.scale.x}get height(){return this.tileHeight*this.rows*this.scale.y}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)}_initialize(t){super._initialize(t),this._engine=t}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:w.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}_updateColliders(){this.collider.$colliderRemoved.notifyAll(this._composite),this._composite.clearColliders();const t=[];this._composite=this.collider.useCompositeCollider([]);let e=null;const i=(n,o)=>n&&o?n.top===o.top&&n.bottom===o.bottom&&n.right===o.left:!1,s=(n,o,a=this.meshingLookBehind)=>{if(!n)return!1;for(let h=o.length-1;h>=0;h--){if(a--<0)return!1;const l=o[h];if(i(l,n))return o[h]=l.combine(n),!0}return!1};for(let n=0;n<this.columns;n++){for(let o=0;o<this.rows;o++){const a=this.tiles[n+o*this.columns];if(a.solid)if(a.getColliders().length>0){for(const h of a.getColliders()){const l=this._getOrSetColliderOriginalOffset(h);h.offset=y(a.x*this.tileWidth*this.scale.x,a.y*this.tileHeight*this.scale.y).add(l),h.owner=this,this._composite.addCollider(h)}e&&!s(e,t)&&t.push(e),e=null}else e?e=e.combine(a.defaultGeometry):e=a.defaultGeometry;else e&&!s(e,t)&&t.push(e),e=null}e&&!s(e,t)&&t.push(e),e=null}for(const n of t){const o=rt.Box(n.width,n.height,w.Zero,y(n.left-this.pos.x,n.top-this.pos.y));o.owner=this,this._composite.addCollider(o)}this.collider.update(),this.collider.$colliderAdded.notifyAll(this._composite)}getCompositeCollider(){return this._composite}getTileByIndex(t){var e;return(e=this.tiles[t])!=null?e:null}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const{x:e,y:i}=this._getTileCoordinates(t),s=this.getTile(e,i);return e>=0&&i>=0&&e<this.columns&&i<this.rows&&s?s:null}_getTileCoordinates(t){t=this.transform.applyInverse(t);const e=Math.floor(t.x/this.tileWidth),i=Math.floor(t.y/this.tileHeight);return{x:e,y:i}}getRows(){return this._rows}getColumns(){return this._cols}getOnScreenTiles(){const t=this._engine.screen.getWorldBounds();let e=y(0,0),i=this.transform.coordPlane===ht.Screen?this._engine.screen.getScreenBounds():t;const s=this.get($i);if(s&&this.isInitialized){const m=w.One.sub(s.parallaxFactor);e=this._engine.currentScene.camera.pos.scale(m),i=i.translate(e.negate())}const n=this._getTileCoordinates(i.topLeft),o=this._getTileCoordinates(i.topRight),a=this._getTileCoordinates(i.bottomRight),h=this._getTileCoordinates(i.bottomLeft),l=Math.min(L(n.x,0,this.columns-1),L(o.x,0,this.columns-1)),c=Math.min(L(n.y,0,this.rows-1),L(o.y,0,this.rows-1)),d=Math.max(L(a.x,0,this.columns-1),L(h.x,0,this.columns-1)),_=Math.max(L(a.y,0,this.rows-1),L(h.y,0,this.rows-1)),f=[];for(let m=l;m<=d;m++)for(let p=c;p<=_;p++)f.push(this.getTile(m,p));return f}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===ht.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t)}update(t,e){this._initialize(t),this.onPreUpdate(t,e),this.emit("preupdate",new de(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._pointerEventDispatcher.clear(),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 ue(t,e,this))}draw(t,e){if(!this.isInitialized)return;this.emit("predraw",new Ge(t,e,this));let i,s,n;const o=this.getOnScreenTiles();for(let a=0;a<o.length;a++){const h=o[a],l=h.getGraphicsOffsets();for(i=h.getGraphics(),s=0,n=i.length;s<n;s++){const c=i[s],d=l[s];if(c){En(c)&&(c==null||c.tick(e,this._token));const _=this.renderFromTopOfGraphic?0:c.height-this.tileHeight;c.draw(t,h.x*this.tileWidth+d.x,h.y*this.tileHeight-_+d.y)}}}this.emit("postdraw",new We(t,e,this))}debug(t,e){const{showAll:i,showGrid:s,gridColor:n,gridWidth:o,showSolidBounds:a,solidBoundsColor:h,showColliderGeometry:l}=e.tilemap,{geometryColor:c,geometryLineWidth:d,geometryPointSize:_}=e.collider,f=this.tileWidth*this.columns*this.scale.x,m=this.tileHeight*this.rows*this.scale.y,p=this.pos;if(s||i){for(let x=0;x<this.rows+1;x++){const v=y(0,x*this.tileHeight*this.scale.y);t.debug.drawLine(p.add(v),p.add(y(f,v.y)),{color:n,lineWidth:o})}for(let x=0;x<this.columns+1;x++){const v=y(x*this.tileWidth*this.scale.x,0);t.debug.drawLine(p.add(v),p.add(y(v.x,m)),{color:n,lineWidth:o})}}if(i||a||l){const x=this._composite.getColliders();t.save(),t.translate(this.pos.x,this.pos.y),t.scale(this.scale.x,this.scale.y);for(const v of x){const g=v.localBounds,b=v.worldPos.sub(this.pos);a&&t.debug.drawRect(b.x,b.y,g.width,g.height,{color:h})}if(t.restore(),l)for(const v of x)v.debug(t,c,{lineWidth:d,pointSize:_})}if(i||a){if(t.save(),t.z=999,a)for(let x=0;x<this.tiles.length;x++)this.tiles[x].bounds.debug(t);t.restore()}}}class Qo{constructor(t){this._posDirty=!1,this.events=new Y,this._solid=!1,this._graphics=[],this._offsets=[],this._colliders=[],this.data=new Map;var e,i;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=(e=t.solid)!=null?e:this.solid,this._graphics=(i=t.graphics)!=null?i:[],this._recalculate()}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;(e=this.map)==null||e.flagCollidersDirty(),this._solid=t}getGraphics(){return this._graphics}getGraphicsOffsets(){return this._offsets}addGraphic(t,e){this._graphics.push(t),e!=null&&e.offset?this._offsets.push(e.offset):this._offsets.push(w.Zero)}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&(this._graphics.splice(e,1),this._offsets.splice(e,1))}clearGraphics(){this._graphics.length=0,this._offsets.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()}flagDirty(){this._posDirty=!0}_recalculate(){const t=this.map.pos.add(y(this.x*this.map.tileWidth,this.y*this.map.tileHeight));this._geometry=new D(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(y(this.x*this._width,this.y*this._height)),this._bounds=new D(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 w(this._pos.x+this._width/2,this._pos.y+this._height/2)}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){e?this.events.off(t,e):this.events.off(t)}}class Si extends Rt{constructor(t){super(),this.elevation=0,this.columns=t.columns,this.rows=t.rows,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight}}class Jo extends Tt{constructor(t,e,i,s){super([new E,new Z({offset:i!=null?i:w.Zero,onPostDraw:(_,f)=>this.draw(_,f)}),new Si(s)]),this.solid=!1,this.events=new Y,this._tileBounds=new D,this._graphics=[],this._colliders=[],this.data=new Map,this.x=t,this.y=e,this.map=s,this._transform=this.get(E),this._isometricEntityComponent=this.get(Si);const n=this.map.tileWidth/2,o=this.map.tileHeight/2,a=(this.x-this.y)*n,h=(this.x+this.y)*o;this._transform.pos=y(a,h),this._isometricEntityComponent.elevation=s.elevation,this._gfx=this.get(Z),this._gfx.isVisible=!1;const l=this.map.tileWidth,c=this.map.tileHeight,d=y(0,this.map.renderFromTopOfGraphic?c:0);this._gfx.localBounds=this._tileBounds=new D({left:-l/2,top:-c,right:l/2,bottom:c}).translate(d)}getGraphics(){return this._graphics}addGraphic(t,e){this._graphics.push(t),this._gfx.isVisible=this.map.isVisible,this._gfx.opacity=this.map.opacity,e!=null&&e.offset&&(this._gfx.offset=e.offset),this._gfx.localBounds=this._recalculateBounds()}_recalculateBounds(){let t=this._tileBounds.clone();for(const e of this._graphics){const i=y(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.isVisible=!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(y(this.x,this.y))}get center(){return this.pos.add(y(0,this.map.tileHeight/2))}draw(t,e){const i=this.map.tileWidth/2;t.save(),t.translate(-i,0);for(const s of this._graphics)s.draw(t,this.map.graphicsOffset.x,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:s.height-this.map.tileHeight));t.restore()}}class Jl extends Tt{constructor(t){super([new E,new U({type:R.Fixed}),new j,new qt,new Xi((c,d)=>this.debug(c,d),!1)],t.name),this.elevation=0,this.isVisible=!0,this.opacity=1,this.renderFromTopOfGraphic=!1,this.graphicsOffset=y(0,0),this._collidersDirty=!1,this._originalOffsets=new WeakMap;const{pos:e,tileWidth:i,tileHeight:s,columns:n,rows:o,renderFromTopOfGraphic:a,graphicsOffset:h,elevation:l}=t;this.transform=this.get(E),e&&(this.transform.pos=e),this.collider=this.get(j),this.collider&&this.collider.set(this._composite=new nt([])),this.pointer=this.get(qt),this.renderFromTopOfGraphic=a!=null?a:this.renderFromTopOfGraphic,this.graphicsOffset=h!=null?h:this.graphicsOffset,this.elevation=l!=null?l:this.elevation,this.tileWidth=i,this.tileHeight=s,this.columns=n,this.rows=o,this._pointerEventDispatcher=new qn,this.tiles=new Array(n*o);for(let c=0;c<o;c++)for(let d=0;d<n;d++){const _=new Jo(d,c,this.graphicsOffset,this);this.tiles[d+c*n]=_,this.addChild(_),this._pointerEventDispatcher.addObject(_,f=>this.getTileByPoint(f.worldPos)===_,()=>!0)}this.pointer.localBounds=D.fromDimension(i*n*this.transform.scale.x,s*o*this.transform.scale.y,y(.5,0))}get visible(){return this.isVisible}set visible(t){this.isVisible=t}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===ht.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t,this.tiles)}update(){this._collidersDirty&&(this.updateColliders(),this._collidersDirty=!1),this._pointerEventDispatcher.clear()}flagCollidersDirty(){this._collidersDirty=!0}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:w.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}updateColliders(){this._composite.clearColliders();const t=this.get(E).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(y(e.x,e.y)).sub(t).add(s).sub(y(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 y(~~((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,s=(t.x-t.y)*e,n=(t.x+t.y)*i;return y(s,n).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(E).z;i>t&&(t=i)}return t}debug(t,e){const{showAll:i,showPosition:s,positionColor:n,positionSize:o,showGrid:a,gridColor:h,gridWidth:l,showColliderGeometry:c}=e.isometric,{geometryColor:d,geometryLineWidth:_,geometryPointSize:f}=e.collider;if(t.save(),t.z=this._getMaxZIndex()+.5,i||a){for(let m=0;m<this.rows+1;m++){const p=this.tileToWorld(y(0,m)),x=this.tileToWorld(y(this.columns,m));t.debug.drawLine(p,x,{color:h,lineWidth:l})}for(let m=0;m<this.columns+1;m++){const p=this.tileToWorld(y(m,0)),x=this.tileToWorld(y(m,this.rows));t.debug.drawLine(p,x,{color:h,lineWidth:l})}}if(i||s)for(const m of this.tiles)t.debug.drawCircle(this.tileToWorld(y(m.x,m.y)),o,n);if(i||c){for(const m of this.tiles)if(m.solid)for(const p of m.getColliders())p.debug(t,d,{lineWidth:_,pointSize:f})}t.restore()}}class Xn extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Update,this.query=this.world.query([E,Si,Mt])}update(){let t,e,i;for(let s=0;s<this.query.entities.length;s++){const n=this.query.entities[s];if(t=n.get(E),e=n.get(Si),i=n.get(Mt),i.paused)continue;const a=Math.max(e.columns*e.tileWidth,e.rows*e.tileHeight)*e.elevation+t.pos.y;t.z=a}}}Xn.priority=Zt.Lower;class Ko{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new ea(t))}lockToActorAxis(t,e){this.camera.addStrategy(new ia(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new sa(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new na(t,e))}limitCameraBounds(t){this.camera.addStrategy(new ra(t))}}var ta=(r=>(r[r.X=0]="X",r[r.Y=1]="Y",r))(ta||{});class ea{constructor(t){this.target=t,this.action=(e,i,s,n)=>e.center}}class ia{constructor(t,e){this.target=t,this.axis=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus();return this.axis===0?new w(a.x,h.y):new w(h.x,a.y)}}}class sa{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(s,n,o,a)=>{const h=s.center;let l=n.getFocus(),c=n.vel.clone();const d=h.sub(l).scale(this.cameraElasticity);c=c.add(d);const _=c.scale(-1).scale(this.cameraFriction);return c=c.add(_),l=l.add(c),l}}}class na{constructor(t,e){this.target=t,this.radius=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus(),l=a.sub(h),c=l.magnitude;if(c>=this.radius){const d=c-this.radius;return h.add(l.normalize().scale(d))}return h}}}class ra{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(e,i,s,n)=>{const o=i.getFocus();this.boundSizeChecked||((e.bottom-e.top<s.drawHeight||e.right-e.left<s.drawWidth)&&F.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let a=o.x,h=o.y;return o.x<e.left+s.halfDrawWidth?a=e.left+s.halfDrawWidth:o.x>e.right-s.halfDrawWidth&&(a=e.right-s.halfDrawWidth),o.y<e.top+s.halfDrawHeight?h=e.top+s.halfDrawHeight:o.y>e.bottom-s.halfDrawHeight&&(h=e.bottom-s.halfDrawHeight),y(a,h)}}}const Kl={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class oa{constructor(){this.events=new Y,this.transform=tt.identity(),this.inverse=tt.identity(),this._cameraStrategies=[],this.strategy=new Ko(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this._angularVelocity=0,this._posChanged=!1,this._pos=new ce(w.Zero,()=>{this._posChanged=!0}),this.drawPos=this.pos.clone(),this._oldPos=this.pos.clone(),this.vel=w.Zero,this.acc=w.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._legacyZoomEasing=Dt.EaseInOutCubic,this._useLegacyZoom=!1,this._zoomEasing=Es,this._legacyEasing=Dt.EaseInOutCubic,this._useLegacyEasing=!1,this._easing=Es,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1,this._snapPos=y(0,0)}get strategies(){return this._cameraStrategies}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._posChanged=!0,this._pos=new ce(t,()=>{this._posChanged=!0})}hasChanged(){return this._posChanged}get x(){return this.pos.x}set x(t){!this._follow&&!this._cameraMoving&&(this.pos=y(t,this.pos.y))}get y(){return this.pos.y}set y(t){!this._follow&&!this._cameraMoving&&(this.pos=y(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=y(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=y(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=y(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=y(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=Dt.EaseInOutCubic){if(typeof i!="function")throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise(s=>{this._lerpResolve=s}),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,Ie(i)?this._legacyEasing=i: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=Dt.EaseInOutCubic){if(this._zoomPromise=new Promise(s=>{this._zoomResolve=s}),e)this._isZooming=!0,Ie(i)?this._legacyZoomEasing=i:this._easing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t;else return this._isZooming=!1,this.zoom=t,Promise.resolve(!0);return this._zoomPromise}get viewport(){return this._viewport?this._viewport:new D(0,0,0,0)}addStrategy(...t){this._cameraStrategies.push(...t)}setStrategies(t){this._cameraStrategies=[...t]}removeStrategy(t){qe(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.events.emit("preupdate",new de(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.events.emit("postupdate",new ue(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=y(e.width/2,e.height/2);if(!this._engine.loadingComplete){const s=this._screen.peekResolution();s&&(i=y(s.width/2,s.height/2))}this._halfWidth=i.x,this._halfHeight=i.y,this._posChanged||(this.pos=i),this.pos.clone(this.drawPos),this.updateTransform(this.pos),this.runStrategies(t,t.clock.elapsed()),this.updateViewport(),this.updateTransform(this.pos),this.pos.clone(this._oldPos),this.onInitialize(t),this.events.emit("initialize",new Ve(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 D(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.clone(this._oldPos),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){let i=this.zoom;if(this._useLegacyZoom){const s=this._legacyZoomEasing;i=s(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration)}else i=X(this._zoomStart,this._zoomEnd,this._zoomEasing(this._currentZoomTime/this._zoomDuration));this.zoom=i,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){let i=this.pos;this._useLegacyEasing?i=Dt.CreateVectorEasingFunction(this._legacyEasing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration):(i.x=X(this._lerpStart.x,this._lerpEnd.x,this._easing(this._currentLerpTime/this._lerpDuration)),i.y=X(this._lerpStart.y,this._lerpEnd.y,this._easing(this._currentLerpTime/this._lerpDuration))),this.pos=i,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const i=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(i)}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=(Math.random()*this._shakeMagnitudeX|0)+1,this._yShake=(Math.random()*this._shakeMagnitudeY|0)+1),this.runStrategies(t,e),this.updateViewport(),this.updateTransform(this.pos),this._postupdate(t,e),this._posChanged=!1}draw(t){if(this.pos.clone(this.drawPos),this._engine.fixedUpdateTimestep){const e=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep,i=this.pos.scale(e).add(this._oldPos.scale(1-e));i.clone(this.drawPos),this.updateTransform(i)}if(t.snapToPixel){const e=this.drawPos.clone(this._snapPos);e.x=~~(e.x+B*q(e.x)),e.y=~~(e.y+B*q(e.y)),e.clone(this.drawPos),this.updateTransform(e)}t.multiply(this.transform)}updateTransform(t){const e=this._screen.resolution.width/this.zoom,i=this._screen.resolution.height/this.zoom,s=y(-t.x+e/2+this._xShake,-t.y+i/2+this._yShake);this.transform.reset(),this.transform.scale(this.zoom,this.zoom),this.transform.translate(e/2,i/2),this.transform.rotate(this.rotation),this.transform.translate(-e/2,-i/2),this.transform.translate(s.x,s.y),this.transform.inverse(this.inverse)}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}const tc={ExitTrigger:"exit",EnterTrigger:"enter"};class aa extends Bt{constructor(t){var e,i,s,n;super({...t}),this.events=new Y,this.filter=(e=t.filter)!=null?e:()=>!0,this.repeat=(i=t.repeat)!=null?i:-1,this.action=(s=t.action)!=null?s:()=>{},this.target=t.target,this.graphics.isVisible=(n=t.visible)!=null?n:!1,this.body.collisionType=R.Passive,this.events.on("collisionstart",({other:o})=>{this._matchesTarget(o.owner)&&(this.events.emit("enter",new tn(this,o.owner)),this._dispatchAction(o.owner),this.repeat===0&&this.kill())}),this.events.on("collisionend",({other:o})=>{this._matchesTarget(o.owner)&&this.events.emit("exit",new en(this,o.owner))})}_matchesTarget(t){return this.filter(t)&&(this.target===void 0||this.target===t)}_dispatchAction(t){this.repeat!==0&&(this.action.call(this,t),this.repeat--)}}class $n extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Draw,this.query=this.world.query([E])}initialize(t,e){this._graphicsContext=e.engine.graphicsContext,this._camera=e.camera,this._engine=e.engine,this._collisionSystem=t.systemManager.get(is)}update(){var t;if(!this._engine.isDebug)return;const e=this._engine.debug.filter;let i,s;const n=this._engine.debug.entity;let o;const a=this._engine.debug.transform;let h;const l=this._engine.debug.motion;let c;const d=this._engine.debug.collider,_=this._engine.debug.physics;let f,m;const p=this._engine.debug.body,x=this._engine.debug.camera;for(let v=0;v<this.query.entities.length;v++){const g=this.query.entities[v];if(g.hasTag("offscreen")||g instanceof Ki||e.useFilter&&(!(e.ids.length===0||e.ids.includes(g.id))||!(e.nameQuery===""||g.name.includes(e.nameQuery))))continue;let b=w.Zero;const S=y(0,16);if(i=g.id,s=g.name,o=g.get(E),this._pushCameraTransform(o),this._graphicsContext.save(),o.coordPlane===ht.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),this._applyTransform(g),o&&((a.showAll||a.showPosition)&&this._graphicsContext.debug.drawPoint(w.Zero,{size:4,color:a.positionColor}),(a.showAll||a.showPositionLabel)&&(this._graphicsContext.debug.drawText(`pos${o.pos.toString(2)}`,b),b=b.add(S)),(a.showAll||a.showZIndex)&&(this._graphicsContext.debug.drawText(`z(${o.z.toFixed(1)})`,b),b=b.add(S)),(n.showAll||n.showId)&&(this._graphicsContext.debug.drawText(`id(${i}) ${g.parent?"child of id("+((t=g.parent)==null?void 0:t.id)+")":""}`,b),b=b.add(S)),(n.showAll||n.showName)&&(this._graphicsContext.debug.drawText(`name(${s})`,b),b=b.add(S)),(a.showAll||a.showRotation)&&(this._graphicsContext.debug.drawLine(w.Zero,w.fromAngle(o.rotation).scale(20).add(w.Zero),{color:a.rotationColor,lineWidth:2}),this._graphicsContext.debug.drawText(`rot deg(${ur(o.rotation).toFixed(2)})`,b),b=b.add(S)),(a.showAll||a.showScale)&&this._graphicsContext.debug.drawLine(w.Zero,o.scale,{color:a.scaleColor,lineWidth:2})),f=g.get(Xi),f&&(f.useTransform||this._graphicsContext.restore(),f.draw(this._graphicsContext,this._engine.debug),f.useTransform||(this._graphicsContext.save(),this._applyTransform(g))),m=g.get(U),m&&((p.showAll||p.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group name(${m.group.name}))`,b),b=b.add(S),this._graphicsContext.debug.drawText(` mask(0x${(m.group.mask>>>0).toString(16)})`,b),b=b.add(S),this._graphicsContext.debug.drawText(` category(0x${(m.group.category>>>0).toString(16)})`,b),b=b.add(S)),(p.showAll||p.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${m.collisionType})`,b),b=b.add(S)),(p.showAll||p.showMass)&&(this._graphicsContext.debug.drawText(`mass(${m.mass})`,b),b=b.add(S)),(p.showAll||p.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${m.sleepMotion.toFixed(3)})`,b),b=b.add(S)),(p.showAll||p.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${m.canSleep?m.isSleeping:"cant sleep"})`,b),b=b.add(S))),this._graphicsContext.restore(),this._graphicsContext.save(),o.coordPlane===ht.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),h=g.get(H),h&&((l.showAll||l.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${h.vel.toString(2)}`,b.add(o.globalPos)),this._graphicsContext.debug.drawLine(o.globalPos,o.globalPos.add(h.vel),{color:l.velocityColor,lineWidth:2}),b=b.add(S)),(l.showAll||l.showAcceleration)&&this._graphicsContext.debug.drawLine(o.globalPos,o.globalPos.add(h.acc),{color:l.accelerationColor,lineWidth:2})),c=g.get(j),c){const A=c.get();if((d.showAll||d.showGeometry)&&A&&A.debug(this._graphicsContext,d.geometryColor,{lineWidth:d.geometryLineWidth,pointSize:d.geometryPointSize}),d.showAll||d.showBounds){if(A instanceof nt){const M=A.getColliders();for(const C of M){const z=C.bounds,O=y(z.left,z.top);this._graphicsContext.debug.drawRect(O.x,O.y,z.width,z.height,{color:d.boundsColor,dashed:!0}),(d.showAll||d.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${C.owner.id})`,O)}c.bounds.debug(this._graphicsContext,{color:d.boundsColor,dashed:!0})}else if(A){const M=c.bounds,C=y(M.left,M.top);this._graphicsContext.debug.drawRect(C.x,C.y,M.width,M.height,{color:d.boundsColor,dashed:!0}),(d.showAll||d.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${c.owner.id})`,C)}}}this._graphicsContext.restore(),this._popCameraTransform(o)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(_.showAll||_.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),_.showAll||_.showCollisionContacts||_.showCollisionNormals)for(const[v,g]of this._engine.debug.stats.currFrame.physics.contacts){if(_.showAll||_.showCollisionContacts)for(const b of g.points)this._graphicsContext.debug.drawPoint(b,{size:_.contactSize,color:_.collisionContactColor});if(_.showAll||_.showCollisionNormals)for(const b of g.points)this._graphicsContext.debug.drawLine(b,g.normal.scale(30).add(b),{color:_.collisionNormalColor})}this._graphicsContext.restore(),x&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(x.showAll||x.showFocus)&&this._graphicsContext.debug.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())}postupdate(t,e){this._engine.isDebug&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext),It.flush(this._graphicsContext),this._graphicsContext.restore())}_applyTransform(t){const e=t.getAncestors();for(const i of e){const s=i==null?void 0:i.get(E);s&&(this._graphicsContext.translate(s.pos.x,s.pos.y),this._graphicsContext.scale(s.scale.x,s.scale.y),this._graphicsContext.rotate(s.rotation))}}_pushCameraTransform(t){t.coordPlane===ht.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===ht.World&&this._graphicsContext.restore()}}$n.priority=Zt.Lowest;class os extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Update,this._graphicsHashGrid=new Bn({size:100}),this._graphics=[],this._entityToPointer=new Map,this._pointerEventDispatcher=new qn,this.overrideUseColliderShape=!1,this.overrideUseGraphicsBounds=!1,this._sortedTransforms=[],this._sortedEntities=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this.query=this.world.query([E,qt]),this.query.entityAdded$.subscribe(e=>{const i=e.get(E),s=e.get(qt);this._pointerEventDispatcher.addObject(e,o=>s&&s.localBounds?s.localBounds.transform(i.get().matrix).contains(i.coordPlane===ht.World?o.worldPos:o.screenPos):!1,()=>e.isActive),this._entityToPointer.set(e,s);const n=e.get(Z);n&&(this._graphics.push(n),this._graphicsHashGrid.track(n)),this._sortedTransforms.push(i),this._sortedEntities.push(i.owner),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{this._pointerEventDispatcher.removeObject(e);const i=e.get(E);this._entityToPointer.delete(e);const s=e.get(Z);if(s){const o=this._graphics.indexOf(s);o>-1&&this._graphics.splice(o,1),this._graphicsHashGrid.untrack(s)}i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const n=this._sortedTransforms.indexOf(i);n>-1&&(this._sortedTransforms.splice(n,1),this._sortedEntities.splice(n,1))})}initialize(t,e){this._engine=e.engine,this._scene=e}preupdate(){this._scene.camera.hasChanged()&&this._scene.camera.updateTransform(this._scene.camera.pos),this._receivers=[this._engine.input.pointers,this._scene.input.pointers],this._engineReceiver=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)}update(){this._graphicsHashGrid.update(this._graphics);for(const[t,e]of this._engineReceiver.currentFramePointerCoords.entries()){const i=this._scene.physics.query(e.worldPos);for(let n=0;n<i.length;n++){const o=i[n],a=this._entityToPointer.get(o.owner);a&&(a.useColliderShape||this.overrideUseColliderShape)&&o.contains(e.worldPos)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}const s=this._graphicsHashGrid.query(e.worldPos);for(let n=0;n<s.length;n++){const o=s[n],a=this._entityToPointer.get(o.owner);a&&(a.useGraphicsBounds||this.overrideUseGraphicsBounds)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}}this._pointerEventDispatcher.processPointerToObject(this._engineReceiver,this._sortedEntities),this._pointerEventDispatcher.dispatchEvents(this._engineReceiver,this._sortedEntities),this._receivers.forEach(t=>t.update()),this._pointerEventDispatcher.clear(),this._receivers.forEach(t=>t.clear())}}os.priority=Zt.Higher;class Yn extends Pt{constructor(t){super(),this.world=t,this.systemType=At.Update,this._actions=[],this.query=this.world.query([re,Mt]),this.query.entityAdded$.subscribe(e=>this._actions.push(e.get(re))),this.query.entityRemoved$.subscribe(e=>{const i=e.get(re),s=this._actions.indexOf(i);s>-1&&this._actions.splice(s,1)})}update(t){var e;for(let i=0;i<this._actions.length;i++){const s=this._actions[i];(e=s.owner)!=null&&e.get(Mt).paused||s.update(t)}}}Yn.priority=Zt.Higher;class as{constructor(){this.events=new Y,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,this._enabled=!0}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}toggleEnabled(t){this._enabled=t}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(s=>typeof s!==void 0).length,i=t.buttons.filter(s=>typeof s!==void 0).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._enableAndUpdate(),this.events.once(t,e)}off(t,e){this._enableAndUpdate(),this.events.off(t,e)}update(){var t,e;if(!this.enabled||!this.supported||!this._enabled)return;this.init();const i=this._navigator.getGamepads();for(let s=0;s<i.length;s++){if(i[s]){const o=this.at(s);!this.at(s).connected&&this._isGamepadValid(i[s])&&(o.events.pipe(this.events),this.events.emit("connect",new Vs(s,this.at(s)))),this.at(s).connected=!0}else{const o=this.at(s);o.connected&&(this.events.emit("disconnect",new qs(s,o)),o.events.unpipe(this.events)),o.connected=!1;continue}if(this.at(s).update(),i[s].timestamp&&i[s].timestamp===this._gamePadTimeStamps[s])continue;this._gamePadTimeStamps[s]=i[s].timestamp,this.at(s).navigatorGamepad=i[s];const n=i[s];if(n){for(let o=0;o<n.buttons.length;o++){const a=n.buttons[o],h=a==null?void 0:a.value;h!==((t=this._oldPads[s])==null?void 0:t.getButton(o))&&(a!=null&&a.pressed?(this.at(s).updateButton(o,h),this.at(s).events.emit("button",new Xs(o in Zn?o:-1,o,h,this.at(s)))):this.at(s).updateButton(o,0))}for(let o=0;o<n.axes.length;o++){const a=n.axes[o];a!==((e=this._oldPads[s])==null?void 0:e.getAxes(o))&&(this.at(s).updateAxes(o,a),this.at(s).events.emit("axis",new $s(o,a,this.at(s))))}}this._oldPads[s]=this._clonePad(i[s])}}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 hs),this._oldPads.push(new hs);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 hs;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}}as.MinAxisMoveThreshold=.05;class hs{constructor(){this.events=new Y,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!!this._buttonsUp[t]}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<as.MinAxisMoveThreshold?0:e}updateButton(t,e){e===0&&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 Zn=(r=>(r[r.Unknown=-1]="Unknown",r[r.Face1=0]="Face1",r[r.Face2=1]="Face2",r[r.Face3=2]="Face3",r[r.Face4=3]="Face4",r[r.LeftBumper=4]="LeftBumper",r[r.RightBumper=5]="RightBumper",r[r.LeftTrigger=6]="LeftTrigger",r[r.RightTrigger=7]="RightTrigger",r[r.Select=8]="Select",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick",r[r.DpadUp=12]="DpadUp",r[r.DpadDown=13]="DpadDown",r[r.DpadLeft=14]="DpadLeft",r[r.DpadRight=15]="DpadRight",r[r.CenterButton=16]="CenterButton",r[r.MiscButton1=17]="MiscButton1",r))(Zn||{}),ha=(r=>(r[r.LeftStickX=0]="LeftStickX",r[r.LeftStickY=1]="LeftStickY",r[r.RightStickX=2]="RightStickX",r[r.RightStickY=3]="RightStickY",r))(ha||{});class la{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)}}function ca(){try{const r=()=>{};window.top.addEventListener("blur",r),window.top.removeEventListener("blur",r)}catch(r){return!0}return!1}function da(){return window!==window.top}function ua(){let r;return ca()?(r=window,F.getInstance().warnOnce("Excalibur might be in a cross-origin iframe, in order to receive keyboard events it must be in focus")):da()?(r=window,F.getInstance().warnOnce("Excalibur might be in a iframe, in order to receive keyboard events it must be in focus")):r=window.top,r}var _a=(r=>(r.Backquote="Backquote",r.Backslash="Backslash",r.BracketLeft="BracketLeft",r.BracketRight="BracketRight",r.Comma="Comma",r.Key0="Digit0",r.Key1="Digit1",r.Key2="Digit2",r.Key3="Digit3",r.Key4="Digit4",r.Key5="Digit5",r.Key6="Digit6",r.Key7="Digit7",r.Key8="Digit8",r.Key9="Digit9",r.Digit0="Digit0",r.Digit1="Digit1",r.Digit2="Digit2",r.Digit3="Digit3",r.Digit4="Digit4",r.Digit5="Digit5",r.Digit6="Digit6",r.Digit7="Digit7",r.Digit8="Digit8",r.Digit9="Digit9",r.Equal="Equal",r.IntlBackslash="IntlBackslash",r.IntlRo="IntlRo",r.IntlYen="IntlYen",r.A="KeyA",r.B="KeyB",r.C="KeyC",r.D="KeyD",r.E="KeyE",r.F="KeyF",r.G="KeyG",r.H="KeyH",r.I="KeyI",r.J="KeyJ",r.K="KeyK",r.L="KeyL",r.M="KeyM",r.N="KeyN",r.O="KeyO",r.P="KeyP",r.Q="KeyQ",r.R="KeyR",r.S="KeyS",r.T="KeyT",r.U="KeyU",r.V="KeyV",r.W="KeyW",r.X="KeyX",r.Y="KeyY",r.Z="KeyZ",r.KeyA="KeyA",r.KeyB="KeyB",r.KeyC="KeyC",r.KeyD="KeyD",r.KeyE="KeyE",r.KeyF="KeyF",r.KeyG="KeyG",r.KeyH="KeyH",r.KeyI="KeyI",r.KeyJ="KeyJ",r.KeyK="KeyK",r.KeyL="KeyL",r.KeyM="KeyM",r.KeyN="KeyN",r.KeyO="KeyO",r.KeyP="KeyP",r.KeyQ="KeyQ",r.KeyR="KeyR",r.KeyS="KeyS",r.KeyT="KeyT",r.KeyU="KeyU",r.KeyV="KeyV",r.KeyW="KeyW",r.KeyX="KeyX",r.KeyY="KeyY",r.KeyZ="KeyZ",r.Minus="Minus",r.Period="Period",r.Quote="Quote",r.Semicolon="Semicolon",r.Slash="Slash",r.AltLeft="AltLeft",r.AltRight="AltRight",r.Alt="Alt",r.AltGraph="AltGraph",r.Backspace="Backspace",r.CapsLock="CapsLock",r.ContextMenu="ContextMenu",r.ControlLeft="ControlLeft",r.ControlRight="ControlRight",r.Enter="Enter",r.MetaLeft="MetaLeft",r.MetaRight="MetaRight",r.ShiftLeft="ShiftLeft",r.ShiftRight="ShiftRight",r.Space="Space",r.Tab="Tab",r.Convert="Convert",r.KanaMode="KanaMode",r.NonConvert="NonConvert",r.Delete="Delete",r.End="End",r.Help="Help",r.Home="Home",r.Insert="Insert",r.PageDown="PageDown",r.PageUp="PageUp",r.Up="ArrowUp",r.Down="ArrowDown",r.Left="ArrowLeft",r.Right="ArrowRight",r.ArrowUp="ArrowUp",r.ArrowDown="ArrowDown",r.ArrowLeft="ArrowLeft",r.ArrowRight="ArrowRight",r.NumLock="NumLock",r.Numpad0="Numpad0",r.Numpad1="Numpad1",r.Numpad2="Numpad2",r.Numpad3="Numpad3",r.Numpad4="Numpad4",r.Numpad5="Numpad5",r.Numpad6="Numpad6",r.Numpad7="Numpad7",r.Numpad8="Numpad8",r.Numpad9="Numpad9",r.Num0="Numpad0",r.Num1="Numpad1",r.Num2="Numpad2",r.Num3="Numpad3",r.Num4="Numpad4",r.Num5="Numpad5",r.Num6="Numpad6",r.Num7="Numpad7",r.Num8="Numpad8",r.Num9="Numpad9",r.NumAdd="NumpadAdd",r.NumpadAdd="NumpadAdd",r.NumDecimal="NumpadDecimal",r.NumpadDecimal="NumpadDecimal",r.NumDivide="NumpadDivide",r.NumpadDivide="NumpadDivide",r.NumEnter="NumpadEnter",r.NumpadEnter="NumpadEnter",r.NumMultiply="NumpadMultiply",r.NumpadMultiply="NumpadMultiply",r.NumSubtract="NumpadSubtract",r.NumpadSubtract="NumpadSubtract",r.Esc="Escape",r.Escape="Escape",r.F1="F1",r.F2="F2",r.F3="F3",r.F4="F4",r.F5="F5",r.F6="F6",r.F7="F7",r.F8="F8",r.F9="F9",r.F10="F10",r.F11="F11",r.F12="F12",r.F13="F13",r.F14="F14",r.F15="F15",r.F16="F16",r.F17="F17",r.F18="F18",r.F19="F19",r.F20="F20",r.PrintScreen="PrintScreen",r.ScrollLock="ScrollLock",r.Pause="Pause",r.Unidentified="Unidentified",r))(_a||{});class Ti extends k{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class fa{constructor(){this.events=new Y,this._enabled=!0,this._keys=[],this._keysUp=[],this._keysDown=[],this._releaseAllKeys=t=>{for(const e of this._keys){const i=new Ti(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=>{if(!this._enabled)return;!t.metaKey&&(this._keys.includes("MetaLeft")||this._keys.includes("MetaRight"))&&this._releaseAllKeys(t);const e=t.code;if(this._keys.indexOf(e)===-1){this._keys.push(e),this._keysDown.push(e);const i=new Ti(e,t.key,t);this.events.emit("down",i),this.events.emit("press",i)}},this._handleKeyUp=t=>{if(!this._enabled)return;const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new Ti(e,t.key,t);this.events.emit("up",s),this.events.emit("release",s),t.key==="Meta"&&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?typeof e=="function"&&(e=e()):e=ua(),i&&e.focus(),e.addEventListener("blur",()=>{this._keys.length=0}),e.addEventListener("keyup",this._handleKeyUp),e.addEventListener("keydown",this._handleKeyDown)}toggleEnabled(t){this._enabled=t}clear(){this._keysDown.length=0,this._keysUp.length=0,this._keys.length=0}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.events.emit("hold",new Ti(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._enabled?this._keysDown.indexOf(t)>-1:!1}isHeld(t){return this._enabled?this._keys.indexOf(t)>-1:!1}wasReleased(t){return this._enabled?this._keysUp.indexOf(t)>-1:!1}triggerEvent(t,e,i){t==="down"&&this._handleKeyDown(new KeyboardEvent("keydown",{code:e,key:i!=null?i:null})),t==="up"&&this._handleKeyUp(new KeyboardEvent("keyup",{code:e,key:i!=null?i:null}))}}class Ai{constructor(t,e,i,s,n,o){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=o,this.active=!0}cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}}class ga{constructor(t,e,i,s,n,o,a,h,l,c,d,_){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=o,this.index=a,this.deltaX=h,this.deltaY=l,this.deltaZ=c,this.deltaMode=d,this.ev=_,this.active=!0}cancel(){this.active=!1}}class jn{constructor(){this.events=new Y,this.lastPagePos=w.Zero,this.lastScreenPos=w.Zero,this.lastWorldPos=w.Zero,this._onPointerMove=t=>{this.lastPagePos=new w(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new w(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new w(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new w(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new w(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new w(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)}_updateWorldPosition(t){const e=Ne.fromPagePosition(this.lastPagePos,t);this.lastScreenPos=e.screenPos,this.lastWorldPos=e.worldPos}}var Pi=(r=>(r.Pixel="Pixel",r.Line="Line",r.Page="Page",r))(Pi||{}),Me=(r=>(r[r.NoButton=-1]="NoButton",r[r.Left=0]="Left",r[r.Middle=1]="Middle",r[r.Right=2]="Right",r[r.Unknown=3]="Unknown",r))(Me||{}),ge=(r=>(r.Left="Left",r.Middle="Middle",r.Right="Right",r.Unknown="Unknown",r.NoButton="NoButton",r))(ge||{}),pe=(r=>(r.Touch="Touch",r.Mouse="Mouse",r.Pen="Pen",r.Unknown="Unknown",r))(pe||{});function ec(r){return globalThis.TouchEvent&&r instanceof globalThis.TouchEvent}function ic(r){return globalThis.PointerEvent&&r instanceof globalThis.PointerEvent}class ls{constructor(t,e){this.target=t,this.engine=e,this.events=new Y,this.primary=new jn,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._enabled=!0,this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}toggleEnabled(t){this._enabled=t}recreate(t,e){const i=new ls(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 jn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return this._enabled&&(e=this.currentFramePointerDown.get(t))!=null?e:!1}wasDown(t){var e;return this._enabled&&(e=this.lastFramePointerDown.get(t))!=null?e:!1}isDragging(t){return this._enabled?this.isDown(t):!1}isDragStart(t){return this._enabled?this.isDown(t)&&!this.wasDown(t):!1}isDragEnd(t){return this._enabled?!this.isDown(t)&&this.wasDown(t):!1}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){if(!t.active)continue;this.emit("down",t),this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){if(!t.active)continue;this.emit("up",t),this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){if(!t.active)continue;this.emit("move",t),this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){if(!t.active)continue;this.emit("cancel",t),this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)t.active&&(this.emit("pointerwheel",t),this.emit("wheel",t),this.primary.emit("pointerwheel",t),this.primary.emit("wheel",t));if(this.engine.currentScene.camera.hasChanged())for(const t of this._pointers)t._updateWorldPosition(this.engine)}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;if(this.engine.isDisposed())return;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===si.All||this.engine.pageScrollPreventionMode===si.Canvas)};if("onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,i):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel,i):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,i),((e=t==null?void 0:t.grabWindowFocus)!=null?e:!0)&&(ca()||da())){const n=()=>{window.focus()};window.PointerEvent?this.target.addEventListener("pointerdown",n):(this.target.addEventListener("touchstart",n),this.target.addEventListener("mousedown",n))}}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):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const i=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort((s,n)=>s-n).findIndex(s=>s===t);return this._activeNativePointerIdsToNormalized.set(t,i),i}_handle(t){if(!this._enabled)return;t.preventDefault();const e=new Map;let i,s;if(ec(t)){i=ge.Unknown,s=pe.Touch;for(let n=0;n<t.changedTouches.length;n++){const o=t.changedTouches[n],a=Ne.fromPagePosition(o.pageX,o.pageY,this.engine),h=n+1,l=this._normalizePointerId(h);this.currentFramePointerCoords.set(l,a),e.set(l,a)}}else{i=this._nativeButtonToPointerButton(t.button),s=pe.Mouse;const n=Ne.fromPagePosition(t.pageX,t.pageY,this.engine);let o=1;ic(t)&&(o=t.pointerId,s=this._stringToPointerType(t.pointerType));const a=this._normalizePointerId(o);this.currentFramePointerCoords.set(a,n),e.set(a,n)}for(const[n,o]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new Ai("down",n,i,s,o,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new Ai("up",n,i,s,o,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new Ai("move",n,i,s,o,t));break;case"touchcancel":case"pointercancel":this.currentFrameCancel.push(new Ai("cancel",n,i,s,o,t));break}}_handleWheel(t){if(!this._enabled)return;(this.engine.pageScrollPreventionMode===si.All||this.engine.pageScrollPreventionMode===si.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(y(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,o=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,a=t.deltaZ||0;let h=Pi.Pixel;t.deltaMode&&(t.deltaMode===1?h=Pi.Line:t.deltaMode===2&&(h=Pi.Page));const l=new ga(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,o,a,h,t);this.currentFrameWheel.push(l)}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.get(os);s.preupdate(this.engine.currentScene,1),s.update(1)}_nativeButtonToPointerButton(t){switch(t){case Me.NoButton:return ge.NoButton;case Me.Left:return ge.Left;case Me.Middle:return ge.Middle;case Me.Right:return ge.Right;case Me.Unknown:return ge.Unknown;default:return Pr(t)}}_stringToPointerType(t){switch(t){case"touch":return pe.Touch;case"mouse":return pe.Mouse;case"pen":return pe.Pen;default:return pe.Unknown}}}class Qn{constructor(t){this._enabled=!0;const{pointerTarget:e,grabWindowFocus:i,engine:s,global:n}=t;this.keyboard=new fa,this.pointers=new ls(e,s),this.gamepads=new as,this.keyboard.init({global:n,grabWindowFocus:i}),this.pointers.init({grabWindowFocus:i}),this.gamepads.init(),this.inputMapper=new la({keyboard:this.keyboard,pointers:this.pointers,gamepads:this.gamepads})}get enabled(){return this._enabled}toggleEnabled(t){this._enabled=t,this.keyboard.toggleEnabled(this._enabled),this.pointers.toggleEnabled(this._enabled),this.gamepads.toggleEnabled(this._enabled)}update(){this._enabled&&(this.inputMapper.execute(),this.keyboard.update(),this.gamepads.update())}clear(){this.keyboard.clear(),this.pointers.clear()}}class pa extends Pt{constructor(t){super(),this.systemType=At.Update,this.isPaused=!1,this.query=t.world.query([Mt]),this.sceneEventEmitter=t.events,this.sceneEventEmitter.on("pause",e=>{this.isPaused=!0}),this.sceneEventEmitter.on("resume",e=>{this.isPaused=!1})}update(t){for(const e of this.query.entities){const i=e.get(Mt);i.canPause===!1?i.paused=!1:i.paused=this.isPaused}}}class sc{}const nc={Initialize:"initialize",Activate:"activate",Deactivate:"deactivate",PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PreLoad:"preload",TransitionStart:"transitionstart",TransitionEnd:"transitionend",Pause:"pause",Resume:"resume"};function ee(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Lt{constructor(){this._logger=F.getInstance(),this.events=new Y,this.camera=new oa,this.world=new Br(this),this.physics=new Oo(ne()),this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(Yn),this.world.add(new es(this.world,this.physics)),this.world.add(new is(this.world,this.physics)),this.world.add(os),this.world.add(Xn),this.world.add(bn),this.world.add(yn),this.world.add($n),this.world.add(new pa(this))}get actors(){return this.world.entityManager.entities.filter(t=>t instanceof Bt)}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter(t=>t instanceof aa)}get tileMaps(){return this.world.entityManager.entities.filter(t=>t instanceof jo)}get timers(){return this._timers}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)}onPreLoad(t){}onTransition(t){}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}async _initialize(t){var e;if(!this.isInitialized){try{this.engine=t,this.physics.config=this.engine.physics,this.input=new Qn({global:t.global,pointerTarget:t.pointerScope===Oe.Canvas?t.canvas:document,grabWindowFocus:t.grabWindowFocus,engine:t}),this.camera._initialize(t),this.world.systemManager.initialize(),await this.onInitialize(t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.events.emit("initialize",new Ve(t,this))}catch(i){throw this._logger.error(`Error during scene initialization for scene ${(e=t.director)==null?void 0:e.getSceneName(this)}!`),i}this._isInitialized=!0}}async _activate(t){var e,i;try{this._logger.debug("Scene.onActivate",this),this.input.toggleEnabled(!0),await this.onActivate(t)}catch(s){throw this._logger.error(`Error during scene activation for scene ${(i=(e=this.engine)==null?void 0:e.director)==null?void 0:i.getSceneName(this)}!`),s}}async _deactivate(t){return this._logger.debug("Scene.onDeactivate",this),this.input.toggleEnabled(!1),await this.onDeactivate(t)}_preupdate(t,e){this.emit("preupdate",new de(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new ue(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new Ge(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new We(t,e,this)),this.onPostDraw(t,e)}update(t,e){var i;if(!this.isInitialized){this._logger.warnOnce(`Scene update called before initialize for scene ${(i=t.director)==null?void 0:i.getSceneName(this)}!`);return}this._preupdate(t,e);let s,n;for(s=0,n=this._cancelQueue.length;s<n;s++)this.removeTimer(this._cancelQueue[s]);this._cancelQueue.length=0;for(const o of this._timers)o.update(e);this.world.update(At.Update,e),this.camera&&this.camera.update(t,e),this._collectActorStats(t),this._postupdate(t,e),this.input.update()}draw(t,e){var i;if(!this.isInitialized){this._logger.warnOnce("Scene draw called before initialize!");return}this._predraw(t,e),this.world.update(At.Draw,e),(i=this.engine)!=null&&i.isDebug&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new Ns(t,this)),this.emit("postdebugdraw",new Hs(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){if(this.emit("entityadded",{target:t}),t instanceof rs){Ar(this._timers,t)||this.addTimer(t);return}this.world.add(t),t.scene=this}transfer(t){let e;t instanceof Tt&&t.scene&&t.scene!==this&&(e=t.scene,t.scene.world.remove(t,!1)),t instanceof rs&&t.scene&&(e=t.scene,t.scene.removeTimer(t)),e==null||e.emit("entityremoved",{target:t}),this.add(t)}remove(t){this.emit("entityremoved",{target:t}),t instanceof Tt&&(t.isActive&&t.kill(),this.world.remove(t)),t instanceof rs&&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 e=this.timers.length-1;e>=0;e--)this.removeTimer(this.timers[e])}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return e!==-1&&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:!1}_collectActorStats(t){const e=this.actors;for(let i=0;i<e.length;i++){const s=e[i];s instanceof Vn&&t.stats.currFrame.actors.ui++,t.stats.currFrame.actors.alive++;for(let n=0;n<s.children.length;n++){const o=s.children[n];$o(o)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}pauseScene(){this.events.emit("pause")}resumeScene(){this.events.emit("resume")}}class ma{constructor(t){this._engine=t,this._colorBlindPostProcessor=new so(Ke.Protanope)}correct(t){this._engine.graphicsContext instanceof Kt&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!1,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}simulate(t){this._engine.graphicsContext instanceof Kt&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!0,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}clear(){this._engine.graphicsContext.removePostProcessor(this._colorBlindPostProcessor)}}class va{constructor(t){this.stats={currFrame:new Ei,prevFrame:new Ei},this.settings={text:{foreground:T.Black,background:T.Transparent,border:T.Transparent},z:{text:Number.POSITIVE_INFINITY,point:Number.MAX_SAFE_INTEGER-1,ray:Number.MAX_SAFE_INTEGER-1,dashed:Number.MAX_SAFE_INTEGER-2,solid:Number.MAX_SAFE_INTEGER-3}},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!1,showName:!1},this.transform={showAll:!1,showPosition:!1,showPositionLabel:!1,positionColor:T.Yellow,showZIndex:!1,showScale:!1,scaleColor:T.Green,showRotation:!1,rotationColor:T.Blue},this.graphics={showAll:!1,showBounds:!1,boundsColor:T.Yellow},this.collider={showAll:!1,showBounds:!1,boundsColor:T.Blue,showOwner:!1,showGeometry:!0,geometryColor:T.Green,geometryLineWidth:2,geometryPointSize:2},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:T.Cyan,showCollisionContacts:!0,contactSize:10,collisionContactColor:T.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:T.Yellow,showAcceleration:!1,accelerationColor:T.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:T.Red,showZoom:!1},this.tilemap={showAll:!1,showGrid:!1,gridColor:T.Red,gridWidth:.5,showSolidBounds:!1,solidBoundsColor:T.fromHex("#8080807F"),showColliderGeometry:!0},this.isometric={showAll:!1,showPosition:!1,positionColor:T.Yellow,positionSize:1,showGrid:!1,gridColor:T.Red,gridWidth:1,showColliderGeometry:!0},this._engine=t,this.colorBlindMode=new ma(this._engine),It.registerDebugConfig(this)}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 Ei{constructor(){this._id=0,this._elapsedMs=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 cs,this._graphicsStats={drawCalls:0,drawnImages:0,rendererSwaps:0},this.systemDuration={}}reset(t){if(t){this.id=t.id,this.elapsedMs=t.elapsedMs,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;for(const e in t.systemDuration)this.systemDuration[e]=t.systemDuration[e];this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages,this.graphics.rendererSwaps=t.graphics.rendererSwaps}else{this.id=this.elapsedMs=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=this.graphics.rendererSwaps=0;for(const e in this.systemDuration)this.systemDuration[e]=0}}clone(){const t=new Ei;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get elapsedMs(){return this._elapsedMs}set elapsedMs(t){this._elapsedMs=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 cs{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 cs;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 Jn{constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}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)}}class wa{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new Jn(this._windowGlobal),this._documentComponent=new Jn(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 xa{constructor(t){this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0;var e;this._fps=t.initialFps,this._samplePeriod=(e=t.samplePeriod)!=null?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=this._frames*1e3/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class Kn{constructor(t){this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._nextScheduleId=0,this._idsToRemove=[];var e,i,s;this._options=t,this.tick=t.tick,this._lastTime=(e=this.now())!=null?e:0,this._maxFps=(i=t.maxFps)!=null?i:this._maxFps,this._onFatalException=(s=t.onFatalException)!=null?s:this._onFatalException,this.fpsSampler=new xa({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new ya({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new tr({...this._options})}setFatalExceptionHandler(t){this._onFatalException=t}schedule(t,e=0,i="preframe"){const s=this._totalElapsed+e,n=this._nextScheduleId++;return this._scheduledCbs.push([n,t,s,i]),n}clearSchedule(t){this._idsToRemove.push(t)}__runScheduledCbs(t="preframe"){for(let e=this._scheduledCbs.length-1;e>-1;e--){const[i,s,n,o]=this._scheduledCbs[e];this._idsToRemove.includes(i)||t===o&&n<=this._totalElapsed&&(s(this._elapsed),this._scheduledCbs.splice(e,1))}for(const e of this._idsToRemove){const i=this._scheduledCbs.findIndex(([s])=>s===e);i!==-1&&this._scheduledCbs.splice(i,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;s!==0&&(n=i%s,i=i-n),i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this.__runScheduledCbs("preframe"),this.tick(t||i),this.__runScheduledCbs("postframe"),s!==0?this._lastTime=e-n:this._lastTime=e,this.fpsSampler.end()}}catch(e){this._onFatalException(e),this.stop()}}}class tr extends Kn{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(e){throw window.cancelAnimationFrame(this._requestId),e}};t()}stop(){window.cancelAnimationFrame(this._requestId),this._running=!1}}class ya extends Kn{constructor(t){super({...t}),this._logger=F.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return(t=this._currentTime)!=null?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=t!=null?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(e!=null?e:this._updateMs)}}const rc="#ex-toast-container{position:absolute;height:0;min-width:50%;left:50%;top:0}.ex-toast-message{left:-50%;position:relative;display:flex;justify-content:space-between;padding:10px;margin-top:5px;font-size:18px;font-family:sans-serif;border-radius:6px;border:3px solid #b7b779;background-color:#fdfdc0}.ex-toast-message button{align-self:flex-start}";class ba{constructor(){this._toasterCss=rc,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(c=>this._createFragment(c));if(e){const c=document.createElement("a");c.href=e,i?c.innerText=i:c.innerText=e,n.splice(1,0,c)}const o=document.createElement("div");n.forEach(c=>{o.appendChild(c)}),s.appendChild(o);const a=document.createElement("button");a.innerText="x",a.addEventListener("click",()=>{this._container.removeChild(s)}),s.appendChild(a);const h=c=>{if(c.key==="Escape")try{this._container.removeChild(s)}catch(d){}document.removeEventListener("keydown",h)};document.addEventListener("keydown",h);const l=this._container.firstChild;this._container.insertBefore(s,l)}}const Ca={NavigationStart:"navigationstart",Navigation:"navigation",NavigationEnd:"navigationend"};class Sa{constructor(t,e){this._engine=t,this.events=new Y,this._logger=F.getInstance(),this._initialized=!1,this.scenes={},this._sceneToInstance=new Map,this._sceneToLoader=new Map,this._sceneToTransition=new Map,this._loadedScenes=new Set,this._isTransitioning=!1,this.rootScene=this.currentScene=new Lt,this.add("root",this.rootScene),this.currentScene=this.rootScene,this.currentSceneName="root";for(const i in e){const s=e[i];this.add(i,s),i==="root"&&(this.rootScene=this.getSceneInstance("root"),this.currentScene=this.rootScene)}}get isTransitioning(){return this._isTransitioning}async onInitialize(){if(!this._initialized)if(this._initialized=!0,this._deferredGoto){const t=this._deferredGoto;this._deferredGoto=void 0;const e=this._deferredTransition;this._deferredTransition=void 0;const i=this.getSceneInstance(t);i&&e&&e._addToTargetScene(this._engine,i);const s=this._getInTransition(t),n=s==null?void 0:s.hideLoader;this.maybeLoadScene(t,n),await this.swapScene(t),i&&e&&await this.playTransition(e,i)}else await this.swapScene("root")}get isInitialized(){return this._initialized}configureStart(t,e){var i,s;const n=e==null?void 0:e.loader;n instanceof Ci?this.mainLoader=n:Gn(n)?this.mainLoader=new n:this.mainLoader=new ns;let o;if(e!=null&&e.inTransition){const{inTransition:h}=e;o=h}this.startScene=t;const a=(s=(i=e==null?void 0:e.inTransition)==null?void 0:i.hideLoader)!=null?s:!1;if(this.maybeLoadScene(t,a),o){const h=this.getSceneInstance(t);h&&(o._addToTargetScene(this._engine,h),this.swapScene(t).then(()=>(h.onTransition("in"),this.playTransition(o,h))))}else this.swapScene(t);this.currentSceneName=this.startScene}_getLoader(t){return this._sceneToLoader.get(t)}_getInTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Lt||ee(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.in}_getOutTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Lt||ee(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.out}getDeferredScene(){const t=this.getSceneDefinition(this._deferredGoto);return this._deferredGoto&&t?t:null}getSceneDefinition(t){const e=this.scenes[t];if(e instanceof Lt||ee(e))return e;if(e)return e.scene}getSceneName(t){for(const[e,i]of Object.entries(this.scenes))if(i instanceof Lt){if(t===i)return e}else if(!ee(i)&&t===i.scene)return e;for(const[e,i]of Object.entries(this.scenes))if(ee(i)){if(t.constructor===i)return e}else if(!(i instanceof Lt)&&t.constructor===i.scene)return e;return null}assertAdded(t){return this}assertRemoved(t){return this}add(t,e){if(!(e instanceof Lt)&&!ee(e)){const{loader:i,transitions:s}=e,{in:n,out:o}=s!=null?s:{};this._sceneToTransition.set(t,{in:n,out:o}),Gn(i)?this._sceneToLoader.set(t,new i):i&&this._sceneToLoader.set(t,i)}return this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e,this.assertAdded(t)}remove(t){if(t instanceof Lt||ee(t)){const e=t;for(const i in this.scenes)if(this.scenes.hasOwnProperty(i)){const s=this.scenes[i];let n;if(s instanceof Lt||ee(s)?n=s:n=s.scene,n===e){if(i===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${i}`);this._sceneToInstance.delete(i),this._sceneToTransition.delete(i),this._sceneToLoader.delete(i),delete this.scenes[i]}}}if(typeof t=="string"){if(t===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${t}`);this._sceneToInstance.delete(t),this._sceneToTransition.delete(t),this._sceneToLoader.delete(t),delete this.scenes[t]}}async goToScene(t,e){var i,s,n,o,a,h;const l=this.getSceneInstance(t);if(!l){this._logger.warn(`Scene ${t} does not exist! Check the name, are you sure you added it?`);return}const c=this.currentScene,d=this.currentSceneName,_=(s=(i=this._engine.input)==null?void 0:i.enabled)!=null?s:!0;this._isTransitioning=!0;const f=(n=this.getSceneInstance(d))==null?void 0:n.onTransition("out"),m=l==null?void 0:l.onTransition("in");e={sourceOut:(o=this._getOutTransition(this.currentSceneName))!=null?o:f,destinationIn:(a=this._getInTransition(t))!=null?a:m,...e};const{sourceOut:p,destinationIn:x,sceneActivationData:v}=e,g=p!=null?p:this._getOutTransition(this.currentSceneName),b=x!=null?x:this._getInTransition(t),S=(g==null?void 0:g.hideLoader)||(b==null?void 0:b.hideLoader);S&&this.maybeLoadScene(t,S),this._emitEvent("navigationstart",d,t),g&&await this.playTransition(g,c),await this.maybeLoadScene(t,S),b&&await b.onPreviousSceneDeactivate(this.currentScene),b&&b._addToTargetScene(this._engine,l),await this.swapScene(t,v),this._emitEvent("navigation",d,t),b&&await this.playTransition(b,l),this._emitEvent("navigationend",d,t),(h=this._engine.input)==null||h.toggleEnabled(_),this._isTransitioning=!1}getSceneInstance(t){const e=this.getSceneDefinition(t);if(!e)return;if(this._sceneToInstance.has(t))return this._sceneToInstance.get(t);if(e instanceof Lt)return this._sceneToInstance.set(t,e),e;const i=new e;return this._sceneToInstance.set(t,i),i}async maybeLoadScene(t,e=!1){var i;const s=(i=this._getLoader(t))!=null?i:new Ci,n=this.getSceneDefinition(t),o=this.getSceneInstance(t);n&&o&&!this._loadedScenes.has(o)&&(o.onPreLoad(s),o.events.emit("preload",{loader:s}),e?this._engine.load(s,e):await this._engine.load(s),this._loadedScenes.add(o))}async playTransition(t,e){var i,s,n,o,a,h,l;if(!this.isInitialized){this._deferredTransition=t;return}if(t){this.currentTransition=t;const c=(s=(i=e.input)==null?void 0:i.enabled)!=null?s:!0;(n=e.input)==null||n.toggleEnabled(!t.blockInput),(o=this._engine.input)==null||o.toggleEnabled(!t.blockInput),e.events.emit("transitionstart",t),this.currentTransition._addToTargetScene(this._engine,e),await this.currentTransition._play(),e.events.emit("transitionend",t),(a=e.input)==null||a.toggleEnabled(c)}(h=this.currentTransition)==null||h.kill(),(l=this.currentTransition)==null||l.reset(),this.currentTransition=void 0}async swapScene(t,e){const i=this._engine;if(!this.isInitialized){this._deferredGoto=t;return}const s=this.getSceneInstance(t);if(s){const n=this.currentScene,o=s;let a;if(this._logger.debug("Going to scene:",t),this.currentScene.isInitialized){const c={engine:i,previousScene:n,nextScene:o};a=await this.currentScene._deactivate(c),this.currentScene.events.emit("deactivate",new Qs(c,this.currentScene)),this.currentScene.input.clear()}const h=this._sceneToLoader.get(t);await(h==null?void 0:h.areResourcesLoaded()),this.currentScene=o,this.currentSceneName=t,i.screen.setCurrentCamera(o.camera),await this.currentScene._initialize(i);const l={engine:i,previousScene:n,previousSceneData:a,nextScene:o,data:e};await this.currentScene._activate(l),this.currentScene.events.emit("activate",new js(l,this.currentScene))}else this._logger.error("Scene",t,"does not exist!")}_emitEvent(t,e,i){const s=this.getSceneDefinition(e),n=this.getSceneDefinition(i);this.events.emit(t,{sourceScene:s,sourceName:e,destinationScene:n,destinationName:i})}}function Ta(){const r={scope:(t,e)=>{const i=r.value;r.value=t;try{const s=e();return s&&typeof s.then=="function"?s.finally(()=>{r.value=i}):s}catch(s){throw s}finally{r.value=i}},value:void 0};return r}function Aa(r){return r.value}const er={textureCollectInterval:6e4};class Pa{constructor(t){this.options=t,this._running=!1,this._collectionMap=new Map,this._collectors=new Map,this.collectStaleResources=e=>{if(this._running){for(const[i,[s,n]]of this._collectors.entries()){const o=this.options.getTimestamp();for(const[a,[h,l]]of this._collectionMap.entries()){if(i!==h||l+n>=o)continue;s(a)&&this._collectionMap.delete(a)}}this._collectHandle=requestIdleCallback(this.collectStaleResources)}}}registerCollector(t,e,i){this._collectors.set(t,[i,e])}addCollectableResource(t,e){this._collectionMap.set(e,[t,this.options.getTimestamp()])}touch(t){const e=this._collectionMap.get(t);e&&this._collectionMap.set(t,[e[0],this.options.getTimestamp()])}forceCollectAll(){for(const[t,[e]]of this._collectors.entries())for(const[i]of this._collectionMap.entries())e(i)&&this._collectionMap.delete(i)}running(){return this._running}start(){this._running=!0,this.collectStaleResources()}stop(){this._running=!1,cancelIdleCallback(this._collectHandle)}}ze();const oc={FallbackGraphicsContext:"fallbackgraphicscontext",Initialize:"initialize",Visible:"visible",Hidden:"hidden",Start:"start",Stop:"stop",PreUpdate:"preupdate",PostUpdate:"postupdate",PreFrame:"preframe",PostFrame:"postframe",PreDraw:"predraw",PostDraw:"postdraw",...Ca};var si=(r=>(r[r.None=0]="None",r[r.Canvas=1]="Canvas",r[r.All=2]="All",r))(si||{});const ds=class ve{constructor(t){this.scope=A=>ve.Context.scope(this,A),this.version=rr,this.events=new Y,this.maxFps=Number.POSITIVE_INFINITY,this._inputEnabled=!0,this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.enableCanvasTransparency=!0,this.onFatalException=A=>{F.getInstance().fatal(A,A.stack)},this._toaster=new ba,this._timescale=1,this._isInitialized=!1,this._hasCreatedCanvas=!1,this._originalOptions={},this._handleWebGLContextLost=A=>{var M;A.preventDefault(),this.clock.stop(),this._logger.fatalOnce("WebGL Graphics Lost",A);const C=document.createElement("div");C.id="ex-webgl-graphics-context-lost",C.style.position="absolute",C.style.zIndex="99",C.style.left="50%",C.style.top="50%",C.style.display="flex",C.style.flexDirection="column",C.style.transform="translate(-50%, -50%)",C.style.backgroundColor="white",C.style.padding="10px",C.style.borderStyle="solid 1px";const z=document.createElement("div");if(z.innerHTML=`
898
- <h1>There was an issue rendering, please refresh the page.</h1>
899
- <div>
900
- <p>WebGL Graphics Context Lost</p>
901
-
902
- <button id="ex-webgl-graphics-reload">Refresh Page</button>
903
-
904
- <p>There are a few reasons this might happen:</p>
905
- <ul>
906
- <li>Two or more pages are placing a high demand on the GPU</li>
907
- <li>Another page or operation has stalled the GPU and the browser has decided to reset the GPU</li>
908
- <li>The computer has multiple GPUs and the user has switched between them</li>
909
- <li>Graphics driver has crashed or restarted</li>
910
- <li>Graphics driver was updated</li>
911
- </ul>
912
- </div>
913
- `,C.appendChild(z),(M=this.canvas)!=null&&M.parentElement){this.canvas.parentElement.appendChild(C);const O=z.querySelector("#ex-webgl-graphics-reload");O==null||O.addEventListener("click",()=>location.reload())}},this._performanceThresholdTriggered=!1,this._fpsSamples=[],this._disposed=!1,this._isLoading=!1,this._hideLoader=!1,this._isReadyFuture=new xt,this.currentFrameElapsedMs=0,this.currentFrameLagMs=0,this._lagMs=0,this._screenShotRequests=[];var e,i,s,n,o,a,h,l,c;t={...ve._DEFAULT_ENGINE_OPTIONS,...t},this._originalOptions=t,Ue.freeze(),this.browser=new wa(window,document);const d=new Xo;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=d.test())){const A=document.createElement("div");if(A.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(A),d.failedTests.forEach(function(M){const C=document.createElement("div");C.innerText="Browser feature missing "+M,document.body.appendChild(C)}),t.canvasElementId){const M=document.getElementById(t.canvasElementId);M&&M.parentElement.removeChild(M)}return}else this._compatible=!0;if(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(`
914
- /| ________________
915
- O|===|* >________________>
916
- \\|`),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=F.getInstance(),this.debug=new va(this),this._logger.defaultLevel===He.Debug&&d.logBrowserFeatures(),this._logger.debug("Building engine..."),t.garbageCollection===!0?this.garbageCollectorConfig={...er}:t.garbageCollection===!1?(this._logger.warn("WebGL Garbage Collection Disabled!!! If you leak any images over time your game will crash when GPU memory is exhausted"),this.garbageCollectorConfig=null):this.garbageCollectorConfig={...er,...t.garbageCollection},this._garbageCollector=new Pa({getTimestamp:Date.now}),this.canvasElementId=t.canvasElementId,t.canvasElementId){if(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),document.getElementById(t.canvasElementId)===null)throw new Error("Cannot find existing element in the DOM, please ensure element is created prior to engine creation.");this.canvas=document.getElementById(t.canvasElementId),this._hasCreatedCanvas=!1}else t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement,this._hasCreatedCanvas=!1):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"),this._hasCreatedCanvas=!0);this.canvas&&!t.enableCanvasContextMenu&&this.canvas.addEventListener("contextmenu",A=>{A.preventDefault()});let _=(e=t.displayMode)!=null?e:yi.Fixed;t.width&&t.height||t.viewport?(t.displayMode===void 0&&(_=yi.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),_=yi.FitScreen);const f=t.global&&typeof t.global=="function"?t.global():t.global;this.global=f!=null?f:ua(),this.grabWindowFocus=t.grabWindowFocus,this.pointerScope=t.pointerScope,this._originalDisplayMode=_;let m,p,x,v,g,b;typeof t.antialiasing=="object"?{pixelArtSampler:m,nativeContextAntialiasing:x,multiSampleAntialiasing:b,filtering:g,canvasImageRendering:v}={...t.pixelArt?Xr:qr,...t.antialiasing}:(m=!!t.pixelArt,x=!1,b=t.antialiasing,v=t.antialiasing?"auto":"pixelated",g=t.antialiasing?vt.Blended:vt.Pixel),x&&b&&this._logger.warnOnce("Cannot use antialias setting nativeContextAntialiasing and multiSampleAntialiasing at the same time, they are incompatible settings. If you aren't sure use multiSampleAntialiasing"),t.pixelArt&&(p=.25),(!t.antialiasing||g===vt.Pixel)&&(p=0),p=(s=(i=t.uvPadding)!=null?i:p)!=null?s:.01;let S=Ue.isEnabled("use-canvas-context");if(!S)try{this.graphicsContext=new Kt({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,pixelArtSampler:m,antialiasing:x,multiSampleAntialiasing:b,uvPadding:p,powerPreference:t.powerPreference,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting,garbageCollector:this.garbageCollectorConfig?{garbageCollector:this._garbageCollector,collectionInterval:this.garbageCollectorConfig.textureCollectInterval}:null,handleContextLost:(n=t.handleContextLost)!=null?n:this._handleWebGLContextLost,handleContextRestored:t.handleContextRestored})}catch(A){this._logger.warn(`Excalibur could not load webgl for some reason (${A.message}) and loaded a Canvas 2D fallback. Some features of Excalibur will not work in this mode.
917
-
918
- Read more about this issue at https://excaliburjs.com/docs/performance`),S=!0}S&&(this.graphicsContext=new Ji({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,antialiasing:x,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})),this.screen=new On({canvas:this.canvas,context:this.graphicsContext,antialiasing:x,canvasImageRendering:v,browser:this.browser,viewport:(o=t.viewport)!=null?o:t.width&&t.height?{width:t.width,height:t.height}:Un.SVGA,resolution:t.resolution,displayMode:_,pixelRatio:t.suppressHiDPIScaling?1:(a=t.pixelRatio)!=null?a:null}),Ze.filtering=g,t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.maxFps=(h=t.maxFps)!=null?h:this.maxFps,this.fixedUpdateTimestep=(l=t.fixedUpdateTimestep)!=null?l:this.fixedUpdateTimestep,this.fixedUpdateFps=(c=t.fixedUpdateFps)!=null?c:this.fixedUpdateFps,this.fixedUpdateTimestep=this.fixedUpdateTimestep||1e3/this.fixedUpdateFps,this.clock=new tr({maxFps:this.maxFps,tick:this._mainloop.bind(this),onFatalException:A=>this.onFatalException(A)}),this.enableCanvasTransparency=t.enableCanvasTransparency,typeof t.physics=="boolean"?this.physics={...ne(),enabled:t.physics}:(this.physics={...ne()},Oi(this.physics,t.physics)),this.director=new Sa(this,t.scenes),this.director.events.pipe(this.events),this._initialize(t),window.___EXCALIBUR_DEVTOOL=this,ve.InstanceCount++}static useEngine(){const t=Aa(ve.Context);if(!t)throw new Error("Cannot inject engine with `useEngine()`, `useEngine()` was called outside of Engine lifecycle scope.");return t}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 currentScene(){return this.director.currentScene}get currentSceneName(){return this.director.currentSceneName}get rootScene(){return this.director.rootScene}get scenes(){return this.director.scenes}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)}_monitorPerformanceThresholdAndTriggerFallback(){const{allow:t}=this._originalOptions.configurePerformanceCanvas2DFallback;let{threshold:e,showPlayerMessage:i}=this._originalOptions.configurePerformanceCanvas2DFallback;if(e===void 0&&(e=ve._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.threshold),i===void 0&&(i=ve._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.showPlayerMessage),!Ue.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 s=0;for(let o=0;o<this._fpsSamples.length;o++)s+=this._fpsSamples[o];const n=s/this._fpsSamples.length;this._fpsSamples.length===e.numberOfFrames&&n<=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.
919
- this might mean your browser doesn't have webgl enabled or hardware acceleration is unavailable.
920
-
921
- If in Chrome:
922
- * Visit Settings > Advanced > System, and ensure "Use Hardware Acceleration" is checked.
923
- * Visit chrome://flags/#ignore-gpu-blocklist and ensure "Override software rendering list" is "enabled"
924
- If in Firefox, visit about:config
925
- * Ensure webgl.disabled = false
926
- * Ensure webgl.force-enabled = true
927
- * Ensure layers.acceleration.force-enabled = true
928
-
929
- Read 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.screen.antialiasing},o=this._originalDisplayMode;this.graphicsContext=new Ji({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,antialiasing:n.antialiasing,backgroundColor:n.backgroundColor,snapToPixel:n.snapToPixel,useDrawSorting:n.useDrawSorting}),this.screen&&this.screen.dispose(),this.screen=new On({canvas:this.canvas,context:this.graphicsContext,antialiasing:(t=n.antialiasing)!=null?t:!0,browser:this.browser,viewport:(e=n.viewport)!=null?e:n.width&&n.height?{width:n.width,height:n.height}:Un.SVGA,resolution:n.resolution,displayMode:o,pixelRatio:n.suppressHiDPIScaling?1:(i=n.pixelRatio)!=null?i:null}),this.screen.setCurrentCamera(this.currentScene.camera),this.input.pointers.detach();const a=n&&n.pointerScope===Oe.Document?document:this.canvas;this.input.pointers=this.input.pointers.recreate(a,this),this.input.pointers.init()}dispose(){this._disposed||(this._disposed=!0,this.stop(),this._garbageCollector.forceCollectAll(),this.input.toggleEnabled(!1),this._hasCreatedCanvas&&this.canvas.parentNode.removeChild(this.canvas),this.canvas=null,this.screen.dispose(),this.graphicsContext.dispose(),this.graphicsContext=null,ve.InstanceCount--)}isDisposed(){return this._disposed}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){if(t<0){F.getInstance().warnOnce("engine.timescale to a value less than 0 are ignored");return}this._timescale=t}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){return this.director.add(t,e),this}removeScene(t){this.director.remove(t)}add(t){if(arguments.length===2){this.director.add(arguments[0],arguments[1]);return}const e=this.director.getDeferredScene();e instanceof Lt?e.add(t):this.currentScene.add(t)}remove(t){t instanceof Tt&&this.currentScene.remove(t),(t instanceof Lt||ee(t))&&this.removeScene(t),typeof t=="string"&&this.removeScene(t)}async goToScene(t,e){await this.scope(async()=>{await this.director.goToScene(t,e)})}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){var e,i;this.pageScrollPreventionMode=t.scrollPreventionMode;const s=t&&t.pointerScope===Oe.Document?document:this.canvas,n=(i=(e=this._originalOptions)==null?void 0:e.grabWindowFocus)!=null?i:!0;this.input=new Qn({global:this.global,pointerTarget:s,grabWindowFocus:n,engine:this}),this.inputMapper=this.input.inputMapper,this.browser.document.on("visibilitychange",()=>{document.visibilityState==="hidden"?(this.events.emit("hidden",new Zs(this)),this._logger.debug("Window hidden")):document.visibilityState==="visible"&&(this.events.emit("visible",new Ys(this)),this._logger.debug("Window visible"))}),!this.canvasElementId&&!t.canvasElement&&document.body.appendChild(this.canvas)}toggleInputEnabled(t){this._inputEnabled=t,this.input.toggleEnabled(this._inputEnabled)}onInitialize(t){}get isInitialized(){return this._isInitialized}async _overrideInitialize(t){this.isInitialized||(await this.director.onInitialize(),await this.onInitialize(t),this.events.emit("initialize",new Ve(t,this)),this._isInitialized=!0)}_update(t){var e;if(this._isLoading){(e=this._loader)==null||e.onUpdate(this,t),this.input.update();return}this.clock.__runScheduledCbs("preupdate"),this._preupdate(t),this.currentScene.update(this,t),this.graphicsContext.updatePostProcessors(t),this.clock.__runScheduledCbs("postupdate"),this._postupdate(t),this.input.update()}_preupdate(t){this.emit("preupdate",new de(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new ue(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){var e,i;if(this.graphicsContext.backgroundColor=(e=this.currentScene.backgroundColor)!=null?e:this.backgroundColor,this.graphicsContext.beginDrawLifecycle(),this.graphicsContext.clear(),this.clock.__runScheduledCbs("predraw"),this._predraw(this.graphicsContext,t),this._isLoading){this._hideLoader||((i=this._loader)==null||i.canvas.draw(this.graphicsContext,0,0),this.clock.__runScheduledCbs("postdraw"),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle());return}this.currentScene.draw(this.graphicsContext,t),this.clock.__runScheduledCbs("postdraw"),this._postdraw(this.graphicsContext,t),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle(),this._checkForScreenShots()}_predraw(t,e){this.emit("predraw",new Ge(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new We(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._isLoading}get ready(){return this._isReadyFuture.isCompleted}isReady(){return this._isReadyFuture.promise}async start(t,e){await this.scope(async()=>{if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");this._isLoading=!0;let i;return t instanceof Ci?i=t:typeof t=="string"&&(this.director.configureStart(t,e),i=this.director.mainLoader),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this.garbageCollectorConfig&&this._garbageCollector.start(),this._logger.debug("Game clock started"),await this.load(i!=null?i:new ns),await this._overrideInitialize(this),this._isReadyFuture.resolve(),this.emit("start",new ks(this)),this._isReadyFuture.promise})}_mainloop(t){this.scope(()=>{this.emit("preframe",new Gs(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.elapsedMs=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps,Q.clear();const s=this.clock.now(),n=this.fixedUpdateTimestep;if(this.fixedUpdateTimestep)for(this._lagMs+=e;this._lagMs>=n;)this._update(n),this._lagMs-=n;else this._update(e);const o=this.clock.now();this.currentFrameLagMs=this._lagMs,this._draw(e);const a=this.clock.now();this.stats.currFrame.duration.update=o-s,this.stats.currFrame.duration.draw=a-o,this.stats.currFrame.graphics.drawnImages=Q.DrawnImagesCount,this.stats.currFrame.graphics.drawCalls=Q.DrawCallCount,this.stats.currFrame.graphics.rendererSwaps=Q.RendererSwaps,this.emit("postframe",new Ws(this,this.stats.currFrame)),this.stats.prevFrame.reset(this.stats.currFrame),this._monitorPerformanceThresholdAndTriggerFallback()})}stop(){this.clock.isRunning()&&(this.emit("stop",new zs(this)),this.browser.pause(),this.clock.stop(),this._garbageCollector.stop(),this._logger.debug("Game stopped"))}isRunning(){return this.clock.isRunning()}screenshot(t=!1){return new Promise(i=>{this._screenShotRequests.push({preserveHiDPIResolution:t,resolve:i})})}_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 o=new Image,a=s.toDataURL("image/png");o.onload=()=>{t.resolve(o)},o.src=a}this._screenShotRequests.length=0}async load(t,e=!1){await this.scope(async()=>{try{if(t.isLoaded())return;this._loader=t,this._isLoading=!0,this._hideLoader=e,t instanceof ns&&(t.suppressPlayButton=t.suppressPlayButton||this._suppressPlayButton),this._loader.onInitialize(this),await t.load()}catch(i){this._logger.error("Error loading resources, things may not behave properly",i),await Promise.resolve()}finally{this._isLoading=!1,this._hideLoader=!1,this._loader=null}})}};ds.Context=Ta(),ds.InstanceCount=0,ds._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,enableCanvasContextMenu:!1,snapToPixel:!1,antialiasing:!0,pixelArt:!1,garbageCollection:!0,powerPreference:"high-performance",pointerScope:Oe.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,grabWindowFocus:!0,scrollPreventionMode:1,backgroundColor:T.fromHex("#2185d0")};let us=ds;class ac extends Bt{constructor(t){super(t),this._font=new Ee,this._text=new wi({text:"",font:this._font});const{text:e,pos:i,x:s,y:n,spriteFont:o,font:a,color:h,maxWidth:l}={text:"",...t};this.pos=i!=null?i:s&&n?y(s,n):this.pos,this.text=e!=null?e:this.text,this.font=a!=null?a:this.font,this.maxWidth=l!=null?l:this.maxWidth,this.spriteFont=o!=null?o:this.spriteFont,this._text.color=h!=null?h:this.color;const c=this.get(Z);c.anchor=w.Zero,c.use(this._text)}set maxWidth(t){this._text.maxWidth=t}get maxWidth(){return this._text.maxWidth}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.graphics.opacity}set opacity(t){this.graphics.opacity=t}get spriteFont(){return this._spriteFont}set spriteFont(t){t&&(this._spriteFont=t,this._text.font=this._spriteFont)}_initialize(t){super._initialize(t)}getTextWidth(){return this._text.width}}var Fe=(r=>(r.Circle="circle",r.Rectangle="rectangle",r))(Fe||{});class hc extends Bt{constructor(t){var e,i;super({width:(e=t.width)!=null?e:0,height:(i=t.height)!=null?i:0}),this._particlesToEmit=0,this._particlePool=new Qe(()=>new Ki({}),m=>m,500),this.numParticles=0,this.isEmitting=!0,this.deadParticles=[],this.emitRate=1,this.emitterType=Fe.Rectangle,this.radius=0,this.particle={life:2e3,transform:Qt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this._activeParticles=[];const{particle:s,x:n,y:o,z:a,pos:h,isEmitting:l,emitRate:c,emitterType:d,radius:_,random:f}={...t};this.particle={...this.particle,...s},this.pos=h!=null?h:y(n!=null?n:0,o!=null?o:0),this.z=a!=null?a:0,this.isEmitting=l!=null?l:this.isEmitting,this.emitRate=c!=null?c:this.emitRate,this.emitterType=d!=null?d:this.emitterType,this.radius=_!=null?_:this.radius,this.body.collisionType=R.PreventCollision,this.random=f!=null?f:new le}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;if(!(t<=0)){t=t|0;for(let i=0;i<t;i++){const s=this._createParticle();(e=this==null?void 0:this.scene)!=null&&e.world&&(this.particle.transform===Qt.Global?this.scene.world.add(s):this.addChild(s)),this._activeParticles.push(s)}}}clearParticles(){for(let t=0;t<this._activeParticles.length;t++)this.removeParticle(this._activeParticles[t])}_createParticle(){let t=0,e=0;const i=Xt(this.particle.minAngle||0,this.particle.maxAngle||Math.PI*2,this.random),s=Xt(this.particle.minSpeed||0,this.particle.maxSpeed||0,this.random),n=this.particle.startSize||Xt(this.particle.minSize||5,this.particle.maxSize||5,this.random),o=s*Math.cos(i),a=s*Math.sin(i);if(this.emitterType===Fe.Rectangle)t=Xt(0,this.width,this.random),e=Xt(0,this.height,this.random);else if(this.emitterType===Fe.Circle){const l=Xt(0,this.radius,this.random);t=l*Math.cos(i),e=l*Math.sin(i)}const h=this._particlePool.rent();return h.unparent(),h.configure({transform:this.particle.transform,life:this.particle.life,opacity:this.particle.opacity,beginColor:this.particle.beginColor,endColor:this.particle.endColor,pos:y(t,e),z:this.particle.transform===Qt.Global?this.z:void 0,vel:y(o,a),acc:this.particle.acc,angularVelocity:this.particle.angularVelocity,startSize:this.particle.startSize,endSize:this.particle.endSize,size:n,graphic:this.particle.graphic,fade:this.particle.fade}),h.registerEmitter(this),this.particle.randomRotation&&(h.transform.rotation=Xt(0,Math.PI*2,this.random)),this.particle.focus&&(h.focus=this.particle.focus.add(y(this.pos.x,this.pos.y)),h.focusAccel=this.particle.focusAccel),h}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 s=0;s<this.deadParticles.length;s++){(i=this==null?void 0:this.scene)!=null&&i.world&&(this.scene.world.remove(this.deadParticles[s],!1),this._particlePool.return(this.deadParticles[s]));const n=this._activeParticles.indexOf(this.deadParticles[s]);n>-1&&this._activeParticles.splice(n,1)}this.deadParticles.length=0}}function ir(r,t){if(!t())throw new Error(r)}class _s{constructor(t,e,i){this.emitRate=1,this._initialized=!1,this._vaos=[],this._buffers=[],this._drawIndex=0,this._numInputFloats=7,this._particleIndex=0,this._uploadIndex=0,this._wrappedLife=0,this._wrappedParticles=0,this._particleLife=0,this._clearRequested=!1,this._emitted=[];var s;this.emitter=t,this.particle=i,this._particleData=new Float32Array(this.emitter.maxParticles*this._numInputFloats),this._random=e,this._particleLife=(s=this.particle.life)!=null?s:2e3}get isInitialized(){return this._initialized}get maxParticles(){return this.emitter.maxParticles}initialize(t,e){if(this._initialized)return;const i=this.emitter.maxParticles,s=this._numInputFloats,n=this._particleData,o=4,a=t.createBuffer(),h=t.createVertexArray();t.bindVertexArray(h),t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),t.bufferSubData(t.ARRAY_BUFFER,0,n);let l=0;t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(h),this._buffers.push(a),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null);const c=t.createBuffer(),d=t.createVertexArray();t.bindVertexArray(d),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),l=0,t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(d),this._buffers.push(c),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._initialized=!0}clearParticles(){this._particleData.fill(0),this._clearRequested=!0}emitParticles(t){const e=this._particleIndex,i=this.maxParticles*this._numInputFloats,s=t*this._numInputFloats+e;for(let n=e;n<s;n+=this._numInputFloats){let o=this._random.floating(this.particle.minAngle||0,this.particle.maxAngle||gt);o+=this.particle.transform===Qt.Local?this.emitter.transform.rotation:this.emitter.transform.globalRotation;const a=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),h=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),l=a*Math.cos(o),c=h*Math.sin(o);let d=0,_=0;if(this.emitter.emitterType===Fe.Rectangle)d=this._random.floating(-.5,.5)*this.emitter.width,_=this._random.floating(-.5,.5)*this.emitter.height;else{const p=this._random.floating(0,this.emitter.radius);d=p*Math.cos(o),_=p*Math.sin(o)}const f=this.emitter.transform.apply(y(d,_)),m=[this.particle.transform===Qt.Local?d:f.x,this.particle.transform===Qt.Local?_:f.y,l,c,this.particle.randomRotation?Xt(0,gt,this._random):this.particle.rotation||0,this.particle.angularVelocity||0,this._particleLife];this._particleData.set(m,n%this._particleData.length)}s>=i?(this._wrappedParticles+=(s-i)/this._numInputFloats,this._wrappedLife=this._particleLife):this._wrappedLife>0&&(this._wrappedParticles+=t),this._particleIndex=s%i,this._emitted.push([this._particleLife,e])}_uploadEmitted(t){this._particleIndex!==this._uploadIndex&&(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),this._particleIndex>=this._uploadIndex?t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleIndex-this._uploadIndex):(t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleData.length-this._uploadIndex),this._wrappedParticles&&t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData,0,this._wrappedParticles*this._numInputFloats),this._wrappedLife=this._particleLife),t.bindBuffer(t.ARRAY_BUFFER,null)),this._uploadIndex=this._particleIndex%(this.maxParticles*this._numInputFloats)}update(t){var e;if(this._particleLife=(e=this.particle.life)!=null?e:this._particleLife,this._wrappedLife>0?this._wrappedLife-=t:(this._wrappedLife=0,this._wrappedParticles=0),!!this._emitted.length){for(let i=this._emitted.length-1;i>=0;i--){const s=this._emitted[i];s[0]-=t,s[0]<=0&&this._emitted.splice(i,1)}this._emitted.sort((i,s)=>i[0]-s[0])}}draw(t){if(this._initialized){if(this._clearRequested?(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData),t.bindBuffer(t.ARRAY_BUFFER,null),this._clearRequested=!1):this._uploadEmitted(t),t.bindVertexArray(this._currentVao),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer),this._wrappedLife&&this._emitted[0]&&this._emitted[0][1]>0){const e=this._emitted[0][1]/this._numInputFloats;ir(`midpoint greater than 0, actual: ${e}`,()=>e>0),ir(`midpoint is less than max, actual: ${e}`,()=>e<this.maxParticles),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,this._emitted[0][1]*4,(this.maxParticles-e)*this._numInputFloats*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,e,this.maxParticles-e),t.endTransformFeedback(),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._emitted[0][1]*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,e),t.endTransformFeedback()}else t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._particleData.length*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,this.maxParticles),t.endTransformFeedback();t.bindVertexArray(null),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._drawIndex=(this._drawIndex+1)%2}}}_s.GPU_MAX_PARTICLES=1e5;class lc extends Bt{constructor(t){super({name:"GpuParticleEmitter",width:t.width,height:t.height}),this.particle={life:2e3,transform:Qt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this.graphics=new Z,this.isEmitting=!1,this.emitRate=1,this.emitterType=Fe.Rectangle,this.radius=0,this.maxParticles=2e3,this._particlesToEmit=0,this.addComponent(this.graphics,!0),this.graphics.onPostDraw=this.draw.bind(this);const{particle:e,maxParticles:i,x:s,y:n,z:o,pos:a,isEmitting:h,emitRate:l,emitterType:c,radius:d,random:_}={...t};this.maxParticles=L(i!=null?i:this.maxParticles,0,_s.GPU_MAX_PARTICLES),this.pos=a!=null?a:y(s!=null?s:0,n!=null?n:0),this.z=o!=null?o:0,this.isEmitting=h!=null?h:this.isEmitting,this.emitRate=l!=null?l:this.emitRate,this.emitterType=c!=null?c:this.emitterType,this.radius=d!=null?d:this.radius,this.particle={...this.particle,...e},this.random=_!=null?_:new le,this.renderer=new _s(this,this.random,this.particle)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get z(){return this.transform.z}set z(t){this.transform.z=t}_initialize(t){super._initialize(t);const e=t.graphicsContext;this.renderer.initialize(e.__gl,e)}update(t,e){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))),this.renderer.update(e)}emitParticles(t){t<=0||this.renderer.emitParticles(t|0)}clearParticles(){this.renderer.clearParticles()}draw(t,e){t.draw("ex.particle",this.renderer,e)}}class sr{constructor(t,e){this.id=G(),this._stopped=!1,this._sequenceBuilder=e,this._sequenceContext=new xi(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 sr(t,this._sequenceBuilder)}}class cc{constructor(t){this.id=G(),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 dc(r){return!!r._initialize}function uc(r){return!!r.onAdd}function _c(r){return!!r.onRemove}function fc(r){return!!r.onInitialize}function gc(r){return!!r._preupdate}function pc(r){return!!r.onPreUpdate}function mc(r){return!!r.onPostUpdate}function vc(r){return!!r.onPostUpdate}function wc(r){return!!r.onAdd}function xc(r){return!!r.onRemove}function yc(r){return!!r.onPreDraw}function bc(r){return!!r.onPostDraw}class Ea{constructor(t,e){this.soundManager=e}stop(t){if(!t)return;const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)e[i].stop()}setVolume(t,e){const i=this.soundManager.getSoundsForChannel(t);for(const s of i)this.soundManager._isMuted(s)||this.soundManager.setVolume(t,e)}play(t,e){e!=null||(e=this.soundManager.defaultVolume);const i=[],s=new Set,n=this.soundManager.getSoundsForChannel(t);for(const o of n){if(s.has(o)||this.soundManager._isMuted(o))continue;const a=this.soundManager._getEffectiveVolume(o);i.push(o.play(a*e)),s.add(o)}return Promise.all(i)}mute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.add(e[i]),e[i].pause()}unmute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.has(e[i])&&(e[i].play(),this.soundManager._muted.delete(e[i]))}toggle(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._isMuted(e[i])?(e[i].play(),this.soundManager._muted.delete(e[i])):(this.soundManager._muted.add(e[i]),e[i].pause())}}class Cc{constructor(t){this._channelToConfig=new Map,this._nameToConfig=new Map,this._mix=new Map,this._muted=new Set,this._all=new Set,this._defaultVolume=1;var e;if(this._defaultVolume=(e=t.volume)!=null?e:1,this.channel=new Ea(t,this),t.sounds)for(const[i,s]of Object.entries(t.sounds))this.track(i,s)}set defaultVolume(t){this._defaultVolume=L(t,0,1)}get defaultVolume(){return this._defaultVolume}getSounds(){return Array.from(this._all)}getSoundsForChannel(t){const e=this._channelToConfig.get(t);return e?e.sounds:[]}_isMuted(t){return this._muted.has(t)}_getEffectiveVolume(t){var e;if(this._isMuted(t))return 0;let i=this._defaultVolume;return this._mix.has(t)&&(i*=(e=this._mix.get(t))!=null?e:this._defaultVolume),i}play(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return Promise.resolve();const{sound:s}=i;if(this._isMuted(s))return Promise.resolve();const n=e*this._getEffectiveVolume(s);return s.play(n)}getSound(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;return i}setVolume(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return;const{sound:s}=i;this._setMix(s,e)}getVolume(t){var e;const i=this.getSound(t);return i&&(e=this._mix.get(i))!=null?e:0}_setMix(t,e){this._mix.set(t,e),t.volume=e}track(t,e){let i,s,n;e instanceof bi?(i=e,s=this._defaultVolume,n=[]):{sound:i,volume:s,channels:n}=e,this._nameToConfig.set(t,{sound:i,volume:s,channels:n}),this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i),n&&this.addChannel(t,n)}untrack(t){this._nameToConfig.delete(t);const e=this.getSound(t);e&&(this._mix.delete(e),this._all.delete(e))}stop(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.stop();return}this._all.forEach(e=>e.stop())}mute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._muted.add(i),i.pause();return}this._muted=new Set(this._all),this._muted.forEach(e=>e.pause())}unmute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.play(),this._muted.delete(i);return}this._muted.forEach(e=>e.play()),this._muted.clear()}toggle(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._isMuted(i)?this.unmute(t):this.mute(t);return}this._muted.size>0?(this._muted.forEach(e=>e.play()),this._muted.clear()):(this._muted=new Set(this._all),this._muted.forEach(e=>e.pause()))}addChannel(t,e){const i=this.getSound(t);if(!i)return;const s=this._mix.get(i);this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i);for(const n of e){let o=this._channelToConfig.get(n);o||(o={sounds:[i]}),o.sounds.indexOf(i)===-1&&o.sounds.push(i),this._channelToConfig.set(n,o)}}removeChannel(t,e){const i=this.getSound(t);if(i)for(const s of e){const n=this._channelToConfig.get(s);if(!n)return;const o=n.sounds.indexOf(i);o>=-1&&n.sounds.splice(o,1),this._channelToConfig.set(s,n)}}}class Sc{constructor(t,e=!1){this.path=t,this.width=0,this.height=0,this._images=[],this.data=[],this._sprites=[],this._resource=new fi(t,"arraybuffer",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 Ia(t),this._gif=new Ra(this._stream);const e=this._gif.images.map(i=>new Wt(i.src,!1));return await Promise.all(e.map(i=>i.load())),this.data=this._images=e,this._sprites=this._images.map(i=>i.toSprite()),this.data}isLoaded(){return!!this.data}toSprite(t=0){var e;return(e=this._sprites[t])!=null?e:null}toSpriteSheet(){const t=this._sprites;return t.length?new Ae({sprites:t}):null}toAnimation(t){var e;const i=(e=this._gif)==null?void 0:e.images;if(i!=null&&i.length){const s=i.map((n,o)=>{var a;return{graphic:this._sprites[o],duration:((a=this._gif)==null?void 0:a.frames[o].delayMs)||void 0}});return this._animation=new Gi({frames:s,frameDuration:t}),this._animation}return null}get readCheckBytes(){var t,e;return(e=(t=this._gif)==null?void 0:t.checkBytes)!=null?e:[]}}const fs=r=>r.reduce(function(t,e){return t*2+e},0),nr=r=>{const t=[];for(let e=7;e>=0;e--)t.push(!!(r&1<<e));return t};class Ia{constructor(t){if(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=e=>{const i=[];for(let s=0;s<e;s++)i.push(this.readByte());return i},this.read=e=>{let i="";for(let s=0;s<e;s++)i+=String.fromCharCode(this.readByte());return i},this.readUnsigned=()=>{const e=this.readBytes(2);return(e[1]<<8)+e[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,this.len===0)throw new Error("No data loaded from file")}}const Tc=function(r,t){let e=0;const i=function(_){let f=0;for(let m=0;m<_;m++)t.charCodeAt(e>>3)&1<<(e&7)&&(f|=1<<m),e++;return f},s=[],n=1<<r,o=n+1;let a=r+1,h=[];const l=function(){h=[],a=r+1;for(let _=0;_<n;_++)h[_]=[_];h[n]=[],h[o]=null};let c=0,d=0;for(;;){if(d=c,c=i(a),c===n){l();continue}if(c===o)break;if(c<h.length)d!==n&&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]))}s.push.apply(s,h[c]),h.length===1<<a&&a<12&&a++}return s};class Ra{constructor(t){this._handler={},this.frames=[],this.images=[],this.globalColorTableBytes=[],this.checkBytes=[],this.parseColorTableBytes=e=>{const i=[];for(let s=0;s<e;s++){const n=this._st.readBytes(3);i.push(n)}return i},this.readSubBlocks=()=>{let e,i;i="";do e=this._st.readByte(),i+=this._st.read(e);while(e!==0);return i},this.parseHeader=()=>{const e={sig:"",ver:"",width:0,height:0,colorResolution:0,globalColorTableSize:0,gctFlag:!1,sortedFlag:!1,globalColorTable:[],backgroundColorIndex:0,pixelAspectRatio:0};if(e.sig=this._st.read(3),e.ver=this._st.read(3),e.sig!=="GIF")throw new Error("Not a GIF file.");e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned(),this._currentFrameCanvas.width=e.width,this._currentFrameCanvas.height=e.height;const i=nr(this._st.readByte());e.gctFlag=i.shift(),e.colorResolution=fs(i.splice(0,3)),e.sortedFlag=i.shift(),e.globalColorTableSize=fs(i.splice(0,3)),e.backgroundColorIndex=this._st.readByte(),e.pixelAspectRatio=this._st.readByte(),e.gctFlag&&(this.globalColorTableBytes=this.parseColorTableBytes(1<<e.globalColorTableSize+1)),this._handler.hdr&&this._handler.hdr(e)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=e=>{const i=h=>{this.checkBytes.push(this._st.readByte());const l=nr(this._st.readByte());return h.reserved=l.splice(0,3),h.disposalMethod=fs(l.splice(0,3)),h.userInputFlag=l.shift(),h.transparentColorFlag=l.shift(),h.delayTime=this._st.readUnsigned(),h.transparentColorIndex=this._st.readByte(),h.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(h)&&this.checkBytes.push(this._handler.gce),h},s=h=>{h.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(h)&&this.checkBytes.push(this._handler.com)},n=h=>{this.checkBytes.push(this._st.readByte()),h.ptHeader=this._st.readBytes(12),h.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(h)&&this.checkBytes.push(this._handler.pte)},o=h=>{const l=d=>{this.checkBytes.push(this._st.readByte()),d.unknown=this._st.readByte(),d.iterations=this._st.readUnsigned(),d.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(d)&&this.checkBytes.push(this._handler.app)},c=d=>{d.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[d.identifier]&&this._handler.app[d.identifier](d)&&this.checkBytes.push(this._handler.app[d.identifier])};switch(this.checkBytes.push(this._st.readByte()),h.identifier=this._st.read(8),h.authCode=this._st.read(3),h.identifier){case"NETSCAPE":l(h);break;default:c(h);break}},a=h=>{h.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(h)&&this.checkBytes.push(this._handler.unknown)};switch(e.label=this._st.readByte(),e.label){case 249:e.extType="gce",this._gce=i(e);break;case 254:e.extType="com",s(e);break;case 1:e.extType="pte",n(e);break;case 255:e.extType="app",o(e);break;default:e.extType="unknown",a(e);break}},this.parseImg=e=>{var i;const s=(a,h)=>{const l=new Array(a.length),c=a.length/h,d=(p,x)=>{const v=a.slice(x*h,(x+1)*h);l.splice.apply(l,[p*h,h].concat(v))},_=[0,4,2,1],f=[8,8,4,2];let m=0;for(let p=0;p<4;p++)for(let x=_[p];x<c;x+=f[p])d(x,m),m++;return l};e.leftPos=this._st.readUnsigned(),e.topPos=this._st.readUnsigned(),e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned();const n=nr(this._st.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=fs(n.splice(0,3)),e.lctFlag&&(e.lctBytes=this.parseColorTableBytes(1<<e.lctSize+1)),e.lzwMinCodeSize=this._st.readByte();const o=this.readSubBlocks();e.pixels=Tc(e.lzwMinCodeSize,o),e.interlaced&&(e.pixels=s(e.pixels,e.width)),(i=this._gce)!=null&&i.delayTime&&(e.delayMs=this._gce.delayTime*10),this.frames.push(e),this.arrayToImage(e,e.lctFlag?e.lctBytes:this.globalColorTableBytes),this._handler.img&&this._handler.img(e)&&this.checkBytes.push(this._handler)},this.parseBlocks=()=>{const e={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(e.sentinel)){case"!":e.type="ext",this.parseExt(e);break;case",":e.type="img",this.parseImg(e);break;case";":e.type="eof",this._handler.eof&&this._handler.eof(e)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+e.sentinel.toString(16))}e.type!=="eof"&&this.parseBlocks()},this.arrayToImage=(e,i)=>{var s,n,o,a;const h=document.createElement("canvas");h.width=e.width,h.height=e.height;const l=h.getContext("2d"),c=l.getImageData(0,0,h.width,h.height);let d=-1;(s=this._gce)!=null&&s.transparentColorFlag&&(d=this._gce.transparentColorIndex);for(let f=0;f<e.pixels.length;f++){const m=e.pixels[f],p=i[m];m===d?c.data.set([0,0,0,0],f*4):c.data.set([...p,255],f*4)}if(l.putImageData(c,0,0),((n=this._gce)==null?void 0:n.disposalMethod)===1&&this.images.length)this._currentFrameContext.drawImage(this.images[this.images.length-1],0,0);else if(((o=this._gce)==null?void 0:o.disposalMethod)===2&&((a=this._hdr)!=null&&a.gctFlag)){const f=i[this._hdr.backgroundColorIndex];this._currentFrameContext.fillStyle=`rgb(${f[0]}, ${f[1]}, ${f[2]})`,this._currentFrameContext.fillRect(0,0,this._hdr.width,this._hdr.height)}else this._currentFrameContext.clearRect(0,0,this._currentFrameCanvas.width,this._currentFrameCanvas.height);this._currentFrameContext.drawImage(h,e.leftPos,e.topPos,e.width,e.height);const _=new Image;_.src=this._currentFrameCanvas.toDataURL(),this.images.push(_)},this._st=t,this._handler={},this._currentFrameCanvas=document.createElement("canvas"),this._currentFrameContext=this._currentFrameCanvas.getContext("2d"),this.parseHeader(),this.parseBlocks()}}class Ac{constructor(t,e,{bustCache:i,...s}={}){this.path=t,this.family=e,this._isLoaded=!1,this._resource=new fi(t,"blob",i),this._options=s}async load(){if(this.isLoaded())return this.data;try{const t=await this._resource.load(),e=URL.createObjectURL(t);this.data||(this.data=new FontFace(this.family,`url(${e})`),document.fonts.add(this.data)),await this.data.load(),this._isLoaded=!0}catch(t){throw`Error loading FontSource from path '${this.path}' with error [${t.message}]`}return this.data}isLoaded(){return this._isLoaded}toFont(t){return new Ee({family:this.family,...this._options,...t})}}const Ma=Ta(),Pc=/^\s*(?:function)?\*/;function Fa(r){return typeof r!="function"?!1:Pc.test(Function.prototype.toString.call(r))?!0:Object.getPrototypeOf?Object.getPrototypeOf(r)===Object.getPrototypeOf(new Function("return function * () {}")()):!1}function Da(...r){var t;const e=F.getInstance();let i,s,n,o;Fa(r[0])&&(s=globalThis,i=r[0],n=r[1]),Fa(r[1])&&(s=r[0],i=r[1],n=r[2]),r[1]instanceof us&&(s=r[0],o=r[1],i=r[2],n=r[3]),r[0]instanceof us&&(s=globalThis,o=r[0],i=r[1],n=r[2]);const a=Aa(Ma),h=n==null?void 0:n.timing,l=a?!1:(t=n==null?void 0:n.autostart)!=null?t:!0;let c;try{c=o!=null?o:us.useEngine()}catch(b){throw Error(`Cannot run coroutine without engine parameter outside of an excalibur lifecycle method.
930
- Pass an engine parameter to ex.coroutine(engine, function * {...})`)}let d=!1,_=!1,f=!1;const m=i.bind(s),p=m();let x;const v=new Promise((b,S)=>{x=A=>{try{if(f){_=!0,b();return}const{done:M,value:C}=Ma.scope(!0,()=>p.next(A));if(M||f){_=!0,b();return}C instanceof Promise?C.then(()=>{c.clock.schedule(x,0,h)}):C===void 0||C===void 0?c.clock.schedule(x,0,h):c.clock.schedule(x,C||0,h)}catch(M){S(M);return}},l&&(d=!0,x(c.clock.elapsed()))}),g={isRunning:()=>d&&!f&&!_,isComplete:()=>_,cancel:()=>{f=!0},start:()=>(d?e.warn(`.start() was called on a coroutine that was already started, this is probably a bug:
931
- `,Function.prototype.toString.call(m)):(d=!0,x(c.clock.elapsed())),g),generator:p,done:v,then:v.then.bind(v),[Symbol.iterator]:()=>p};return g}class gs extends Tt{constructor(t){var e,i,s,n,o;super(),this._logger=F.getInstance(),this.transform=new E,this.graphics=new Z,this._completeFuture=new xt,this.started=!1,this._currentDistance=0,this._currentProgress=0,this.done=this._completeFuture.promise,this._useLegacyEasing=!1,this.name=`Transition#${this.id}`,this.duration=t.duration,Ie(t.easing)?(this.legacyEasing=(e=t.easing)!=null?e:Dt.Linear,this._useLegacyEasing=!0):this.easing=(i=t.easing)!=null?i:Mi,this.direction=(s=t.direction)!=null?s:"out",this.hideLoader=(n=t.hideLoader)!=null?n:!1,this.blockInput=(o=t.blockInput)!=null?o:!1,this.transform.coordPlane=ht.Screen,this.transform.pos=w.Zero,this.transform.z=1/0,this.graphics.anchor=w.Zero,this.addComponent(this.transform),this.addComponent(this.graphics),this.direction==="out"?this._currentProgress=0:this._currentProgress=1}get progress(){return this._currentProgress}get distance(){return this._currentDistance}get complete(){return this.direction==="out"?this.progress>=1:this.progress<=0}updateTransition(t,e){this.complete||(this._currentDistance+=L(e/this.duration,0,1),this._currentDistance>=1&&(this._currentDistance=1),this.direction==="out"?this._useLegacyEasing?this._currentProgress=L(this.legacyEasing(this._currentDistance,0,1,1),0,1):this._currentProgress=L(X(0,1,this.easing(this._currentDistance)),0,1):this._useLegacyEasing?this._currentProgress=L(this.legacyEasing(this._currentDistance,1,0,1),0,1):this._currentProgress=L(X(1,0,this.easing(this._currentDistance)),0,1))}async onPreviousSceneDeactivate(t){}onStart(t){}onUpdate(t){}onEnd(t){}onReset(){}reset(){this.started=!1,this._completeFuture=new xt,this.done=this._completeFuture.promise,this._currentDistance=0,this.direction==="out"?this._currentProgress=0:this._currentProgress=1,this.onReset()}_addToTargetScene(t,e){const i=e;if(this.started&&this._logger.warn(`Attempted to add a transition ${this.name} that is already playing.`),i.world.entityManager.getById(this.id))return this._co;this._engine=t,i.add(this);const s=this;return this._co=Da(t,function*(){for(;!s.complete;){const n=yield;s.updateTransition(s._engine,n),s._execute()}},{autostart:!1}),this._co}async _play(){this.started&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that is already playing, reset transition.`)),(!this._engine||!this._co)&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that hasn't been added`)),this._co&&await this._co.start()}_execute(){this.isInitialized&&(this.started||(this.started=!0,this.onStart(this.progress)),this.onUpdate(this.progress),this.complete&&!this._completeFuture.isCompleted&&(this.onEnd(this.progress),this._completeFuture.resolve()))}}class Ec extends gs{constructor(t){var e,i;super({...t,duration:(e=t.duration)!=null?e:2e3}),this.name=`FadeInOut#${this.id}`,this.color=(i=t.color)!=null?i:T.Black}onInitialize(t){this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=new mi({width:t.screen.resolution.width,height:t.screen.resolution.height,color:this.color}),this.graphics.add(this.screenCover),this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=t}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class Ic extends gs{constructor(t){super({direction:"in",...t}),this.name=`CrossFade#${this.id}`}async onPreviousSceneDeactivate(t){this.image=await t.engine.screenshot(!0),await this.image.decode()}onInitialize(t){this.engine=t,this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=Wt.fromHtmlImageElement(this.image).toSprite(),this.graphics.add(this.screenCover),this.transform.scale=y(1/t.screen.pixelRatio,1/t.screen.pixelRatio),this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class Rc extends gs{constructor(t){var e;super({direction:"in",...t}),this._easing=Dt.Linear,this._start=w.Zero,this._end=w.Zero,this.name=`Slide#${this.id}`,this.slideDirection=t.slideDirection,this.transform.coordPlane=ht.Screen,this.graphics.forceOnScreen=!0,this._easing=(e=t.easingFunction)!=null?e:this._easing}async onPreviousSceneDeactivate(t){this._image=await t.engine.screenshot(!0),await this._image.decode(),this._screenCover=Wt.fromHtmlImageElement(this._image).toSprite()}onInitialize(t){this._engine=t;let e=t.screen.unsafeArea;switch(e.hasZeroDimensions()&&(e=t.screen.contentArea),this.slideDirection){case"up":{this._directionOffset=y(0,-e.height);break}case"down":{this._directionOffset=y(0,e.height);break}case"left":{this._directionOffset=y(-e.width,0);break}case"right":{this._directionOffset=y(e.width,0);break}}this._camera=this._engine.currentScene.camera,this._destinationCameraPosition=this._camera.pos.clone(),this._camera.pos=this._camera.pos.add(this._directionOffset),this.transform.pos=this.transform.pos.add(this._directionOffset),this._startCameraPosition=this._camera.pos.clone(),this._start=e.topLeft,this._end=this._start.add(this._directionOffset),this.transform.pos=this._start,this.graphics.use(this._screenCover),this.transform.scale=y(1/t.screen.pixelRatio,1/t.screen.pixelRatio)}onStart(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=X(this._start.x,this._end.x,e),this.transform.pos.y=X(this._start.y,this._end.y,e),this._camera.pos.x=X(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=X(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}onUpdate(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=X(this._start.x,this._end.x,e),this.transform.pos.y=X(this._start.y,this._end.y,e),this._camera.pos.x=X(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=X(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}}const De=class P{static init(t=!0){if(P._INITIALIZED){P._LOGGER.warn("Serializer already initialized. Call reset() before re-initializing.");return}P._REGISTERBUILTINSERIALIZERS(),t&&P._REGISTERCOMMONCOMPONENTS(),P._INITIALIZED=!0}static isInitialized(){return P._INITIALIZED}static registerComponent(t){const e=t.name;if(P._COMPONENTREGISTRY.has(e)){P._LOGGER.warn(`Component ${e} is already registered`);return}P._COMPONENTREGISTRY.set(e,t)}static _REGISTERCOMMONCOMPONENTS(){const t=[E,H,Z,qt,re,U,j];P.registerComponents(t)}static registerComponents(t){for(const e of t)P.registerComponent(e)}static isComponentRegistered(t){return P._COMPONENTREGISTRY.has(t)}static getRegisteredComponents(){return Array.from(P._COMPONENTREGISTRY.keys())}static unregisterComponent(t){return P._INITIALIZED?P._COMPONENTREGISTRY.delete(t):(P._LOGGER.warn("Serializer not initialized. Call init() before registering components."),!1)}static clearComponents(){P._COMPONENTREGISTRY.clear()}static registerCustomActor(t){const e=t.name;if(P._ACTORREGISTRY.has(e)){P._LOGGER.warn(`Custom Actor ${e} is already registered`);return}P._ACTORREGISTRY.set(e,t)}static registerCustomActors(t){for(const e of t)P.registerCustomActor(e)}static isCustomActorRegistered(t){return!!P._ACTORREGISTRY.has(t)}static getRegisteredCustomActors(){return P._ACTORREGISTRY.size>0?Array.from(P._ACTORREGISTRY.keys()):[]}static getCustomActor(t){return P._ACTORREGISTRY.has(t)?P._ACTORREGISTRY.get(t):null}static unregisterCustomActor(t){return P._ACTORREGISTRY.has(t)?P._ACTORREGISTRY.delete(t):!1}static clearCustomActors(){P._ACTORREGISTRY.clear()}static registerGraphic(t,e){if(P._GRAPHICSREGISTRY.has(t)){P._LOGGER.warn(`Graphic ${t} is already registered`);return}P._GRAPHICSREGISTRY.set(t,e)}static registerGraphics(t){for(const[e,i]of Object.entries(t))P.registerGraphic(e,i)}static getGraphic(t){return P._GRAPHICSREGISTRY.get(t)}static isGraphicRegistered(t){return P._GRAPHICSREGISTRY.has(t)}static getRegisteredGraphics(){return Array.from(P._GRAPHICSREGISTRY.keys())}static unregisterGraphic(t){return P._GRAPHICSREGISTRY.delete(t)}static clearGraphics(){P._GRAPHICSREGISTRY.clear()}static serializeComponent(t){if(!P._INITIALIZED)return P._LOGGER.warn("Serializer not initialized. Call init() before registering components."),null;if(!t.serialize)return P._LOGGER.warn(`Component ${t.constructor.name} does not have a serialize method`),null;try{const e=t.serialize();return{type:t.constructor.name,...e}}catch(e){return P._LOGGER.error(`Error serializing component ${t.constructor.name}:`,e),null}}static deserializeComponent(t){if(!P._INITIALIZED)return P._LOGGER.warn("Serializer not initialized. Call init() before registering components."),null;if(!t.type)return P._LOGGER.error("Component data missing type field"),null;const e=t.type==="GraphicsComponent",i=P._COMPONENTREGISTRY.get(t.type);if(!i)return P._LOGGER.warn(`Component type ${t.type} is not registered`),null;try{const s=new i;if(s.deserialize&&(s.deserialize(t),e)){const n=P.getGraphic(t.current).clone();n&&s.use(n),t.tint&&(s.current.tint=P._CUSTOMSERIALIZERS.get("Color").deserialize(t.tint))}return s}catch(s){return P._LOGGER.error(`Error deserializing component ${t.type}:`,s),null}}static serializeEntity(t){const e=[],i=[];for(const n of t.tags)i.push(n);for(const n of t.getComponents()){const o=P.serializeComponent(n);o&&e.push(o)}const s=[];for(const n of t.children)s.push(P.serializeEntity(n));return{type:"Entity",name:t.name,tags:i,components:e,children:s}}static deserializeEntity(t){try{const e=new Tt;e.name=t.name;for(const i of t.components){const s=P.deserializeComponent(i);s&&e.addComponent(s)}for(const i of t.children){const s=P.deserializeEntity(i);s&&e.addChild(s)}return e}catch(e){return P._LOGGER.error("Error deserializing entity:",e),null}}static serializeActor(t){const e=[];let i;for(const[o,a]of P._ACTORREGISTRY.entries())if(t instanceof a){i=o;break}const s=[];for(const o of t.tags)s.push(o);for(const o of t.getComponents()){const a=P.serializeComponent(o);a&&e.push(a)}const n=[];for(const o of t.children)n.push(P.serializeEntity(o));return{type:"Actor",name:t.name,tags:s,components:e,children:n,customInstance:i}}static deserializeActor(t){try{let e;if(t.customInstance){const i=P._ACTORREGISTRY.get(t.customInstance);i&&(e=new i)}else e=new Bt;e.name=t.name;for(const i of e.getComponents())e.removeComponent(i,!0);for(const i of t.components){const s=P.deserializeComponent(i);s&&e.addComponent(s)}e.get(E)&&(e.transform=e.get(E)),e.get(qt)&&(e.pointer=e.get(qt)),e.get(Z)&&(e.graphics=e.get(Z)),e.get(H)&&(e.motion=e.get(H)),e.get(re)&&(e.actions=e.get(re)),e.get(U)&&(e.body=e.get(U)),e.get(j)&&(e.collider=e.get(j));for(const i of t.children){const s=P.deserializeEntity(i);s&&e.addChild(s)}return e}catch(e){return P._LOGGER.error("Error deserializing entity:",e),null}}static entityToJSON(t,e=!1){const i=P.serializeEntity(t);return JSON.stringify(i,null,e?2:0)}static entityFromJSON(t){try{const e=JSON.parse(t);return P.deserializeEntity(e)}catch(e){return P._LOGGER.error("Error parsing entity JSON:",e),null}}static actorToJSON(t,e=!1){const i=P.serializeActor(t);return JSON.stringify(i,null,e?2:0)}static actorFromJSON(t){try{const e=JSON.parse(t);return P.deserializeActor(e)}catch(e){return P._LOGGER.error("Error parsing actor JSON:",e),null}}static validateEntityData(t){if(!t||typeof t!="object"||t.type!=="Entity"||typeof t.name!="string"||!Array.isArray(t.components)||!Array.isArray(t.children))return!1;for(const e of t.components)if(!e.type||typeof e.type!="string")return!1;for(const e of t.children)if(!P.validateEntityData(e))return!1;return!0}static reset(){P._COMPONENTREGISTRY.clear(),P._CUSTOMSERIALIZERS.clear(),P._GRAPHICSREGISTRY.clear(),P._ACTORREGISTRY.clear(),P._INITIALIZED=!1}static _REGISTERBUILTINSERIALIZERS(){P.registerCustomSerializer("Vector",t=>({x:t.x,y:t.y}),t=>({x:t.x,y:t.y})),P.registerCustomSerializer("Color",t=>({r:t.r,g:t.g,b:t.b,a:t.a}),t=>({r:t.r,g:t.g,b:t.b,a:t.a})),P.registerCustomSerializer("BoundingBox",t=>({left:t.left,top:t.top,right:t.right,bottom:t.bottom}),t=>({left:t.left,top:t.top,right:t.right,bottom:t.bottom}))}static registerCustomSerializer(t,e,i){P._CUSTOMSERIALIZERS.set(t,{serialize:e,deserialize:i})}static getCustomSerializer(t){return P._CUSTOMSERIALIZERS.get(t)}static getRegistry(t){switch(t){case"graphics":return P._GRAPHICSREGISTRY;case"actors":return P._ACTORREGISTRY;case"components":return P._COMPONENTREGISTRY}}};De._LOGGER=F.getInstance(),De._COMPONENTREGISTRY=new Map,De._GRAPHICSREGISTRY=new Map,De._ACTORREGISTRY=new Map,De._CUSTOMSERIALIZERS=new Map,De._INITIALIZED=!1;let Ba=De;const Mc=Object.freeze(Object.defineProperty({__proto__:null,ConsoleAppender:Rs,DrawUtil:Xl,EasingFunctions:Dt,LogLevel:He,Logger:F,Observable:pt,ScreenAppender:yr,Serializer:Ba,addItemToArray:Dh,contains:Ar,delay:zi,fail:Pr,getMinIndex:Tr,getPosition:ci,isLegacyEasing:Ie,isObject:Ui,mergeDeep:Oi,omit:Er,removeItemFromArray:qe},Symbol.toStringTag,{value:"Module"})),La=5,ni={},Fc=()=>{for(const r in ni)ni[r]=0},ps=(r,t)=>{const e=Ue.isEnabled("suppress-obsolete-message");ni[r]<La&&!e&&(F.getInstance().warn(r),console.trace&&t.showStackTrace&&console.trace()),ni[r]++};function Dc(r){return r={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...r},function(t,e,i){if(i&&!(typeof i.value=="function"||typeof i.get=="function"||typeof i.set=="function"))throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${t.name||""}${t.name&&e?".":""}${e||""}`} is marked obsolete: ${r.message}`+(r.alternateMethod?` Use ${r.alternateMethod} instead`:"");ni[n]||(ni[n]=0);const o=i?{...i}:t;if(!i){class a extends o{constructor(...l){ps(n,r),super(...l)}}return a}return i&&i.value?(o.value=function(){return ps(n,r),i.value.apply(this,arguments)},o):(i&&i.get&&(o.get=function(){return ps(n,r),i.get.apply(this,arguments)}),i&&i.set&&(o.set=function(){return ps(n,r),i.set.apply(this,arguments)}),o)}}class Bc{constructor(){this._queue=[]}get length(){return this._queue.length}enqueue(){const t=new xt;return this._queue.push(t),t.promise}dequeue(t){this._queue.shift().resolve(t)}}class Lc{constructor(t){this._count=t,this._waitQueue=new Bc}get count(){return this._count}get waiting(){return this._waitQueue.length}async enter(){return this._count!==0?(this._count--,Promise.resolve()):this._waitQueue.enqueue()}exit(t=1){if(t!==0){for(;t!==0&&this._waitQueue.length!==0;)this._waitQueue.dequeue(null),t--;this._count+=t}}}const rr="0.33.0-alpha.99+77deb55";ze(),u.ActionCompleteEvent=nn,u.ActionContext=xi,u.ActionQueue=ho,u.ActionSequence=sr,u.ActionStartEvent=sn,u.ActionsComponent=re,u.ActionsSystem=Yn,u.ActivateEvent=js,u.Actor=Bt,u.ActorEvents=Fl,u.AddEvent=rn,u.AddedComponent=Bh,u.AffineMatrix=tt,u.Animation=Gi,u.AnimationDirection=Nr,u.AnimationEvents=Wh,u.AnimationStrategy=Hr,u.ArcadeSolver=kn,u.AudioContextFactory=fe,u.Axes=ha,u.Axis=ta,u.BaseAlign=pn,u.BezierCurve=ai,u.Blink=Io,u.BodyComponent=U,u.BoundingBox=D,u.BrowserComponent=Jn,u.BrowserEvents=wa,u.Buttons=Zn,u.Camera=oa,u.CameraEvents=Kl,u.Canvas=ji,u.ChannelCollection=Ea,u.Circle=Zi,u.CircleCollider=dt,u.Clock=Kn,u.ClosestLineJumpTable=jt,u.Collider=di,u.ColliderComponent=j,u.CollisionContact=Se,u.CollisionEndEvent=li,u.CollisionGroup=Yt,u.CollisionGroupManager=Fi,u.CollisionJumpTable=Ht,u.CollisionPostSolveEvent=ki,u.CollisionPreSolveEvent=Li,u.CollisionStartEvent=hi,u.CollisionSystem=is,u.CollisionType=R,u.Color=T,u.ColorBlindFlags=ma,u.ColorBlindnessMode=Ke,u.ColorBlindnessPostProcessor=so,u.Component=Rt,u.CompositeCollider=nt,u.ConsoleAppender=Rs,u.ContactConstraintPoint=Uo,u.ContactEndEvent=Bi,u.ContactSolveBias=_e,u.ContactStartEvent=Di,u.CoordPlane=ht,u.CrossFade=Ic,u.CurveBy=Lo,u.CurveTo=Bo,u.DeactivateEvent=Qs,u.Debug=It,u.DebugConfig=va,u.DebugGraphicsComponent=Xi,u.DebugSystem=$n,u.DebugText=wn,u.DefaultAntialiasOptions=qr,u.DefaultGarbageCollectionOptions=er,u.DefaultLoader=Ci,u.DefaultPixelArtOptions=Xr,u.DegreeOfFreedom=oe,u.Delay=Mo,u.Detector=Xo,u.Die=Fo,u.Direction=vn,u.Director=Sa,u.DirectorEvents=Ca,u.DisplayMode=yi,u.DynamicTree=cn,u.DynamicTreeCollisionProcessor=Ni,u.EX_VERSION=rr,u.EaseBy=Eo,u.EaseTo=Po,u.EasingFunctions=Dt,u.Edge=Ts,u.EdgeCollider=Et,u.ElasticToActorStrategy=sa,u.EmitterType=Fe,u.Engine=us,u.EngineEvents=oc,u.EnterTriggerEvent=tn,u.EnterViewPortEvent=Ks,u.Entity=Tt,u.EntityEvents=Uh,u.EntityManager=Rr,u.EventEmitter=Y,u.EventTypes=Fs,u.Events=Fh,u.ExResponse=Nn,u.ExcaliburGraphicsContext2DCanvas=Ji,u.ExcaliburGraphicsContextWebGL=Kt,u.ExitTriggerEvent=en,u.ExitViewPortEvent=Js,u.Fade=Ro,u.FadeInOut=Ec,u.Flags=Ue,u.Flash=Do,u.Follow=Mn,u.Font=Ee,u.FontCache=Yi,u.FontSource=Ac,u.FontStyle=mn,u.FontUnit=fn,u.FpsSampler=xa,u.FrameStats=Ei,u.Future=xt,u.GameEvent=k,u.GameStartEvent=ks,u.GameStopEvent=zs,u.Gamepad=hs,u.GamepadAxisEvent=$s,u.GamepadButtonEvent=Xs,u.GamepadConnectEvent=Vs,u.GamepadDisconnectEvent=qs,u.Gamepads=as,u.GarbageCollector=Pa,u.Gif=Sc,u.GifParser=Ra,u.GlobalCoordinates=Ne,u.GpuParticleEmitter=lc,u.GpuParticleRenderer=_s,u.Graph=Ss,u.Graphic=ot,u.GraphicsComponent=Z,u.GraphicsGroup=$e,u.GraphicsSystem=yn,u.HashColliderProxy=zo,u.HashGridCell=te,u.HashGridProxy=Dn,u.HiddenEvent=Zs,u.HorizontalFirst=un,u.ImageFiltering=vt,u.ImageSource=Wt,u.ImageSourceAttributeConstants=N,u.ImageWrapping=_t,u.InitializeEvent=Ve,u.InputHost=Qn,u.InputMapper=la,u.IsometricEntityComponent=Si,u.IsometricEntitySystem=Xn,u.IsometricMap=Jl,u.IsometricTile=Jo,u.KeyEvent=Ti,u.Keyboard=fa,u.Keys=_a,u.KillEvent=Ds,u.Label=ac,u.LimitCameraBoundsStrategy=ra,u.Line=xn,u.LineSegment=it,u.Loader=ns,u.LoaderEvents=Hl,u.LockCameraToActorAxisStrategy=ia,u.LockCameraToActorStrategy=ea,u.LogLevel=He,u.Logger=F,u.Material=ro,u.Matrix=St,u.MatrixLocations=fr,u.MediaEvent=Hn,u.Meet=ts,u.MotionComponent=H,u.MotionSystem=es,u.MoveBy=In,u.MoveByWithOptions=_o,u.MoveTo=Rn,u.MoveToWithOptions=go,u.NativePointerButton=Me,u.NativeSoundEvent=Re,u.NativeSoundProcessedEvent=Wo,u.NineSlice=Sn,u.NineSliceStretch=Vr,u.Node=As,u.None=_n,u.Observable=pt,u.OffscreenSystem=bn,u.Pair=mt,u.ParallaxComponent=$i,u.ParallelActions=cc,u.Particle=Ki,u.ParticleEmitter=hc,u.ParticleRenderer=eo,u.ParticleTransform=Qt,u.PauseComponent=Mt,u.PauseEvent=Cr,u.PauseSystem=pa,u.PhysicsStats=cs,u.PhysicsWorld=Oo,u.PointerAbstraction=jn,u.PointerButton=ge,u.PointerComponent=qt,u.PointerEvent=Ai,u.PointerEventReceiver=ls,u.PointerScope=Oe,u.PointerSystem=os,u.PointerType=pe,u.Polygon=Cn,u.PolygonCollider=lt,u.Pool=Hi,u.PositionNode=mr,u.PostCollisionEvent=Ce,u.PostDebugDrawEvent=Hs,u.PostDrawEvent=We,u.PostFrameEvent=Ws,u.PostKillEvent=Ls,u.PostTransformDrawEvent=Os,u.PostUpdateEvent=ue,u.PreCollisionEvent=be,u.PreDebugDrawEvent=Ns,u.PreDrawEvent=Ge,u.PreFrameEvent=Gs,u.PreKillEvent=Bs,u.PreLoadEvent=sc,u.PreTransformDrawEvent=Us,u.PreUpdateEvent=de,u.Projection=ri,u.QuadIndexBuffer=ti,u.QuadTree=ii,u.Query=Nt,u.QueryManager=Mr,u.RadiusAroundActorStrategy=na,u.Random=le,u.Raster=je,u.Ray=xe,u.RealisticSolver=zn,u.Rectangle=mi,u.RemoveEvent=on,u.RemovedComponent=kh,u.RentalPool=Qe,u.Repeat=lo,u.RepeatForever=co,u.Resolution=Un,u.Resource=fi,u.ResourceEvents=Vh,u.ResumeEvent=Sr,u.RotateBy=wo,u.RotateByWithOptions=vo,u.RotateTo=mo,u.RotateToWithOptions=po,u.RotationType=et,u.ScaleBy=To,u.ScaleByWithOptions=So,u.ScaleTo=bo,u.ScaleToWithOptions=yo,u.Scene=Lt,u.SceneEvents=nc,u.Screen=On,u.ScreenAppender=yr,u.ScreenElement=Vn,u.ScreenEvents=Ll,u.ScreenShader=io,u.ScrollPreventionMode=si,u.Semaphore=Lc,u.SeparatingAxis=Xe,u.SeparationInfo=zr,u.Serializer=Ba,u.Shader=Ut,u.Shape=rt,u.Slide=Rc,u.SolverStrategy=ui,u.Sound=bi,u.SoundEvents=Ol,u.SoundManager=Cc,u.SparseHashGrid=Bn,u.SparseHashGridCollisionProcessor=Ln,u.SpatialPartitionStrategy=_i,u.Sprite=zt,u.SpriteFont=Wi,u.SpriteSheet=Ae,u.StandardClock=tr,u.StateMachine=ss,u.StrategyContainer=Ko,u.Stream=Ia,u.System=Pt,u.SystemManager=Dr,u.SystemPriority=Zt,u.SystemType=At,u.TagQuery=an,u.TestClock=ya,u.Text=wi,u.TextAlign=gn,u.TextureLoader=Ze,u.Tile=Qo,u.TileMap=jo,u.TileMapEvents=Ql,u.TiledAnimation=Tn,u.TiledSprite=pi,u.Timer=rs,u.TimerEvents=Zl,u.Toaster=ba,u.Transform=se,u.TransformComponent=E,u.Transition=gs,u.TreeNode=ln,u.Trigger=aa,u.TriggerEvents=tc,u.TwoPI=gt,u.UniformBuffer=$r,u.Util=Mc,u.Vector=w,u.VectorView=bs,u.VertexBuffer=Vt,u.VertexLayout=Jt,u.VerticalFirst=dn,u.VisibleEvent=Ys,u.WebAudio=Ho,u.WebAudioInstance=Go,u.WheelDeltaMode=Pi,u.WheelEvent=ga,u.World=Br,u.angleDifference=dr,u.approximatelyEqual=cr,u.assert=ir,u.canonicalizeAngle=Ot,u.clamp=L,u.coroutine=Da,u.createId=we,u.easeInBack=Sh,u.easeInBounce=wr,u.easeInCirc=yh,u.easeInCubic=ch,u.easeInElastic=Ph,u.easeInExpo=vh,u.easeInOutBack=Ah,u.easeInOutBounce=Rh,u.easeInOutCirc=Ch,u.easeInOutCubic=Es,u.easeInOutElastic=Ih,u.easeInOutExpo=xh,u.easeInOutQuad=lh,u.easeInOutQuart=fh,u.easeInOutQuint=mh,u.easeInOutSine=oh,u.easeInQuad=ah,u.easeInQuart=uh,u.easeInQuint=gh,u.easeInSine=nh,u.easeOutBack=Th,u.easeOutBounce=Is,u.easeOutCirc=bh,u.easeOutCubic=dh,u.easeOutElastic=Eh,u.easeOutExpo=wh,u.easeOutQuad=hh,u.easeOutQuart=_h,u.easeOutQuint=ph,u.easeOutSine=rh,u.frac=ja,u.getDefaultPhysicsConfig=ne,u.glTypeToUniformTypeName=Jr,u.hasGraphicsTick=En,u.hasOnAdd=wc,u.hasOnInitialize=fc,u.hasOnPostUpdate=vc,u.hasOnPreUpdate=pc,u.hasOnRemove=xc,u.hasPostDraw=bc,u.hasPreDraw=yc,u.has_add=uc,u.has_initialize=dc,u.has_postupdate=mc,u.has_preupdate=gc,u.has_remove=_c,u.inverseLerp=gr,u.inverseLerpVector=pr,u.isActor=Ml,u.isAddedComponent=Lh,u.isComponentCtor=br,u.isLegacyEasing=Ie,u.isLoaderConstructor=Gn,u.isMoveByOptions=uo,u.isMoveToOptions=fo,u.isRemovedComponent=zh,u.isRotateByOptions=Rl,u.isRotateToOptions=Il,u.isScaleByOptions=Co,u.isScaleToOptions=xo,u.isSceneConstructor=ee,u.isScreenElement=$o,u.isSystemConstructor=Fr,u.lerp=X,u.lerpAngle=Cs,u.lerpVector=oi,u.linear=Mi,u.maxMessages=La,u.nextActionId=G,u.obsolete=Dc,u.parseImageFiltering=Ye,u.parseImageWrapping=Gt,u.pixelSnapEpsilon=B,u.randomInRange=Xt,u.randomIntInRange=Ka,u.range=Ja,u.remap=$t,u.remapVector=th,u.resetObsoleteCounter=Fc,u.sign=q,u.smootherstep=sh,u.smoothstep=ih,u.toDegrees=ur,u.toRadians=Qa,u.vec=y,u.webgl=Kh,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});