@codexo/exojs 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +119 -0
- package/README.md +137 -0
- package/dist/esm/audio/AbstractMedia.d.ts +45 -0
- package/dist/esm/audio/AbstractMedia.js +98 -0
- package/dist/esm/audio/AbstractMedia.js.map +1 -0
- package/dist/esm/audio/AudioAnalyser.d.ts +30 -0
- package/dist/esm/audio/AudioAnalyser.js +82 -0
- package/dist/esm/audio/AudioAnalyser.js.map +1 -0
- package/dist/esm/audio/Media.d.ts +25 -0
- package/dist/esm/audio/Music.d.ts +20 -0
- package/dist/esm/audio/Music.js +118 -0
- package/dist/esm/audio/Music.js.map +1 -0
- package/dist/esm/audio/Sound.d.ts +56 -0
- package/dist/esm/audio/Sound.js +393 -0
- package/dist/esm/audio/Sound.js.map +1 -0
- package/dist/esm/audio/audio-context.d.ts +11 -0
- package/dist/esm/audio/audio-context.js +115 -0
- package/dist/esm/audio/audio-context.js.map +1 -0
- package/dist/esm/audio/index.d.ts +6 -0
- package/dist/esm/core/Application.d.ts +76 -0
- package/dist/esm/core/Application.js +198 -0
- package/dist/esm/core/Application.js.map +1 -0
- package/dist/esm/core/Bounds.d.ts +19 -0
- package/dist/esm/core/Bounds.js +61 -0
- package/dist/esm/core/Bounds.js.map +1 -0
- package/dist/esm/core/Clock.d.ts +18 -0
- package/dist/esm/core/Clock.js +67 -0
- package/dist/esm/core/Clock.js.map +1 -0
- package/dist/esm/core/Color.d.ts +176 -0
- package/dist/esm/core/Color.js +261 -0
- package/dist/esm/core/Color.js.map +1 -0
- package/dist/esm/core/Quadtree.d.ts +20 -0
- package/dist/esm/core/Quadtree.js +84 -0
- package/dist/esm/core/Quadtree.js.map +1 -0
- package/dist/esm/core/Scene.d.ts +83 -0
- package/dist/esm/core/Scene.js +82 -0
- package/dist/esm/core/Scene.js.map +1 -0
- package/dist/esm/core/SceneManager.d.ts +66 -0
- package/dist/esm/core/SceneManager.js +395 -0
- package/dist/esm/core/SceneManager.js.map +1 -0
- package/dist/esm/core/SceneNode.d.ts +58 -0
- package/dist/esm/core/SceneNode.js +176 -0
- package/dist/esm/core/SceneNode.js.map +1 -0
- package/dist/esm/core/Signal.d.ts +18 -0
- package/dist/esm/core/Signal.js +61 -0
- package/dist/esm/core/Signal.js.map +1 -0
- package/dist/esm/core/Time.d.ts +38 -0
- package/dist/esm/core/Time.js +106 -0
- package/dist/esm/core/Time.js.map +1 -0
- package/dist/esm/core/Timer.d.ts +12 -0
- package/dist/esm/core/Timer.js +33 -0
- package/dist/esm/core/Timer.js.map +1 -0
- package/dist/esm/core/index.d.ts +13 -0
- package/dist/esm/core/types.d.ts +29 -0
- package/dist/esm/core/utils.d.ts +22 -0
- package/dist/esm/core/utils.js +136 -0
- package/dist/esm/core/utils.js.map +1 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +134 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.d.ts +5 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.js +29 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.js.map +1 -0
- package/dist/esm/input/GameCubeGamepadMapping.d.ts +5 -0
- package/dist/esm/input/GameCubeGamepadMapping.js +12 -0
- package/dist/esm/input/GameCubeGamepadMapping.js.map +1 -0
- package/dist/esm/input/Gamepad.d.ts +45 -0
- package/dist/esm/input/Gamepad.js +150 -0
- package/dist/esm/input/Gamepad.js.map +1 -0
- package/dist/esm/input/GamepadChannels.d.ts +39 -0
- package/dist/esm/input/GamepadChannels.js +43 -0
- package/dist/esm/input/GamepadChannels.js.map +1 -0
- package/dist/esm/input/GamepadControl.d.ts +15 -0
- package/dist/esm/input/GamepadControl.js +24 -0
- package/dist/esm/input/GamepadControl.js.map +1 -0
- package/dist/esm/input/GamepadDefinitions.d.ts +31 -0
- package/dist/esm/input/GamepadDefinitions.js +175 -0
- package/dist/esm/input/GamepadDefinitions.js.map +1 -0
- package/dist/esm/input/GamepadMapping.d.ts +23 -0
- package/dist/esm/input/GamepadMapping.js +30 -0
- package/dist/esm/input/GamepadMapping.js.map +1 -0
- package/dist/esm/input/GamepadPromptLayouts.d.ts +9 -0
- package/dist/esm/input/GamepadPromptLayouts.js +140 -0
- package/dist/esm/input/GamepadPromptLayouts.js.map +1 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.d.ts +5 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.js +53 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.js.map +1 -0
- package/dist/esm/input/Input.d.ts +28 -0
- package/dist/esm/input/Input.js +67 -0
- package/dist/esm/input/Input.js.map +1 -0
- package/dist/esm/input/InputManager.d.ts +76 -0
- package/dist/esm/input/InputManager.js +342 -0
- package/dist/esm/input/InputManager.js.map +1 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.d.ts +5 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.js +12 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.js.map +1 -0
- package/dist/esm/input/JoyConRightGamepadMapping.d.ts +5 -0
- package/dist/esm/input/JoyConRightGamepadMapping.js +12 -0
- package/dist/esm/input/JoyConRightGamepadMapping.js.map +1 -0
- package/dist/esm/input/PlayStationGamepadMapping.d.ts +5 -0
- package/dist/esm/input/PlayStationGamepadMapping.js +12 -0
- package/dist/esm/input/PlayStationGamepadMapping.js.map +1 -0
- package/dist/esm/input/Pointer.d.ts +52 -0
- package/dist/esm/input/Pointer.js +118 -0
- package/dist/esm/input/Pointer.js.map +1 -0
- package/dist/esm/input/SteamControllerGamepadMapping.d.ts +5 -0
- package/dist/esm/input/SteamControllerGamepadMapping.js +12 -0
- package/dist/esm/input/SteamControllerGamepadMapping.js.map +1 -0
- package/dist/esm/input/SwitchProGamepadMapping.d.ts +5 -0
- package/dist/esm/input/SwitchProGamepadMapping.js +12 -0
- package/dist/esm/input/SwitchProGamepadMapping.js.map +1 -0
- package/dist/esm/input/XboxGamepadMapping.d.ts +5 -0
- package/dist/esm/input/XboxGamepadMapping.js +12 -0
- package/dist/esm/input/XboxGamepadMapping.js.map +1 -0
- package/dist/esm/input/index.d.ts +19 -0
- package/dist/esm/input/types.d.ts +111 -0
- package/dist/esm/input/types.js +111 -0
- package/dist/esm/input/types.js.map +1 -0
- package/dist/esm/math/AbstractVector.d.ts +33 -0
- package/dist/esm/math/AbstractVector.js +106 -0
- package/dist/esm/math/AbstractVector.js.map +1 -0
- package/dist/esm/math/Circle.d.ts +41 -0
- package/dist/esm/math/Circle.js +134 -0
- package/dist/esm/math/Circle.js.map +1 -0
- package/dist/esm/math/CircleLike.d.ts +5 -0
- package/dist/esm/math/Collision.d.ts +28 -0
- package/dist/esm/math/Ellipse.d.ts +37 -0
- package/dist/esm/math/Ellipse.js +109 -0
- package/dist/esm/math/Ellipse.js.map +1 -0
- package/dist/esm/math/EllipseLike.d.ts +6 -0
- package/dist/esm/math/Flags.d.ts +12 -0
- package/dist/esm/math/Flags.js +41 -0
- package/dist/esm/math/Flags.js.map +1 -0
- package/dist/esm/math/Interval.d.ts +16 -0
- package/dist/esm/math/Interval.js +43 -0
- package/dist/esm/math/Interval.js.map +1 -0
- package/dist/esm/math/Line.d.ts +36 -0
- package/dist/esm/math/Line.js +111 -0
- package/dist/esm/math/Line.js.map +1 -0
- package/dist/esm/math/LineLike.d.ts +6 -0
- package/dist/esm/math/Matrix.d.ts +32 -0
- package/dist/esm/math/Matrix.js +125 -0
- package/dist/esm/math/Matrix.js.map +1 -0
- package/dist/esm/math/ObservableSize.d.ts +16 -0
- package/dist/esm/math/ObservableSize.js +55 -0
- package/dist/esm/math/ObservableSize.js.map +1 -0
- package/dist/esm/math/ObservableVector.d.ts +21 -0
- package/dist/esm/math/ObservableVector.js +71 -0
- package/dist/esm/math/ObservableVector.js.map +1 -0
- package/dist/esm/math/PointLike.d.ts +4 -0
- package/dist/esm/math/PolarVector.d.ts +8 -0
- package/dist/esm/math/PolarVector.js +17 -0
- package/dist/esm/math/PolarVector.js.map +1 -0
- package/dist/esm/math/Polygon.d.ts +38 -0
- package/dist/esm/math/Polygon.js +161 -0
- package/dist/esm/math/Polygon.js.map +1 -0
- package/dist/esm/math/PolygonLike.d.ts +6 -0
- package/dist/esm/math/Random.d.ts +15 -0
- package/dist/esm/math/Random.js +72 -0
- package/dist/esm/math/Random.js.map +1 -0
- package/dist/esm/math/Rectangle.d.ts +48 -0
- package/dist/esm/math/Rectangle.js +205 -0
- package/dist/esm/math/Rectangle.js.map +1 -0
- package/dist/esm/math/RectangleLike.d.ts +6 -0
- package/dist/esm/math/Segment.d.ts +25 -0
- package/dist/esm/math/Segment.js +77 -0
- package/dist/esm/math/Segment.js.map +1 -0
- package/dist/esm/math/ShapeLike.d.ts +4 -0
- package/dist/esm/math/Size.d.ts +24 -0
- package/dist/esm/math/Size.js +69 -0
- package/dist/esm/math/Size.js.map +1 -0
- package/dist/esm/math/Transformable.d.ts +47 -0
- package/dist/esm/math/Transformable.js +142 -0
- package/dist/esm/math/Transformable.js.map +1 -0
- package/dist/esm/math/Vector.d.ts +28 -0
- package/dist/esm/math/Vector.js +77 -0
- package/dist/esm/math/Vector.js.map +1 -0
- package/dist/esm/math/collision-detection.d.ts +41 -0
- package/dist/esm/math/collision-detection.js +394 -0
- package/dist/esm/math/collision-detection.js.map +1 -0
- package/dist/esm/math/collision-primitives.d.ts +39 -0
- package/dist/esm/math/collision-primitives.js +164 -0
- package/dist/esm/math/collision-primitives.js.map +1 -0
- package/dist/esm/math/geometry.d.ts +8 -0
- package/dist/esm/math/geometry.js +195 -0
- package/dist/esm/math/geometry.js.map +1 -0
- package/dist/esm/math/index.d.ts +27 -0
- package/dist/esm/math/utils.d.ts +21 -0
- package/dist/esm/math/utils.js +54 -0
- package/dist/esm/math/utils.js.map +1 -0
- package/dist/esm/particles/Particle.d.ts +40 -0
- package/dist/esm/particles/Particle.js +108 -0
- package/dist/esm/particles/Particle.js.map +1 -0
- package/dist/esm/particles/ParticleProperties.d.ts +14 -0
- package/dist/esm/particles/ParticleSystem.d.ts +43 -0
- package/dist/esm/particles/ParticleSystem.js +185 -0
- package/dist/esm/particles/ParticleSystem.js.map +1 -0
- package/dist/esm/particles/affectors/ColorAffector.d.ts +17 -0
- package/dist/esm/particles/affectors/ColorAffector.js +40 -0
- package/dist/esm/particles/affectors/ColorAffector.js.map +1 -0
- package/dist/esm/particles/affectors/ForceAffector.d.ts +13 -0
- package/dist/esm/particles/affectors/ForceAffector.js +27 -0
- package/dist/esm/particles/affectors/ForceAffector.js.map +1 -0
- package/dist/esm/particles/affectors/ParticleAffector.d.ts +6 -0
- package/dist/esm/particles/affectors/ScaleAffector.d.ts +13 -0
- package/dist/esm/particles/affectors/ScaleAffector.js +27 -0
- package/dist/esm/particles/affectors/ScaleAffector.js.map +1 -0
- package/dist/esm/particles/affectors/TorqueAffector.d.ts +12 -0
- package/dist/esm/particles/affectors/TorqueAffector.js +25 -0
- package/dist/esm/particles/affectors/TorqueAffector.js.map +1 -0
- package/dist/esm/particles/emitters/ParticleEmitter.d.ts +6 -0
- package/dist/esm/particles/emitters/ParticleOptions.d.ts +35 -0
- package/dist/esm/particles/emitters/ParticleOptions.js +84 -0
- package/dist/esm/particles/emitters/ParticleOptions.js.map +1 -0
- package/dist/esm/particles/emitters/UniversalEmitter.d.ts +17 -0
- package/dist/esm/particles/emitters/UniversalEmitter.js +43 -0
- package/dist/esm/particles/emitters/UniversalEmitter.js.map +1 -0
- package/dist/esm/particles/index.d.ts +11 -0
- package/dist/esm/physics/RapierPhysicsWorld.d.ts +136 -0
- package/dist/esm/physics/RapierPhysicsWorld.js +464 -0
- package/dist/esm/physics/RapierPhysicsWorld.js.map +1 -0
- package/dist/esm/physics/index.d.ts +1 -0
- package/dist/esm/rendering/CallbackRenderPass.d.ts +7 -0
- package/dist/esm/rendering/CallbackRenderPass.js +11 -0
- package/dist/esm/rendering/CallbackRenderPass.js.map +1 -0
- package/dist/esm/rendering/Container.d.ts +36 -0
- package/dist/esm/rendering/Container.js +197 -0
- package/dist/esm/rendering/Container.js.map +1 -0
- package/dist/esm/rendering/Drawable.d.ts +16 -0
- package/dist/esm/rendering/Drawable.js +57 -0
- package/dist/esm/rendering/Drawable.js.map +1 -0
- package/dist/esm/rendering/RenderBackendType.d.ts +4 -0
- package/dist/esm/rendering/RenderBackendType.js +8 -0
- package/dist/esm/rendering/RenderBackendType.js.map +1 -0
- package/dist/esm/rendering/RenderNode.d.ts +51 -0
- package/dist/esm/rendering/RenderNode.js +238 -0
- package/dist/esm/rendering/RenderNode.js.map +1 -0
- package/dist/esm/rendering/RenderPass.d.ts +4 -0
- package/dist/esm/rendering/RenderStats.d.ts +12 -0
- package/dist/esm/rendering/RenderStats.js +24 -0
- package/dist/esm/rendering/RenderStats.js.map +1 -0
- package/dist/esm/rendering/RenderTarget.d.ts +34 -0
- package/dist/esm/rendering/RenderTarget.js +105 -0
- package/dist/esm/rendering/RenderTarget.js.map +1 -0
- package/dist/esm/rendering/RenderTargetPass.d.ts +18 -0
- package/dist/esm/rendering/RenderTargetPass.js +27 -0
- package/dist/esm/rendering/RenderTargetPass.js.map +1 -0
- package/dist/esm/rendering/Renderer.d.ts +15 -0
- package/dist/esm/rendering/RendererRegistry.d.ts +43 -0
- package/dist/esm/rendering/RendererRegistry.js +88 -0
- package/dist/esm/rendering/RendererRegistry.js.map +1 -0
- package/dist/esm/rendering/SceneRenderRuntime.d.ts +29 -0
- package/dist/esm/rendering/View.d.ts +102 -0
- package/dist/esm/rendering/View.js +360 -0
- package/dist/esm/rendering/View.js.map +1 -0
- package/dist/esm/rendering/filters/BlurFilter.d.ts +20 -0
- package/dist/esm/rendering/filters/BlurFilter.js +68 -0
- package/dist/esm/rendering/filters/BlurFilter.js.map +1 -0
- package/dist/esm/rendering/filters/ColorFilter.d.ts +12 -0
- package/dist/esm/rendering/filters/ColorFilter.js +41 -0
- package/dist/esm/rendering/filters/ColorFilter.js.map +1 -0
- package/dist/esm/rendering/filters/Filter.d.ts +5 -0
- package/dist/esm/rendering/filters/Filter.js +5 -0
- package/dist/esm/rendering/filters/Filter.js.map +1 -0
- package/dist/esm/rendering/index.d.ts +52 -0
- package/dist/esm/rendering/primitives/CircleGeometry.d.ts +4 -0
- package/dist/esm/rendering/primitives/CircleGeometry.js +21 -0
- package/dist/esm/rendering/primitives/CircleGeometry.js.map +1 -0
- package/dist/esm/rendering/primitives/DrawableShape.d.ts +11 -0
- package/dist/esm/rendering/primitives/DrawableShape.js +18 -0
- package/dist/esm/rendering/primitives/DrawableShape.js.map +1 -0
- package/dist/esm/rendering/primitives/Geometry.d.ts +13 -0
- package/dist/esm/rendering/primitives/Geometry.js +13 -0
- package/dist/esm/rendering/primitives/Geometry.js.map +1 -0
- package/dist/esm/rendering/primitives/Graphics.d.ts +36 -0
- package/dist/esm/rendering/primitives/Graphics.js +211 -0
- package/dist/esm/rendering/primitives/Graphics.js.map +1 -0
- package/dist/esm/rendering/shader/Shader.d.ts +27 -0
- package/dist/esm/rendering/shader/Shader.js +61 -0
- package/dist/esm/rendering/shader/Shader.js.map +1 -0
- package/dist/esm/rendering/shader/ShaderAttribute.d.ts +9 -0
- package/dist/esm/rendering/shader/ShaderAttribute.js +17 -0
- package/dist/esm/rendering/shader/ShaderAttribute.js.map +1 -0
- package/dist/esm/rendering/shader/ShaderUniform.d.ts +16 -0
- package/dist/esm/rendering/shader/ShaderUniform.js +33 -0
- package/dist/esm/rendering/shader/ShaderUniform.js.map +1 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.d.ts +43 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.js +177 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.js.map +1 -0
- package/dist/esm/rendering/sprite/Sprite.d.ts +43 -0
- package/dist/esm/rendering/sprite/Sprite.js +169 -0
- package/dist/esm/rendering/sprite/Sprite.js.map +1 -0
- package/dist/esm/rendering/sprite/Spritesheet.d.ts +34 -0
- package/dist/esm/rendering/sprite/Spritesheet.js +87 -0
- package/dist/esm/rendering/sprite/Spritesheet.js.map +1 -0
- package/dist/esm/rendering/text/Text.d.ts +26 -0
- package/dist/esm/rendering/text/Text.js +126 -0
- package/dist/esm/rendering/text/Text.js.map +1 -0
- package/dist/esm/rendering/text/TextStyle.d.ts +65 -0
- package/dist/esm/rendering/text/TextStyle.js +179 -0
- package/dist/esm/rendering/text/TextStyle.js.map +1 -0
- package/dist/esm/rendering/texture/RenderTexture.d.ts +36 -0
- package/dist/esm/rendering/texture/RenderTexture.js +118 -0
- package/dist/esm/rendering/texture/RenderTexture.js.map +1 -0
- package/dist/esm/rendering/texture/Sampler.d.ts +29 -0
- package/dist/esm/rendering/texture/Sampler.js +69 -0
- package/dist/esm/rendering/texture/Sampler.js.map +1 -0
- package/dist/esm/rendering/texture/Texture.d.ts +52 -0
- package/dist/esm/rendering/texture/Texture.js +171 -0
- package/dist/esm/rendering/texture/Texture.js.map +1 -0
- package/dist/esm/rendering/types.d.ts +68 -0
- package/dist/esm/rendering/types.js +79 -0
- package/dist/esm/rendering/types.js.map +1 -0
- package/dist/esm/rendering/utils.d.ts +9 -0
- package/dist/esm/rendering/utils.js +39 -0
- package/dist/esm/rendering/utils.js.map +1 -0
- package/dist/esm/rendering/video/Video.d.ts +62 -0
- package/dist/esm/rendering/video/Video.js +288 -0
- package/dist/esm/rendering/video/Video.js.map +1 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.d.ts +49 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js +168 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.d.ts +44 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js +59 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.d.ts +11 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js +110 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.d.ts +26 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js +211 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.d.ts +26 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.js +52 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.d.ts +99 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.js +592 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RendererRuntime.d.ts +15 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.d.ts +17 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.js +55 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.d.ts +3 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js +59 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.d.ts +2 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js +154 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.d.ts +11 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js +82 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.d.ts +40 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js +68 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/particle.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/particle.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/particle.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/particle.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.vert.js.map +1 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.d.ts +28 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js +52 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.d.ts +6 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js +79 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.d.ts +33 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js +423 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.d.ts +43 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js +425 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.d.ts +111 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js +763 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuRendererRuntime.d.ts +8 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.d.ts +33 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js +488 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js.map +1 -0
- package/dist/esm/resources/AbstractAssetFactory.d.ts +10 -0
- package/dist/esm/resources/AbstractAssetFactory.js +26 -0
- package/dist/esm/resources/AbstractAssetFactory.js.map +1 -0
- package/dist/esm/resources/AssetFactory.d.ts +6 -0
- package/dist/esm/resources/AssetManifest.d.ts +28 -0
- package/dist/esm/resources/AssetManifest.js +64 -0
- package/dist/esm/resources/AssetManifest.js.map +1 -0
- package/dist/esm/resources/CacheFirstStrategy.d.ts +5 -0
- package/dist/esm/resources/CacheFirstStrategy.js +34 -0
- package/dist/esm/resources/CacheFirstStrategy.js.map +1 -0
- package/dist/esm/resources/CacheStore.d.ts +7 -0
- package/dist/esm/resources/CacheStrategy.d.ts +12 -0
- package/dist/esm/resources/Database.d.ts +13 -0
- package/dist/esm/resources/FactoryRegistry.d.ts +9 -0
- package/dist/esm/resources/FactoryRegistry.js +44 -0
- package/dist/esm/resources/FactoryRegistry.js.map +1 -0
- package/dist/esm/resources/IndexedDbDatabase.d.ts +21 -0
- package/dist/esm/resources/IndexedDbDatabase.js +139 -0
- package/dist/esm/resources/IndexedDbDatabase.js.map +1 -0
- package/dist/esm/resources/IndexedDbStore.d.ts +16 -0
- package/dist/esm/resources/IndexedDbStore.js +31 -0
- package/dist/esm/resources/IndexedDbStore.js.map +1 -0
- package/dist/esm/resources/Loader.d.ts +88 -0
- package/dist/esm/resources/Loader.js +597 -0
- package/dist/esm/resources/Loader.js.map +1 -0
- package/dist/esm/resources/NetworkOnlyStrategy.d.ts +5 -0
- package/dist/esm/resources/NetworkOnlyStrategy.js +12 -0
- package/dist/esm/resources/NetworkOnlyStrategy.js.map +1 -0
- package/dist/esm/resources/factories/BinaryFactory.d.ts +6 -0
- package/dist/esm/resources/factories/BinaryFactory.js +17 -0
- package/dist/esm/resources/factories/BinaryFactory.js.map +1 -0
- package/dist/esm/resources/factories/FontFactory.d.ts +13 -0
- package/dist/esm/resources/factories/FontFactory.js +39 -0
- package/dist/esm/resources/factories/FontFactory.js.map +1 -0
- package/dist/esm/resources/factories/ImageFactory.d.ts +10 -0
- package/dist/esm/resources/factories/ImageFactory.js +38 -0
- package/dist/esm/resources/factories/ImageFactory.js.map +1 -0
- package/dist/esm/resources/factories/JsonFactory.d.ts +6 -0
- package/dist/esm/resources/factories/JsonFactory.js +17 -0
- package/dist/esm/resources/factories/JsonFactory.js.map +1 -0
- package/dist/esm/resources/factories/MusicFactory.d.ts +16 -0
- package/dist/esm/resources/factories/MusicFactory.js +40 -0
- package/dist/esm/resources/factories/MusicFactory.js.map +1 -0
- package/dist/esm/resources/factories/SoundFactory.d.ts +14 -0
- package/dist/esm/resources/factories/SoundFactory.js +25 -0
- package/dist/esm/resources/factories/SoundFactory.js.map +1 -0
- package/dist/esm/resources/factories/SvgFactory.d.ts +6 -0
- package/dist/esm/resources/factories/SvgFactory.js +37 -0
- package/dist/esm/resources/factories/SvgFactory.js.map +1 -0
- package/dist/esm/resources/factories/TextFactory.d.ts +6 -0
- package/dist/esm/resources/factories/TextFactory.js +17 -0
- package/dist/esm/resources/factories/TextFactory.js.map +1 -0
- package/dist/esm/resources/factories/TextureFactory.d.ts +13 -0
- package/dist/esm/resources/factories/TextureFactory.js +40 -0
- package/dist/esm/resources/factories/TextureFactory.js.map +1 -0
- package/dist/esm/resources/factories/VideoFactory.d.ts +18 -0
- package/dist/esm/resources/factories/VideoFactory.js +43 -0
- package/dist/esm/resources/factories/VideoFactory.js.map +1 -0
- package/dist/esm/resources/factories/VttFactory.d.ts +6 -0
- package/dist/esm/resources/factories/VttFactory.js +60 -0
- package/dist/esm/resources/factories/VttFactory.js.map +1 -0
- package/dist/esm/resources/factories/WasmFactory.d.ts +6 -0
- package/dist/esm/resources/factories/WasmFactory.js +17 -0
- package/dist/esm/resources/factories/WasmFactory.js.map +1 -0
- package/dist/esm/resources/index.d.ts +26 -0
- package/dist/esm/resources/tokens.d.ts +30 -0
- package/dist/esm/resources/tokens.js +33 -0
- package/dist/esm/resources/tokens.js.map +1 -0
- package/dist/esm/resources/utils.d.ts +1 -0
- package/dist/esm/resources/utils.js +129 -0
- package/dist/esm/resources/utils.js.map +1 -0
- package/dist/esm/vendor/webgl-debug.js +1160 -0
- package/dist/esm/vendor/webgl-debug.js.map +1 -0
- package/dist/exo.d.ts +4748 -0
- package/dist/exo.esm.js +16850 -0
- package/dist/exo.esm.js.map +1 -0
- package/dist/exo.esm.min.js +2 -0
- package/dist/exo.esm.min.js.map +1 -0
- package/dist/exo.global.js +17067 -0
- package/dist/exo.global.js.map +1 -0
- package/dist/exo.global.min.js +2 -0
- package/dist/exo.global.min.js.map +1 -0
- package/package.json +99 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var Exo=function(t){"use strict";let e=null;class i{constructor(t=0,e=0){this._width=t,this._height=e}get width(){return this._width}set width(t){this._width=t}get height(){return this._height}set height(t){this._height=t}set(t,e=t){return this._width=t,this._height=e,this}add(t,e=t){return this._width+=t,this._height+=e,this}subtract(t,e=t){return this._width-=t,this._height-=e,this}scale(t,e=t){return this._width*=t,this._height*=e,this}divide(t,e=t){return this._width/=t,this._height/=e,this}copy(t){return this._width=t.width,this._height=t.height,this}clone(){return new i(this._width,this._height)}equals({width:t,height:e}={}){return!(void 0!==t&&this.width!==t||void 0!==e&&this.height!==e)}destroy(){}static get temp(){return null===e&&(e=new i),e}}i.zero=new i(0,0);class r{constructor(t=Date.now()){this._state=new Uint32Array(624),this._iteration=0,this._seed=0,this._value=0,this.setSeed(t),this._twist()}get seed(){return this._seed}get value(){return this._value}get iteration(){return this._iteration}setSeed(t){return this._seed=t,this.reset(),this}reset(){this._state[0]=this._seed;for(let t=1;t<624;t++){const e=this._state[t-1]^this._state[t-1]>>>30;this._state[t]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+t,this._state[t]|=0}return this._iteration=0,this}next(t=0,e=1){return this._iteration>=624&&this._twist(),this._value=this._state[this._iteration++],this._value^=this._value>>>11,this._value^=this._value<<7&2636928640,this._value^=this._value<<15&4022730752,this._value^=this._value>>>18,this._value=(this._value>>>0)/4294967295*(e-t)+t,this._value}destroy(){}_twist(){const t=this._state;for(let e=0;e<227;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e+397]^i>>>1^2567483615*(1&i)}for(let e=227;e<623;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e-227]^i>>>1^2567483615*(1&i)}const e=2147483648&t[623]|2147483647&t[0];t[623]=t[396]^e>>>1^2567483615*(1&e),this._iteration=0,this._value=0}}let s=null;class n{constructor(t=0,e=n.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/n.seconds}set seconds(t){this._milliseconds=t*n.seconds}get minutes(){return this._milliseconds/n.minutes}set minutes(t){this._milliseconds=t*n.minutes}get hours(){return this._milliseconds/n.hours}set hours(t){this._milliseconds=t*n.hours}set(t=0,e=n.milliseconds){return this._milliseconds=t*e,this}setMilliseconds(t){return this.milliseconds=t,this}setSeconds(t){return this.seconds=t,this}setMinutes(t){return this.minutes=t,this}setHours(t){return this.hours=t,this}equals({milliseconds:t,seconds:e,minutes:i,hours:r}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==r&&this.hours!==r)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new n(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=n.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=n.milliseconds){return this._milliseconds-=t*e,this}subtractTime(t){return this._milliseconds-=t.milliseconds,this}destroy(){}static get temp(){return null===s&&(s=new n),s}}n.milliseconds=1,n.seconds=1e3,n.minutes=6e4,n.hours=36e5,n.zero=new n(0),n.oneMillisecond=new n(1),n.oneSecond=new n(1,n.seconds),n.oneMinute=new n(1,n.minutes),n.oneHour=new n(1,n.hours);const o=/^no$/;let a=null,h=null,l=null,u=null,d=null;const c=()=>"undefined"!=typeof document,p=()=>"undefined"!=typeof window,_=()=>{if(!c())throw new Error("Canvas operations require a document context.");return null===h&&(h=document.createElement("canvas")),h},f=()=>{},m=t=>{t.preventDefault(),t.stopImmediatePropagation()},g="undefined"!=typeof AudioContext,y="undefined"!=typeof indexedDB,x=p()&&"ontouchstart"in window,w="undefined"!=typeof PointerEvent,v=()=>performance.now(),b=t=>new n(t,n.milliseconds),S=new ArrayBuffer(0),T=(t,e,i)=>{if(e<t.length&&i>0){const r=e+i>t.length?t.length-e:i,s=t.length-r;for(let i=e;i<s;i++)t[i]=t[i+r];t.length=s}return t},C=t=>{const e=t;return t instanceof HTMLImageElement?i.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?i.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?i.temp.copy(t.getBoundingClientRect()):"number"==typeof e.displayWidth&&"number"==typeof e.displayHeight?i.temp.set(e.displayWidth,e.displayHeight):"number"==typeof e.width&&"number"==typeof e.height?i.temp.set(e.width,e.height):i.zero},M=t=>null===t?i.zero:C(t),P=t=>{const{width:e,height:i}=C(t),r=_();return r.width=e,r.height=i,(()=>{if(null===l){const t=_().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");l=t}return l})().drawImage(t,0,0,e,i),r.toDataURL()};class B{constructor(t=n.zero,e=!1){this._elapsedTime=new n(0),this._running=!1,this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=v();this._elapsedTime.add(t-this._startTime.milliseconds),this._startTime.milliseconds=t}return this._elapsedTime}get elapsedMilliseconds(){return this.elapsedTime.milliseconds}get elapsedSeconds(){return this.elapsedTime.seconds}get elapsedMinutes(){return this.elapsedTime.minutes}get elapsedHours(){return this.elapsedTime.hours}start(){return this._running||(this._running=!0,this._startTime.milliseconds=v()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(v()-this._startTime.milliseconds)),this}reset(){return this._running=!1,this._elapsedTime.setMilliseconds(0),this}restart(){return this.reset(),this.start(),this}destroy(){this._startTime.destroy(),this._elapsedTime.destroy()}}class E{constructor(){this._bindings=new Array}get bindings(){return this._bindings}has(t,e){return this._bindings.some(i=>i.handler===t&&i.context===e)}add(t,e){return this.has(t,e)||this._bindings.push({handler:t,context:e}),this}once(t,e){const i=(...r)=>{this.remove(i,e),t.call(e,...r)};return this.add(i,e),this}remove(t,e){const i=this._bindings.findIndex(i=>i.handler===t&&i.context===e);return-1!==i&&T(this._bindings,i,1),this}clearByContext(t){const e=this._bindings.filter(e=>e.context===t);for(const t of e)T(this._bindings,this._bindings.indexOf(t),1);return this}clear(){return this._bindings.length=0,this}dispatch(...t){if(this._bindings.length)for(const e of this._bindings)if(!1===e.handler.call(e.context,...t))break;return this}destroy(){this.clear()}}const R=2*Math.PI,A=Math.PI/180,F=180/Math.PI,k=t=>{const e=t%360;return e<0?e+360:e},L=t=>t*A,D=(t,e,i)=>Math.min(i,Math.max(e,t)),I=(t,e,i)=>(1-i)*t+i*e,N=t=>0!==t&&!(t&t-1),G=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),U=(t,e,i,r)=>{const s=t-i,n=e-r;return Math.sqrt(s*s+n*n)},V=(t,e,i,r,s,n,o,a,h=[],l=20)=>{h.push(t,e);for(let u=1,d=0,c=0,p=0,_=0,f=0,m=0;u<=l;u++)d=u/l,c=1-d,p=c*c,_=p*c,f=d*d,m=f*d,h.push(_*t+3*p*d*i+3*c*f*s+m*o,_*e+3*p*d*r+3*c*f*n+m*a);return h},O=(t,e,i,r,s,n,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(I(I(t,i,l),I(i,s,l),l),I(I(e,r,l),I(r,n,l),l))}return o};class z{constructor(t=0,e=0,i=0,r=1){this._rgba=null,this._array=null,this._r=255&t,this._g=255&e,this._b=255&i,this._a=D(r,0,1)}get r(){return this._r}set r(t){this._r=255&t,this._rgba=null}get g(){return this._g}set g(t){this._g=255&t,this._rgba=null}get b(){return this._b}set b(t){this._b=255&t,this._rgba=null}get a(){return this._a}set a(t){this._a=D(t,0,1),this._rgba=null}get red(){return this.r}set red(t){this.r=t}get green(){return this.g}set green(t){this.g=t}get blue(){return this.b}set blue(t){this.b=t}get alpha(){return this.a}set alpha(t){this.a=t}set(t=this._r,e=this._g,i=this._b,r=this._a){return this._r=255&t,this._g=255&e,this._b=255&i,this._a=D(r,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new z(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:r}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==r&&this.a!==r)}toArray(t=!1){return this._array||(this._array=new Float32Array(4)),t?(this._array[0]=this._r/255,this._array[1]=this._g/255,this._array[2]=this._b/255,this._array[3]=this._a):(this._array[0]=this._r,this._array[1]=this._g,this._array[2]=this._b,this._array[3]=this._a),this._array}toString(t=!0){return`${t?"#":""}${((1<<24)+(this._r<<16)+(this._g<<8)+this._b).toString(16).substr(1)}`}toRgba(){return null===this._rgba&&(this._rgba=this._a&&(255*this._a<<24)+(this._b<<16)+(this._g<<8)+this._r>>>0),this._rgba}destroy(){this._array&&(this._array=null)}}var W,q,H,X,j,Y,$;z.aliceBlue=new z(240,248,255,1),z.antiqueWhite=new z(250,235,215,1),z.aqua=new z(0,255,255,1),z.aquamarine=new z(127,255,212,1),z.azure=new z(240,255,255,1),z.beige=new z(245,245,220,1),z.bisque=new z(255,228,196,1),z.black=new z(0,0,0,1),z.blanchedAlmond=new z(255,235,205,1),z.blue=new z(0,0,255,1),z.blueViolet=new z(138,43,226,1),z.brown=new z(165,42,42,1),z.burlyWood=new z(222,184,135,1),z.cadetBlue=new z(95,158,160,1),z.chartreuse=new z(127,255,0,1),z.chocolate=new z(210,105,30,1),z.coral=new z(255,127,80,1),z.cornflowerBlue=new z(100,149,237,1),z.cornsilk=new z(255,248,220,1),z.crimson=new z(220,20,60,1),z.cyan=new z(0,255,255,1),z.darkBlue=new z(0,0,139,1),z.darkCyan=new z(0,139,139,1),z.darkGoldenrod=new z(184,134,11,1),z.darkGray=new z(169,169,169,1),z.darkGreen=new z(0,100,0,1),z.darkKhaki=new z(189,183,107,1),z.darkMagenta=new z(139,0,139,1),z.darkOliveGreen=new z(85,107,47,1),z.darkOrange=new z(255,140,0,1),z.darkOrchid=new z(153,50,204,1),z.darkRed=new z(139,0,0,1),z.darkSalmon=new z(233,150,122,1),z.darkSeaGreen=new z(143,188,139,1),z.darkSlateBlue=new z(72,61,139,1),z.darkSlateGray=new z(47,79,79,1),z.darkTurquoise=new z(0,206,209,1),z.darkViolet=new z(148,0,211,1),z.deepPink=new z(255,20,147,1),z.deepSkyBlue=new z(0,191,255,1),z.dimGray=new z(105,105,105,1),z.dodgerBlue=new z(30,144,255,1),z.firebrick=new z(178,34,34,1),z.floralWhite=new z(255,250,240,1),z.forestGreen=new z(34,139,34,1),z.fuchsia=new z(255,0,255,1),z.gainsboro=new z(220,220,220,1),z.ghostWhite=new z(248,248,255,1),z.gold=new z(255,215,0,1),z.goldenrod=new z(218,165,32,1),z.gray=new z(128,128,128,1),z.green=new z(0,128,0,1),z.greenYellow=new z(173,255,47,1),z.honeydew=new z(240,255,240,1),z.hotPink=new z(255,105,180,1),z.indianRed=new z(205,92,92,1),z.indigo=new z(75,0,130,1),z.ivory=new z(255,255,240,1),z.khaki=new z(240,230,140,1),z.lavender=new z(230,230,250,1),z.lavenderBlush=new z(255,240,245,1),z.lawnGreen=new z(124,252,0,1),z.lemonChiffon=new z(255,250,205,1),z.lightBlue=new z(173,216,230,1),z.lightCoral=new z(240,128,128,1),z.lightCyan=new z(224,255,255,1),z.lightGoldenrodYellow=new z(250,250,210,1),z.lightGray=new z(211,211,211,1),z.lightGreen=new z(144,238,144,1),z.lightPink=new z(255,182,193,1),z.lightSalmon=new z(255,160,122,1),z.lightSeaGreen=new z(32,178,170,1),z.lightSkyBlue=new z(135,206,250,1),z.lightSlateGray=new z(119,136,153,1),z.lightSteelBlue=new z(176,196,222,1),z.lightYellow=new z(255,255,224,1),z.lime=new z(0,255,0,1),z.limeGreen=new z(50,205,50,1),z.linen=new z(250,240,230,1),z.magenta=new z(255,0,255,1),z.maroon=new z(128,0,0,1),z.mediumAquamarine=new z(102,205,170,1),z.mediumBlue=new z(0,0,205,1),z.mediumOrchid=new z(186,85,211,1),z.mediumPurple=new z(147,112,219,1),z.mediumSeaGreen=new z(60,179,113,1),z.mediumSlateBlue=new z(123,104,238,1),z.mediumSpringGreen=new z(0,250,154,1),z.mediumTurquoise=new z(72,209,204,1),z.mediumVioletRed=new z(199,21,133,1),z.midnightBlue=new z(25,25,112,1),z.mintCream=new z(245,255,250,1),z.mistyRose=new z(255,228,225,1),z.moccasin=new z(255,228,181,1),z.navajoWhite=new z(255,222,173,1),z.navy=new z(0,0,128,1),z.oldLace=new z(253,245,230,1),z.olive=new z(128,128,0,1),z.oliveDrab=new z(107,142,35,1),z.orange=new z(255,165,0,1),z.orangeRed=new z(255,69,0,1),z.orchid=new z(218,112,214,1),z.paleGoldenrod=new z(238,232,170,1),z.paleGreen=new z(152,251,152,1),z.paleTurquoise=new z(175,238,238,1),z.paleVioletRed=new z(219,112,147,1),z.papayaWhip=new z(255,239,213,1),z.peachPuff=new z(255,218,185,1),z.peru=new z(205,133,63,1),z.pink=new z(255,192,203,1),z.plum=new z(221,160,221,1),z.powderBlue=new z(176,224,230,1),z.purple=new z(128,0,128,1),z.red=new z(255,0,0,1),z.rosyBrown=new z(188,143,143,1),z.royalBlue=new z(65,105,225,1),z.saddleBrown=new z(139,69,19,1),z.salmon=new z(250,128,114,1),z.sandyBrown=new z(244,164,96,1),z.seaGreen=new z(46,139,87,1),z.seaShell=new z(255,245,238,1),z.sienna=new z(160,82,45,1),z.silver=new z(192,192,192,1),z.skyBlue=new z(135,206,235,1),z.slateBlue=new z(106,90,205,1),z.slateGray=new z(112,128,144,1),z.snow=new z(255,250,250,1),z.springGreen=new z(0,255,127,1),z.steelBlue=new z(70,130,180,1),z.tan=new z(210,180,140,1),z.teal=new z(0,128,128,1),z.thistle=new z(216,191,216,1),z.tomato=new z(255,99,71,1),z.transparentBlack=new z(0,0,0,0),z.transparentWhite=new z(255,255,255,0),z.turquoise=new z(64,224,208,1),z.violet=new z(238,130,238,1),z.wheat=new z(245,222,179,1),z.white=new z(255,255,255,1),z.whiteSmoke=new z(245,245,245,1),z.yellow=new z(255,255,0,1),z.yellowGreen=new z(154,205,50,1),t.BlendModes=void 0,(W=t.BlendModes||(t.BlendModes={}))[W.Normal=0]="Normal",W[W.Additive=1]="Additive",W[W.Subtract=2]="Subtract",W[W.Multiply=3]="Multiply",W[W.Screen=4]="Screen",t.ScaleModes=void 0,(q=t.ScaleModes||(t.ScaleModes={}))[q.Nearest=9728]="Nearest",q[q.Linear=9729]="Linear",q[q.NearestMipmapNearest=9984]="NearestMipmapNearest",q[q.LinearMipmapNearest=9985]="LinearMipmapNearest",q[q.NearestMipmapLinear=9986]="NearestMipmapLinear",q[q.LinearMipmapLinear=9987]="LinearMipmapLinear",t.WrapModes=void 0,(H=t.WrapModes||(t.WrapModes={}))[H.Repeat=10497]="Repeat",H[H.ClampToEdge=33071]="ClampToEdge",H[H.MirroredRepeat=33648]="MirroredRepeat",t.RenderingPrimitives=void 0,(X=t.RenderingPrimitives||(t.RenderingPrimitives={}))[X.Points=0]="Points",X[X.Lines=1]="Lines",X[X.LineLoop=2]="LineLoop",X[X.LineStrip=3]="LineStrip",X[X.Triangles=4]="Triangles",X[X.TriangleStrip=5]="TriangleStrip",X[X.TriangleFan=6]="TriangleFan",t.BufferTypes=void 0,(j=t.BufferTypes||(t.BufferTypes={}))[j.ArrayBuffer=34962]="ArrayBuffer",j[j.ElementArrayBuffer=34963]="ElementArrayBuffer",j[j.CopyReadBuffer=36662]="CopyReadBuffer",j[j.CopyWriteBuffer=36663]="CopyWriteBuffer",j[j.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",j[j.UniformBuffer=35345]="UniformBuffer",j[j.PixelPackBuffer=35051]="PixelPackBuffer",j[j.PixelUnpackBuffer=35052]="PixelUnpackBuffer",t.BufferUsage=void 0,(Y=t.BufferUsage||(t.BufferUsage={}))[Y.StaticDraw=35044]="StaticDraw",Y[Y.StaticRead=35045]="StaticRead",Y[Y.StaticCopy=35046]="StaticCopy",Y[Y.DynamicDraw=35048]="DynamicDraw",Y[Y.DynamicRead=35049]="DynamicRead",Y[Y.DynamicCopy=35050]="DynamicCopy",Y[Y.StreamDraw=35040]="StreamDraw",Y[Y.StreamRead=35041]="StreamRead",Y[Y.StreamCopy=35042]="StreamCopy",t.ShaderPrimitives=void 0,($=t.ShaderPrimitives||(t.ShaderPrimitives={}))[$.Int=5124]="Int",$[$.IntVec2=35667]="IntVec2",$[$.IntVec3=35668]="IntVec3",$[$.IntVec4=35669]="IntVec4",$[$.Float=5126]="Float",$[$.FloatVec2=35664]="FloatVec2",$[$.FloatVec3=35665]="FloatVec3",$[$.FloatVec4=35666]="FloatVec4",$[$.Bool=35670]="Bool",$[$.BoolVec2=35671]="BoolVec2",$[$.BoolVec3=35672]="BoolVec3",$[$.BoolVec4=35673]="BoolVec4",$[$.FloatMat2=35674]="FloatMat2",$[$.FloatMat3=35675]="FloatMat3",$[$.FloatMat4=35676]="FloatMat4",$[$.Sampler2D=35678]="Sampler2D";class K{get direction(){return Math.atan2(this.x,this.y)}set direction(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get angle(){return this.direction}set angle(t){this.direction=t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.direction;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(t){this.length=Math.sqrt(t)}get magnitude(){return this.length}set magnitude(t){this.length=t}set(t,e=t){return this.x=t,this.y=e,this}equals({x:t,y:e}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e)}add(t,e=t){return this.x+=t,this.y+=e,this}subtract(t,e=t){return this.x-=t,this.y-=e,this}multiply(t,e=t){return this.x*=t,this.y*=e,this}divide(t,e=t){return 0!==t&&0!==e&&(this.x/=t,this.y/=e),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(t){return this.set(this.x*t.a+this.y*t.b+t.x,this.x*t.c+this.y*t.d+t.y)}transformInverse(t){const e=1/(t.a*t.d+t.c*-t.b);return this.set(this.x*t.d*e+this.y*-t.c*e+(t.y*t.c-t.x*t.d)*e,this.y*t.a*e+this.x*-t.b*e+(-t.y*t.a+t.x*t.b)*e)}perp(){return this.set(-this.y,this.x)}rperp(){return this.set(this.y,-this.x)}min(){return Math.min(this.x,this.y)}max(){return Math.max(this.x,this.y)}dot(t,e){return this.x*t+this.y*e}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){return U(this.x,this.y,t.x,t.y)}}class Q extends K{constructor(t,e=0,i=0){super(),this._x=e,this._y=i,this._callback=t}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._callback?.())}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._callback?.())}set direction(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}set length(t){const e=this.direction;this.set(Math.cos(e)*t,Math.sin(e)*t)}set(t=this._x,e=this._y){return this._x===t&&this._y===e||(this._x=t,this._y=e,this._callback?.()),this}add(t,e=t){return this.set(this._x+t,this._y+e)}subtract(t,e=t){return this.set(this._x-t,this._y-e)}scale(t,e=t){return this.set(this._x*t,this._y*e)}divide(t,e=t){return 0!==t&&0!==e?this.set(this._x/t,this._y/e):this}clone(){return new Q(this._callback,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){}}let Z=null;class J{constructor(t=1,e=0,i=0,r=0,s=1,n=0,o=0,a=0,h=1){this._array=null,this.a=t,this.b=e,this.x=i,this.c=r,this.d=s,this.y=n,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,r=this.c,s=this.d,n=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=r,this.d=s,this.y=n,this.e=o,this.f=a,this.z=h,this}copy(t){return this.a=t.a,this.b=t.b,this.x=t.x,this.c=t.c,this.d=t.d,this.y=t.y,this.e=t.e,this.f=t.f,this.z=t.z,this}clone(){return new J(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:t,b:e,x:i,c:r,d:s,y:n,e:o,f:a,z:h}={}){return!(void 0!==t&&this.a!==t||void 0!==e&&this.b!==e||void 0!==i&&this.x!==i||void 0!==r&&this.c!==r||void 0!==s&&this.d!==s||void 0!==n&&this.y!==n||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(t){return this.set(this.a*t.a+this.c*t.b+this.e*t.x,this.b*t.a+this.d*t.b+this.f*t.x,this.x*t.a+this.y*t.b+this.z*t.x,this.a*t.c+this.c*t.d+this.e*t.y,this.b*t.c+this.d*t.d+this.f*t.y,this.x*t.c+this.y*t.d+this.z*t.y,this.a*t.e+this.c*t.f+this.e*t.z,this.b*t.e+this.d*t.f+this.f*t.z,this.x*t.e+this.y*t.f+this.z*t.z)}getInverse(t=this){const e=this.a*(this.z*this.d-this.y*this.f)-this.b*(this.z*this.c-this.y*this.e)+this.x*(this.f*this.c-this.d*this.e);return 0===e?t.copy(J.identity):t.set((this.z*this.d-this.y*this.f)/e,(this.z*this.c-this.y*this.e)/-e,(this.f*this.c-this.d*this.e)/e,(this.z*this.b-this.x*this.f)/-e,(this.z*this.a-this.x*this.e)/e,(this.f*this.a-this.b*this.e)/-e,(this.y*this.b-this.x*this.d)/e,(this.y*this.a-this.x*this.c)/-e,(this.d*this.a-this.b*this.c)/e)}translate(t,e=t){return this.combine(J.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const r=L(t),s=Math.cos(r),n=Math.sin(r);return this.combine(J.temp.set(s,-n,e*(1-s)+i*n,n,s,i*(1-s)-e*n,0,0,1))}scale(t,e=t,i=0,r=i){return this.combine(J.temp.set(t,0,i*(1-t),0,e,r*(1-e),0,0,1))}toArray(t=!1){const e=this._array||(this._array=new Float32Array(9));return t?(e[0]=this.a,e[1]=this.b,e[2]=this.x,e[3]=this.c,e[4]=this.d,e[5]=this.y,e[6]=this.e,e[7]=this.f,e[8]=this.z):(e[0]=this.a,e[1]=this.c,e[2]=this.e,e[3]=this.b,e[4]=this.d,e[5]=this.f,e[6]=this.x,e[7]=this.y,e[8]=this.z),e}destroy(){this._array&&(this._array=null)}static get temp(){return null===Z&&(Z=new J),Z}}J.identity=new J(1,0,0,0,1,0,0,0,1);class tt{get value(){return this._value}constructor(...t){this._value=0,t.length&&this.push(...t)}push(...t){for(const e of t)this._value|=e;return this}pop(t){const e=this.has(t);return this.remove(t),e}remove(...t){for(const e of t)this._value&=~e;return this}has(...t){return t.some(t=>0!==(this._value&t))}clear(){return this._value=0,this}destroy(){this.clear()}}var et;t.TransformableFlags=void 0,(et=t.TransformableFlags||(t.TransformableFlags={}))[et.None=0]="None",et[et.Translation=1]="Translation",et[et.Rotation=2]="Rotation",et[et.Scaling=4]="Scaling",et[et.Origin=8]="Origin",et[et.Transform=15]="Transform",et[et.TransformInverse=16]="TransformInverse";class it{constructor(){this.flags=new tt(t.TransformableFlags.Transform),this._transform=new J,this._position=new Q(this._setPositionDirty.bind(this),0,0),this._scale=new Q(this._setScalingDirty.bind(this),1,1),this._origin=new Q(this._setOriginDirty.bind(this),0,0),this._rotation=0,this._sin=0,this._cos=1}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get origin(){return this._origin}set origin(t){this._origin.copy(t)}setPosition(t,e=t){return this._position.set(t,e),this}setRotation(t){const e=k(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setScale(t,e=t){return this._scale.set(t,e),this}setOrigin(t,e=t){return this._origin.set(t,e),this}move(t,e){return this.setPosition(this.x+t,this.y+e)}rotate(t){return this.setRotation(this._rotation+t)}getTransform(){return this.flags.has(t.TransformableFlags.Transform)&&(this.updateTransform(),this.flags.remove(t.TransformableFlags.Transform)),this._transform}updateTransform(){if(this.flags.has(t.TransformableFlags.Rotation)){const t=L(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(t.TransformableFlags.Rotation|t.TransformableFlags.Scaling)){const{x:t,y:e}=this._scale;this._transform.a=t*this._cos,this._transform.b=e*this._sin,this._transform.c=-t*this._sin,this._transform.d=e*this._cos}if(this._rotation){const{x:t,y:e}=this._origin;this._transform.x=t*-this._transform.a-e*this._transform.b+this._position.x,this._transform.y=t*-this._transform.c-e*this._transform.d+this._position.y}else this._transform.x=this._origin.x*-this._scale.x+this._position.x,this._transform.y=this._origin.y*-this._scale.y+this._position.y;return this}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy()}_setPositionDirty(){this.flags.push(t.TransformableFlags.Translation)}_setRotationDirty(){this.flags.push(t.TransformableFlags.Rotation)}_setScalingDirty(){this.flags.push(t.TransformableFlags.Scaling)}_setOriginDirty(){this.flags.push(t.TransformableFlags.Origin)}}let rt=null;class st{constructor(t=0,e=t){this.min=t,this.max=e}set(t,e){return this.min=t,this.max=e,this}copy(t){return this.set(t.min,t.max)}clone(){return new st(this.min,this.max)}containsInterval(t){return t.min>this.min&&t.max<this.max}includes(t){return t<=this.max&&t>=this.min}overlaps(t){return!(this.min>t.max||t.min>this.max)}getOverlap(t){return this.max<t.max?this.max-t.min:t.max-this.min}destroy(){}static get temp(){return null===rt&&(rt=new st),rt}}st.zero=new st(0,0);const nt=1e-10,ot=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),at=({x:t,y:e,rx:i,ry:r})=>{if(i<=0||r<=0)return[];const s=ot(i,r),n=2*Math.PI/s,o=[];for(let a=0;a<s;a++){const s=a*n;o.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*r})}return o},ht=({x:t,y:e},{x:i,y:r},{x:s,y:n})=>t<=Math.max(i,s)+nt&&t>=Math.min(i,s)-nt&&e<=Math.max(r,n)+nt&&e>=Math.min(r,n)-nt,lt=({x:t,y:e},{x:i,y:r},{x:s,y:n})=>{const o=(r-e)*(s-i)-(i-t)*(n-r);return Math.abs(o)<=nt?0:o>0?1:2},ut=(t,e,i,r)=>{const s=lt(t,e,i),n=lt(t,e,r),o=lt(i,r,t),a=lt(i,r,e);return s!==n&&o!==a||(!(0!==s||!ht(i,t,e))||(!(0!==n||!ht(r,t,e))||(!(0!==o||!ht(t,i,r))||!(0!==a||!ht(e,i,r)))))},dt=({x:t,y:e},i)=>{const r=i.length;if(r<3)return!1;let s=!1;for(let n=0,o=r-1;n<r;o=n++){const r=i[o],a=i[n];a.y>e!=r.y>e&&t<(r.x-a.x)*((e-a.y)/(r.y-a.y))+a.x&&(s=!s)}return s},ct=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const r=t[i],s=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];if(ut(r,s,i,n))return!0}}return dt(t[0],e)||dt(e[0],t)},pt=({x:t,y:e},{x:i,y:r},{x:s,y:n},o=.1)=>{const a=U(t,e,i,r),h=U(t,e,s,n),l=U(i,r,s,n);return a+h>=l-o&&a+h<=l+o},_t=(t,e,i,r)=>{const s=(e.x-t.x)*(r.y-i.y)-(r.x-i.x)*(e.y-t.y);if(Math.abs(s)<=nt)return!1;const n=((r.x-i.x)*(t.y-i.y)-(r.y-i.y)*(t.x-i.x))/s,o=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/s;return n>=0&&n<=1&&o>=0&&o<=1},ft=(t,e)=>Math.sqrt(t*t+e*e),mt=(t,e,i,r)=>{const s=i*t+r*e;const n=(o=t)*o+(a=e)*a;var o,a;return s<0?-1:s>n?1:0},gt=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=new st,n=new st;for(const r of i)if(t.project(r,s),e.project(r,n),!s.overlaps(n))return!1;for(const i of r)if(t.project(i,s),e.project(i,n),!s.overlaps(n))return!1;return!0},yt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:r},s=0)=>U(t,e,i,r)<=s)(t,e,i),xt=(t,e,i=.1)=>pt(t,e.fromPosition,e.toPosition,i),wt=(t,e)=>(({x:t,y:e},{x:i,y:r,width:s,height:n})=>G(t,i,i+s)&&G(e,r,r+n))(t,e),vt=(t,e)=>(({x:t,y:e},{x:i,y:r,radius:s})=>s>0&&U(t,e,i,r)<=s)(t,e),bt=(t,e)=>(({x:t,y:e},{x:i,y:r,rx:s,ry:n})=>{if(s<=0||n<=0)return!1;const o=(t-i)/s,a=(e-r)/n;return o*o+a*a<=1})(t,e),St=(t,e)=>((t,{points:e})=>dt(t,e))(t,e),Tt=(t,e)=>_t(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Ct=(t,e)=>{const{x:i,y:r,width:s,height:n}=e,o={x:i,y:r},a={x:i+s,y:r},h={x:i,y:r+n},l={x:i+s,y:r+n};return _t(t.fromPosition,t.toPosition,o,h)||_t(t.fromPosition,t.toPosition,a,l)||_t(t.fromPosition,t.toPosition,o,a)||_t(t.fromPosition,t.toPosition,h,l)},Mt=(t,e)=>{if(vt(t.fromPosition,e)||vt(t.toPosition,e))return!0;const{fromX:i,fromY:r,toX:s,toY:n}=t,{x:o,y:a,radius:h}=e,l=U(i,r,s,n);if(0===l)return!1;const u=((o-i)*(s-i)+(a-r)*(n-r))/(l*l),d=i+u*(s-i),c=r+u*(n-r);return!!pt({x:d,y:c},t.fromPosition,t.toPosition)&&U(d,c,o,a)<=h},Pt=(t,e)=>{const{x:i,y:r,rx:s,ry:n}=e;if(s<=0||n<=0)return!1;const o=(t.fromX-i)/s,a=(t.fromY-r)/n,h=(t.toX-i)/s-o,l=(t.toY-r)/n-a,u=h*h+l*l,d=2*(o*h+a*l),c=o*o+a*a-1;if(c<=0)return!0;if(u<=Number.EPSILON)return!1;const p=d*d-4*u*c;if(p<0)return!1;const _=Math.sqrt(p),f=(-d-_)/(2*u),m=(-d+_)/(2*u);return f>=0&&f<=1||m>=0&&m<=1},Bt=(t,e)=>{const{x:i,y:r,points:s}=e,n=s.length;for(let e=0;e<n;e++){const o=s[e],a=s[(e+1)%n];if(_t(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+r},{x:a.x+i,y:a.y+r}))return!0}return!1},Et=(t,e)=>(({x:t,y:e,width:i,height:r},{x:s,y:n,width:o,height:a})=>!(s>t+i||n>e+r||t>s+o||e>n+a))(t,e),Rt=({x:t,y:e,width:i,height:r},{x:s,y:n,radius:o})=>{const a=D(s,t,t+i),h=D(n,e,e+r);return U(s,n,a,h)<=o},At=(t,e)=>ct((({x:t,y:e,width:i,height:r})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+r},{x:t,y:e+r}])(t),at(e)),Ft=(t,e)=>gt(t,e),kt=({x:t,y:e,radius:i},{x:r,y:s,radius:n})=>U(t,e,r,s)<=i+n,Lt=(t,e)=>ct((({x:t,y:e,radius:i})=>{if(i<=0)return[];const r=ot(i),s=2*Math.PI/r,n=[];for(let o=0;o<r;o++){const r=o*s;n.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*i})}return n})(t),at(e)),Dt=(t,e,i,r,s,n,o,a,h)=>{if(-1!==mt(a,h,s,n))return!1;return 1===mt(r.x,r.y,t-i.x,e-i.y)&&ft(s,n)>o},It=(t,e,i,r,s,n,o,a,h)=>{if(1!==mt(a,h,s,n))return!1;return-1===mt(r.x,r.y,t-i.x,e-i.y)&&ft(s,n)>o},Nt=(t,e,i,r,s)=>{const n=s,o=-r,a=ft(n,o);if(0===a)return!1;const h=(t*n+e*o)/a;return h>0&&Math.abs(h)>i},Gt=({x:t,y:e,radius:i},{x:r,y:s,points:n,edges:o})=>{const a=r-t,h=s-e,l=n.length;for(let t=0;t<l;t++){const e=n[t],r=a-e.x,s=h-e.y,u=0===t?l-1:t-1,d=(t+1)%l,c=o[t];if(Dt(a,h,n[u],o[u],r,s,i,c.x,c.y))return!1;if(It(a,h,n[d],o[d],r,s,i,c.x,c.y))return!1;if(Nt(r,s,i,c.x,c.y))return!1}return!0},Ut=(t,e)=>ct(at(t),at(e)),Vt=(t,e)=>ct(at(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:r})=>({x:i+t,y:r+e})))(e)),Ot=(t,e)=>gt(t,e),zt=(t,e)=>{if(e.left>t.right||e.top>t.bottom)return null;if(t.left>e.right||t.top>e.bottom)return null;const i=t.position.clone().set(0,0),r=t.position.clone().set(0,0);return{shapeA:t,shapeB:e,overlap:0,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:i,projectionV:r}},Wt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),r=i.length,s=t.radius+e.radius-r;if(s<0)return i.destroy(),null;const n=i.clone().normalize(),o=i.multiply(s);return{shapeA:t,shapeB:e,overlap:s,shapeAinB:t.radius<=e.radius&&r<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&r<=t.radius-e.radius,projectionN:n,projectionV:o}},qt=(t,e,i=!1)=>{const r=t.radius,s=e.width/2,n=e.height/2,o=U(t.x,t.y,e.x-s,e.y-n),a=r<=Math.min(s,n)&&o<=Math.min(s,n)-r,h=Math.max(s,n)<=r&&o<=r-Math.max(s,n);if(o>t.radius)return null;const l=t.position.clone().set(0,0),u=t.position.clone().set(0,0);return{shapeA:i?e:t,shapeB:i?t:e,overlap:r-o,shapeAinB:i?h:a,shapeBinA:i?a:h,projectionN:l,projectionV:u}},Ht=(t,e,i=!1)=>{const r=e.radius,s=t.points,n=e.x-t.x,o=e.y-t.y,a=e.position.clone().set(0,0),h=s.length;let l=!0,u=!0,d=1/0;for(let t=0;t<h;t++){const e=s[t],i=s[(t+1)%h],c=i.x-e.x,p=i.y-e.y,_=n-e.x,f=o-e.y,m=mt(c,p,_,f),g=ft(_,f);if(g>r&&(l=!1),-1===m){const i=s[0===t?h-1:t-1],l=e.x-i.x,c=e.y-i.y,p=n-i.x,m=o-i.y;if(1===mt(l,c,p,m)){if(g>r)return a.destroy(),null;const t=r-g;Math.abs(t)<Math.abs(d)&&(d=t,a.set(_,f).normalize()),u=!1}}else if(1===m){const e=s[(t+2)%h],l=e.x-i.x,c=e.y-i.y,p=n-i.x,_=o-i.y,f=ft(p,_);if(-1===mt(l,c,p,_)){if(f>r)return a.destroy(),null;const t=r-f;Math.abs(t)<Math.abs(d)&&(d=t,a.set(p,_).normalize()),u=!1}}else{const t=p,e=-c,i=ft(t,e),s=0===i?0:(_*t+f*e)/i;if(s>0&&Math.abs(s)>r)return a.destroy(),null;(s>=0||r-s<2*r)&&(u=!1);const n=r-s;Math.abs(n)<Math.abs(d)&&(d=n,a.set(t,e).normalize())}}const c=a.clone().multiply(d);return{shapeA:i?e:t,shapeB:i?t:e,overlap:d,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:c}},Xt=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=(i[0]||r[0]).clone(),n=new st,o=new st;let a=1/0,h=!0,l=!0,u=!1,d=!1,c=0;for(const r of i){if(t.project(r,n),e.project(r,o),!n.overlaps(o))return s.destroy(),null;c=n.getOverlap(o),u=o.containsInterval(n),d=n.containsInterval(o),!u&&h&&(h=!1),!d&&l&&(l=!1),(u||d)&&(c+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),c<a&&(a=c,s.copy(r))}for(const i of r){if(t.project(i,n),e.project(i,o),!n.overlaps(o))return s.destroy(),null;c=n.getOverlap(o),u=o.containsInterval(n),d=n.containsInterval(o),!u&&h&&(h=!1),!d&&l&&(l=!1),(u||d)&&(c+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),c<a&&(a=c,s.copy(i))}const p=s.clone().multiply(a,a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:h,shapeBinA:l,projectionN:s,projectionV:p}};let jt=null;const Yt=()=>{},$t=new Q(Yt);class Kt{constructor(t=0,e=t,r=0,s=r){this.collisionType=2,this._normals=null,this._normalsDirty=!1,this._position=new Q(()=>{this._normalsDirty=!0},t,e),this._size=new i(r,s)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get size(){return this._size}set size(t){this._size.copy(t),this._normalsDirty=!0}get width(){return this._size.width}set width(t){this._size.width=t,this._normalsDirty=!0}get height(){return this._size.height}set height(t){this._size.height=t,this._normalsDirty=!0}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}setPosition(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setSize(t,e){return this._size.set(t,e),this._normalsDirty=!0,this}set(t,e,i,r){return this.setPosition(t,e),this.setSize(i,r),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new Kt(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:r}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.width!==i||void 0!==r&&this.height!==r)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new Q(Yt),new Q(Yt),new Q(Yt),new Q(Yt)])),this._normalsDirty=!1),this._normals}project(t,e=new st){const i=t.dot(this.left,this.top),r=t.dot(this.right,this.top),s=t.dot(this.right,this.bottom),n=t.dot(this.left,this.bottom);return e.set(Math.min(i,r,s,n),Math.max(i,r,s,n))}transform(t,e=this){const i=$t.set(this.left,this.top).transform(t);let r=i.x,s=i.x,n=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),e.set(r,n,s-r,o-n)}contains(t,e){return wt($t.set(t,e),this)}containsRect(t){return G(t.left,this.left,this.right)&&G(t.right,this.left,this.right)&&G(t.top,this.top,this.bottom)&&G(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?Et(this,t.getBounds()):gt(this,t);case 2:return Et(this,t);case 5:return Ft(this,t);case 3:return Rt(this,t);case 4:return At(this,t);case 1:return Ct(t,this);case 0:return wt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?zt(this,t.getBounds()):Xt(this,t);case 2:return zt(this,t);case 5:return Xt(this,t);case 3:return qt(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(t){t[0].set(this.right-this.left,0).rperp().normalize(),t[1].set(0,this.bottom-this.top).rperp().normalize(),t[2].set(this.left-this.right,0).rperp().normalize(),t[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===jt&&(jt=new Kt),jt}}class Qt{constructor(){this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this._rect=new Kt}get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(t,e){return this._minX=Math.min(this._minX,t),this._minY=Math.min(this._minY,e),this._maxX=Math.max(this._maxX,t),this._maxY=Math.max(this._maxY,e),this._dirty=!0,this}addRect(t,e){return e&&(t=t.transform(e,Kt.temp)),this.addCoords(t.left,t.top).addCoords(t.right,t.bottom)}getRect(){return this._dirty&&(this._rect.set(this._minX,this._minY,this._maxX-this._minX,this._maxY-this._minY),this._dirty=!1),this._rect}reset(){return this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this}destroy(){this._rect.destroy()}}class Zt extends it{constructor(){super(...arguments),this.collisionType=6,this._bounds=new Qt,this._visible=!0,this._globalTransform=new J,this._localBounds=new Kt,this._anchor=new Q(this._updateOrigin.bind(this),0,0),this._parentNode=null,this._zIndex=0,this._childOrder=0,this._cullable=!0}get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get parentNode(){return this._parentNode}set parentNode(t){this._parentNode=t}get visible(){return this._visible}set visible(t){this._visible=t}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this._parentNode?.markSortDirty())}get childOrder(){return this._childOrder}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get globalTransform(){return this.getGlobalTransform()}get localBounds(){return this.getLocalBounds()}get bounds(){return this.getBounds()}get isAlignedBox(){return this.rotation%90==0}setAnchor(t,e=t){return this._anchor.set(t,e),this}setChildOrder(t){return this._childOrder=t,this}setCullable(t){return this._cullable=t,this}getLocalBounds(){return this._localBounds}getBounds(){return this.updateParentTransform(),this.updateBounds(),this._bounds.getRect()}updateBounds(){return this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform()),this}updateParentTransform(){return this._parentNode&&this._parentNode.updateParentTransform(),this.updateTransform(),this}getGlobalTransform(){return this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this._globalTransform}getNormals(){return this.getBounds().getNormals()}project(t,e=new st){return this.getBounds().project(t,e)}intersectsWith(t){if(this.isAlignedBox)return this.getBounds().intersectsWith(t);switch(t.collisionType){case 6:case 2:case 5:return gt(this,t);case 3:return Rt(this.getBounds(),t);case 4:return At(this.getBounds(),t);case 1:return Ct(t,this.getBounds());case 0:return wt(t,this.getBounds());default:return!1}}collidesWith(t){if(this.isAlignedBox)return this.getBounds().collidesWith(t);switch(t.collisionType){case 6:case 2:case 5:case 3:return Xt(this,t);default:return null}}contains(t,e){return this.getBounds().contains(t,e)}inView(t){return!this._cullable||t.getBounds().intersectsWith(this.getBounds())}render(t){return this}destroy(){super.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:r}=this.getBounds();this.setOrigin(i*t,r*e)}}class Jt extends i{constructor(t,e=0,i=0){super(e,i),this._callback=t}get width(){return this._width}set width(t){this._width!==t&&(this._width=t,this._callback())}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this._callback())}set(t=this._width,e=this._height){return this._width===t&&this._height===e||(this._width=t,this._height=e,this._callback()),this}add(t,e=t){return this.set(this._width+t,this._height+e)}subtract(t,e=t){return this.set(this._width-t,this._height-e)}scale(t,e=t){return this.set(this._width*t,this._height*e)}divide(t,e=t){return this.set(this._width/t,this._height/e)}copy(t){return this.set(t.width,t.height)}clone(){return new Jt(this._callback,this._width,this._height)}}var te;t.ViewFlags=void 0,(te=t.ViewFlags||(t.ViewFlags={}))[te.None=0]="None",te[te.Translation=1]="Translation",te[te.Rotation=2]="Rotation",te[te.Scaling=4]="Scaling",te[te.Origin=8]="Origin",te[te.Transform=15]="Transform",te[te.TransformInverse=16]="TransformInverse",te[te.BoundingBox=32]="BoundingBox",te[te.TextureCoords=64]="TextureCoords",te[te.VertexTint=128]="VertexTint";class ee{constructor(e,i,r,s){this._viewport=new Kt(0,0,1,1),this._transform=new J,this._inverseTransform=new J,this._bounds=new Qt,this._flags=new tt,this._rotation=0,this._sin=0,this._cos=1,this._zoomLevel=1,this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this._boundsConstraint=null,this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakeFrequency=16,this._shakeDecay=!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._updateId=0,this._center=new Q(this._setPositionDirty.bind(this),e,i),this._size=new Jt(this._setScalingDirty.bind(this),r,s),this._zoomBaseWidth=r,this._zoomBaseHeight=s,this._flags.push(t.ViewFlags.Transform,t.ViewFlags.TransformInverse,t.ViewFlags.BoundingBox)}get center(){return this._center}set center(t){this._center.copy(t)}get size(){return this._size}set size(t){this._size.copy(t)}get width(){return this._size.width}set width(t){this._size.width=t}get height(){return this._size.height}set height(t){this._size.height=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get viewport(){return this._viewport}set viewport(t){this._viewport.equals(t)||(this._viewport.copy(t),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(t,e){return this._center.set(t,e),this}resize(t,e){return this._zoomBaseWidth=t,this._zoomBaseHeight=e,this._zoomLevel=1,this._size.set(t,e),this}setRotation(t){const e=k(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}move(t,e){return this.setCenter(this._center.x+t,this._center.y+e),this}zoom(t){return this.resize(this._size.width*t,this._size.height*t),this}setZoom(t){const e=Math.max(1e-4,t);return this._zoomLevel=e,this._size.set(this._zoomBaseWidth/e,this._zoomBaseHeight/e),this}zoomIn(t=.1){return this.setZoom(this._zoomLevel+t)}zoomOut(t=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-t))}follow(t,e={}){return this._followTarget=t,this._followLerp=D(e.lerp??1,0,1),this._followOffsetX=e.offsetX??0,this._followOffsetY=e.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(t){return null===t?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=t.clone():this._boundsConstraint.copy(t),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(t,e,i={}){return this._shakeIntensity=Math.max(0,t),this._shakeDurationMs=Math.max(0,e),this._shakeElapsedMs=0,this._shakeFrequency=Math.max(0,i.frequency??16),this._shakeDecay=i.decay??!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty(),this}stopShake(){return this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakePhase=0,0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()),this}update(t){return this._updateFollowTarget(),this._updateShake(t),this._applyBoundsConstraint(),this}rotate(t){return this.setRotation(this._rotation+t),this}reset(e,i,r,s){return this._zoomBaseWidth=r,this._zoomBaseHeight=s,this._zoomLevel=1,this._size.set(r,s),this._center.set(e,i),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(t.ViewFlags.Transform),this}getTransform(){return this._flags.has(t.ViewFlags.Transform)&&(this.updateTransform(),this._flags.remove(t.ViewFlags.Transform)),this._transform}updateTransform(){const e=this._center.x+this._shakeOffsetX,i=this._center.y+this._shakeOffsetY,r=2/this.width,s=-2/this.height;if(this._flags.has(t.ViewFlags.Rotation)){const t=L(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(t.ViewFlags.Rotation|t.ViewFlags.Scaling)&&(this._transform.a=r*this._cos,this._transform.b=r*this._sin,this._transform.c=-s*this._sin,this._transform.d=s*this._cos),this._transform.x=r*-this._transform.a-s*this._transform.b+-r*e,this._transform.y=r*-this._transform.c-s*this._transform.d+-s*i,this}getInverseTransform(){return this._flags.has(t.ViewFlags.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(t.ViewFlags.TransformInverse)),this._inverseTransform}getBounds(){return this._flags.has(t.ViewFlags.BoundingBox)&&(this.updateBounds(),this._flags.remove(t.ViewFlags.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,r=this.height/2;return this._bounds.reset().addCoords(t-i,e-r).addCoords(t+i,e+r),this}destroy(){this.stopShake(),this.clearFollow(),this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this._center.destroy(),this._size.destroy(),this._viewport.destroy(),this._transform.destroy(),this._inverseTransform.destroy(),this._bounds.destroy(),this._flags.destroy()}_setDirty(){this._flags.push(t.ViewFlags.TransformInverse,t.ViewFlags.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(t.ViewFlags.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(t.ViewFlags.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(t.ViewFlags.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;const t=this._followTarget.x+this._followOffsetX,e=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(t,e):this.setCenter(this._center.x+(t-this._center.x)*this._followLerp,this._center.y+(e-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const t=this._boundsConstraint,e=this.width/2,i=this.height/2,r=t.left+e,s=t.right-e,n=t.top+i,o=t.bottom-i,a=r>s?(t.left+t.right)/2:D(this._center.x,r,s),h=n>o?(t.top+t.bottom)/2:D(this._center.y,n,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(t){if(this._shakeDurationMs<=0||this._shakeIntensity<=0)return void(0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()));this._shakeElapsedMs=Math.min(this._shakeDurationMs,this._shakeElapsedMs+Math.max(0,t));const e=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-e):this._shakeIntensity;this._shakePhase+=Math.max(0,t)/1e3*this._shakeFrequency*Math.PI*2;const r=Math.sin(1.7*this._shakePhase)*i,s=Math.cos(1.3*this._shakePhase)*i;r===this._shakeOffsetX&&s===this._shakeOffsetY||(this._shakeOffsetX=r,this._shakeOffsetY=s,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}let ie=null;class re extends K{constructor(t=0,e=0){super(),this.collisionType=0,this.x=t,this.y=e}clone(){return new re(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case 6:return wt(this,t.getBounds());case 2:return wt(this,t);case 5:return St(this,t);case 3:return vt(this,t);case 4:return bt(this,t);case 1:return xt(this,t);case 0:return yt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return Kt.temp.set(this.x,this.y,0,0)}contains(t,e){return yt(re.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new st){return e}destroy(){}static get temp(){return null===ie&&(ie=new re),ie}static add(t,e){return new re(t.x+e.x,t.y+e.y)}static subtract(t,e){return new re(t.x-e.x,t.y-e.y)}static multiply(t,e){return new re(t.x*e.x,t.y*e.y)}static divide(t,e){return new re(t.x/e.x,t.y/e.y)}}re.zero=new re(0,0),re.one=new re(1,1);class se{constructor(t,e,r=!1){this._destroyListeners=new Set,this._version=0,this._viewport=new Kt,this._size=new i(t,e),this._root=r,this._defaultView=new ee(t/2,e/2,t,e),this._view=this._defaultView}get view(){return this._view}set view(t){this.setView(t)}get size(){return this._size}set size(t){this.resize(t.width,t.height)}get width(){return this._size.width}set width(t){this.resize(t,this.height)}get height(){return this._size.height}set height(t){this.resize(this.width,t)}get root(){return this._root}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setView(t){const e=t||this._defaultView;return this._view!==e&&(this._view=e,this._touch()),this}resize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}getViewport(t=this._view){const{x:e,y:i,width:r,height:s}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(r*this.width),Math.round(s*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new re(2*(t.x-i.left)/i.width-1,1-2*(t.y-i.top)/i.height).transform(e.getInverseTransform())}mapCoordsToPixel(t,e=this._view){const i=this.getViewport(e),r=t.clone().transform(e.getTransform());return r.set((r.x+1)/2*i.width+i.left|0,(1-r.y)/2*i.height+i.top|0)}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class ne extends se{constructor(t,e,i){super(t,e,!1),this._source=null,this._textureVersion=0;const{scaleMode:r,wrapMode:s,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...ne.defaultSamplerOptions,...i};this._scaleMode=r,this._wrapMode=s,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(t){this.setSource(t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return N(this.width)&&N(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touchTexture()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touchTexture()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touchTexture()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._defaultView.resize(t,e),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}ne.defaultSamplerOptions={scaleMode:t.ScaleModes.Linear,wrapMode:t.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};class oe{constructor(t,e={}){this._callback=t,this._target=e.target??null,this._view=e.view??null,this._clearColor=e.clearColor??null}execute(t){const e=t.renderTarget,i=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(e),t.setView(i)}}}const ae=t=>"destroy"in t&&"function"==typeof t.destroy;class he extends Zt{constructor(){super(...arguments),this._filters=[],this._cacheBounds=new Kt,this._cacheSprite=null,this._captureView=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheDirty=!0,this._cacheTexture=null}get filters(){return this._filters}set filters(t){this.setFilters(t)}get mask(){return this._mask}set mask(t){this._mask!==t&&(this._mask=t,this.invalidateCache())}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this.setCacheAsBitmap(t)}setFilters(t){return this._filters.length=0,this._filters.push(...t),this.invalidateCache()}addFilter(t){return this._filters.push(t),this.invalidateCache()}removeFilter(t){const e=this._filters.indexOf(t);return-1!==e&&(this._filters.splice(e,1),this.invalidateCache()),this}static setInternalSpriteFactory(t){he._spriteFactory=t}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}setCacheAsBitmap(t){return this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture()),this}invalidateCache(){return this._cacheDirty=!0,this}renderVisualContent(e,i,r=t.BlendModes.Normal){const s=this._filters.length>0,n=this._cacheAsBitmap;if(!s&&!n)return void this._withMask(e,i);const o=this.getBounds();if(o.width<=0||o.height<=0)return;const a=Math.floor(o.left),h=Math.floor(o.top),l=Math.max(1,Math.ceil(o.width)),u=Math.max(1,Math.ceil(o.height)),d=!this._cacheBounds.equals({x:a,y:h,width:l,height:u}),c=n&&(this._cacheDirty||null===this._cacheTexture||d);if(n&&!c&&null!==this._cacheTexture)return void this._withMask(e,()=>{this._drawTexture(e,this._cacheTexture,a,h,l,u,r)});const p=[],_=n?this._ensureCacheTexture(l,u):null;try{const t=n&&!s?_:e.acquireRenderTexture(l,u);t!==_&&p.push(t),this._renderContentToTexture(e,t,a,h,l,u,i);let o=t;if(s)for(let t=0;t<this._filters.length;t++){const i=t===this._filters.length-1&&n?_:e.acquireRenderTexture(l,u);i!==_&&p.push(i),this._filters[t].apply(e,o,i),o=i}n&&(this._cacheTexture=_,this._cacheBounds.set(a,h,l,u),this._cacheDirty=!1),this._withMask(e,()=>{this._drawTexture(e,o,a,h,l,u,r)})}finally{for(const t of p)e.releaseRenderTexture(t)}}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const t of this._filters)ae(t)&&t.destroy();this._filters.length=0,this._mask=null}_withMask(t,e){if(null===this._mask)return void e();const i=this._mask.getBounds();if(!(i.width<=0||i.height<=0)){t.pushMask(i);try{e()}finally{t.popMask()}}}_renderContentToTexture(t,e,i,r,s,n,o){null===this._captureView?this._captureView=new ee(i+s/2,r+n/2,s,n):this._captureView.reset(i+s/2,r+n/2,s,n),t.execute(new oe(()=>{o()},{target:e,view:this._captureView,clearColor:z.transparentBlack}))}_drawTexture(t,e,i,r,s,n,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(z.white).setPosition(i,r).setRotation(0).setScale(1,1),a.width=s,a.height=n,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new ne(t,e):this._cacheTexture.width===t&&this._cacheTexture.height===e||this._cacheTexture.setSize(t,e),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===he._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=he._spriteFactory()}return this._cacheSprite}}he._spriteFactory=null;class le extends he{constructor(){super(...arguments),this._tint=z.white.clone(),this._blendMode=t.BlendModes.Normal}get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}render(t){return this.visible?this.inView(t.view)?(this.renderVisualContent(t,()=>{t.draw(this)},this._blendMode),this):(t.stats.culledNodes++,this):this}destroy(){super.destroy(),this._tint.destroy()}}class ue extends le{constructor(e,i,r=t.RenderingPrimitives.Triangles){super(),this.geometry=e,this.color=i.clone(),this.drawMode=r}destroy(){super.destroy(),this.color.destroy()}}class de{constructor({vertices:t=[],indices:e=[],points:i=[]}={}){this.vertices=new Float32Array(t),this.indices=new Uint16Array(e),this.points=i}destroy(){}}class ce extends ue{render(t){return this.visible&&t.draw(this),this}}class pe{constructor(e){this._stack=[],this._transitionOverlay=new ce(new de({vertices:[0,0,1,0,0,1,1,1],indices:[0,1,2,3],points:[0,0,1,0,0,1,1,1]}),z.black,t.RenderingPrimitives.TriangleStrip),this._transition=null,this.onChangeScene=new E,this.onStartScene=new E,this.onUpdateScene=new E,this.onStopScene=new E,this._handleKeyDown=t=>{this._dispatchInput({type:"keyDown",channel:t})},this._handleKeyUp=t=>{this._dispatchInput({type:"keyUp",channel:t})},this._handlePointerEnter=t=>{this._dispatchInput({type:"pointerEnter",pointer:t})},this._handlePointerLeave=t=>{this._dispatchInput({type:"pointerLeave",pointer:t})},this._handlePointerDown=t=>{this._dispatchInput({type:"pointerDown",pointer:t})},this._handlePointerMove=t=>{this._dispatchInput({type:"pointerMove",pointer:t})},this._handlePointerUp=t=>{this._dispatchInput({type:"pointerUp",pointer:t})},this._handlePointerTap=t=>{this._dispatchInput({type:"pointerTap",pointer:t})},this._handlePointerSwipe=t=>{this._dispatchInput({type:"pointerSwipe",pointer:t})},this._handlePointerCancel=t=>{this._dispatchInput({type:"pointerCancel",pointer:t})},this._handleMouseWheel=t=>{this._dispatchInput({type:"mouseWheel",wheel:t})},this._app=e,this._subscribeInputRouting()}get scene(){return this._stack.length>0?this._stack[this._stack.length-1].scene:null}set scene(t){this.setScene(t)}get scenes(){return this._stack.map(t=>t.scene)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(null===t)return await this._unloadAllScenes(),void this.onChangeScene.dispatch(null);if(this.scene===t)return void(this._stack.length>1&&await this._unloadCoveredScenes());if(this._stack.some(e=>e.scene===t))throw new Error("Cannot set a scene that is already present in the scene stack.");const e=this._resolveParticipationPolicy(t);await this._prepareScene(t),await this._unloadAllScenes(),this._stack.push({scene:t,policy:e}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async pushScene(t,e={}){return await this._runWithTransition(async()=>{if(this._stack.some(e=>e.scene===t))throw new Error("Cannot push a scene instance that is already present in the stack.");const i=this._resolveParticipationPolicy(t,e);await this._prepareScene(t),this._stack.push({scene:t,policy:i}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async popScene(t={}){return await this._runWithTransition(async()=>{if(0===this._stack.length)return;const t=this._stack[this._stack.length-1];await this._disposeScene(t.scene),this._stack.pop(),this.onChangeScene.dispatch(this.scene)},t.transition),this}update(t){this._advanceTransition(t.milliseconds);const{updateScenes:e,drawScenes:i}=this._resolveParticipants();for(const i of e)i.update(t);for(const t of i)t.draw(this._app.renderManager);const r=this._getTransitionAlpha();return r>0&&this._renderTransitionOverlay(r),null!==this.scene&&this.onUpdateScene.dispatch(this.scene),this}destroy(){if(this._unsubscribeInputRouting(),this._transition){const t=this._transition;this._transition=null,t.color.destroy(),t.reject(new Error("SceneManager was destroyed while a transition was active."))}this._unloadAllScenesOnDestroy(),this._transitionOverlay.destroy(),this.onChangeScene.destroy(),this.onStartScene.destroy(),this.onUpdateScene.destroy(),this.onStopScene.destroy()}async _prepareScene(t){t.app=this._app;try{await t.load(this._app.loader),await t.init(this._app.loader)}catch(e){let i=null;try{await t.unload(this._app.loader)}catch(t){i=t}if(t.destroy(),t.app=null,i){const t=e instanceof Error?e.message:String(e),r=i instanceof Error?i.message:String(i);throw new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${r}.`)}throw e}}async _disposeScene(t){this.onStopScene.dispatch(t),await t.unload(this._app.loader),t.destroy(),t.app=null}async _unloadAllScenes(){for(let t=this._stack.length-1;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0}async _unloadCoveredScenes(){if(this._stack.length<=1)return;const t=this._stack[this._stack.length-1];for(let t=this._stack.length-2;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0,this._stack.push(t)}async _unloadAllScenesOnDestroy(){for(let t=this._stack.length-1;t>=0;t--)try{await this._disposeScene(this._stack[t].scene)}catch(t){console.error("SceneManager.destroy() failed to unload the active scene.",t)}this._stack.length=0}_resolveParticipationPolicy(t,e={}){const i=t.getParticipationPolicy(),r=e.mode??i.mode??"overlay";return{mode:r,input:e.input??i.input??("overlay"===r?"passthrough":"capture")}}_resolveParticipants(){const t=new Array,e=new Array;let i=!0,r=!0;for(let s=this._stack.length-1;s>=0;s--){const n=this._stack[s];i&&t.push(n.scene),r&&e.push(n.scene),"opaque"===n.policy.mode?(i=!1,r=!1):"modal"===n.policy.mode&&(i=!1)}return t.reverse(),e.reverse(),{updateScenes:t,drawScenes:e}}_subscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.add?.(this._handleKeyDown),t?.onKeyUp?.add?.(this._handleKeyUp),t?.onPointerEnter?.add?.(this._handlePointerEnter),t?.onPointerLeave?.add?.(this._handlePointerLeave),t?.onPointerDown?.add?.(this._handlePointerDown),t?.onPointerMove?.add?.(this._handlePointerMove),t?.onPointerUp?.add?.(this._handlePointerUp),t?.onPointerTap?.add?.(this._handlePointerTap),t?.onPointerSwipe?.add?.(this._handlePointerSwipe),t?.onPointerCancel?.add?.(this._handlePointerCancel),t?.onMouseWheel?.add?.(this._handleMouseWheel)}_unsubscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.remove?.(this._handleKeyDown),t?.onKeyUp?.remove?.(this._handleKeyUp),t?.onPointerEnter?.remove?.(this._handlePointerEnter),t?.onPointerLeave?.remove?.(this._handlePointerLeave),t?.onPointerDown?.remove?.(this._handlePointerDown),t?.onPointerMove?.remove?.(this._handlePointerMove),t?.onPointerUp?.remove?.(this._handlePointerUp),t?.onPointerTap?.remove?.(this._handlePointerTap),t?.onPointerSwipe?.remove?.(this._handlePointerSwipe),t?.onPointerCancel?.remove?.(this._handlePointerCancel),t?.onMouseWheel?.remove?.(this._handleMouseWheel)}_dispatchInput(t){for(let e=this._stack.length-1;e>=0;e--){const i=this._stack[e];if("transparent"===i.policy.input)continue;if(!1===i.scene.handleInput(t)||"capture"===i.policy.input)break}}async _runWithTransition(t,e){if(!e||"fade"!==e.type)return void await t();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,e.duration??220);0!==i?await new Promise((r,s)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:r,reject:s,color:(e.color??z.black).clone(),elapsedMs:0,phase:"out"}}):await t()}_advanceTransition(t){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),void(this._transition.elapsedMs>=this._transition.durationMs&&(this._transition.phase="switching",this._executeTransitionAction()))):void("in"===this._transition.phase&&(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const t=this._transition;if(t&&"switching"===t.phase){try{await t.action()}catch(e){return void(this._transition===t&&(this._transition=null,t.color.destroy(),t.reject(e)))}this._transition===t&&(t.phase="in",t.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const t=this._transition;this._transition=null,t.color.destroy(),t.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const t=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?t:1-t}_renderTransitionOverlay(t){const e=this._transition,i=e?e.color:z.black,r=this._app.renderManager,s=r.view.getBounds(),n=this._transitionOverlay.geometry.vertices;n[0]=s.left,n[1]=s.top,n[2]=s.right,n[3]=s.top,n[4]=s.left,n[5]=s.bottom,n[6]=s.right,n[7]=s.bottom,this._transitionOverlay.color.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),this._transitionOverlay.render(r)}}const _e=function(){var t=function(t){window.console&&window.console.error?window.console.error(t):function(t){window.console&&window.console.log&&window.console.log(t)}(t)},e={enable:{1:{0:!0}},disable:{1:{0:!0}},getParameter:{1:{0:!0}},drawArrays:{3:{0:!0}},drawElements:{4:{0:!0,2:!0}},createShader:{1:{0:!0}},getShaderParameter:{2:{1:!0}},getProgramParameter:{2:{1:!0}},getShaderPrecisionFormat:{2:{0:!0,1:!0}},getVertexAttrib:{2:{1:!0}},vertexAttribPointer:{6:{2:!0}},bindTexture:{2:{0:!0}},activeTexture:{1:{0:!0}},getTexParameter:{2:{0:!0,1:!0}},texParameterf:{3:{0:!0,1:!0}},texParameteri:{3:{0:!0,1:!0,2:!0}},copyTexImage2D:{8:{0:!0,2:!0}},copyTexSubImage2D:{8:{0:!0}},generateMipmap:{1:{0:!0}},bindBuffer:{2:{0:!0}},getBufferParameter:{2:{0:!0,1:!0}},pixelStorei:{2:{0:!0,1:!0}},bindRenderbuffer:{2:{0:!0}},bindFramebuffer:{2:{0:!0}},checkFramebufferStatus:{1:{0:!0}},framebufferRenderbuffer:{4:{0:!0,1:!0,2:!0}},framebufferTexture2D:{5:{0:!0,1:!0,2:!0}},getFramebufferAttachmentParameter:{3:{0:!0,1:!0,2:!0}},getRenderbufferParameter:{2:{0:!0,1:!0}},renderbufferStorage:{4:{0:!0,1:!0}},clear:{1:{0:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]}}},depthFunc:{1:{0:!0}},blendFunc:{2:{0:!0,1:!0}},blendFuncSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},blendEquation:{1:{0:!0}},blendEquationSeparate:{2:{0:!0,1:!0}},stencilFunc:{3:{0:!0}},stencilFuncSeparate:{4:{0:!0,1:!0}},stencilMaskSeparate:{2:{0:!0}},stencilOp:{3:{0:!0,1:!0,2:!0}},stencilOpSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},cullFace:{1:{0:!0}},frontFace:{1:{0:!0}},drawArraysInstancedANGLE:{4:{0:!0}},drawElementsInstancedANGLE:{5:{0:!0,2:!0}},blendEquationEXT:{1:{0:!0}},bufferData:{3:{0:!0,2:!0},4:{0:!0,2:!0},5:{0:!0,2:!0}},bufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},copyBufferSubData:{5:{0:!0,1:!0}},getBufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},blitFramebuffer:{10:{8:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]},9:!0}},framebufferTextureLayer:{5:{0:!0,1:!0}},invalidateFramebuffer:{2:{0:!0}},invalidateSubFramebuffer:{6:{0:!0}},readBuffer:{1:{0:!0}},getInternalformatParameter:{3:{0:!0,1:!0,2:!0}},renderbufferStorageMultisample:{5:{0:!0,2:!0}},texStorage2D:{5:{0:!0,2:!0}},texStorage3D:{6:{0:!0,2:!0}},texImage2D:{9:{0:!0,2:!0,6:!0,7:!0},6:{0:!0,2:!0,3:!0,4:!0},10:{0:!0,2:!0,6:!0,7:!0}},texImage3D:{10:{0:!0,2:!0,7:!0,8:!0},11:{0:!0,2:!0,7:!0,8:!0}},texSubImage2D:{9:{0:!0,6:!0,7:!0},7:{0:!0,4:!0,5:!0},10:{0:!0,6:!0,7:!0}},texSubImage3D:{11:{0:!0,8:!0,9:!0},12:{0:!0,8:!0,9:!0}},copyTexSubImage3D:{9:{0:!0}},compressedTexImage2D:{7:{0:!0,2:!0},8:{0:!0,2:!0},9:{0:!0,2:!0}},compressedTexImage3D:{8:{0:!0,2:!0},9:{0:!0,2:!0},10:{0:!0,2:!0}},compressedTexSubImage2D:{8:{0:!0,6:!0},9:{0:!0,6:!0},10:{0:!0,6:!0}},compressedTexSubImage3D:{10:{0:!0,8:!0},11:{0:!0,8:!0},12:{0:!0,8:!0}},vertexAttribIPointer:{5:{2:!0}},drawArraysInstanced:{4:{0:!0}},drawElementsInstanced:{5:{0:!0,2:!0}},drawRangeElements:{6:{0:!0,4:!0}},readPixels:{7:{4:!0,5:!0},8:{4:!0,5:!0}},clearBufferfv:{3:{0:!0},4:{0:!0}},clearBufferiv:{3:{0:!0},4:{0:!0}},clearBufferuiv:{3:{0:!0},4:{0:!0}},clearBufferfi:{4:{0:!0}},beginQuery:{2:{0:!0}},endQuery:{1:{0:!0}},getQuery:{2:{0:!0,1:!0}},getQueryParameter:{2:{1:!0}},samplerParameteri:{3:{1:!0,2:!0}},samplerParameterf:{3:{1:!0}},getSamplerParameter:{2:{1:!0}},fenceSync:{2:{0:!0,1:{enumBitwiseOr:[]}}},clientWaitSync:{3:{1:{enumBitwiseOr:["SYNC_FLUSH_COMMANDS_BIT"]}}},waitSync:{3:{1:{enumBitwiseOr:[]}}},getSyncParameter:{2:{1:!0}},bindTransformFeedback:{2:{0:!0}},beginTransformFeedback:{1:{0:!0}},transformFeedbackVaryings:{3:{2:!0}},bindBufferBase:{3:{0:!0}},bindBufferRange:{5:{0:!0}},getIndexedParameter:{2:{0:!0}},getActiveUniforms:{3:{2:!0}},getActiveUniformBlockParameter:{3:{2:!0}}},i=null,r=null;function s(t){if(null==i)for(var e in i={},r={},t)"number"==typeof t[e]&&(i[t[e]]=e,r[e]=t[e])}function n(){if(null==i)throw"WebGLDebugUtils.init(ctx) not called"}function o(t){n();var e=i[t];return void 0!==e?"gl."+e:"/*UNKNOWN WebGL ENUM*/ 0x"+t.toString(16)}function a(t,i,s,n){var a;if(void 0!==(a=e[t])&&(void 0!==(a=a[i])&&a[s])){if("object"==typeof a[s]&&void 0!==a[s].enumBitwiseOr){for(var h=a[s].enumBitwiseOr,l=0,u=[],d=0;d<h.length;++d){var c=r[h[d]];0!==(n&c)&&(l|=c,u.push(o(c)))}return l===n?u.join(" | "):o(n)}return o(n)}return null===n?"null":void 0===n?"undefined":n.toString()}function h(t,e,i){t.__defineGetter__(i,function(){return e[i]}),t.__defineSetter__(i,function(t){e[i]=t})}function l(t){var e=!!t.createTransformFeedback;e&&t.bindVertexArray(null);var i=t.getParameter(t.MAX_VERTEX_ATTRIBS),r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r);for(var s=0;s<i;++s)t.disableVertexAttribArray(s),t.vertexAttribPointer(s,4,t.FLOAT,!1,0,0),t.vertexAttrib1f(s,0),e&&t.vertexAttribDivisor(s,0);t.deleteBuffer(r);var n=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(s=0;s<n;++s)t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_CUBE_MAP,null),t.bindTexture(t.TEXTURE_2D,null),e&&(t.bindTexture(t.TEXTURE_2D_ARRAY,null),t.bindTexture(t.TEXTURE_3D,null),t.bindSampler(s,null));if(t.activeTexture(t.TEXTURE0),t.useProgram(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindRenderbuffer(t.RENDERBUFFER,null),t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.DITHER),t.disable(t.SCISSOR_TEST),t.blendColor(0,0,0,0),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.clearColor(0,0,0,0),t.clearDepth(1),t.clearStencil(-1),t.colorMask(!0,!0,!0,!0),t.cullFace(t.BACK),t.depthFunc(t.LESS),t.depthMask(!0),t.depthRange(0,1),t.frontFace(t.CCW),t.hint(t.GENERATE_MIPMAP_HINT,t.DONT_CARE),t.lineWidth(1),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.UNPACK_COLORSPACE_CONVERSION_WEBGL&&t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.polygonOffset(0,0),t.sampleCoverage(1,!1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilMask(4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),e){t.drawBuffers([t.BACK]),t.readBuffer(t.BACK),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null);var o=t.getParameter(t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);for(s=0;s<o;++s)t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,s,null);var a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);for(s=0;s<a;++s)t.bindBufferBase(t.UNIFORM_BUFFER,s,null);t.disable(t.RASTERIZER_DISCARD),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.hint(t.FRAGMENT_SHADER_DERIVATIVE_HINT,t.DONT_CARE)}for(;t.getError(););}return{init:s,mightBeEnum:function(t){return n(),void 0!==i[t]},glEnumToString:o,glFunctionArgToString:a,glFunctionArgsToString:function(t,e){for(var i="",r=e.length,s=0;s<r;++s)i+=(0==s?"":", ")+a(t,r,s,e[s]);return i},makeDebugContext:function e(i,r,n,l){l=l||i,s(i),r=r||function(e,i,r){for(var s="",n=r.length,h=0;h<n;++h)s+=(0==h?"":", ")+a(i,n,h,r[h]);t("WebGL error "+o(e)+" in "+i+"("+s+")")};var u={};function d(t,e){return function(){n&&n(e,arguments);var i=t[e].apply(t,arguments),s=l.getError();return 0!=s&&(u[s]=!0,r(s,e,arguments)),i}}var c={};for(var p in i)if("function"==typeof i[p])if("getExtension"!=p)c[p]=d(i,p);else{var _=d(i,p);c[p]=function(){var t=_.apply(i,arguments);return t?e(t,r,n,l):null}}else h(c,i,p);return c.getError=function(){for(var t in u)if(u.hasOwnProperty(t)&&u[t])return u[t]=!1,t;return i.NO_ERROR},c},makeLostContextSimulatingCanvas:function(t){var e,i,r,s=[],n=[],o={},a=1,u=!1,d=[],c=0,p=0,_=!1,f=0,m={};function g(t){return"function"==typeof t?t:function(e){t.handleEvent(e)}}function y(){++p,u||c==p&&t.loseContext()}function x(t,e){var i=t[e];return function(){if(y(),!u)return i.apply(t,arguments)}}function w(t){return{statusMessage:t,preventDefault:function(){_=!0}}}return t.getContext=(r=t.getContext,function(){var s=r.apply(t,arguments);if(s instanceof WebGLRenderingContext||window.WebGL2RenderingContext&&s instanceof WebGL2RenderingContext){if(s!=e){if(e)throw"got different context";i=window.WebGL2RenderingContext&&s instanceof WebGL2RenderingContext,o=function(t){for(var r in t)"function"==typeof t[r]?o[r]=x(t,r):h(o,t,r);o.getError=function(){if(y(),!u)for(;t=e.getError();)m[t]=!0;for(var t in m)if(m[t])return delete m[t],t;return o.NO_ERROR};var s=["createBuffer","createFramebuffer","createProgram","createRenderbuffer","createShader","createTexture"];i&&s.push("createQuery","createSampler","fenceSync","createTransformFeedback","createVertexArray");for(var n=0;n<s.length;++n){var l=s[n];o[l]=function(e){return function(){if(y(),u)return null;var i=e.apply(t,arguments);return i.__webglDebugContextLostId__=a,d.push(i),i}}(t[l])}var c=["getActiveAttrib","getActiveUniform","getBufferParameter","getContextAttributes","getAttachedShaders","getFramebufferAttachmentParameter","getParameter","getProgramParameter","getProgramInfoLog","getRenderbufferParameter","getShaderParameter","getShaderInfoLog","getShaderSource","getTexParameter","getUniform","getUniformLocation","getVertexAttrib"];for(i&&c.push("getInternalformatParameter","getQuery","getQueryParameter","getSamplerParameter","getSyncParameter","getTransformFeedbackVarying","getIndexedParameter","getUniformIndices","getActiveUniforms","getActiveUniformBlockParameter","getActiveUniformBlockName"),n=0;n<c.length;++n)l=c[n],o[l]=function(e){return function(){return y(),u?null:e.apply(t,arguments)}}(o[l]);var p=["isBuffer","isEnabled","isFramebuffer","isProgram","isRenderbuffer","isShader","isTexture"];for(i&&p.push("isQuery","isSampler","isSync","isTransformFeedback","isVertexArray"),n=0;n<p.length;++n)l=p[n],o[l]=function(e){return function(){return y(),!u&&e.apply(t,arguments)}}(o[l]);return o.checkFramebufferStatus=function(e){return function(){return y(),u?o.FRAMEBUFFER_UNSUPPORTED:e.apply(t,arguments)}}(o.checkFramebufferStatus),o.getAttribLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getAttribLocation),o.getVertexAttribOffset=function(e){return function(){return y(),u?0:e.apply(t,arguments)}}(o.getVertexAttribOffset),o.isContextLost=function(){return u},i&&(o.getFragDataLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getFragDataLocation),o.clientWaitSync=function(e){return function(){return y(),u?o.WAIT_FAILED:e.apply(t,arguments)}}(o.clientWaitSync),o.getUniformBlockIndex=function(e){return function(){return y(),u?o.INVALID_INDEX:e.apply(t,arguments)}}(o.getUniformBlockIndex)),o}(e=s)}return o}return s}),function(t){var e=t.addEventListener;t.addEventListener=function(i,r,o){switch(i){case"webglcontextlost":!function(t){s.push(g(t))}(r);break;case"webglcontextrestored":!function(t){n.push(g(t))}(r);break;default:e.apply(t,arguments)}}}(t),t.loseContext=function(){if(!u){for(u=!0,c=0,++a;e.getError(););!function(){for(var t=Object.keys(m),e=0;e<t.length;++e)delete m[t[e]]}(),m[e.CONTEXT_LOST_WEBGL]=!0;var i=w("context lost"),r=s.slice();setTimeout(function(){for(var e=0;e<r.length;++e)r[e](i);f>=0&&setTimeout(function(){t.restoreContext()},f)},0)}},t.restoreContext=function(){u&&n.length&&setTimeout(function(){if(!_)throw"can not restore. webglcontestlost listener did not call event.preventDefault";!function(){for(var t=0;t<d.length;++t){var r=d[t];r instanceof WebGLBuffer?e.deleteBuffer(r):r instanceof WebGLFramebuffer?e.deleteFramebuffer(r):r instanceof WebGLProgram?e.deleteProgram(r):r instanceof WebGLRenderbuffer?e.deleteRenderbuffer(r):r instanceof WebGLShader?e.deleteShader(r):r instanceof WebGLTexture?e.deleteTexture(r):i&&(r instanceof WebGLQuery?e.deleteQuery(r):r instanceof WebGLSampler?e.deleteSampler(r):r instanceof WebGLSync?e.deleteSync(r):r instanceof WebGLTransformFeedback?e.deleteTransformFeedback(r):r instanceof WebGLVertexArrayObject&&e.deleteVertexArray(r))}}(),l(e),u=!1,p=0,_=!1;for(var t=n.slice(),r=w("context restored"),s=0;s<t.length;++s)t[s](r)},0)},t.loseContextInNCalls=function(t){if(u)throw"You can not ask a lost contet to be lost";c=p+t},t.getNumCalls=function(){return p},t.setRestoreTimeout=function(t){f=t},t},resetToInitialState:l}}();class fe{constructor(e=t.RenderingPrimitives.Triangles){this._attributes=[],this._indexBuffer=null,this._runtime=null,this._version=0,this._drawMode=e}get attributes(){return this._attributes}get indexBuffer(){return this._indexBuffer}get drawMode(){return this._drawMode}get version(){return this._version}connect(t){return this._runtime=t,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(e,i,r=t.ShaderPrimitives.Float,s=!1,n=0,o=0){const{location:a,size:h}=i;return this._attributes.push({buffer:e,location:a,size:h,type:r,normalized:s,stride:n,start:o}),this._version++,this}addIndex(t){return this._indexBuffer=t,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(t,e,i=this._drawMode){return this._runtime?.draw(this,t,e,i),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}var me;t.RenderBackendType=void 0,(me=t.RenderBackendType||(t.RenderBackendType={}))[me.WebGl2=0]="WebGl2",me[me.WebGpu=1]="WebGpu";class ge{constructor(){this.backendType=t.RenderBackendType.WebGl2,this._runtime=null}connect(e){if(null===this._runtime){if(e.backendType!==t.RenderBackendType.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 runtime, but received backendType ${String(e.backendType)}.`);this._runtime=e,this.onConnect(e)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}class ye{constructor(t,e){this.attributes=new Map,this.uniforms=new Map,this._runtime=null,this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._runtime=t,t.initialize(this),this}disconnect(){return this._runtime=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}sync(){return this._runtime?.sync(this),this}getAttribute(t){const e=this.attributes.get(t);if(!e)throw new Error(`Attribute "${t}" is not available.`);return e}getUniform(t){const e=this.uniforms.get(t);if(!e)throw new Error(`Uniform "${t}" is not available.`);return e}destroy(){this._runtime?.destroy(this),this._runtime=null,this.attributes.clear(),this.uniforms.clear()}}const xe={[t.ShaderPrimitives.Float]:1,[t.ShaderPrimitives.FloatVec2]:2,[t.ShaderPrimitives.FloatVec3]:3,[t.ShaderPrimitives.FloatVec4]:4,[t.ShaderPrimitives.Int]:1,[t.ShaderPrimitives.IntVec2]:2,[t.ShaderPrimitives.IntVec3]:3,[t.ShaderPrimitives.IntVec4]:4,[t.ShaderPrimitives.Bool]:1,[t.ShaderPrimitives.BoolVec2]:2,[t.ShaderPrimitives.BoolVec3]:3,[t.ShaderPrimitives.BoolVec4]:4,[t.ShaderPrimitives.FloatMat2]:4,[t.ShaderPrimitives.FloatMat3]:9,[t.ShaderPrimitives.FloatMat4]:16,[t.ShaderPrimitives.Sampler2D]:1},we={[t.ShaderPrimitives.Float]:Float32Array,[t.ShaderPrimitives.FloatVec2]:Float32Array,[t.ShaderPrimitives.FloatVec3]:Float32Array,[t.ShaderPrimitives.FloatVec4]:Float32Array,[t.ShaderPrimitives.Int]:Int32Array,[t.ShaderPrimitives.IntVec2]:Int32Array,[t.ShaderPrimitives.IntVec3]:Int32Array,[t.ShaderPrimitives.IntVec4]:Int32Array,[t.ShaderPrimitives.Bool]:Uint8Array,[t.ShaderPrimitives.BoolVec2]:Uint8Array,[t.ShaderPrimitives.BoolVec3]:Uint8Array,[t.ShaderPrimitives.BoolVec4]:Uint8Array,[t.ShaderPrimitives.FloatMat2]:Float32Array,[t.ShaderPrimitives.FloatMat3]:Float32Array,[t.ShaderPrimitives.FloatMat4]:Float32Array,[t.ShaderPrimitives.Sampler2D]:Uint8Array},ve={[t.ShaderPrimitives.Float]:"FLOAT",[t.ShaderPrimitives.FloatVec2]:"FLOAT_VEC2",[t.ShaderPrimitives.FloatVec3]:"FLOAT_VEC3",[t.ShaderPrimitives.FloatVec4]:"FLOAT_VEC4",[t.ShaderPrimitives.Int]:"INT",[t.ShaderPrimitives.IntVec2]:"INT_VEC2",[t.ShaderPrimitives.IntVec3]:"INT_VEC3",[t.ShaderPrimitives.IntVec4]:"INT_VEC4",[t.ShaderPrimitives.Bool]:"BOOL",[t.ShaderPrimitives.BoolVec2]:"BOOL_VEC2",[t.ShaderPrimitives.BoolVec3]:"BOOL_VEC3",[t.ShaderPrimitives.BoolVec4]:"BOOL_VEC4",[t.ShaderPrimitives.FloatMat2]:"FLOAT_MAT2",[t.ShaderPrimitives.FloatMat3]:"FLOAT_MAT3",[t.ShaderPrimitives.FloatMat4]:"FLOAT_MAT4",[t.ShaderPrimitives.Sampler2D]:"SAMPLER_2D"};class be{constructor(t,e,i){this.location=-1,this.index=t,this.name=e,this.type=i,this.size=xe[i]}destroy(){}}class Se{constructor(t,e,i,r,s){this._dirty=!0,this.name=r.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=s}get propName(){return this.name.substr(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(t){return this._value.set(t),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class Te{constructor(t,e,i){this._uniforms=new Map,this._context=t,this._program=e,this.index=i,this.name=t.getActiveUniformBlockName(e,i)||"",this.binding=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_BINDING),this.dataSize=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=t.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferData(t.UNIFORM_BUFFER,this._blockData,t.DYNAMIC_DRAW),t.bindBufferBase(t.UNIFORM_BUFFER,this.binding,this._uniformBuffer),t.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(t){if(!this._uniforms.has(t))throw new Error(`Uniform "${t}" is not available.`);return this._uniforms.get(t)}upload(){const t=this._context;t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferSubData(t.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const t of this._uniforms.values())t.destroy();this._uniforms.clear()}_extractUniforms(){const t=this._context,e=this._program,i=this._blockData,r=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),s=t.getActiveUniforms(e,r,t.UNIFORM_OFFSET),n=r.length;for(let o=0;o<n;o++){const{type:n,size:a,name:h}=t.getActiveUniform(e,r[o]),l=new we[n](i,s[o],xe[n]*a),u=new Se(r[o],n,a,h,l);this._uniforms.set(u.propName,u)}}}const Ce={[t.ShaderPrimitives.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[t.ShaderPrimitives.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[t.ShaderPrimitives.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[t.ShaderPrimitives.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[t.ShaderPrimitives.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[t.ShaderPrimitives.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[t.ShaderPrimitives.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[t.ShaderPrimitives.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[t.ShaderPrimitives.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[t.ShaderPrimitives.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[t.ShaderPrimitives.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[t.ShaderPrimitives.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[t.ShaderPrimitives.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[t.ShaderPrimitives.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[t.ShaderPrimitives.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[t.ShaderPrimitives.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function Me(t){let e=null,i=null,r=null;const s=[],n=[];function o(o){e||(i=Pe(t,t.VERTEX_SHADER,o.vertexSource),r=Pe(t,t.FRAGMENT_SHADER,o.fragmentSource),e=function(t,e,i){const r=t.createProgram();if(!r)throw new Error("Could not create shader program.");if(t.attachShader(r,e),t.attachShader(r,i),t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){const s=t.getProgramInfoLog(r);throw t.detachShader(r,e),t.detachShader(r,i),t.deleteProgram(r),new Error(`Shader program linking failed: ${s}`)}return r}(t,i,r),function(t,e,i){const r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let s=0;s<r;s++){const r=t.getActiveAttrib(e,s);if(!r)continue;const n=new be(s,r.name,r.type);n.location=t.getAttribLocation(e,r.name),i.attributes.set(r.name,n)}}(t,e,o),function(t,e,i,r){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),n=new Uint8Array(s).map((t,e)=>e),o=t.getActiveUniforms(e,n,t.UNIFORM_BLOCK_INDEX),a=n.filter(t=>-1===o[t]);for(const s of a){const n=t.getActiveUniform(e,s);if(!n)continue;const o=new we[n.type](xe[n.type]*n.size),a=new Se(s,n.type,n.size,n.name,o),h=t.getUniformLocation(e,a.name),l=Ce[n.type];i.uniforms.set(a.name,a),h&&r.push({location:h,uploadFn:l,uniform:a})}}(t,e,o,s),function(t,e,i){const r=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<r;s++){const r=new Te(t,e,s);i.push(r)}}(t,e,n))}function a(){for(const e of s)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of n)t.upload()}return{initialize:o,bind:i=>{o(i),t.useProgram(e),a()},unbind:()=>{t.useProgram(null)},sync:()=>{a()},destroy:o=>{t.deleteShader(i),t.deleteShader(r),t.deleteProgram(e);for(const t of n)t.destroy();i=null,r=null,e=null,s.length=0,n.length=0,o.disconnect()}}}function Pe(t,e,i){const r=t.createShader(e);if(!r)throw new Error("Could not create shader.");if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(r);throw t.deleteShader(r),new Error(`Shader compilation failed: ${e}`)}return r}class Be{constructor(t,e,i){this._runtime=null,this._data=S,this._version=0,this._type=t,this._usage=i,e&&this.upload(e)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(t){return this._runtime=t,this._data.byteLength>0&&t.upload(this,0),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e)}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null}}const Ee=(t={})=>{const{canvas:e,fillStyle:i,width:r,height:s}=t,n=e??document.createElement("canvas"),o=n.getContext("2d");return n.width=r??10,n.height=s??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,n.width,n.height),n},Re=new Map;class Ae extends ge{constructor(t,e,i,r){super(),this.batchIndex=0,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.vao=null,this.indexBuffer=null,this.vertexBuffer=null,this.connection=null,this.batchSize=t,this.attributeCount=e,this.vertexData=new ArrayBuffer(t*e*4),this.float32View=new Float32Array(this.vertexData),this.uint32View=new Uint32Array(this.vertexData),this.indexData=(t=>{const e=new Uint16Array(6*t),i=e.length;for(let t=0,r=0;t<i;t+=6,r+=4)e[t]=r,e[t+1]=r+1,e[t+2]=r+2,e[t+3]=r,e[t+4]=r+2,e[t+5]=r+3;return e})(t),this.shader=new ye(i,r)}flush(){const t=this.getRuntimeOrNull(),e=this.vertexBuffer,i=this.vao;if(0===this.batchIndex||null===t||null===e||null===i)return;const r=t.view;this.currentView===r&&this.currentViewId===r.updateId||(this.currentView=r,this.currentViewId=r.updateId,this.updateView(r)),this.shader.sync(),t.bindVertexArrayObject(i),e.upload(this.float32View.subarray(0,this.batchIndex*this.attributeCount)),i.draw(6*this.batchIndex,0),t.stats.batches++,t.stats.drawCalls++,this.batchIndex=0}destroy(){this.disconnect(),this.shader.destroy(),this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.connection=null}onConnect(e){const i=e.context;this.shader.connect(Me(i)),this.connection=this.createConnection(i),this.indexBuffer=new Be(t.BufferTypes.ElementArrayBuffer,this.indexData,t.BufferUsage.StaticDraw).connect(this.createBufferRuntime(this.connection)),this.vertexBuffer=new Be(t.BufferTypes.ArrayBuffer,this.vertexData,t.BufferUsage.DynamicDraw).connect(this.createBufferRuntime(this.connection)),this.vao=this.createVao(i,this.indexBuffer,this.vertexBuffer).connect(this.createVaoRuntime(this.connection))}onDisconnect(){this.flush(),this.shader.disconnect(),this.indexBuffer?.destroy(),this.indexBuffer=null,this.vertexBuffer?.destroy(),this.vertexBuffer=null,this.vao?.destroy(),this.vao=null,this.connection=null,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.batchIndex=0}createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("Could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("Could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,r)=>{const s=t.gl,n=i.data,o=t.buffers.get(i);s.bindBuffer(i.type,e),o&&o.dataByteLength>=n.byteLength?(s.bufferSubData(i.type,r,n),o.dataByteLength=n.byteLength):(s.bufferData(i.type,n,i.usage),t.buffers.set(i,{handle:e,dataByteLength:n.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}createVaoRuntime(t){let e=-1;return{bind:i=>{const r=t.gl;if(r.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),r.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),r.enableVertexAttribArray(e.location);i.indexBuffer&&i.indexBuffer.bind(),e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,r,s)=>{const n=t.gl;e.indexBuffer?n.drawElements(s,i,n.UNSIGNED_SHORT,r):n.drawArrays(s,r,i)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}class Fe extends Ae{constructor(t){super(t,16,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,blendMode:i,tint:r,vertices:s,texCoords:n}=t,o=this.batchIndex>=this.batchSize,a=e!==this.currentTexture,h=i!==this.currentBlendMode,l=o||a||h,u=l?0:this.batchIndex*this.attributeCount,d=this.float32View,c=this.uint32View,p=this.getRuntime();return l&&(this.flush(),a&&(this.currentTexture=e),h&&(this.currentBlendMode=i,p.setBlendMode(i))),a&&e&&p.bindTexture(e),d[u+0]=s[0],d[u+1]=s[1],d[u+4]=s[2],d[u+5]=s[3],d[u+8]=s[4],d[u+9]=s[5],d[u+12]=s[6],d[u+13]=s[7],c[u+2]=n[0],c[u+6]=n[1],c[u+10]=n[2],c[u+14]=n[3],c[u+3]=c[u+7]=c[u+11]=c[u+15]=r.toRgba(),this.batchIndex++,this}createVao(t,e,i){return(new fe).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,12)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class ke extends Ae{constructor(t){super(t,36,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec2 a_translation;\r\nlayout(location = 3) in vec2 a_scale;\r\nlayout(location = 4) in float a_rotation;\r\nlayout(location = 5) in vec4 a_color;\n\nuniform mat3 u_projection;\nuniform mat3 u_translation;\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\n vec2 rotation = vec2(sin(radians(a_rotation)), cos(radians(a_rotation)));\n vec3 position = vec3(\n (a_position.x * (a_scale.x * rotation.y)) + (a_position.y * (a_scale.y * rotation.x)) + a_translation.x,\n (a_position.x * (a_scale.x * -rotation.x)) + (a_position.y * (a_scale.y * rotation.y)) + a_translation.y,\n 1.0\n );\n\n gl_Position = vec4((u_projection * u_translation * position).xy, 0.0, 1.0);\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,vertices:i,texCoords:r,particles:s,blendMode:n}=t,o=e!==this.currentTexture,a=n!==this.currentBlendMode,h=this.float32View,l=this.uint32View,u=this.getRuntime();this.flush(),(o||a)&&(o&&(this.currentTexture=e),a&&(this.currentBlendMode=n,u.setBlendMode(n))),o&&u.bindTexture(e),this.shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));for(const t of s){this.batchIndex>=this.batchSize&&this.flush();const{position:e,scale:s,rotation:n,tint:o}=t,a=this.batchIndex*this.attributeCount;h[a+0]=h[a+27]=i[0],h[a+1]=h[a+10]=i[1],h[a+9]=h[a+18]=i[2],h[a+19]=h[a+28]=i[3],l[a+2]=r[0],l[a+11]=r[1],l[a+20]=r[2],l[a+29]=r[3],h[a+3]=h[a+12]=h[a+21]=h[a+30]=e.x,h[a+4]=h[a+13]=h[a+22]=h[a+31]=e.y,h[a+5]=h[a+14]=h[a+23]=h[a+32]=s.x,h[a+6]=h[a+15]=h[a+24]=h[a+33]=s.y,h[a+7]=h[a+16]=h[a+25]=h[a+34]=n,l[a+8]=l[a+17]=l[a+26]=l[a+35]=o.toRgba(),this.batchIndex++}return this}createVao(t,e,i){return(new fe).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_translation"),t.FLOAT,!1,this.attributeCount,12).addAttribute(i,this.shader.getAttribute("a_scale"),t.FLOAT,!1,this.attributeCount,20).addAttribute(i,this.shader.getAttribute("a_rotation"),t.FLOAT,!1,this.attributeCount,28).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,32)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class Le extends ge{constructor(t){super(),this._shader=new ye("#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\nuniform mat3 u_translation;\r\n\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * u_translation * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nin vec4 v_color;\r\n\r\nvoid main(void) {\r\n fragColor = v_color;\r\n}\r\n"),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1,this._vertexCapacity=Math.max(4,t),this._indexCapacity=Math.max(6,3*this._vertexCapacity),this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._indexData=new Uint16Array(this._indexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}render(t){const e=this._connection;if(!e)throw new Error("Renderer not connected");const i=this.getRuntime(),{geometry:r,drawMode:s,color:n,blendMode:o}=t,a=r.vertices,h=r.indices,l=a.length/2,u=h.length>0?h.length:l;if(0===l||0===u)return;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u),o!==this._currentBlendMode&&(this._currentBlendMode=o,i.setBlendMode(o));const d=i.view;this._currentView===d&&this._viewId===d.updateId||(this._currentView=d,this._viewId=d.updateId,this._shader.getUniform("u_projection").setValue(d.getTransform().toArray(!1))),this._shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));const c=n.toRgba();for(let t=0;t<l;t++){const e=2*t,i=3*t;this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._uint32View[i+2]=c}if(h.length>0)this._indexData.set(h,0);else for(let t=0;t<l;t++)this._indexData[t]=t;this._shader.sync(),i.bindVertexArrayObject(e.vao),e.vertexBuffer.upload(this._float32View.subarray(0,3*l)),e.indexBuffer.upload(this._indexData.subarray(0,u)),e.vao.draw(u,0,s),i.stats.batches++,i.stats.drawCalls++}flush(){}destroy(){this.disconnect(),this._shader.destroy(),this._currentBlendMode=null,this._currentView=null}onConnect(e){const i=e.context,r=i.createVertexArray();if(this._shader.connect(Me(i)),null===r)throw new Error("Could not create vertex array object.");const s=new Map,n=new Be(t.BufferTypes.ElementArrayBuffer,this._indexData,t.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,s)),o=new Be(t.BufferTypes.ArrayBuffer,this._vertexData,t.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,s)),a=(new fe).addIndex(n).addAttribute(o,this._shader.getAttribute("a_position"),i.FLOAT,!1,12,0).addAttribute(o,this._shader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,12,8).connect(this._createVaoRuntime(i,r));this._connection={gl:i,buffers:s,vaoHandle:r,vao:a,indexBuffer:n,vertexBuffer:o}}onDisconnect(){const t=this._connection;t&&(this._shader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(r,s)=>{const n=e.get(r),o=r.data;t.bindBuffer(r.type,i),n&&n.dataByteLength>=o.byteLength?(t.bufferSubData(r.type,s,o),n.dataByteLength=o.byteLength):(t.bufferData(r.type,o,r.usage),e.set(r,{handle:i,dataByteLength:o.byteLength}))},destroy:r=>{t.deleteBuffer(i),e.delete(r),r.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:r=>{if(t.bindVertexArray(e),i!==r.version){let e=null;for(const i of r.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);r.indexBuffer&&r.indexBuffer.bind(),i=r.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,r,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,r):t.drawArrays(s,r,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}var De;t.SpriteFlags=void 0,(De=t.SpriteFlags||(t.SpriteFlags={}))[De.None=0]="None",De[De.Translation=1]="Translation",De[De.Rotation=2]="Rotation",De[De.Scaling=4]="Scaling",De[De.Origin=8]="Origin",De[De.Transform=15]="Transform",De[De.TransformInverse=16]="TransformInverse",De[De.BoundingBox=32]="BoundingBox",De[De.TextureCoords=64]="TextureCoords",De[De.VertexTint=128]="VertexTint";class Ie extends le{constructor(t){super(),this._texture=null,this._textureFrame=new Kt,this._vertices=new Float32Array(8),this._texCoords=new Uint32Array(4),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(t){this.scale.x=t/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(t){this.scale.y=t/this._textureFrame.height}get vertices(){const{left:t,top:e,right:i,bottom:r}=this.getLocalBounds(),{a:s,b:n,x:o,c:a,d:h,y:l}=this.getGlobalTransform();return this._vertices[0]=t*s+e*n+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*s+e*n+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*s+r*n+o,this._vertices[5]=i*a+r*h+l,this._vertices[6]=t*s+r*n+o,this._vertices[7]=t*a+r*h+l,this._vertices}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(t.SpriteFlags.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:r,right:s,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(r/e*65535&65535)<<16,h=s/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o)}return this._texCoords}setTexture(t){return this._texture!==t&&(this._texture=t,this.updateTexture(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(e,i=!0){const r=this.width,s=this.height;return this._textureFrame.copy(e),this.flags.push(t.SpriteFlags.TextureCoords),this.localBounds.set(0,0,e.width,e.height),i?(this.width=e.width,this.height=e.height):(this.width=r,this.height=s),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(Kt.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){const[t,e,i,r,s,n,o,a]=this.vertices;return[new re(i-t,r-e).rperp().normalize(),new re(s-i,n-r).rperp().normalize(),new re(o-s,a-n).rperp().normalize(),new re(t-o,e-a).rperp().normalize()]}project(t,e=new st){const[i,r,s,n,o,a,h,l]=this.vertices,u=t.dot(i,r),d=t.dot(s,n),c=t.dot(o,a),p=t.dot(h,l);return e.set(Math.min(u,d,c,p),Math.max(u,d,c,p))}contains(t,e){if(this.rotation%90==0)return this.getBounds().contains(t,e);const[i,r,s,n,o,a]=this.vertices,h=re.temp,l=h.set(s-i,n-r),u=l.dot(t-i,e-r),d=l.lengthSq,c=h.set(o-s,a-n),p=c.dot(t-s,e-n),_=c.lengthSq;return u>0&&u<=d&&p>0&&p<=_}destroy(){super.destroy(),this._textureFrame.destroy(),this._texture=null}}he.setInternalSpriteFactory(()=>new Ie(null));class Ne{constructor(){this._totalLifetime=n.oneSecond.clone(),this._elapsedLifetime=n.zero.clone(),this._position=re.zero.clone(),this._velocity=re.zero.clone(),this._scale=re.one.clone(),this._rotation=0,this._rotationSpeed=0,this._textureIndex=0,this._tint=z.white.clone()}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get tint(){return this._tint}set tint(t){this._tint.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=k(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get remainingLifetime(){return n.temp.set(this._totalLifetime.milliseconds-this._elapsedLifetime.milliseconds)}get elapsedRatio(){return this._elapsedLifetime.milliseconds/this._totalLifetime.milliseconds}get remainingRatio(){return this.remainingLifetime.milliseconds/this._totalLifetime.milliseconds}get expired(){return this._elapsedLifetime.greaterThan(this._totalLifetime)}applyOptions(t){const{totalLifetime:e,elapsedLifetime:i,position:r,velocity:s,scale:n,tint:o,rotation:a,rotationSpeed:h,textureIndex:l}=t;return this._totalLifetime.copy(e),this._elapsedLifetime.copy(i),this._position.copy(r),this._velocity.copy(s),this._scale.copy(n),this._tint.copy(o),this._rotation=a,this._rotationSpeed=h,this._textureIndex=l,this}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class Ge extends le{constructor(t){super(),this._emitters=[],this._affectors=[],this._particles=[],this._graveyard=[],this._textureFrame=new Kt,this._vertices=new Float32Array(4),this._texCoords=new Uint32Array(4),this._updateTexCoords=!0,this._updateVertices=!0,this._texture=t,this.resetTextureFrame()}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get vertices(){if(this._updateVertices){const{x:t,y:e,width:i,height:r}=this._textureFrame,s=i/2,n=r/2;this._vertices[0]=t-s,this._vertices[1]=e-n,this._vertices[2]=i-s,this._vertices[3]=r-n,this._updateVertices=!1}return this._vertices}get texCoords(){if(this._updateTexCoords){const{width:t,height:e}=this._texture,{left:i,top:r,right:s,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(r/e*65535&65535)<<16,h=s/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o),this._updateTexCoords=!1}return this._texCoords}get emitters(){return this._emitters}get affectors(){return this._affectors}get particles(){return this._particles}get graveyard(){return this._graveyard}setTexture(t){return this._texture!==t&&(this._texture=t,this.resetTextureFrame()),this}setTextureFrame(t){return this._textureFrame.copy(t),this._updateTexCoords=!0,this._updateVertices=!0,this.localBounds.set(0,0,t.width,t.height),this}resetTextureFrame(){return this.setTextureFrame(Kt.temp.set(0,0,this._texture.width,this._texture.height))}addEmitter(t){return this._emitters.push(t),this}clearEmitters(){for(const t of this._emitters)t.destroy();return this._emitters.length=0,this}addAffector(t){return this._affectors.push(t),this}clearAffectors(){for(const t of this._affectors)t.destroy();return this._affectors.length=0,this}requestParticle(){return this._graveyard.pop()||new Ne}emitParticle(t){return this._particles.push(t),this}updateParticle(t,e){const i=e.seconds;return t.elapsedLifetime.addTime(e),t.position.add(i*t.velocity.x,i*t.velocity.y),t.rotation+=i*t.rotationSpeed,this}clearParticles(){for(const t of this._particles)t.destroy();for(const t of this._graveyard)t.destroy();return this._particles.length=0,this._graveyard.length=0,this}update(t){const e=this._emitters,i=this._affectors,r=this._particles,s=this._graveyard,n=r.length;for(const i of e)i.apply(this,t);let o=0;for(let e=n-1;e>=0;e--)if(this.updateParticle(r[e],t),r[e].expired)s.push(r[e]),o++;else{o>0&&(r.splice(e+1,o),o=0);for(const s of i)s.apply(r[e],t)}return o>0&&r.splice(0,o),this}destroy(){super.destroy(),this.clearEmitters(),this.clearAffectors(),this.clearParticles(),this._textureFrame.destroy()}}class Ue{static get black(){return null===Ue._black&&(Ue._black=new Ue(Ee({fillStyle:"#000"}))),Ue._black}static get white(){return null===Ue._white&&(Ue._white=new Ue(Ee({fillStyle:"#fff"}))),Ue._white}constructor(t=null,e){this._version=0,this._source=null,this._size=new i(0,0),this._destroyListeners=new Set,this._premultiplyAlpha=!1,this._generateMipMap=!1,this._flipY=!1;const{scaleMode:r,wrapMode:s,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...Ue.defaultSamplerOptions,...e};this._scaleMode=r,this._wrapMode=s,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,null!==t&&this.setSource(t)}get source(){return this._source}set source(t){this.setSource(t)}get size(){return this._size}set size(t){this.setSize(t.width,t.height)}get width(){return this._size.width}set width(t){this.setSize(t,this.height)}get height(){return this._size.height}set height(t){this.setSize(this.width,t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return N(this.width)&&N(this.height)}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touch()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touch()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touch()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){const{width:t,height:e}=M(this._source);return this.setSize(t,e),this._touch(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}Ue._black=null,Ue._white=null,Ue.defaultSamplerOptions={scaleMode:t.ScaleModes.Linear,wrapMode:t.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1},Ue.empty=new Ue(null);class Ve{constructor(){this._renderers=new Map,this._runtime=null}registerRenderer(t,e){if(this._renderers.has(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),null!==this._runtime&&e.connect(this._runtime)}resolve(t){let e,i=t.constructor;for(;null!==i&&!e;)if(e=this._renderers.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No renderer registered for ${t.constructor.name}. Register one with registry.registerRenderer() before the first draw call.`);return e}connect(t){this._runtime=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._runtime=null}destroy(){this.disconnect();for(const t of this._renderers.values())"destroy"in t&&"function"==typeof t.destroy&&t.destroy();this._renderers.clear()}}const Oe=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0}),ze=t=>(t.frame++,t.submittedNodes=0,t.culledNodes=0,t.drawCalls=0,t.batches=0,t.renderPasses=0,t.renderTargetChanges=0,t.frameTimeMs=0,t),We=(t,e)=>{throw`${_e.glEnumToString(t)} was caused by call to: ${e}`},qe=(t,e)=>{((t,e)=>{console.log(`gl.${t}(${_e.glFunctionArgsToString(t,e)})`)})(t,e),((t,e)=>{for(const i of e)void 0===i&&console.error(`undefined passed to gl.${t}(${_e.glFunctionArgsToString(t,e)})`)})(t,e)};class He{constructor(e){this.backendType=t.RenderBackendType.WebGl2,this.rendererRegistry=new Ve,this._textureStates=new Map,this._renderTargetStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new re,this._maskPointB=new re,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._textureUnit=0,this._vao=null,this._clearColor=new z,this._boundFramebuffer=null,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:i,height:r,clearColor:s,webglAttributes:n,debug:o,spriteRendererBatchSize:a,particleRendererBatchSize:h,primitiveRendererBatchSize:l}=e.options;this._canvas=e.canvas;const u=this._createContext(n);if(!u)throw new Error("This browser or hardware does not support WebGL.");this._context=o?_e.makeDebugContext(u,We,qe,u):u,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),s&&this.clearColor.copy(s),this._rootRenderTarget=new se(i,r,!0),this._renderTarget=this._rootRenderTarget,this._cursor=this._canvas.style.cursor,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.registerRenderer(Ie,new Fe(a)),this.rendererRegistry.registerRenderer(Ge,new ke(h)),this.rendererRegistry.registerRenderer(ue,new Le(l)),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(t.BlendModes.Normal),this.resize(i,r)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get cursor(){return this._cursor}get stats(){return this._stats}async initialize(){return this}resetStats(){return ze(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget;return this._renderTarget!==e&&(this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,r=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(r),this._applyMaskState(),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this._applyMaskState(),this}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const r=this._temporaryRenderTextures[i];if(r.width===t&&r.height===e)return this._temporaryRenderTextures.splice(i,1),r}return new ne(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(t){return this._vao!==t&&(t&&t.bind(),this._vao&&this._vao.unbind(),this._vao=t),this}bindShader(t){return this._shader!==t&&(this._shader&&(this._shader.unbind(),this._shader=null),t&&t.bind(),this._shader=t),this}bindTexture(t,e){if(void 0!==e&&this._setTextureUnit(e),null===t)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(t);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=t,this}setBlendMode(e){if(e!==this._blendMode){const i=this._context;switch(this._blendMode=e,e){case t.BlendModes.Additive:i.blendFunc(i.ONE,i.ONE);break;case t.BlendModes.Subtract:i.blendFunc(i.ZERO,i.ONE_MINUS_SRC_COLOR);break;case t.BlendModes.Multiply:i.blendFunc(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA);break;case t.BlendModes.Screen:i.blendFunc(i.ONE,i.ONE_MINUS_SRC_COLOR);break;default:i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(t){if(this._textureUnit!==t){const e=this._context;this._textureUnit=t,e.activeTexture(e.TEXTURE0+t)}}setClearColor(t){if(!this._clearColor.equals(t)){const e=this._context;this._clearColor.copy(t),e.clearColor(t.r/255,t.g/255,t.b/255,t.a)}return this}setCursor(t){const e=t instanceof Ue?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${P(e)})`,this._canvas.style.cursor=this._cursor,this}clear(t){const e=this._context;return t&&this.setClearColor(t),this._bindRenderTarget(this._renderTarget),e.clear(e.COLOR_BUFFER_BIT),this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),this.setRenderTarget(null),this._setActiveRenderer(null),this.bindVertexArrayObject(null),this.bindShader(null),this.bindTexture(null),this.rendererRegistry.destroy(),this._clearColor.destroy(),this._destroyManagedResources(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy(),this._rootRenderTarget.destroy(),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null}_createContext(t){try{return this._canvas.getContext("webgl2",t)}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:r,a:s}=this._clearColor;t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.clearColor(e/255,i/255,r/255,s)}_addEvents(){this._canvas.addEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.addEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_removeEvents(){this._canvas.removeEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_onContextLost(){this._contextLost=!0,this._restoreContext()}_onContextRestored(){this._contextLost=!1}_createFramebuffer(){const t=this._context.createFramebuffer();if(null===t)throw new Error("Could not create framebuffer.");return t}_createTextureHandle(){const t=this._context.createTexture();if(null===t)throw new Error("Could not create texture.");return t}_destroyManagedResources(){for(const t of Array.from(this._renderTargetStates.keys()))this._evictRenderTarget(t,!1);for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t,!1)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(t){let e=this._renderTargetStates.get(t);return e||(this._subscribeToDestroy(t,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(t,!0)}),e={framebuffer:t.root?null:this._createFramebuffer(),version:-1,attachedTexture:null},this._renderTargetStates.set(t,e)),e}_getTextureState(t){let e=this._textureStates.get(t);return e||(this._subscribeToDestroy(t,this._textureDestroyHandlers,()=>{this._evictTexture(t,!0)}),e={handle:this._createTextureHandle(),version:-1,width:0,height:0},this._textureStates.set(t,e)),e}_subscribeToDestroy(t,e,i){e.has(t)||(t.addDestroyListener(i),e.set(t,i))}_unsubscribeFromDestroy(t,e){const i=e.get(t);i&&(t.removeDestroyListener(i),e.delete(t))}_evictRenderTarget(t,e){const i=this._renderTargetStates.get(t);this._unsubscribeFromDestroy(t,this._renderTargetDestroyHandlers),t instanceof ne&&this._evictTexture(t,!1),i&&(this._boundFramebuffer===i.framebuffer&&(this._context.bindFramebuffer(this._context.FRAMEBUFFER,null),this._boundFramebuffer=null),null!==i.framebuffer&&this._context.deleteFramebuffer(i.framebuffer),this._renderTargetStates.delete(t)),this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget,e&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(t,e){const i=this._textureStates.get(t);this._unsubscribeFromDestroy(t,this._textureDestroyHandlers),i&&(this._texture===t&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this._context.deleteTexture(i.handle),this._textureStates.delete(t)),this._texture===t&&(this._texture=null),e&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(t){const e=this._prepareRenderTarget(t);if(this._boundFramebuffer!==e.framebuffer||e.version!==t.version){const i=this._context,{x:r,y:s,width:n,height:o}=t.getViewport();i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(r,s,n,o),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._maskPixelStack.length>0&&this._applyMaskState()}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(t){const e=this._getRenderTargetState(t);if(t instanceof ne&&e.framebuffer){const i=this._boundFramebuffer,r=this._syncTexture(t);if(e.attachedTexture!==r.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=r.handle}}return e}_syncTexture(t){const e=this._context,i=this._getTextureState(t),r=t instanceof ne?t.textureVersion:t.version;return e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==r&&(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t.wrapMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t.wrapMode),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),t instanceof ne?-1===i.version||i.width!==t.width||i.height!==t.height||null===t.source?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.width,t.height,0,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source):t.source&&(-1===i.version||i.width!==t.width||i.height!==t.height?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source)),t.generateMipMap&&(t instanceof ne||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=r,i.width=t.width,i.height=t.height),i}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),r=Math.min(e.x,i.x),s=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(r))),u=Math.max(0,Math.min(a,Math.ceil(s))),d=Math.max(0,Math.min(h,Math.floor(n))),c=Math.max(0,Math.min(h,Math.ceil(o))),p=Math.max(0,u-l),_=Math.max(0,c-d);return{x:l,y:Math.max(0,h-c),width:p,height:_}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),r=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:r,width:Math.max(0,s-i),height:Math.max(0,n-r)}}_applyMaskState(){const t=this._context;if(0===this._maskPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=this._maskPixelStack[this._maskPixelStack.length-1];t.enable(t.SCISSOR_TEST),t.scissor(e.x,e.y,e.width,e.height)}}class Xe{constructor(){this.backendType=t.RenderBackendType.WebGpu,this._runtime=null}connect(e){if(null===this._runtime){if(e.backendType!==t.RenderBackendType.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU runtime, but received backendType ${String(e.backendType)}.`);this._runtime=e,this.onConnect(e)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}function je(e){switch(e){case t.BlendModes.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case t.BlendModes.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case t.BlendModes.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case t.BlendModes.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}class Ye extends Xe{constructor(){super(...arguments),this._combinedTransform=new J,this._drawCalls=[],this._drawCallCount=0,this._transformData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT),this._pipelines=new Map,this._renderManager=null,this._device=null,this._shaderModule=null,this._bindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._bindGroup=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._generatedIndexData=new Uint16Array(0),this._sequentialIndexData=new Uint16Array(0)}render(e){const i=this._renderManager;if(null===i)throw new Error("Renderer not connected");if(e.drawMode!==t.RenderingPrimitives.Points&&e.drawMode!==t.RenderingPrimitives.Lines&&e.drawMode!==t.RenderingPrimitives.LineLoop&&e.drawMode!==t.RenderingPrimitives.LineStrip&&e.drawMode!==t.RenderingPrimitives.Triangles&&e.drawMode!==t.RenderingPrimitives.TriangleFan&&e.drawMode!==t.RenderingPrimitives.TriangleStrip)throw new Error(`WebGPU primitive renderer does not support draw mode "${e.drawMode}" yet.`);if(i.setBlendMode(e.blendMode),0===e.geometry.vertices.length)return;const r=this._drawCallCount++,s=this._drawCalls[r];s?(s.shape=e,s.blendMode=e.blendMode):this._drawCalls.push({shape:e,blendMode:e.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._bindGroup,r=this._uniformBuffer;if(!(t&&e&&i&&r))return;if(0===this._drawCallCount&&!t.clearRequested)return;const s=e.createCommandEncoder(),n=s.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const o=t.getScissorRect(),a=null!==o&&(o.width<=0||o.height<=0);if(null===o||a||n.setScissorRect(o.x,o.y,o.width,o.height),!a)for(let s=0;s<this._drawCallCount;s++){const o=this._drawCalls[s],a=o.shape,h=a.geometry.vertices,l=this._resolveDrawCall(a);if(null===l)continue;const u=this._getPipeline({topology:l.topology,usesStripIndex:l.usesStripIndex,blendMode:o.blendMode,format:t.renderTargetFormat});this._ensureVertexCapacity(l.vertexCount),this._writeVertexData(h,a.color.toRgba()),this._writeTransformData(t,a),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,12*l.vertexCount),e.queue.writeBuffer(r,0,this._transformData.buffer,this._transformData.byteOffset,this._transformData.byteLength),n.setPipeline(u),n.setBindGroup(0,i),n.setVertexBuffer(0,this._vertexBuffer),null!==l.indices&&l.indexCount>0?(this._ensureIndexCapacity(l.indexCount),e.queue.writeBuffer(this._indexBuffer,0,l.indices.buffer,l.indices.byteOffset,l.indexCount*Uint16Array.BYTES_PER_ELEMENT),n.setIndexBuffer(this._indexBuffer,"uint16"),n.drawIndexed(l.indexCount)):n.draw(l.vertexCount),t.stats.batches++,t.stats.drawCalls++}n.end(),t.submit(s.finish()),this._drawCallCount=0}destroy(){this.disconnect(),this._combinedTransform.destroy()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct TransformUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: TransformUniforms;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = uniforms.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return input.color;\n}\n"}),this._bindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=this._device.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]})}onDisconnect(){this.flush(),this._destroyBuffers(),this._pipelines.clear(),this._uniformBuffer?.destroy(),this._uniformBuffer=null,this._bindGroup=null,this._bindGroupLayout=null,this._pipelineLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._drawCallCount=0}_writeTransformData(t,e){const i=this._combinedTransform.copy(t.view.getTransform()).combine(e.getGlobalTransform());this._transformData.set([i.a,i.c,0,0,i.b,i.d,0,0,0,0,1,0,i.x,i.y,0,i.z])}_writeVertexData(t,e){const i=t.length/2;for(let r=0;r<i;r++){const i=2*r,s=3*r;this._float32View[s]=t[i],this._float32View[s+1]=t[i+1],this._uint32View[s+2]=e}}_ensureVertexCapacity(t){const e=12*t;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?12:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(t),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,0===this._vertexBufferCapacity?12:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(t){const e=t*Uint16Array.BYTES_PER_ELEMENT;e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?Uint16Array.BYTES_PER_ELEMENT:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_getPipeline(t){const e=`${t.topology}:${t.usesStripIndex?1:0}:${t.blendMode}:${t.format}`,i=this._pipelines.get(e);if(i)return i;const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t.format,blend:je(t.blendMode),writeMask:GPUColorWrite.ALL}]},primitive:{topology:t.topology,stripIndexFormat:t.usesStripIndex?"uint16":void 0}});return this._pipelines.set(e,r),r}_getTopology(e){switch(e){case t.RenderingPrimitives.Points:return"point-list";case t.RenderingPrimitives.Lines:return"line-list";case t.RenderingPrimitives.LineLoop:case t.RenderingPrimitives.LineStrip:return"line-strip";case t.RenderingPrimitives.Triangles:case t.RenderingPrimitives.TriangleFan:return"triangle-list";case t.RenderingPrimitives.TriangleStrip:return"triangle-strip";default:throw new Error(`WebGPU primitive renderer does not support draw mode "${e}" yet.`)}}_resolveDrawCall(e){const i=e.geometry.vertices.length/2;if(0===i)return null;switch(e.drawMode){case t.RenderingPrimitives.LineLoop:return this._resolveLineLoopDrawCall(e.geometry.indices,i);case t.RenderingPrimitives.TriangleFan:return this._resolveTriangleFanDrawCall(e.geometry.indices,i);default:{const r=e.geometry.indices,s=this._getTopology(e.drawMode),n=r.length,o=n>0&&(e.drawMode===t.RenderingPrimitives.LineStrip||e.drawMode===t.RenderingPrimitives.TriangleStrip);return n>0?{topology:s,usesStripIndex:o,vertexCount:i,indices:r,indexCount:n}:{topology:s,usesStripIndex:o,vertexCount:i,indices:null,indexCount:0}}}}_resolveLineLoopDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),r=i.length;if(r<2)return null;const s=r+1,n=this._ensureGeneratedIndexCapacity(s);return n.set(i.subarray(0,r),0),n[r]=i[0],{topology:"line-strip",usesStripIndex:!0,vertexCount:e,indices:n,indexCount:s}}_resolveTriangleFanDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),r=i.length;if(r<3)return null;const s=3*(r-2),n=this._ensureGeneratedIndexCapacity(s);let o=0;for(let t=1;t<r-1;t++)n[o++]=i[0],n[o++]=i[t],n[o++]=i[t+1];return{topology:"triangle-list",usesStripIndex:!1,vertexCount:e,indices:n,indexCount:s}}_getSequentialIndices(t){if(t>this._sequentialIndexData.length){let e=Math.max(1,this._sequentialIndexData.length);for(;e<t;)e*=2;this._sequentialIndexData=new Uint16Array(e)}for(let e=0;e<t;e++)this._sequentialIndexData[e]=e;return this._sequentialIndexData.subarray(0,t)}_ensureGeneratedIndexCapacity(t){if(t>this._generatedIndexData.length){let e=Math.max(1,this._generatedIndexData.length);for(;e<t;)e*=2;this._generatedIndexData=new Uint16Array(e)}return this._generatedIndexData.subarray(0,t)}_destroyBuffers(){this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0}}const $e=28/Uint32Array.BYTES_PER_ELEMENT;class Ke extends Xe{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._pipelines=new Map}onConnect(t){this._renderManager||(this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar spriteTexture0: texture_2d<f32>;\n@group(1) @binding(1)\nvar spriteTexture1: texture_2d<f32>;\n@group(1) @binding(2)\nvar spriteTexture2: texture_2d<f32>;\n@group(1) @binding(3)\nvar spriteTexture3: texture_2d<f32>;\n@group(1) @binding(4)\nvar spriteTexture4: texture_2d<f32>;\n@group(1) @binding(5)\nvar spriteTexture5: texture_2d<f32>;\n@group(1) @binding(6)\nvar spriteTexture6: texture_2d<f32>;\n@group(1) @binding(7)\nvar spriteTexture7: texture_2d<f32>;\n\n@group(1) @binding(8)\nvar spriteSampler0: sampler;\n@group(1) @binding(9)\nvar spriteSampler1: sampler;\n@group(1) @binding(10)\nvar spriteSampler2: sampler;\n@group(1) @binding(11)\nvar spriteSampler3: sampler;\n@group(1) @binding(12)\nvar spriteSampler4: sampler;\n@group(1) @binding(13)\nvar spriteSampler5: sampler;\n@group(1) @binding(14)\nvar spriteSampler6: sampler;\n@group(1) @binding(15)\nvar spriteSampler7: sampler;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(3) premultiplySample: u32,\n @location(4) textureSlot: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.premultiplySample = input.premultiplySample;\n output.textureSlot = input.textureSlot;\n\n return output;\n}\n\nfn sampleTexture(slot: u32, uv: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSample(spriteTexture0, spriteSampler0, uv);\n }\n case 1u: {\n return textureSample(spriteTexture1, spriteSampler1, uv);\n }\n case 2u: {\n return textureSample(spriteTexture2, spriteSampler2, uv);\n }\n case 3u: {\n return textureSample(spriteTexture3, spriteSampler3, uv);\n }\n case 4u: {\n return textureSample(spriteTexture4, spriteSampler4, uv);\n }\n case 5u: {\n return textureSample(spriteTexture5, spriteSampler5, uv);\n }\n case 6u: {\n return textureSample(spriteTexture6, spriteSampler6, uv);\n }\n default: {\n return textureSample(spriteTexture7, spriteSampler7, uv);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = sampleTexture(input.textureSlot, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n\n return resolvedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[...Array.from({length:8},(t,e)=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(t,e)=>({binding:8+e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}))]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._ensureBatchCapacity(32))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._drawCallCount=0}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof Ue)&&!(i instanceof ne)||0===i.width||0===i.height||i instanceof Ue&&null===i.source)return;e.setBlendMode(t.blendMode);const r=this._drawCallCount++,s=this._drawCalls[r];s?(s.sprite=t,s.texture=i,s.color=t.tint.toRgba(),s.blendMode=t.blendMode):this._drawCalls.push({sprite:t,texture:i,color:t.tint.toRgba(),blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,r=this._uniformBindGroup,s=this._vertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&r&&s&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=t.view.getTransform();this._projectionData.set([o.a,o.c,0,0,o.b,o.d,0,0,0,0,1,0,o.x,o.y,0,o.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const a=e.createCommandEncoder(),h=a.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const l=t.getScissorRect(),u=null!==l&&(l.width<=0||l.height<=0);if(null===l||u||h.setScissorRect(l.x,l.y,l.width,l.height),this._drawCallCount>0&&!u){h.setBindGroup(0,r),h.setVertexBuffer(0,this._vertexBuffer),h.setIndexBuffer(this._indexBuffer,"uint32");for(let i=0;i<this._drawCallCount;){const r=this._getBatchRange(i),s=this._getPipeline(r.blendMode,t.renderTargetFormat),n=r.end-r.start;this._ensureBatchCapacity(n),this._writeBatchVertexData(r),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,4*n*28);const o=this._createTextureBindGroup(e,t,r.textures);h.setPipeline(s),h.setBindGroup(1,o),h.drawIndexed(6*r.spriteCount,1,0,0,0),t.stats.batches++,t.stats.drawCalls++,i=r.end}}h.end(),t.submit(a.finish()),this._drawCallCount=0}destroy(){this.disconnect()}_ensureBatchCapacity(t){if(!this._device||t<=this._vertexCapacity)return;let e=Math.max(this._vertexCapacity,32);for(;e<t;)e*=2;const i=new ArrayBuffer(4*e*28),r=this._device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),s=new Uint32Array(6*e),n=this._device.createBuffer({size:s.byteLength*Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});for(let t=0;t<e;t++){const e=4*t,i=6*t;s[i]=e,s[i+1]=e+1,s[i+2]=e+2,s[i+3]=e,s[i+4]=e+2,s[i+5]=e+3}this._device.queue.writeBuffer(n,0,s.buffer,s.byteOffset,s.byteLength),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexCapacity=e,this._vertexData=i,this._float32View=new Float32Array(i),this._uint32View=new Uint32Array(i),this._vertexBuffer=r,this._indexBuffer=n}_writeBatchVertexData(t){const e=this._renderManager;if(!e)return;let i=0;for(let r=t.start;r<t.end;r++){const s=this._drawCalls[r],n=t.textureSlots.get(s.texture)??0,o=e.shouldPremultiplyTextureSample(s.texture)?1:0,a=s.sprite.vertices,h=s.sprite.texCoords;for(let t=0;t<4;t++){const e=2*t,r=h[t];this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._float32View[i+2]=(65535&r)/65535,this._float32View[i+3]=(r>>>16&65535)/65535,this._uint32View[i+4]=s.color,this._uint32View[i+5]=o,this._uint32View[i+6]=n,i+=$e}}}_getBatchRange(t){const e=this._drawCalls[t],i=new Map,r=new Array;let s=t+1;for(i.set(e.texture,0),r.push(e.texture);s<this._drawCallCount;){const t=this._drawCalls[s];if(t.blendMode!==e.blendMode)break;if(!i.has(t.texture)){if(r.length>=8)break;i.set(t.texture,r.length),r.push(t.texture)}if(i.size>8)break;s++}return{start:t,end:s,spriteCount:s-t,blendMode:e.blendMode,textures:r,textureSlots:i}}_createTextureBindGroup(t,e,i){const r=i[0],s=e.getTextureBinding(r),n=[],o=new Array(8);for(let t=0;t<8;t++){const n=i[t]??r,a=n===r?s:e.getTextureBinding(n);o[t]=a}for(let t=0;t<8;t++)n.push({binding:t,resource:o[t].view});for(let t=0;t<8;t++)n.push({binding:8+t,resource:o[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:n})}_getPipeline(t,e){const i=`${t}:${e}`,r=this._pipelines.get(i);if(r)return r;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._renderManager))throw new Error("Renderer has to be connected first!");const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:24,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:je(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const Qe=56,Ze=new Float32Array([0,0,1,0,1,1,0,1]),Je=new Uint16Array([0,1,2,0,2,3]);class ti extends Xe{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._uniformData=new Float32Array(144/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._indexBuffer=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._pipelines=new Map}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof Ue)||null===i.source||0===i.width||0===i.height||0===t.particles.length)return;e.setBlendMode(t.blendMode);const r=this._drawCallCount++,s=this._drawCalls[r];s?(s.system=t,s.texture=i,s.blendMode=t.blendMode):this._drawCalls.push({system:t,texture:i,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,r=this._uniformBindGroup,s=this._staticVertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&r&&s&&this._instanceBuffer&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=e.createCommandEncoder(),a=o.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const h=t.getScissorRect(),l=null!==h&&(h.width<=0||h.height<=0);if(null===h||l||a.setScissorRect(h.x,h.y,h.width,h.height),!l){a.setBindGroup(0,r);for(let r=0;r<this._drawCallCount;r++){const o=this._drawCalls[r],h=o.system,l=h.particles.length;if(0===l)continue;const u=this._getPipeline(o.blendMode,t.renderTargetFormat),d=t.getTextureBinding(o.texture),c=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:d.view},{binding:1,resource:d.sampler}]});this._ensureCapacity(l),this._writeInstanceData(h.vertices,h.texCoords,h.particles),this._writeUniformData(t,h,o.texture),e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,l*Qe),e.queue.writeBuffer(i,0,this._uniformData.buffer,this._uniformData.byteOffset,this._uniformData.byteLength),a.setPipeline(u),a.setBindGroup(1,c),a.setVertexBuffer(0,s),a.setVertexBuffer(1,this._instanceBuffer),a.setIndexBuffer(n,"uint16"),a.drawIndexed(6,l,0,0,0),t.stats.batches++,t.stats.drawCalls++}}a.end(),t.submit(o.finish()),this._drawCallCount=0}destroy(){this.disconnect()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n projection: mat4x4<f32>,\n translation: mat4x4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar particleTexture: texture_2d<f32>;\n\n@group(1) @binding(1)\nvar particleSampler: sampler;\n\nstruct VertexInput {\n @location(0) unitPosition: vec2<f32>,\n @location(1) quadMin: vec2<f32>,\n @location(2) quadSize: vec2<f32>,\n @location(3) uvMin: vec2<f32>,\n @location(4) uvMax: vec2<f32>,\n @location(5) translation: vec2<f32>,\n @location(6) scale: vec2<f32>,\n @location(7) rotation: f32,\n @location(8) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let localPosition = input.quadMin + (input.unitPosition * input.quadSize);\n let radians = radians(input.rotation);\n let sinValue = sin(radians);\n let cosValue = cos(radians);\n let rotated = vec2<f32>(\n (localPosition.x * (input.scale.x * cosValue)) + (localPosition.y * (input.scale.y * sinValue)) + input.translation.x,\n (localPosition.x * (input.scale.x * -sinValue)) + (localPosition.y * (input.scale.y * cosValue)) + input.translation.y\n );\n\n var output: VertexOutput;\n\n output.position = uniforms.projection * uniforms.translation * vec4<f32>(rotated, 0.0, 1.0);\n output.texcoord = input.uvMin + ((input.uvMax - input.uvMin) * input.unitPosition);\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(particleTexture, particleSampler, input.texcoord);\n let premultipliedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), uniforms.flags.x > 0.5);\n\n return premultipliedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:144,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._staticVertexBuffer=this._device.createBuffer({size:Ze.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._staticVertexBuffer,0,Ze.buffer,Ze.byteOffset,Ze.byteLength),this._indexBuffer=this._device.createBuffer({size:Je.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Je.buffer,Je.byteOffset,Je.byteLength),this._ensureCapacity(1)}onDisconnect(){this.flush(),this._staticVertexBuffer?.destroy(),this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._indexBuffer=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._drawCallCount=0}_ensureCapacity(t){const e=t*Qe;if(e>this._instanceData.byteLength){let t=this._instanceData.byteLength;for(;t<e;)t*=2;this._instanceData=new ArrayBuffer(t),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData)}if(e>this._instanceBufferByteLength){let t=this._instanceBufferByteLength||Qe;for(;t<e;)t*=2;this._instanceBuffer?.destroy(),this._instanceBuffer=this._device.createBuffer({size:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._instanceBufferByteLength=t}}_writeUniformData(t,e,i){const r=t.view.getTransform().toArray(!1),s=e.getGlobalTransform().toArray(!1),n=t.shouldPremultiplyTextureSample(i);this._uniformData.set([r[0],r[1],0,0,r[3],r[4],0,0,0,0,1,0,r[6],r[7],0,r[8],s[0],s[1],0,0,s[3],s[4],0,0,0,0,1,0,s[6],s[7],0,s[8],n?1:0,0,0,0])}_writeInstanceData(t,e,i){const r=t[0],s=t[1],n=t[2]-t[0],o=t[3]-t[1],a=(65535&e[0])/65535,h=(e[0]>>>16&65535)/65535,l=(65535&e[2])/65535,u=(e[2]>>>16&65535)/65535;for(let t=0;t<i.length;t++){const e=i[t],d=14*t;this._float32View[d]=r,this._float32View[d+1]=s,this._float32View[d+2]=n,this._float32View[d+3]=o,this._float32View[d+4]=a,this._float32View[d+5]=h,this._float32View[d+6]=l,this._float32View[d+7]=u,this._float32View[d+8]=e.position.x,this._float32View[d+9]=e.position.y,this._float32View[d+10]=e.scale.x,this._float32View[d+11]=e.scale.y,this._float32View[d+12]=e.rotation,this._uint32View[d+13]=e.tint.toRgba()}}_getPipeline(t,e){const i=`${t}:${e}`,r=this._pipelines.get(i);if(r)return r;const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:Qe,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x2"},{shaderLocation:2,offset:8,format:"float32x2"},{shaderLocation:3,offset:16,format:"float32x2"},{shaderLocation:4,offset:24,format:"float32x2"},{shaderLocation:5,offset:32,format:"float32x2"},{shaderLocation:6,offset:40,format:"float32x2"},{shaderLocation:7,offset:48,format:"float32"},{shaderLocation:8,offset:52,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:je(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const ei="rgba8unorm";class ii{constructor(e){this.backendType=t.RenderBackendType.WebGpu,this.rendererRegistry=new Ve,this._clearColor=new z,this._textureStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new re,this._maskPointB=new re,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._renderer=null,this._blendMode=null,this._texture=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:i,height:r,clearColor:s}=e.options;this._canvas=e.canvas,this._rootRenderTarget=new se(i,r,!0),this._renderTarget=this._rootRenderTarget,s&&this._clearColor.copy(s),this.rendererRegistry.registerRenderer(ue,new Ye),this.rendererRegistry.registerRenderer(Ie,new Ke),this.rendererRegistry.registerRenderer(Ge,new ti),this.resize(i,r)}get view(){return this._renderTarget.view}get renderTarget(){return this._renderTarget}get device(){if(null===this._device)throw new Error("WebGPU device is not initialized yet.");return this._device}get context(){if(null===this._context)throw new Error("WebGPU canvas context is not initialized yet.");return this._context}get format(){if(null===this._format)throw new Error("WebGPU canvas format is not initialized yet.");return this._format}get renderTargetFormat(){return this._renderTarget===this._rootRenderTarget?this.format:ei}get clearRequested(){return this._clearRequested}get stats(){return this._stats}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return ze(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setShader(t){if(null!==t)throw new Error("WebGPU shaders are not implemented yet.");return this}setTexture(t,e){if(null===t)return this._texture=null,this;if(t instanceof se&&!(t instanceof ne))throw new Error("WebGPU render textures are not implemented yet.");return this._syncTexture(t),this._texture=t,this}setBlendMode(e){if(null===e)return this._blendMode=null,this;if(e!==t.BlendModes.Normal&&e!==t.BlendModes.Additive&&e!==t.BlendModes.Subtract&&e!==t.BlendModes.Multiply&&e!==t.BlendModes.Screen)throw new Error(`WebGPU blend mode "${e}" is not implemented yet.`);return this._blendMode=e,this}setVao(t){if(null!==t)throw new Error("WebGPU vertex array objects are not implemented yet.");return this}setRenderTarget(t){const e=t??this._rootRenderTarget;if(!(e.root||e instanceof ne))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");return this._renderTarget!==e&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=e,this._stats.renderTargetChanges++,e!==this._rootRenderTarget&&this._subscribeRenderTarget(e)),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,r=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(r),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this}getScissorRect(){if(0===this._maskPixelStack.length)return null;const t=this._maskPixelStack[this._maskPixelStack.length-1];return{x:t.x,y:t.y,width:t.width,height:t.height}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const r=this._temporaryRenderTextures[i];if(r.width===t&&r.height===e)return this._temporaryRenderTextures.splice(i,1),r}return new ne(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this}clear(t){return t&&this._clearColor.copy(t),this._clearRequested=!0,this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._hasPresentedFrame=!1,this}flush(){if(!this._device||!this._context)return this;if(this._renderer)this._flushActiveRenderer();else if(this._clearRequested){const t=this._device.createCommandEncoder();t.beginRenderPass({colorAttachments:[this.createColorAttachment()]}).end(),this._stats.renderPasses++,this.submit(t.finish())}return this}destroy(){this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy();for(const t of Array.from(this._renderTargetDestroyHandlers.keys()))this._unsubscribeRenderTarget(t);this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._texture=null,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._renderTarget=this._rootRenderTarget,this._clearColor.destroy(),this._rootRenderTarget.destroy()}createColorAttachment(){const t=this._renderTarget;let e=null;if(t===this._rootRenderTarget)e={view:this.context.getCurrentTexture().createView(),shouldClear:this._clearRequested||!this._hasPresentedFrame};else{if(!(t instanceof ne))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");{const i=this._syncTexture(t);e={view:i.view,shouldClear:this._clearRequested||!i.hasContent}}}return this._clearRequested=!1,{view:e.view,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:e.shouldClear?"clear":"load",storeOp:"store"}}submit(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof ne){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}shouldPremultiplyTextureSample(t){return!(t instanceof ne)&&t.premultiplyAlpha}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}async _initialize(){const e=this._getGpuNavigator();if(null===e)throw new Error("This browser does not support WebGPU.");if("function"!=typeof e.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof e.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");const i=this._canvas.getContext("webgpu");if(null===i)throw new Error("Could not create WebGPU canvas context.");let r=null;try{r=await e.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===r)throw new Error("Could not acquire a WebGPU adapter.");if("function"!=typeof r.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");let s=null;try{s=await r.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}if(null===s)throw new Error("Could not acquire a WebGPU device.");const n=e.gpu.getPreferredCanvasFormat();try{i.configure({device:s,format:n,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}return this._context=i,this._device=s,this._format=n,this._blendMode=t.BlendModes.Normal,this._hasPresentedFrame=!1,this.rendererRegistry.connect(this),this.resize(this._canvas.width,this._canvas.height),this}_getGpuNavigator(){const t=navigator;return t.gpu?t:null}_createInitializationError(t,e){return e instanceof Error&&e.message.length>0?new Error(`${t} ${e.message}`):new Error(t)}_destroyManagedTextures(){for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getTextureState(t){let e=this._textureStates.get(t);if(!e){const i=this.device.createTexture({size:{width:Math.max(t.width,1),height:Math.max(t.height,1)},format:ei,mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)});e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:this._getMipLevelCount(t),hasContent:!1};const r=()=>{this._evictTexture(t)};t.addDestroyListener(r),this._textureDestroyHandlers.set(t,r),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof ne||null!==t.source&&0!==t.width&&0!==t.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const e=this._getTextureState(t),i=t instanceof ne?t.textureVersion:t.version,r=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==r){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:ei,mipLevelCount:r,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=r,e.hasContent=!1}if(e.sampler=this._createSampler(t),!(t instanceof ne)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}e.version=i}return e}_evictTexture(t){const e=this._textureStates.get(t),i=this._textureDestroyHandlers.get(t);i&&(t.removeDestroyListener(i),this._textureDestroyHandlers.delete(t)),e&&(e.texture.destroy(),this._textureStates.delete(t)),this._texture===t&&(this._texture=null)}_subscribeRenderTarget(t){if(!this._renderTargetDestroyHandlers.has(t)){const e=()=>{this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget),this._renderTargetDestroyHandlers.delete(t)};t.addDestroyListener(e),this._renderTargetDestroyHandlers.set(t,e)}}_unsubscribeRenderTarget(t){const e=this._renderTargetDestroyHandlers.get(t);e&&(t.removeDestroyListener(e),this._renderTargetDestroyHandlers.delete(t))}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),r=Math.min(e.x,i.x),s=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(r))),u=Math.max(0,Math.min(a,Math.ceil(s))),d=Math.max(0,Math.min(h,Math.floor(n))),c=Math.max(0,Math.min(h,Math.ceil(o)));return{x:l,y:d,width:Math.max(0,u-l),height:Math.max(0,c-d)}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),r=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:r,width:Math.max(0,s-i),height:Math.max(0,n-r)}}_createSampler(t){return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:this._getFilterMode(t.scaleMode),minFilter:this._getFilterMode(t.scaleMode),mipmapFilter:this._getMipmapFilterMode(t.scaleMode)})}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof ne?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(e){switch(e){case t.WrapModes.Repeat:return"repeat";case t.WrapModes.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(e){switch(e){case t.ScaleModes.Nearest:case t.ScaleModes.NearestMipmapNearest:case t.ScaleModes.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(e){switch(e){case t.ScaleModes.NearestMipmapLinear:case t.ScaleModes.LinearMipmapLinear:return"linear";default:return"nearest"}}_getMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_generateMipmaps(t,e){if(e<=1)return;const i=this._getMipmapResources(),r=this.device.createCommandEncoder();for(let s=1;s<e;s++){const e=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:t.createView({baseMipLevel:s-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),n=r.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:s,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});n.setPipeline(i.pipeline),n.setBindGroup(0,e),n.draw(3),n.end()}this.device.queue.submit([r.finish()])}_getMipmapResources(){return null!==this._mipmapShaderModule&&null!==this._mipmapBindGroupLayout&&null!==this._mipmapPipelineLayout&&null!==this._mipmapPipeline&&null!==this._mipmapSampler||(this._mipmapShaderModule=this.device.createShaderModule({code:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@group(0) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(0) @binding(1)\nvar sourceSampler: sampler;\n\n@vertex\nfn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0)\n );\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 0.0),\n vec2<f32>(2.0, 0.0),\n vec2<f32>(0.0, 2.0)\n );\n var output: VertexOutput;\n\n output.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);\n output.texcoord = texcoords[vertexIndex];\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(sourceTexture, sourceSampler, input.texcoord);\n}\n"}),this._mipmapBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._mipmapPipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:[this._mipmapBindGroupLayout]}),this._mipmapPipeline=this.device.createRenderPipeline({layout:this._mipmapPipelineLayout,vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:ei,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}}),this._mipmapSampler=this.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"nearest"})),{bindGroupLayout:this._mipmapBindGroupLayout,pipeline:this._mipmapPipeline,sampler:this._mipmapSampler}}}var ri,si,ni,oi,ai,hi;t.ChannelSize=void 0,(ri=t.ChannelSize||(t.ChannelSize={}))[ri.Container=768]="Container",ri[ri.Category=256]="Category",ri[ri.Gamepad=64]="Gamepad",t.Keyboard=void 0,(si=t.Keyboard||(t.Keyboard={}))[si.Backspace=8]="Backspace",si[si.Tab=9]="Tab",si[si.Clear=12]="Clear",si[si.Enter=13]="Enter",si[si.Shift=16]="Shift",si[si.Control=17]="Control",si[si.Alt=18]="Alt",si[si.Pause=19]="Pause",si[si.CapsLock=20]="CapsLock",si[si.Escape=27]="Escape",si[si.Space=32]="Space",si[si.PageUp=33]="PageUp",si[si.PageDown=34]="PageDown",si[si.End=35]="End",si[si.Home=36]="Home",si[si.Left=37]="Left",si[si.Up=38]="Up",si[si.Right=39]="Right",si[si.Down=40]="Down",si[si.Insert=45]="Insert",si[si.Delete=46]="Delete",si[si.Help=47]="Help",si[si.Zero=48]="Zero",si[si.One=49]="One",si[si.Two=50]="Two",si[si.Three=51]="Three",si[si.Four=52]="Four",si[si.Five=53]="Five",si[si.Six=54]="Six",si[si.Seven=55]="Seven",si[si.Eight=56]="Eight",si[si.Nine=57]="Nine",si[si.A=65]="A",si[si.B=66]="B",si[si.C=67]="C",si[si.D=68]="D",si[si.E=69]="E",si[si.F=70]="F",si[si.G=71]="G",si[si.H=72]="H",si[si.I=73]="I",si[si.J=74]="J",si[si.K=75]="K",si[si.L=76]="L",si[si.M=77]="M",si[si.N=78]="N",si[si.O=79]="O",si[si.P=80]="P",si[si.Q=81]="Q",si[si.R=82]="R",si[si.S=83]="S",si[si.T=84]="T",si[si.U=85]="U",si[si.V=86]="V",si[si.W=87]="W",si[si.X=88]="X",si[si.Y=89]="Y",si[si.Z=90]="Z",si[si.NumPad0=96]="NumPad0",si[si.NumPad1=97]="NumPad1",si[si.NumPad2=98]="NumPad2",si[si.NumPad3=99]="NumPad3",si[si.NumPad4=100]="NumPad4",si[si.NumPad5=101]="NumPad5",si[si.NumPad6=102]="NumPad6",si[si.NumPad7=103]="NumPad7",si[si.NumPad8=104]="NumPad8",si[si.NumPad9=105]="NumPad9",si[si.NumPadMultiply=106]="NumPadMultiply",si[si.NumPadAdd=107]="NumPadAdd",si[si.NumPadEnter=108]="NumPadEnter",si[si.NumPadSubtract=109]="NumPadSubtract",si[si.NumPadDecimal=110]="NumPadDecimal",si[si.NumPadDivide=111]="NumPadDivide",si[si.F1=112]="F1",si[si.F2=113]="F2",si[si.F3=114]="F3",si[si.F4=115]="F4",si[si.F5=116]="F5",si[si.F6=117]="F6",si[si.F7=118]="F7",si[si.F8=119]="F8",si[si.F9=120]="F9",si[si.F10=121]="F10",si[si.F11=122]="F11",si[si.F12=123]="F12",si[si.NumLock=144]="NumLock",si[si.ScrollLock=145]="ScrollLock",si[si.Colon=186]="Colon",si[si.Equals=187]="Equals",si[si.Comma=188]="Comma",si[si.Dash=189]="Dash",si[si.Period=190]="Period",si[si.QuestionMark=191]="QuestionMark",si[si.Tilde=192]="Tilde",si[si.OpenBracket=219]="OpenBracket",si[si.BackwardSlash=220]="BackwardSlash",si[si.ClosedBracket=221]="ClosedBracket",si[si.Quotes=222]="Quotes";class li{constructor(e,i,r){this.onConnect=new E,this.onDisconnect=new E,this.onUpdate=new E,this.browserGamepad=null,this.info={name:"Generic Gamepad",label:"Generic Gamepad",vendorId:null,productId:null,productKey:null};const s="number"!=typeof e,n=s?e:null,o=s?e.index:e;if(this.indexValue=o,this.channelsValue=i,this.channelOffset=512+o*t.ChannelSize.Gamepad,this.mappingValue=n?r.mapping:r,n){const t=r;this.setInfo({name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey}),this.connect(n)}}get mapping(){return this.mappingValue}set mapping(t){this.mappingValue=t}get mappingFamily(){return this.mappingValue.family}get channels(){return this.channelsValue}get gamepad(){return this.browserGamepad}get index(){return this.indexValue}get connected(){return null!==this.browserGamepad}get name(){return this.info.name}get label(){return this.info.label}get vendorId(){return this.info.vendorId}get productId(){return this.info.productId}get productKey(){return this.info.productKey}setInfo(t){return this.info=t,this}connect(t){const e=this.connected;return this.browserGamepad=t,e||this.onConnect.dispatch(this),this}disconnect(){return this.connected&&(this.browserGamepad=null,this.clearMappedChannels(),this.onDisconnect.dispatch(this)),this}update(){if(null===this.browserGamepad)return this;const t=this.channelsValue,{buttons:e,axes:i}=this.browserGamepad;for(const i of this.mappingValue.buttons){const r=this.resolveChannelOffset(i.channel);if(i.index<e.length){const s=i.transformValue(e[i.index].value)||0;t[r]!==s&&(t[r]=s,this.onUpdate.dispatch(i.channel,s,this))}}for(const e of this.mappingValue.axes){const r=this.resolveChannelOffset(e.channel);if(e.index<i.length){const s=e.transformValue(i[e.index])||0;t[r]!==s&&(t[r]=s,this.onUpdate.dispatch(e.channel,s,this))}}return this}clearChannels(){return this.clearMappedChannels(),this}destroy(){this.disconnect(),this.clearMappedChannels(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onUpdate.destroy()}resolveChannelOffset(t){return this.channelOffset+(512^t)}static resolveChannelOffset(e,i){return 512+e*t.ChannelSize.Gamepad+(512^i)}clearMappedChannels(){for(const t of this.mappingValue.buttons)this.channelsValue[this.resolveChannelOffset(t.channel)]=0;for(const t of this.mappingValue.axes)this.channelsValue[this.resolveChannelOffset(t.channel)]=0}}t.PointerStateFlag=void 0,(ni=t.PointerStateFlag||(t.PointerStateFlag={}))[ni.None=0]="None",ni[ni.Over=1]="Over",ni[ni.Leave=2]="Leave",ni[ni.Down=4]="Down",ni[ni.Move=8]="Move",ni[ni.Up=16]="Up",ni[ni.Cancel=32]="Cancel",t.PointerState=void 0,(oi=t.PointerState||(t.PointerState={}))[oi.Unknown=0]="Unknown",oi[oi.InsideCanvas=1]="InsideCanvas",oi[oi.OutsideCanvas=2]="OutsideCanvas",oi[oi.Pressed=3]="Pressed",oi[oi.Moving=4]="Moving",oi[oi.Released=5]="Released",oi[oi.Cancelled=6]="Cancelled";class ui{constructor(e,r){this.startPos=new re(-1,-1),this.stateFlags=new tt,this._currentState=t.PointerState.Unknown;const{pointerId:s,pointerType:n,clientX:o,clientY:a,width:h,height:l,tiltX:u,tiltY:d,buttons:c,pressure:p,twist:_}=e,{left:f,top:m}=r.getBoundingClientRect();this._canvas=r,this.id=s,this.type=n,this.position=new re(o-f,a-m),this.size=new i(h,l),this.tilt=new re(u,d),this._buttons=c,this._pressure=p,this._rotation=_,this.stateFlags.push(t.PointerStateFlag.Over)}get x(){return this.position.x}get y(){return this.position.y}get width(){return this.size.width}get height(){return this.size.height}get buttons(){return this._buttons}get pressure(){return this._pressure}get rotation(){return this._rotation}get currentState(){return this._currentState}handleEnter(e){this.handleEvent(e),this._currentState=t.PointerState.InsideCanvas}handleLeave(e){this.handleEvent(e),this.stateFlags.push(t.PointerStateFlag.Leave),this._currentState=t.PointerState.OutsideCanvas}handlePress(e){this.handleEvent(e),this.startPos.copy(this.position),this.stateFlags.push(t.PointerStateFlag.Down),this._currentState=t.PointerState.Pressed}handleMove(e){this.handleEvent(e),this.stateFlags.push(t.PointerStateFlag.Move),this._currentState=t.PointerState.Moving}handleRelease(e){this.handleEvent(e),this.stateFlags.push(t.PointerStateFlag.Up),this._currentState=t.PointerState.Released}handleCancel(e){this.handleEvent(e),this.stateFlags.push(t.PointerStateFlag.Cancel),this._currentState=t.PointerState.Cancelled}destroy(){this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._canvas=null}handleEvent(t){const{clientX:e,clientY:i,width:r,height:s,tiltX:n,tiltY:o,buttons:a,pressure:h,twist:l}=t,{left:u,top:d}=this._canvas.getBoundingClientRect();return this.position.set(e-u,i-d),this.size.set(r,s),this.tilt.set(n,o),this._buttons=a,this._pressure=h,this._rotation=l,this}}t.GamepadChannel=void 0,(ai=t.GamepadChannel||(t.GamepadChannel={}))[ai.ButtonSouth=512]="ButtonSouth",ai[ai.ButtonWest=513]="ButtonWest",ai[ai.ButtonEast=514]="ButtonEast",ai[ai.ButtonNorth=515]="ButtonNorth",ai[ai.LeftShoulder=516]="LeftShoulder",ai[ai.RightShoulder=517]="RightShoulder",ai[ai.LeftTrigger=518]="LeftTrigger",ai[ai.RightTrigger=519]="RightTrigger",ai[ai.Select=520]="Select",ai[ai.Start=521]="Start",ai[ai.LeftStick=522]="LeftStick",ai[ai.RightStick=523]="RightStick",ai[ai.DPadUp=524]="DPadUp",ai[ai.DPadDown=525]="DPadDown",ai[ai.DPadLeft=526]="DPadLeft",ai[ai.DPadRight=527]="DPadRight",ai[ai.Guide=528]="Guide",ai[ai.Share=529]="Share",ai[ai.Capture=530]="Capture",ai[ai.Touchpad=531]="Touchpad",ai[ai.Paddle1=532]="Paddle1",ai[ai.LeftStickLeft=533]="LeftStickLeft",ai[ai.LeftStickRight=534]="LeftStickRight",ai[ai.LeftStickUp=535]="LeftStickUp",ai[ai.LeftStickDown=536]="LeftStickDown",ai[ai.RightStickLeft=537]="RightStickLeft",ai[ai.RightStickRight=538]="RightStickRight",ai[ai.RightStickUp=539]="RightStickUp",ai[ai.RightStickDown=540]="RightStickDown",ai[ai.AuxiliaryAxis0Negative=541]="AuxiliaryAxis0Negative",ai[ai.AuxiliaryAxis0Positive=542]="AuxiliaryAxis0Positive",ai[ai.AuxiliaryAxis1Negative=543]="AuxiliaryAxis1Negative",ai[ai.AuxiliaryAxis1Positive=544]="AuxiliaryAxis1Positive",ai[ai.AuxiliaryAxis2Negative=545]="AuxiliaryAxis2Negative",ai[ai.AuxiliaryAxis2Positive=546]="AuxiliaryAxis2Positive",ai[ai.AuxiliaryAxis3Negative=547]="AuxiliaryAxis3Negative",ai[ai.AuxiliaryAxis3Positive=548]="AuxiliaryAxis3Positive";class di{constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=D(i.threshold??.2,0,1)}transformValue(t){let e=D(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),e>this.threshold?e:0}}t.GamepadMappingFamily=void 0,(hi=t.GamepadMappingFamily||(t.GamepadMappingFamily={})).GenericDualAnalog="genericDualAnalog",hi.Xbox="xbox",hi.PlayStation="playStation",hi.SwitchPro="switchPro",hi.JoyConLeft="joyConLeft",hi.JoyConRight="joyConRight",hi.GameCube="gameCube",hi.SteamController="steamController",hi.ArcadeStick="arcadeStick";class ci{constructor(t,e){this.buttons=t,this.axes=e}destroy(){this.buttons.length=0,this.axes.length=0}static createControls(t){return t.map(([t,e,i])=>new di(t,e,i))}}const pi=[[0,t.GamepadChannel.ButtonSouth],[1,t.GamepadChannel.ButtonEast],[2,t.GamepadChannel.ButtonWest],[3,t.GamepadChannel.ButtonNorth],[4,t.GamepadChannel.LeftShoulder],[5,t.GamepadChannel.RightShoulder],[6,t.GamepadChannel.LeftTrigger],[7,t.GamepadChannel.RightTrigger],[8,t.GamepadChannel.Select],[9,t.GamepadChannel.Start],[12,t.GamepadChannel.DPadUp],[13,t.GamepadChannel.DPadDown],[14,t.GamepadChannel.DPadLeft],[15,t.GamepadChannel.DPadRight],[16,t.GamepadChannel.Guide]];class _i extends ci{constructor(){super(ci.createControls(pi),[]),this.family=t.GamepadMappingFamily.ArcadeStick}}const fi=[[0,t.GamepadChannel.ButtonSouth],[1,t.GamepadChannel.ButtonEast],[2,t.GamepadChannel.ButtonWest],[3,t.GamepadChannel.ButtonNorth],[4,t.GamepadChannel.LeftShoulder],[5,t.GamepadChannel.RightShoulder],[6,t.GamepadChannel.LeftTrigger],[7,t.GamepadChannel.RightTrigger],[8,t.GamepadChannel.Select],[9,t.GamepadChannel.Start],[10,t.GamepadChannel.LeftStick],[11,t.GamepadChannel.RightStick],[12,t.GamepadChannel.DPadUp],[13,t.GamepadChannel.DPadDown],[14,t.GamepadChannel.DPadLeft],[15,t.GamepadChannel.DPadRight],[16,t.GamepadChannel.Guide],[17,t.GamepadChannel.Share],[18,t.GamepadChannel.Capture],[19,t.GamepadChannel.Touchpad],[20,t.GamepadChannel.Paddle1]],mi=[[0,t.GamepadChannel.LeftStickLeft,{invert:!0}],[0,t.GamepadChannel.LeftStickRight],[1,t.GamepadChannel.LeftStickUp,{invert:!0}],[1,t.GamepadChannel.LeftStickDown],[2,t.GamepadChannel.RightStickLeft,{invert:!0}],[2,t.GamepadChannel.RightStickRight],[3,t.GamepadChannel.RightStickUp,{invert:!0}],[3,t.GamepadChannel.RightStickDown],[4,t.GamepadChannel.AuxiliaryAxis0Negative,{invert:!0}],[4,t.GamepadChannel.AuxiliaryAxis0Positive],[5,t.GamepadChannel.AuxiliaryAxis1Negative,{invert:!0}],[5,t.GamepadChannel.AuxiliaryAxis1Positive],[6,t.GamepadChannel.AuxiliaryAxis2Negative,{invert:!0}],[6,t.GamepadChannel.AuxiliaryAxis2Positive],[7,t.GamepadChannel.AuxiliaryAxis3Negative,{invert:!0}],[7,t.GamepadChannel.AuxiliaryAxis3Positive]];class gi extends ci{constructor(){super(ci.createControls(fi),ci.createControls(mi)),this.family=t.GamepadMappingFamily.GenericDualAnalog}}class yi extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.GameCube}}class xi extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.JoyConLeft}}class wi extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.JoyConRight}}class vi extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.PlayStation}}class bi extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.SteamController}}class Si extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.SwitchPro}}class Ti extends gi{constructor(){super(...arguments),this.family=t.GamepadMappingFamily.Xbox}}const Ci=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Mi=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,Pi=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,Bi=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,Ei=(t,e,i)=>({ids:i,name:t,resolve:()=>({name:t,mapping:e()})}),Ri=t=>t.trim().toLowerCase(),Ai=t=>{const e=t.replace(Mi,"").replace(Ci,"").replace(Bi,"").replace(Pi,"").replace(/\s+/g," ").trim();return e.length>0?e:null},Fi=t=>{if(!t)return[];return(Array.isArray(t)?t:[t]).map(Ri)},ki=(t,e)=>{if(!e)return!0;for(const i of Fi(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},Li=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=Mi.exec(t)||Ci.exec(t)||Bi.exec(t)||Pi.exec(t);return e?`${e[1].toLowerCase()}:${e[2].toLowerCase()}`:null})(e),r=i?.slice(0,4)??null,s=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:r,productId:s,productKey:i,name:Ai(e)}},Di=(t,e)=>ki(e,t.ids)?((t,e)=>{const i=t.resolve(e);return null==i?null:"mapping"in i?{descriptor:e,name:i.name??t.name??e.name??e.label,mapping:i.mapping}:{descriptor:e,name:t.name??e.name??e.label,mapping:i}})(t,e):null,Ii=(t,e=Ni)=>{const i="connected"in t?Li(t):t;for(const t of e){const e=Di(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new gi}},Ni=[...[Ei("Xbox 360 Controller",()=>new Ti,"045e:028e"),Ei("Xbox One Controller",()=>new Ti,["045e:02d1","045e:02dd"]),Ei("Xbox Wireless Controller",()=>new Ti,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),Ei("Xbox One Elite Controller",()=>new Ti,"045e:02e3"),Ei("Xbox Elite Wireless Controller Series 2",()=>new Ti,["045e:0b00","045e:0b05","045e:0b22"]),Ei("Xbox Series Controller",()=>new Ti,["045e:0b12","045e:0b13"]),Ei("PlayStation 3 Controller",()=>new vi,"054c:0268"),Ei("DualShock 4 Controller",()=>new vi,["054c:05c4","054c:09cc","054c:0ba0"]),Ei("DualSense Controller",()=>new vi,"054c:0ce6"),Ei("DualSense Edge Controller",()=>new vi,"054c:0df2"),Ei("GameCube Controller Adapter",()=>new yi,"057e:0337"),Ei("Joy-Con (L)",()=>new xi,"057e:2006"),Ei("Joy-Con (R)",()=>new wi,"057e:2007"),Ei("Joy-Con Charging Grip",()=>new Si,"057e:200e"),Ei("Switch Pro Controller",()=>new Si,"057e:2009"),Ei("Joy-Con 2 (L)",()=>new xi,"057e:2066"),Ei("Joy-Con 2 (R)",()=>new wi,"057e:2067"),Ei("Switch 2 Pro Controller",()=>new Si,"057e:2069"),Ei("Switch 2 GameCube Controller",()=>new yi,"057e:2073"),Ei("Steam Controller",()=>new bi,["28de:1102","28de:1142"]),Ei("F310 Gamepad",()=>new gi,"046d:c216"),Ei("F710 Gamepad",()=>new gi,["046d:c219","046d:c21f"]),Ei("8BitDo P30 Controller",()=>new gi,["2dc8:5107","2dc8:5108"]),Ei("8BitDo SF30 Pro Controller",()=>new Si,["2dc8:3000","2dc8:6100","2dc8:6101"]),Ei("8BitDo SN30 Controller",()=>new Si,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),Ei("8BitDo NES30 Controller",()=>new gi,"2dc8:ab12"),Ei("PowerA Switch Controller",()=>new Si,"20d6:a713"),Ei("PowerA OPS Pro Wireless Controller",()=>new gi,"20d6:4033"),Ei("PowerA OPS Wireless Controller",()=>new gi,"20d6:4026"),Ei("Nacon Revolution 3 Controller",()=>new vi,"146b:0611"),Ei("Nacon Revolution Unlimited Pro Controller",()=>new vi,"146b:0d08"),Ei("Nacon Revolution Infinity Controller",()=>new vi,"146b:0d10"),Ei("Nacon Revolution 5 Pro Controller",()=>new vi,["3285:0d17","3285:0d19"]),Ei("Razer Raiju Controller",()=>new vi,"1532:1000"),Ei("Razer Raiju Mobile Controller",()=>new vi,["1532:0705","1532:0707"]),Ei("Razer Raiju Tournament Edition Controller",()=>new vi,["1532:1007","1532:100a"]),Ei("Razer Raiju Ultimate Controller",()=>new vi,["1532:1004","1532:1009"]),Ei("Razer Raion Controller",()=>new _i,"1532:1100")],...[Ei("Microsoft Controller",()=>new Ti,"045e"),Ei("Sony Controller",()=>new vi,"054c")],Ei("Generic Gamepad",()=>new gi)];var Gi;!function(t){t[t.None=0]="None",t[t.KeyDown=1]="KeyDown",t[t.KeyUp=2]="KeyUp",t[t.MouseWheel=4]="MouseWheel",t[t.PointerUpdate=8]="PointerUpdate"}(Gi||(Gi={}));class Ui{constructor(e){this.channels=new Float32Array(t.ChannelSize.Container),this.inputs=new Set,this.pointers={},this.gamepadsValue=[],this.gamepadsByIndex=new Map,this.gamepadSlotsActive=new Uint8Array(t.ChannelSize.Category/t.ChannelSize.Gamepad),this.wheelOffset=new re,this.flags=new tt,this.channelsPressed=[],this.channelsReleased=[],this.keyDownHandler=this.handleKeyDown.bind(this),this.keyUpHandler=this.handleKeyUp.bind(this),this.canvasFocusHandler=this.handleCanvasFocus.bind(this),this.canvasBlurHandler=this.handleCanvasBlur.bind(this),this.windowBlurHandler=this.handleWindowBlur.bind(this),this.mouseWheelHandler=this.handleMouseWheel.bind(this),this.pointerOverHandler=this.handlePointerOver.bind(this),this.pointerLeaveHandler=this.handlePointerLeave.bind(this),this.pointerDownHandler=this.handlePointerDown.bind(this),this.pointerMoveHandler=this.handlePointerMove.bind(this),this.pointerUpHandler=this.handlePointerUp.bind(this),this.pointerCancelHandler=this.handlePointerCancel.bind(this),this.onPointerEnter=new E,this.onPointerLeave=new E,this.onPointerDown=new E,this.onPointerMove=new E,this.onPointerUp=new E,this.onPointerTap=new E,this.onPointerSwipe=new E,this.onPointerCancel=new E,this.onMouseWheel=new E,this.onKeyDown=new E,this.onKeyUp=new E,this.onGamepadConnected=new E,this.onGamepadDisconnected=new E,this.onGamepadUpdated=new E;const{gamepadDefinitions:i=[],pointerDistanceThreshold:r}=e.options;this.canvas=e.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=r,this.gamepadDefinitions=[...i,...Ni],this.addEventListeners()}get pointersInCanvas(){return Object.values(this.pointers).some(e=>e.currentState!==t.PointerState.OutsideCanvas&&e.currentState!==t.PointerState.Cancelled)}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this.gamepadsValue}getGamepad(t){return this.gamepadsByIndex.get(t)??null}add(t){return Array.isArray(t)?(t.forEach(t=>this.add(t)),this):(this.inputs.add(t),this)}remove(t){return Array.isArray(t)?(t.forEach(t=>this.remove(t)),this):(this.inputs.delete(t),this)}clear(t=!1){if(t)for(const t of this.inputs)t.destroy();return this.inputs.clear(),this}update(){this.updateGamepads();for(const t of this.inputs)t.update(this.channels);return this.flags.value!==Gi.None&&this.updateEvents(),this}destroy(){this.removeEventListeners();for(const t of Object.values(this.pointers))t.destroy();for(const t of this.gamepadsValue)t.destroy();this.inputs.clear(),this.gamepadsByIndex.clear(),this.gamepadsValue.length=0,this.channelsPressed.length=0,this.channelsReleased.length=0,this.wheelOffset.destroy(),this.flags.destroy(),this.onPointerEnter.destroy(),this.onPointerLeave.destroy(),this.onPointerDown.destroy(),this.onPointerMove.destroy(),this.onPointerUp.destroy(),this.onPointerTap.destroy(),this.onPointerSwipe.destroy(),this.onPointerCancel.destroy(),this.onMouseWheel.destroy(),this.onKeyDown.destroy(),this.onKeyUp.destroy(),this.onGamepadConnected.destroy(),this.onGamepadDisconnected.destroy(),this.onGamepadUpdated.destroy()}handleKeyDown(t){const e=0+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(Gi.KeyDown)}handleKeyUp(t){const e=0+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(Gi.KeyUp)}handlePointerOver(t){this.pointers[t.pointerId]=new ui(t,this.canvas),this.flags.push(Gi.PointerUpdate)}handlePointerLeave(t){this.pointers[t.pointerId].handleLeave(t),this.flags.push(Gi.PointerUpdate)}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0,this.pointers[t.pointerId].handlePress(t),this.flags.push(Gi.PointerUpdate),t.preventDefault()}handlePointerMove(t){this.pointers[t.pointerId].handleMove(t),this.flags.push(Gi.PointerUpdate)}handlePointerUp(t){this.pointers[t.pointerId].handleRelease(t),this.flags.push(Gi.PointerUpdate),t.preventDefault()}handlePointerCancel(t){this.pointers[t.pointerId].handleCancel(t),this.flags.push(Gi.PointerUpdate)}handleMouseWheel(t){this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(Gi.MouseWheel),this.canvasFocusedValue&&t.preventDefault()}handleCanvasFocus(){this.canvasFocusedValue=!0}handleCanvasBlur(){this.canvasFocusedValue=!1}handleWindowBlur(){this.canvasFocusedValue=!1}addEventListeners(){const t=window,e={capture:!0,passive:!1},i={capture:!0,passive:!0};t.addEventListener("keydown",this.keyDownHandler,!0),t.addEventListener("keyup",this.keyUpHandler,!0),t.addEventListener("blur",this.windowBlurHandler,!0),this.canvas.addEventListener("focus",this.canvasFocusHandler,!0),this.canvas.addEventListener("blur",this.canvasBlurHandler,!0),this.canvas.addEventListener("wheel",this.mouseWheelHandler,e),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,e),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",m,e),this.canvas.addEventListener("selectstart",m,e)}removeEventListeners(){const t={capture:!0,passive:!1},e={capture:!0,passive:!0};window.removeEventListener("keydown",this.keyDownHandler,!0),window.removeEventListener("keyup",this.keyUpHandler,!0),window.removeEventListener("blur",this.windowBlurHandler,!0),this.canvas.removeEventListener("focus",this.canvasFocusHandler,!0),this.canvas.removeEventListener("blur",this.canvasBlurHandler,!0),this.canvas.removeEventListener("wheel",this.mouseWheelHandler,t),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,e),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,e),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,e),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,t),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,e),this.canvas.removeEventListener("contextmenu",m,t),this.canvas.removeEventListener("selectstart",m,t)}updateGamepads(){const t=window.navigator.getGamepads();this.gamepadSlotsActive.fill(0);for(const e of t){if(!e)continue;const t=e.index;if(t<0||t>=this.gamepadSlotsActive.length)continue;this.gamepadSlotsActive[t]=1;let i=this.gamepadsByIndex.get(t);if(i)i.connect(e);else{const r=Ii(e,this.gamepadDefinitions);i=new li(e,this.channels,r),this.gamepadsByIndex.set(t,i),this.insertGamepadByIndex(i),this.onGamepadConnected.dispatch(i,this.gamepadsValue)}i.update(),this.onGamepadUpdated.dispatch(i,this.gamepadsValue)}for(let t=this.gamepadsValue.length-1;t>=0;t-=1){const e=this.gamepadsValue[t];0===this.gamepadSlotsActive[e.index]&&(e.disconnect(),this.gamepadsValue.splice(t,1),this.gamepadsByIndex.delete(e.index),this.onGamepadDisconnected.dispatch(e,this.gamepadsValue),e.destroy())}return this}insertGamepadByIndex(t){let e=0;for(;e<this.gamepadsValue.length&&this.gamepadsValue[e].index<t.index;)e+=1;this.gamepadsValue.splice(e,0,t)}updateEvents(){if(this.flags.pop(Gi.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(Gi.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(Gi.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(Gi.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const e of Object.values(this.pointers)){const{stateFlags:i}=e;if(i.value!==t.PointerStateFlag.None){if(i.pop(t.PointerStateFlag.Over)&&this.onPointerEnter.dispatch(e),i.pop(t.PointerStateFlag.Down)&&this.onPointerDown.dispatch(e),i.pop(t.PointerStateFlag.Move)&&this.onPointerMove.dispatch(e),i.pop(t.PointerStateFlag.Up)){const{x:t,y:i}=e.startPos;this.onPointerUp.dispatch(e),t>=0&&i>=0&&(U(t,i,e.x,e.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(e):this.onPointerSwipe.dispatch(e)),e.startPos.set(-1,-1)}i.pop(t.PointerStateFlag.Cancel)&&this.onPointerCancel.dispatch(e),i.pop(t.PointerStateFlag.Leave)&&(this.onPointerLeave.dispatch(e),delete this.pointers[e.id])}}}}class Vi{get duration(){return this._duration}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}constructor(t){this.onStart=new E,this.onStop=new E;const{duration:e,volume:i,playbackRate:r,loop:s,muted:n}=t;this._duration=e,this._volume=i,this._playbackRate=r,this._loop=s,this._muted=n}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:r,time:s,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==r&&(this.playbackRate=r),void 0!==s&&(this.currentTime=s),void 0!==n&&(this.muted=n),this}destroy(){this.stop(),this.onStart.destroy(),this.onStop.destroy()}}const Oi=["mousedown","touchstart","touchend"];let zi=null,Wi=null,qi=!1,Hi=!1,Xi=!1;const ji=()=>"undefined"!=typeof document,Yi=()=>zi,$i=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===zi&&(zi=new AudioContext),zi},Ki=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===Wi){const t=$i();Wi=new OfflineAudioContext(1,2,t.sampleRate)}return Wi},Qi=()=>{const t=Yi();t&&"running"===t.state&&!Xi&&(Xi=!0,(()=>{if(qi&&ji()){for(const t of Oi)document.removeEventListener(t,tr,!1);qi=!1}})(),er.dispatch(t))},Zi=()=>{Qi()},Ji=()=>{const t=$i();Hi||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",Zi),Hi=!0),Qi(),Xi||(()=>{if(!qi&&ji()){for(const t of Oi)document.addEventListener(t,tr,!1);qi=!0}})()},tr=()=>{const t=$i();"running"!==t.state?t.resume().then(()=>{Qi()}):Qi()};const er=new class extends E{add(t,e){return super.add(t,e),Ji(),this}once(t,e){return super.once(t,e),Ji(),this}},ir=()=>{const t=$i();return Ji(),t},rr=()=>{const t=Yi();return null!==t&&"running"===t.state},sr=async t=>Ki().decodeAudioData(t);class nr extends Vi{constructor(t,e){super(t),this._audioSetup=null,this._audioElement=t,e&&this.applyOptions(e),rr()?this.setupWithAudioContext(ir()):er.once(this.setupWithAudioContext,this)}setVolume(t){const e=D(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._audioElement.loop=t),this}setPlaybackRate(t){const e=D(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._audioElement.playbackRate=e),this}getTime(){return this._audioElement.currentTime}setTime(t){return this._audioElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}get paused(){return this._audioElement.paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._audioElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._audioElement.pause(),this.onStop.dispatch()),this}destroy(){super.destroy(),er.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._audioElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class or extends Vi{get paused(){return this._paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}get poolSize(){return this._poolSize}set poolSize(t){this.setPoolSize(t)}constructor(t,e={}){super({duration:t.duration,volume:1,playbackRate:1,loop:!1,muted:!1}),this._pooledSources=[],this._queuedPooledPlays=[],this._sprites=new Map,this._audioSetup=null,this._paused=!0,this._startTime=0,this._currentTime=0,this._sourceNode=null,this._poolSize=1,this._audioBuffer=t;const{poolSize:i,sprites:r,...s}=e;this._poolSize=Math.max(1,Math.floor(i??1)),Object.keys(s).length>0&&this.applyOptions(s),r&&this.setSprites(r),rr()?this.setupWithAudioContext(ir()):er.once(this.setupWithAudioContext,this)}setVolume(t){const e=D(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop=t,this._sourceNode&&(this._sourceNode.loop=t,t&&(this._sourceNode.loopStart=0,this._sourceNode.loopEnd=this.duration)),this}setPlaybackRate(t){return this._playbackRate=D(t,.1,20),this._sourceNode&&(this._sourceNode.playbackRate.value=this._playbackRate),this}getTime(){return this._audioSetup&&!this._paused&&this._sourceNode?this._currentTime+(this._audioSetup.audioContext.currentTime-this._startTime)*this._playbackRate:this._currentTime}setTime(t){const e=Math.max(0,t);return this.paused||!this._audioSetup?(this._currentTime=e,this):(this.pause(),this._currentTime=e,this.play(),this)}setMuted(t){if(this._muted=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimPooledSources()),this}setSprites(t){this._sprites.clear();for(const[e,i]of Object.entries(t))this.defineSprite(e,i);return this}defineSprite(t,e){if(0===t.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=e.start,r=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(r)||r<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${r}).`);if(r>this.duration)throw new Error(`Sound sprite "${t}" ends at ${r}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:r,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}play(t){return t&&this.applyOptions(t),this._paused?(this._audioSetup&&this.createSourceNode(this._audioSetup),this._paused=!1,this.onStart.dispatch(),this):this}playPooled(t={}){const e=D(t.playbackRate??this._playbackRate,.1,20),i=Math.max(0,t.time??0),r=t.loop??!1;if(void 0!==t.volume&&this.setVolume(t.volume),void 0!==t.muted&&this.setMuted(t.muted),i>=this.duration)return this;const s=r?void 0:this.duration-i;return this._enqueuePooledPlay({offset:i,duration:s,loop:r,loopStart:0,loopEnd:this.duration,playbackRate:e}),this.onStart.dispatch(),this}playSprite(t,e={}){const i=this._sprites.get(t);if(!i)throw new Error(`Sound sprite "${t}" is not defined.`);const r=Math.max(0,e.time??0),s=i.start+r;if(s>=i.end)throw new Error(`Sound sprite "${t}" offset (${r}s) exceeds clip duration (${i.end-i.start}s).`);const n=e.loop??i.loop,o=D(e.playbackRate??this._playbackRate,.1,20);return void 0!==e.volume&&this.setVolume(e.volume),void 0!==e.muted&&this.setMuted(e.muted),this._enqueuePooledPlay({offset:s,duration:n?void 0:i.end-s,loop:n,loopStart:i.start,loopEnd:i.end,playbackRate:o}),this.onStart.dispatch(),this}stopPooled(){return this._pooledSources.length>0&&(this._stopPooledSources(),this.onStop.dispatch()),this._queuedPooledPlays.length=0,this}pause(t){if(t&&this.applyOptions(t),this._paused&&0===this._pooledSources.length)return this;if(!this._paused&&this._audioSetup){const t=this.duration,e=this.currentTime;this._currentTime=t>0?e%t:0}const e=this._pooledSources.length>0;this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0;const i=!this._paused||e;return this._paused=!0,i&&this.onStop.dispatch(),this}destroy(){super.destroy(),er.clearByContext(this),this._audioSetup?.gainNode.disconnect(),this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0,this._sprites.clear()}createSourceNode(t){const{audioContext:e}=t;this._stopPrimarySource();const i=this._createBufferSourceNode(t,{offset:Math.min(Math.max(0,this._currentTime),Math.max(0,this.duration)),duration:void 0,loop:this._loop,loopStart:0,loopEnd:this.duration,playbackRate:this._playbackRate});i.onended=()=>{this._sourceNode===i&&(this._sourceNode=null,this._startTime=0,this._currentTime=0,this._paused||(this._paused=!0,this.onStop.dispatch()))},this._sourceNode=i,this._startTime=e.currentTime}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination),this._audioSetup={audioContext:t,gainNode:e},this._paused||this.createSourceNode(this._audioSetup),this._flushQueuedPooledPlays()}_enqueuePooledPlay(t){this._audioSetup?this._playPooledNow(t):this._queuedPooledPlays.push(t)}_flushQueuedPooledPlays(){if(!this._audioSetup||0===this._queuedPooledPlays.length)return;const t=[...this._queuedPooledPlays];this._queuedPooledPlays.length=0;for(const e of t)this._playPooledNow(e)}_playPooledNow(t){if(!this._audioSetup)return;const e=this._createBufferSourceNode(this._audioSetup,t);e.onended=()=>{const t=this._pooledSources.indexOf(e);-1!==t&&this._pooledSources.splice(t,1),e.disconnect()},this._pooledSources.push(e),this._trimPooledSources()}_trimPooledSources(){for(;this._pooledSources.length>this._poolSize;){const t=this._pooledSources.shift();t&&(t.onended=null,this._stopSourceNode(t))}}_stopPrimarySource(){this._sourceNode&&(this._sourceNode.onended=null,this._stopSourceNode(this._sourceNode),this._sourceNode=null,this._startTime=0)}_stopPooledSources(){for(const t of this._pooledSources)t.onended=null,this._stopSourceNode(t);this._pooledSources.length=0}_stopSourceNode(t){try{t.stop(0)}catch{}t.disconnect()}_createBufferSourceNode(t,e){const{gainNode:i}=t,r=t.audioContext.createBufferSource();r.buffer=this._audioBuffer,r.loop=e.loop,r.playbackRate.value=e.playbackRate,e.loop&&(r.loopStart=e.loopStart??0,r.loopEnd=e.loopEnd??this.duration),r.connect(i);const s=e.duration;return!e.loop&&void 0!==s&&s>0?r.start(0,e.offset,s):r.start(0,e.offset),r}}class ar extends Ie{constructor(t,e,i){super(new Ue(t,i)),this.onStart=new E,this.onStop=new E,this._volume=1,this._playbackRate=1,this._loop=!1,this._muted=!1,this._audioSetup=null,this._textureDirty=!0,this._lastVideoTime=Number.NaN,this._videoFrameCallbackHandle=null;const{duration:r,volume:s,playbackRate:n,loop:o,muted:a}=t;this._videoElement=t,this._duration=r,this._volume=s,this._playbackRate=n,this._loop=o,this._muted=a,this._onMetadataHandler=this._onVideoMetadataUpdated.bind(this),this._onResizeHandler=this._onVideoMetadataUpdated.bind(this),this._onVideoFrameHandler=this._onVideoFrame.bind(this),0!==this._videoElement.videoWidth&&0!==this._videoElement.videoHeight||(this._videoElement.addEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.addEventListener("resize",this._onResizeHandler)),e&&this.applyOptions(e),rr()?this.setupWithAudioContext(ir()):er.once(this.setupWithAudioContext,this),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get paused(){return this._videoElement.paused}set paused(t){t?this.pause():this.play()}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:r,time:s,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==r&&(this.playbackRate=r),void 0!==s&&(this.currentTime=s),void 0!==n&&(this.muted=n),this}setVolume(t){const e=D(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=D(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._videoElement.playbackRate=e),this}getTime(){return this._videoElement.currentTime}setTime(t){return this._videoElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}render(t){return this.visible&&(this._markTextureDirtyIfPlaybackAdvanced(),this.updateTexture(),super.render(t)),this}updateTexture(){const t=this.texture;if(!t||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const e=this.textureFrame.width>0&&this.textureFrame.height>0;return t.updateSource(),t.width>0&&t.height>0&&this.setTextureFrame(Kt.temp.set(0,0,t.width,t.height),!e),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),er.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null),this.onStart.destroy(),this.onStop.destroy()}_onVideoMetadataUpdated(){this._textureDirty=!0,this.updateTexture()}_onVideoFrame(t,e){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyIfPlaybackAdvanced(){const t=this._videoElement.currentTime;this._lastVideoTime!==t&&(this._lastVideoTime=t,this._textureDirty=!0)}_requestVideoFrameCallback(){const t=this._videoElement;t.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=t.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const t=this._videoElement;t.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(t.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._videoElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class hr{}class lr{}class ur{}class dr{}class cr{constructor(){this._factories=new Map}register(t,e){this._factories.set(t,e)}resolve(t){let e,i=t;for(;null!==i&&!e;)if(e=this._factories.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){let e=t;for(;null!==e;){if(this._factories.has(e))return!0;const t=Object.getPrototypeOf(e.prototype);e=t?.constructor??null}return!1}destroy(){for(const t of this._factories.values())t.destroy();this._factories.clear()}}class pr{constructor(){this._objectUrls=[]}createObjectUrl(t){const e=URL.createObjectURL(t);return this._objectUrls.push(e),e}revokeObjectUrl(t){URL.revokeObjectURL(t);const e=this._objectUrls.indexOf(t);-1!==e&&this._objectUrls.splice(e,1)}destroy(){for(const t of this._objectUrls)URL.revokeObjectURL(t);this._objectUrls.length=0}}class _r extends pr{constructor(){super(...arguments),this.storageName="font",this._addedFontFaces=[]}async process(t){return await t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:r,addToDocument:s}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const n=await new FontFace(i,t,r).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==s&&(document.fonts.add(n),this._addedFontFaces.push(n)),n}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const fr=[{mimeType:"image/x-icon",pattern:[0,0,1,0],mask:[255,255,255,255]},{mimeType:"image/x-icon",pattern:[0,0,2,0],mask:[255,255,255,255]},{mimeType:"image/bmp",pattern:[66,77],mask:[255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,55,97],mask:[255,255,255,255,255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,57,97],mask:[255,255,255,255,255,255]},{mimeType:"image/webp",pattern:[82,73,70,70,0,0,0,0,87,69,66,80,86,80],mask:[255,255,255,255,0,0,0,0,255,255,255,255,255,255]},{mimeType:"image/png",pattern:[137,80,78,71,13,10,26,10],mask:[255,255,255,255,255,255,255,255]},{mimeType:"image/jpeg",pattern:[255,216,255],mask:[255,255,255]},{mimeType:"audio/basic",pattern:[46,115,110,100],mask:[255,255,255,255]},{mimeType:"audio/mpeg",pattern:[73,68,51],mask:[255,255,255]},{mimeType:"audio/wave",pattern:[82,73,70,70,0,0,0,0,87,65,86,69],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"audio/midi",pattern:[77,84,104,100,0,0,0,6],mask:[255,255,255,255,255,255,255,255]},{mimeType:"audio/aiff",pattern:[70,79,82,77,0,0,0,0,65,73,70,70],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"video/avi",pattern:[82,73,70,70,0,0,0,0,65,86,73,32],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"application/ogg",pattern:[79,103,103,83,0],mask:[255,255,255,255,255]}],mr=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of fr)if(!(e.length<t.pattern.length)&&t.pattern.every((i,r)=>(e[r]&t.mask[r])===i))return t.mimeType;return(t=>{const e=new Uint8Array(t),i=new DataView(t).getUint32(0,!1);return!(e.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...e.subarray(4,11))})(t)?"video/mp4":(t=>{const e=new Uint8Array(t),i=[26,69,223,163].every((t,i)=>t===e[i]),r=e.subarray(4,4100),s=r.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===s)&&"webm"===String.fromCharCode(...r.subarray(s+3,s+7))})(t)?"video/webm":(t=>{if(t.byteLength<12)return!1;const e=new Uint8Array(t);if("ftyp"!==String.fromCharCode(e[4],e[5],e[6],e[7]))return!1;const i=String.fromCharCode(e[8],e[9],e[10],e[11]);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class gr extends pr{constructor(){super(...arguments),this.storageName="image"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??mr(t)}),r=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(r)};i.addEventListener("load",()=>{s(),t(i)},{once:!0}),i.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),i.src=r})}}class yr extends pr{constructor(){super(...arguments),this.storageName="json"}async process(t){return await t.json()}async create(t){return t}}const xr={once:!0};class wr extends pr{constructor(){super(...arguments),this.storageName="music",this._audioElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:r,playbackOptions:s}=e,n=new Blob([t],{type:i??mr(t)});return new Promise((t,e)=>{const i=document.createElement("audio");this._audioElements.push(i),i.addEventListener("error",()=>e(Error("Error loading audio source.")),xr),i.addEventListener("abort",()=>e(Error("Audio loading was canceled.")),xr),i.addEventListener(r??"canplaythrough",()=>t(new nr(i,s)),xr),i.preload="auto",i.src=this.createObjectUrl(n)})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class vr extends pr{constructor(){super(...arguments),this.storageName="sound"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=await sr(t);return new or(i,{...e.playbackOptions,poolSize:e.poolSize,sprites:e.sprites})}}class br extends pr{constructor(){super(...arguments),this.storageName="text"}async process(t){return await t.text()}async create(t){return t}}class Sr extends pr{constructor(){super(...arguments),this.storageName="texture"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:r}=e,s=new Blob([t],{type:i??mr(t)}),n=this.createObjectUrl(s);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{s(),t(new Ue(i,r))},{once:!0}),i.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Tr={once:!0};class Cr extends pr{constructor(){super(...arguments),this.storageName="video",this._videoElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:r,playbackOptions:s,samplerOptions:n}=e,o=new Blob([t],{type:i??mr(t)});return new Promise((t,e)=>{const i=document.createElement("video");this._videoElements.push(i),i.addEventListener("error",()=>e(Error("Video loading error.")),Tr),i.addEventListener("abort",()=>e(Error("Video loading error: cancelled.")),Tr),i.addEventListener("emptied",()=>e(Error("Video loading error: emptied.")),Tr),i.addEventListener(r??"canplaythrough",()=>t(new ar(i,s,n)),Tr),i.preload="auto",i.src=this.createObjectUrl(o)})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class Mr extends pr{constructor(){super(...arguments),this.storageName="svg"}async process(t){return await t.text()}async create(t){const e=new Blob([t],{type:"image/svg+xml"}),i=this.createObjectUrl(e);return new Promise((t,e)=>{const r=new Image,s=()=>{this.revokeObjectUrl(i)};r.addEventListener("load",()=>{s(),t(r)},{once:!0}),r.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),r.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),r.src=i})}}class Pr extends pr{constructor(){super(...arguments),this.storageName="binary"}async process(t){return t.arrayBuffer()}async create(t){return t}}class Br extends pr{constructor(){super(...arguments),this.storageName="wasm"}async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}const Er=t=>{const e=t.split(":");let i=0;return i=3===e.length?3600*Number(e[0])+60*Number(e[1])+Number(e[2]):2===e.length?60*Number(e[0])+Number(e[1]):Number(e[0]),i};class Rr extends pr{constructor(){super(...arguments),this.storageName="vtt"}async process(t){return t.text()}async create(t){const e=[],i=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n");let r=0;for(;r<i.length&&!i[r].includes("--\x3e");)r++;for(;r<i.length;){const t=i[r].trim();if(t.includes("--\x3e")){const s=t.indexOf("--\x3e"),n=t.slice(0,s).trim(),o=t.slice(s+3).trim().split(/\s+/)[0],a=Er(n),h=Er(o);r++;const l=[];for(;r<i.length&&""!==i[r].trim();)l.push(i[r]),r++;e.push(new VTTCue(a,h,l.join("\n")))}else r++}return e}}class Ar extends Error{constructor(t,e){super(`Failed to load bundle "${t}" (${e.length} failure${1===e.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=t,this.failures=e}}function Fr(t){return function(t){if(!kr(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!kr(t.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[e,i]of Object.entries(t.bundles)){if(0===e.trim().length)throw new Error("Invalid asset manifest: bundle names must be non-empty strings.");if(!Array.isArray(i))throw new Error(`Invalid asset manifest: bundle "${e}" must be an array of entries.`);const t=new Map;i.forEach((i,r)=>{const s=`bundle "${e}" entry[${r}]`;if(!kr(i))throw new Error(`Invalid asset manifest: ${s} must be an object.`);if("function"!=typeof i.type)throw new Error(`Invalid asset manifest: ${s} has an invalid "type" token.`);Lr(i.alias,`${s} has an invalid "alias".`),Lr(i.path,`${s} has an invalid "path".`);const n=i.type,o=i.alias;t.has(n)||t.set(n,new Set);const a=t.get(n);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Dr(n)}, "${o}") in bundle "${e}".`);a.add(o)})}}(t),t}function kr(t){return"object"==typeof t&&null!==t}function Lr(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function Dr(t){return t.name.length>0?t.name:"(anonymous type)"}class Ir{constructor(t={}){this._registry=new cr,this._resources=new Map,this._manifest=new Map,this._bundles=new Map,this._inFlight=new Map,this._typeIds=new WeakMap,this._preventStoreKeys=new Set,this._nextTypeId=1,this._backgroundQueue=[],this._backgroundActive=0,this._backgroundTotal=0,this._backgroundLoaded=0,this._backgroundResolve=null,this.onProgress=new E,this.onBundleProgress=new E,this.onLoaded=new E,this.onError=new E,this._resourcePath=t.resourcePath??"",this._requestOptions=t.requestOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._registerBuiltinFactories()}register(t,e){return this._registry.register(t,e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e))for(const t of e)this._addManifestEntry(i,t,t);else for(const[t,r]of Object.entries(e))this._addManifestEntry(i,t,r);return this}registerManifest(t){const e=Fr(t),i=new Map,r=new Array;for(const[t,s]of Object.entries(e.bundles)){if(this._bundles.has(t))throw new Error(`Bundle "${t}" is already registered.`);const e=new Array;for(const r of s){const s=r.type,n=this._key(s,r.alias),o=i.get(n)??this._getManifestEntry(s,r.alias);if(o&&!this._isManifestDefinitionEquivalent(o,r.path,r.options))throw new Error(`Conflicting asset definition for (${this._describeType(s)}, "${r.alias}") while registering bundle "${t}".`);i.set(n,{path:r.path,options:r.options}),e.push({type:s,alias:r.alias,path:r.path,options:r.options})}r.push([t,e])}for(const[t,e]of r){for(const t of e)this._addManifestEntry(t.type,t.alias,t.path,t.options);this._bundles.set(t,e)}return this}async loadBundle(t,e={}){const i=this._bundles.get(t);if(!i)throw new Error(`Unknown bundle "${t}".`);const r=i.length;let s=0;const n=new Array;if(0!==r){if(await Promise.all(i.map(async i=>{try{e.background?await this._loadSingleBackground(i.type,i.alias,i.path,i.options):await this._loadSingle(i.type,i.alias,i.options,i.path)}catch(t){n.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{s++,this._emitBundleProgress(t,s,r,e.onProgress)}})),n.length>0)throw new Ar(t,n)}else this._emitBundleProgress(t,0,0,e.onProgress)}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}async load(t,e,i){const r=t;if("string"==typeof e)return this._loadSingle(r,e,i);if(Array.isArray(e))return Promise.all(e.map(t=>this._loadSingle(r,t,i)));const s=Object.entries(e),n={};return await Promise.all(s.map(async([t,e])=>{n[t]=await this._loadSingle(r,t,i,e)})),n}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,r]of e){if(this._hasResource(t,i))continue;const e=this._key(t,i);this._inFlight.has(e)||this._backgroundQueue.push({type:t,alias:i,path:r.path,options:r.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(t=>{this._backgroundResolve=t,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,t())})}setConcurrency(t){return this._concurrency=t,this}get(t,e){const i=t,r=this._resources.get(i);if(!r?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return r.get(e)}peek(t,e){const i=t;return this._resources.get(i)?.get(e)??null}has(t,e){const i=t;return this._resources.get(i)?.has(e)??!1}unload(t,e){const i=t,r=this._key(i,e);return this._resources.get(i)?.delete(e),this._inFlight.has(r)&&this._preventStoreKeys.add(r),this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get resourcePath(){return this._resourcePath}set resourcePath(t){this._resourcePath=t}get requestOptions(){return this._requestOptions}set requestOptions(t){this._requestOptions=t}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy()}async _loadSingle(t,e,i,r){if(this._hasResource(t,e))return this._resources.get(t).get(e);const s=this._key(t,e);if(this._inFlight.has(s))return this._inFlight.get(s);if(this._boostFromQueue(t,e),this._inFlight.has(s))return this._inFlight.get(s);const n=this._getManifestEntry(t,e),o=r??n?.path??e,a=i??n?.options;return this._trackInFlight(s,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,r){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const s=this._key(t,e),n=this._inFlight.get(s);if(n)return n;this._isQueuedInBackground(t,e)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:t,alias:e,path:i,options:r}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(s);return o||this._waitForBackgroundEntry(t,e)}async _fetch(t,e,i,r){const s=this._registry.resolve(t),n=this._resolveUrl(i);let o=null;for(const i of this._stores)if(o=await i.load(s.storageName,e),null!=o)try{const i=await s.create(o,r);return this._storeResource(t,e,i),i}catch{await i.delete(s.storageName,e),o=null}const a=await fetch(n,this._requestOptions);if(!a.ok)throw new Error(`Failed to fetch "${e}" from "${n}" (${a.status} ${a.statusText}).`);o=await s.process(a);const h=await s.create(o,r).catch(t=>{const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to create "${e}" from "${n}": ${i}`)});for(const t of this._stores)try{await t.save(s.storageName,e,o)}catch{}return this._storeResource(t,e,h),h}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift(),e=this._key(t.type,t.alias);this._hasResource(t.type,t.alias)||this._inFlight.has(e)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(t)}}_boostFromQueue(t,e){const i=this._backgroundQueue.findIndex(i=>i.type===t&&i.alias===e);if(-1===i)return;const[r]=this._backgroundQueue.splice(i,1);this._startBackgroundEntry(r)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const i=this._key(t,e),r=this._inFlight.get(i);return r||new Promise((r,s)=>{const n=(i,s,n)=>{i===t&&s===e&&(a(),r(n))},o=(i,r,n)=>{i===t&&r===e&&(a(),s(n))},a=()=>{this.onLoaded.remove(n),this.onError.remove(o)};this.onLoaded.add(n),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(r,s);this._hasResource(t,e)&&(a(),r(this._resources.get(t).get(e)))})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const t=this._backgroundResolve;this._backgroundResolve=null,t()}}_startBackgroundEntry(t){const e=this._key(t.type,t.alias);this._backgroundActive++,this._trackInFlight(e,this._fetch(t.type,t.alias,t.path,t.options)).catch(e=>{const i=e instanceof Error?e:new Error(String(e));this.onError.dispatch(t.type,t.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(t,e){const i=e.finally(()=>{this._inFlight.delete(t),this._preventStoreKeys.delete(t)});return this._inFlight.set(t,i),i}_emitBundleProgress(t,e,i,r){this.onBundleProgress.dispatch(t,e,i),r&&r(e,i)}_addManifestEntry(t,e,i,r){this._manifest.has(t)||this._manifest.set(t,new Map),this._manifest.get(t).set(e,{path:i,options:r})}_getManifestEntry(t,e){return this._manifest.get(t)?.get(e)}_isManifestDefinitionEquivalent(t,e,i){return t.path===e&&this._areOptionsEquivalent(t.options,i)}_areOptionsEquivalent(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this._areOptionsEquivalent(t[i],e[i]))return!1;return!0}const i=Object.getPrototypeOf(t);if(i!==Object.getPrototypeOf(e))return!1;if(i!==Object.prototype&&null!==i)return!1;const r=t,s=e,n=Object.keys(r),o=Object.keys(s);if(n.length!==o.length)return!1;for(const t of n){if(!Object.prototype.hasOwnProperty.call(s,t))return!1;if(!this._areOptionsEquivalent(r[t],s[t]))return!1}return!0}_normalizeError(t){return t instanceof Error?t:new Error(String(t))}_describeType(t){return t.name.length>0?t.name:"(anonymous type)"}_hasResource(t,e){return this._resources.get(t)?.has(e)??!1}_storeResource(t,e,i){const r=this._key(t,e);this._preventStoreKeys.delete(r)||(this._resources.has(t)||this._resources.set(t,new Map),this._resources.get(t).set(e,i),this.onLoaded.dispatch(t,e,i))}_key(t,e){let i=this._typeIds.get(t);return void 0===i&&(i=this._nextTypeId++,this._typeIds.set(t,i)),`${i}:${e}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?t:`${this._resourcePath}${t}`}_registerBuiltinFactories(){this._registry.register(Ue,new Sr),this._registry.register(or,new vr),this._registry.register(nr,new wr),this._registry.register(ar,new Cr),this._registry.register(hr,new yr),this._registry.register(lr,new br),this._registry.register(ur,new Mr),this._registry.register(dr,new Rr),this._registry.register(ArrayBuffer,new Pr),"undefined"!=typeof FontFace&&this._registry.register(FontFace,new _r),"undefined"!=typeof HTMLImageElement&&this._registry.register(HTMLImageElement,new gr),"undefined"!=typeof WebAssembly&&this._registry.register(WebAssembly.Module,new Br)}}var Nr;t.ApplicationStatus=void 0,(Nr=t.ApplicationStatus||(t.ApplicationStatus={}))[Nr.Loading=1]="Loading",Nr[Nr.Running=2]="Running",Nr[Nr.Halting=3]="Halting",Nr[Nr.Stopped=4]="Stopped";const Gr={type:"auto"},Ur={width:800,height:600,clearColor:z.cornflowerBlue,debug:!1,spriteRendererBatchSize:4096,particleRendererBatchSize:8192,primitiveRendererBatchSize:65536,gamepadDefinitions:[],pointerDistanceThreshold:10,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1},resourcePath:"",requestOptions:{method:"GET",mode:"cors",cache:"default"},cache:void 0,backend:Gr};class Vr{constructor(t,e=0){this._quadTrees=new Map,this._sceneNodes=new Set,this._bounds=t.clone(),this.level=e}addSceneNode(t){const e=this._getQuadTree(t);return e?(e.addSceneNode(t),this):(this._sceneNodes.add(t),this._sceneNodes.size>Vr.maxSceneNodes&&this.level<Vr.maxLevel&&this._split(),this)}getRelatedChildren(t){const e=this._getQuadTree(t);return null===e?[...this._sceneNodes]:[...e.getRelatedChildren(t),...this._sceneNodes]}getBounds(){return this._bounds}clear(){if(this._quadTrees.size>0){for(const t of this._quadTrees.values())t.destroy();this._quadTrees.clear()}return this._sceneNodes.clear(),this}destroy(){this.clear(),this._bounds.destroy()}_getQuadTree(t){if(this._quadTrees.size>0){const e=t.getBounds();for(const t of this._quadTrees.values())if(t.getBounds().containsRect(e))return t}return null}_split(){if(0===this._quadTrees.size){const{top:t,left:e,width:i,height:r}=this.getBounds(),s=i/2|0,n=r/2|0,o=this.level+1;this._quadTrees.set(0,new Vr(Kt.temp.set(e,t,s,n),o)),this._quadTrees.set(1,new Vr(Kt.temp.set(e+s,t,s,n),o)),this._quadTrees.set(2,new Vr(Kt.temp.set(e,t+n,s,n),o)),this._quadTrees.set(3,new Vr(Kt.temp.set(e+s,t+n,s,n),o))}this._passSceneNodesToQuadTrees()}_passSceneNodesToQuadTrees(){for(const t of this._sceneNodes){const e=this._getQuadTree(t);e&&(this._sceneNodes.delete(t),e.addSceneNode(t))}}}Vr.maxSceneNodes=50,Vr.maxLevel=5;class Or extends he{constructor(){super(...arguments),this._children=[],this._sortableChildren=!1,this._sortDirty=!1,this._nextChildOrder=0}get children(){return this._children}get sortableChildren(){return this._sortableChildren}set sortableChildren(t){this._sortableChildren!==t&&(this._sortableChildren=t,this._sortDirty=t)}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this.scale.x=t/this.bounds.width}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this.scale.y=t/this.bounds.height}get left(){return this.x-this.width*this.origin.x}get top(){return this.y-this.height*this.origin.y}get right(){return this.x+this.width-this.origin.x}get bottom(){return this.y+this.height-this.origin.y}addChild(t){return this.addChildAt(t,this._children.length)}addChildAt(t,e){if(e<0||e>this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return t===this||(t.parentNode&&t.parentNode.removeChild(t),t.parentNode=this,t.setChildOrder(this._nextChildOrder++),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache()),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),r=this.getChildIndex(e);this._children[i]=e,this._children[r]=t,this.markSortDirty(),this.invalidateCache()}return this}getChildIndex(t){const e=this._children.indexOf(t);if(-1===e)throw new Error("Drawable is not a child of the container.");return e}setChildIndex(t,e){if(e<0||e>=this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return T(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache(),this}getChildAt(t){if(t<0||t>=this._children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this._children[t]}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&this.removeChildAt(e),this}removeChildAt(t){const e=this._children[t];return T(this._children,t,1),e&&e.parentNode===this&&(e.parentNode=null),this.markSortDirty(),this.invalidateCache(),this}removeChildren(t=0,e=this._children.length){const i=e-t;if(i<0||i>e)throw new Error("Values are outside the acceptable range.");for(let i=t;i<e;i++){const t=this._children[i];t&&t.parentNode===this&&(t.parentNode=null)}return T(this._children,t,i),this.markSortDirty(),this.invalidateCache(),this}render(t){return this.visible&&0!==this._children.length?this.inView(t.view)?(this.renderVisualContent(t,()=>{this._sortChildrenIfNeeded();for(const e of this._children)e.render(t)}),this):(t.stats.culledNodes++,this):this}contains(t,e){return this._children.some(i=>i.contains(t,e))}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const t of this._children)t.visible&&this._bounds.addRect(t.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}markSortDirty(){return this._sortableChildren&&(this._sortDirty=!0),this}sortChildren(){return!this._sortableChildren||!this._sortDirty||this._children.length<=1?(this._sortDirty=!1,this):(this._children.sort((t,e)=>t.zIndex===e.zIndex?t.childOrder-e.childOrder:t.zIndex-e.zIndex),this._sortDirty=!1,this.invalidateCache(),this)}_sortChildrenIfNeeded(){this._sortableChildren&&this._sortDirty&&this.sortChildren()}}class zr{static create(t){return Object.assign(new zr,t)}constructor(){this._app=null,this._root=new Or,this._stackMode="overlay",this._inputMode="capture"}get app(){return this._app}set app(t){this._app=t}get root(){return this._root}get stackMode(){return this._stackMode}set stackMode(t){this._stackMode=t}get inputMode(){return this._inputMode}set inputMode(t){this._inputMode=t}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}setParticipationPolicy(t){return t.mode&&(this._stackMode=t.mode),t.input&&(this._inputMode=t.input),this}getParticipationPolicy(){return{mode:this._stackMode,input:this._inputMode}}load(t){}init(t){}update(t){}draw(t){}handleInput(t){}unload(t){}destroy(){this._root.destroy(),this._app=null}}class Wr extends B{constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}set limit(t){this._limit.copy(t)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/n.seconds}get remainingMinutes(){return this.remainingMilliseconds/n.minutes}get remainingHours(){return this.remainingMilliseconds/n.hours}}const qr=new Map([["DPad",[.22,.58]],["DPadUp",[.22,.5]],["DPadDown",[.22,.66]],["DPadLeft",[.14,.58]],["DPadRight",[.3,.58]],["ButtonNorth",[.78,.5]],["ButtonWest",[.7,.58]],["ButtonEast",[.86,.58]],["ButtonSouth",[.78,.66]],["LeftShoulder",[.28,.28]],["RightShoulder",[.72,.28]],["LeftTrigger",[.2,.16]],["RightTrigger",[.8,.16]],["Select",[.46,.5]],["Start",[.54,.5]],["LeftStick",[.38,.66]],["RightStick",[.62,.66]]]),Hr=new Map([["ButtonNorth",t.GamepadChannel.ButtonNorth],["ButtonWest",t.GamepadChannel.ButtonWest],["ButtonEast",t.GamepadChannel.ButtonEast],["ButtonSouth",t.GamepadChannel.ButtonSouth],["LeftShoulder",t.GamepadChannel.LeftShoulder],["RightShoulder",t.GamepadChannel.RightShoulder],["LeftTrigger",t.GamepadChannel.LeftTrigger],["RightTrigger",t.GamepadChannel.RightTrigger],["Select",t.GamepadChannel.Select],["Start",t.GamepadChannel.Start],["LeftStick",t.GamepadChannel.LeftStick],["RightStick",t.GamepadChannel.RightStick],["DPadUp",t.GamepadChannel.DPadUp],["DPadDown",t.GamepadChannel.DPadDown],["DPadLeft",t.GamepadChannel.DPadLeft],["DPadRight",t.GamepadChannel.DPadRight]]),Xr=new Map([["ButtonNorth","North"],["ButtonWest","West"],["ButtonEast","East"],["ButtonSouth","South"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Select"],["Start","Start"],["LeftStick","L3"],["RightStick","R3"]]),jr=new Map([["ButtonNorth","Y"],["ButtonWest","X"],["ButtonEast","B"],["ButtonSouth","A"],["LeftShoulder","LB"],["RightShoulder","RB"],["LeftTrigger","LT"],["RightTrigger","RT"],["Select","View"],["Start","Menu"],["LeftStick","L3"],["RightStick","R3"]]),Yr=new Map([["ButtonNorth","Triangle"],["ButtonWest","Square"],["ButtonEast","Circle"],["ButtonSouth","Cross"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Create"],["Start","Options"],["LeftStick","L3"],["RightStick","R3"]]),$r=new Map([["ButtonNorth","X"],["ButtonWest","Y"],["ButtonEast","A"],["ButtonSouth","B"],["LeftShoulder","L"],["RightShoulder","R"],["LeftTrigger","ZL"],["RightTrigger","ZR"],["Select","Minus"],["Start","Plus"],["LeftStick","L3"],["RightStick","R3"]]),Kr=new Map([[t.GamepadMappingFamily.GenericDualAnalog,Xr],[t.GamepadMappingFamily.Xbox,jr],[t.GamepadMappingFamily.PlayStation,Yr],[t.GamepadMappingFamily.SwitchPro,$r],[t.GamepadMappingFamily.JoyConLeft,$r],[t.GamepadMappingFamily.JoyConRight,$r],[t.GamepadMappingFamily.GameCube,Xr],[t.GamepadMappingFamily.SteamController,Xr],[t.GamepadMappingFamily.ArcadeStick,Xr]]);class Qr{static getControlPosition(t){return qr.get(t)??[.5,.5]}static getControlLabels(t){return Kr.get(t)??Xr}static buildControlChannelMap(){return Hr}}Qr.controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];class Zr{constructor(t,{onStart:e,onStop:i,onActive:r,onTrigger:s,context:n,threshold:o}={}){this.channels=new Set,this.valueState=0,this.onStart=new E,this.onStop=new E,this.onActive=new E,this.onTrigger=new E,this.channels=new Set(Array.isArray(t)?t:[t]),this.triggerTimer=new Wr(b(o??Zr.triggerThreshold)),e&&this.onStart.add(e,n),i&&this.onStop.add(i,n),r&&this.onActive.add(r,n),s&&this.onTrigger.add(s,n)}get activeChannels(){return this.channels}get value(){return this.valueState}update(t){this.valueState=0;for(const e of this.channels)this.valueState=Math.max(t[e],this.valueState);return this.valueState?(this.triggerTimer.running||(this.triggerTimer.restart(),this.onStart.dispatch(this.valueState)),this.onActive.dispatch(this.valueState)):this.triggerTimer.running&&(this.onStop.dispatch(this.valueState),this.triggerTimer.expired||this.onTrigger.dispatch(this.valueState),this.triggerTimer.stop()),this}destroy(){this.channels.clear(),this.triggerTimer.destroy(),this.onStart.destroy(),this.onStop.destroy(),this.onActive.destroy(),this.onTrigger.destroy()}}function Jr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}Zr.triggerThreshold=300;var ts,es={exports:{}};var is=function(){if(ts)return es.exports;function t(t,i,s){s=s||2;var n,o,a,u,d,p,_,f=i&&i.length,m=f?i[0]*s:t.length,g=e(t,0,m,s,!0),y=[];if(!g||g.next===g.prev)return y;if(f&&(g=function(t,i,r,s){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*s,n<o-1?i[n+1]*s:t.length,s,!1))===a.next&&(a.steiner=!0),u.push(c(a));for(u.sort(h),n=0;n<u.length;n++)r=l(u[n],r);return r}(t,i,g,s)),t.length>80*s){n=a=t[0],o=u=t[1];for(var x=s;x<m;x+=s)(d=t[x])<n&&(n=d),(p=t[x+1])<o&&(o=p),d>a&&(a=d),p>u&&(u=p);_=0!==(_=Math.max(a-n,u-o))?32767/_:0}return r(g,y,s,n,o,_,0),y}function e(t,e,i,r,s){var n,o;if(s===C(t,e,i,r)>0)for(n=e;n<i;n+=r)o=b(n,t[n],t[n+1],o);else for(n=i-r;n>=e;n-=r)o=b(n,t[n],t[n+1],o);return o&&m(o,o.next)&&(S(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,r=t;do{if(i=!1,r.steiner||!m(r,r.next)&&0!==f(r.prev,r,r.next))r=r.next;else{if(S(r),(r=e=r.prev)===r.next)break;i=!0}}while(i||r!==e);return e}function r(t,e,h,l,u,c,p){if(t){!p&&c&&function(t,e,i,r){var s=t;do{0===s.z&&(s.z=d(s.x,s.y,e,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,r,s,n,o,a,h,l=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,r=i,a=0,e=0;e<l&&(a++,r=r.nextZ);e++);for(h=l;a>0||h>0&&r;)0!==a&&(0===h||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,h--),n?n.nextZ=s:t=s,s.prevZ=n,n=s;i=r}n.nextZ=null,l*=2}while(o>1)}(s)}(t,l,u,c);for(var _,f,m=t;t.prev!==t.next;)if(_=t.prev,f=t.next,c?n(t,l,u,c):s(t))e.push(_.i/h|0),e.push(t.i/h|0),e.push(f.i/h|0),S(t),t=f.next,m=f.next;else if((t=f)===m){p?1===p?r(t=o(i(t),e,h),e,h,l,u,c,2):2===p&&a(t,e,h,l,u,c):r(i(t),e,h,l,u,c,1);break}}}function s(t){var e=t.prev,i=t,r=t.next;if(f(e,i,r)>=0)return!1;for(var s=e.x,n=i.x,o=r.x,a=e.y,h=i.y,l=r.y,u=s<n?s<o?s:o:n<o?n:o,d=a<h?a<l?a:l:h<l?h:l,c=s>n?s>o?s:o:n>o?n:o,_=a>h?a>l?a:l:h>l?h:l,m=r.next;m!==e;){if(m.x>=u&&m.x<=c&&m.y>=d&&m.y<=_&&p(s,a,n,h,o,l,m.x,m.y)&&f(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function n(t,e,i,r){var s=t.prev,n=t,o=t.next;if(f(s,n,o)>=0)return!1;for(var a=s.x,h=n.x,l=o.x,u=s.y,c=n.y,_=o.y,m=a<h?a<l?a:l:h<l?h:l,g=u<c?u<_?u:_:c<_?c:_,y=a>h?a>l?a:l:h>l?h:l,x=u>c?u>_?u:_:c>_?c:_,w=d(m,g,e,i,r),v=d(y,x,e,i,r),b=t.prevZ,S=t.nextZ;b&&b.z>=w&&S&&S.z<=v;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==s&&b!==o&&p(a,u,h,c,l,_,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,S.x>=m&&S.x<=y&&S.y>=g&&S.y<=x&&S!==s&&S!==o&&p(a,u,h,c,l,_,S.x,S.y)&&f(S.prev,S,S.next)>=0)return!1;S=S.nextZ}for(;b&&b.z>=w;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==s&&b!==o&&p(a,u,h,c,l,_,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;S&&S.z<=v;){if(S.x>=m&&S.x<=y&&S.y>=g&&S.y<=x&&S!==s&&S!==o&&p(a,u,h,c,l,_,S.x,S.y)&&f(S.prev,S,S.next)>=0)return!1;S=S.nextZ}return!0}function o(t,e,r){var s=t;do{var n=s.prev,o=s.next.next;!m(n,o)&&g(n,s,s.next,o)&&w(n,o)&&w(o,n)&&(e.push(n.i/r|0),e.push(s.i/r|0),e.push(o.i/r|0),S(s),S(s.next),s=t=o),s=s.next}while(s!==t);return i(s)}function a(t,e,s,n,o,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&_(h,l)){var u=v(h,l);return h=i(h,h.next),u=i(u,u.next),r(h,e,s,n,o,a,0),void r(u,e,s,n,o,a,0)}l=l.next}h=h.next}while(h!==t)}function h(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var i,r=e,s=t.x,n=t.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o&&(o=a,i=r.x<r.next.x?r:r.next,a===s))return i}r=r.next}while(r!==e);if(!i)return null;var h,l=i,d=i.x,c=i.y,_=1/0;r=i;do{s>=r.x&&r.x>=d&&s!==r.x&&p(n<c?s:o,n,d,c,n<c?o:s,n,r.x,r.y)&&(h=Math.abs(n-r.y)/(s-r.x),w(r,t)&&(h<_||h===_&&(r.x>i.x||r.x===i.x&&u(i,r)))&&(i=r,_=h)),r=r.next}while(r!==l);return i}(t,e);if(!r)return e;var s=v(r,t);return i(s,s.next),i(r,r.next)}function u(t,e){return f(t.prev,t,e.prev)<0&&f(e.next,t,t.next)<0}function d(t,e,i,r,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*s|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function c(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,r,s,n,o,a){return(s-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(r-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(s-o)*(r-a)}function _(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&g(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(w(t,e)&&w(e,t)&&function(t,e){var i=t,r=!1,s=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==t);return r}(t,e)&&(f(t.prev,t,e.prev)||f(t,e.prev,e))||m(t,e)&&f(t.prev,t,t.next)>0&&f(e.prev,e,e.next)>0)}function f(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function m(t,e){return t.x===e.x&&t.y===e.y}function g(t,e,i,r){var s=x(f(t,e,i)),n=x(f(t,e,r)),o=x(f(i,r,t)),a=x(f(i,r,e));return s!==n&&o!==a||(!(0!==s||!y(t,i,e))||(!(0!==n||!y(t,r,e))||(!(0!==o||!y(i,t,r))||!(0!==a||!y(i,e,r)))))}function y(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function w(t,e){return f(t.prev,t,t.next)<0?f(t,e,t.next)>=0&&f(t,t.prev,e)>=0:f(t,e,t.prev)<0||f(t,t.next,e)<0}function v(t,e){var i=new T(t.i,t.x,t.y),r=new T(e.i,e.x,e.y),s=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function b(t,e,i,r){var s=new T(t,e,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function S(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function T(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function C(t,e,i,r){for(var s=0,n=e,o=i-r;n<i;n+=r)s+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return s}return ts=1,es.exports=t,es.exports.default=t,t.deviation=function(t,e,i,r){var s=e&&e.length,n=s?e[0]*i:t.length,o=Math.abs(C(t,0,n,i));if(s)for(var a=0,h=e.length;a<h;a++){var l=e[a]*i,u=a<h-1?e[a+1]*i:t.length;o-=Math.abs(C(t,l,u,i))}var d=0;for(a=0;a<r.length;a+=3){var c=r[a]*i,p=r[a+1]*i,_=r[a+2]*i;d+=Math.abs((t[c]-t[_])*(t[p+1]-t[c+1])-(t[c]-t[p])*(t[_+1]-t[c+1]))}return 0===o&&0===d?0:Math.abs((d-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},r=0,s=0;s<t.length;s++){for(var n=0;n<t[s].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[s][n][o]);s>0&&(r+=t[s-1].length,i.holes.push(r))}return i},es.exports}(),rs=Jr(is);const ss=(t,e,i,r,s,n=[],o=[])=>{const a=[t,e,i,r],h=s/2,l=n.length/6,u=new re(t-i,e-r).perp().normalize().multiply(h),d=new re(i-t,r-e).perp().normalize().multiply(h);return n.push(t-u.x,e-u.y),n.push(t+u.x,e+u.y),n.push(i-d.x,r-d.y),n.push(i+d.x,r+d.y),o.push(l,l,l+1,l+2,l+3,l+3),new de({vertices:n,indices:o,points:a})},ns=(t,e,i=[],r=[])=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const s=e/2,n=new re(t[0],t[1]),o=new re(t[t.length-2],t[t.length-1]);if(n.x===o.x&&n.y===o.y){(t=t.slice()).pop(),t.pop(),o.set(t[t.length-2],t[t.length-1]);const e=o.x+.5*(n.x-o.x),i=o.y+.5*(n.y-o.y);t.unshift(e,i),t.push(e,i)}const a=t.length/2;let h=t.length,l=i.length/6,u=t[0],d=t[1],c=t[2],p=t[3],_=0,f=0,m=-(d-p),g=u-c,y=0,x=0,w=0,v=0,b=Math.sqrt(m*m+g*g);m/=b,g/=b,m*=s,g*=s,i.push(u-m,d-g),i.push(u+m,d+g);for(let e=1;e<a-1;e++){u=t[2*(e-1)],d=t[2*(e-1)+1],c=t[2*e],p=t[2*e+1],_=t[2*(e+1)],f=t[2*(e+1)+1],m=-(d-p),g=u-c,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=s,g*=s,y=-(p-f),x=c-_,b=Math.sqrt(y*y+x*x),y/=b,x/=b,y*=s,x*=s;const r=-g+d-(-g+p),n=-m+c-(-m+u),o=(-m+u)*(-g+p)-(-m+c)*(-g+d),a=-x+f-(-x+p),l=-y+c-(-y+_),S=(-y+_)*(-x+p)-(-y+c)*(-x+f);let T=r*l-a*n;if(Math.abs(T)<.1){T+=10.1,i.push(c-m,p-g),i.push(c+m,p+g);continue}const C=(n*S-l*o)/T,M=(a*o-r*S)/T;(C-c)*(C-c)+(M-p)*(M-p)>196*s*s?(w=m-y,v=g-x,b=Math.sqrt(w*w+v*v),w/=b,v/=b,w*=s,v*=s,i.push(c-w,p-v),i.push(c+w,p+v),i.push(c-w,p-v),h++):(i.push(C,M),i.push(c-(C-c),p-(M-p)))}u=t[2*(a-2)],d=t[2*(a-2)+1],c=t[2*(a-1)],p=t[2*(a-1)+1],m=-(d-p),g=u-c,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=s,g*=s,i.push(c-m,p-g),i.push(c+m,p+g),r.push(l);for(let t=0;t<h;t++)r.push(l++);return r.push(l-1),new de({vertices:i,indices:r,points:t})},os=(t,e,i,r,s=[],n=[])=>{const o=Math.floor(15*Math.sqrt(i+r)),a=2*Math.PI/o,h=[];let l=s.length/6;n.push(l);for(let u=0;u<o+1;u++){const o=t+Math.sin(a*u)*i,d=e+Math.cos(a*u)*r;h.push(o,d),s.push(t,e),s.push(o,d),n.push(l++,l++)}return n.push(l-1),new de({vertices:s,indices:n,points:h})},as=(t,e=[],i=[])=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const r=e.length/6,s=t.length/2,n=rs(t,[],2);if(n){for(let t=0;t<n.length;t+=3)i.push(n[t]+r),i.push(n[t]+r),i.push(n[t+1]+r),i.push(n[t+2]+r),i.push(n[t+2]+r);for(let i=0;i<s;i++)e.push(t[2*i],t[2*i+1])}return new de({vertices:e,indices:i,points:t})},hs=(t,e,i,r,s=[],n=[])=>{const o=[t,e,t+i,e,t,e+r,t+i,e+r],a=s.length/6;return s.push(...o),n.push(a,a,a+1,a+2,a+3,a+3),new de({vertices:s,indices:n,points:o})},ls=(t,e,i,r,s=r/2,n=0)=>{const o=Math.PI/-2+n,a=2*i,h=R/a,l=[];for(let i=0;i<a;i++){const n=o+i*h,a=i%2?s:r;l.push(t+a*Math.cos(n),e+a*Math.sin(n))}return as(l)};let us=null;class ds{constructor(t=0,e=0,i=0,r=0){this.collisionType=1,this._fromPosition=new re(t,e),this._toPosition=new re(i,r)}get fromPosition(){return this._fromPosition}set fromPosition(t){this._fromPosition.copy(t)}get fromX(){return this._fromPosition.x}set fromX(t){this._fromPosition.x=t}get fromY(){return this._fromPosition.y}set fromY(t){this._fromPosition.y=t}get toPosition(){return this._toPosition}set toPosition(t){this._toPosition.copy(t)}get toX(){return this._toPosition.x}set toX(t){this._toPosition.x=t}get toY(){return this._toPosition.y}set toY(t){this._toPosition.y=t}set(t,e,i,r){return this._fromPosition.set(t,e),this._toPosition.set(i,r),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new ds(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:r}=this,s=Math.min(t,i),n=Math.min(e,r);return new Kt(s,n,Math.max(t,i)-s,Math.max(e,r)-n)}getNormals(){return[]}project(t,e=new st){return e}intersectsWith(t){switch(t.collisionType){case 6:return Ct(this,t.getBounds());case 2:return Ct(this,t);case 5:return Bt(this,t);case 3:return Mt(this,t);case 4:return Pt(this,t);case 1:return Tt(this,t);case 0:return xt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return xt(re.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:r}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==r&&this.toY!==r)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===us&&(us=new ds),us}}let cs=null;class ps{constructor(t=0,e=0,i=0){this.collisionType=3,this._collisionVertices=null,this._position=new re(t,e),this._radius=i}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t){return this._radius=t,this}set(t,e,i){return this._position.set(t,e),this._radius=i,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this}clone(){return new ps(this.x,this.y,this.radius)}equals({x:t,y:e,radius:i}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.radius!==i)}getBounds(){return new Kt(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){return this.getCollisionVertices().map((t,e,i)=>i[(e+1)%i.length].clone().subtract(t.x,t.y).rperp().normalize())}project(t,e=new st){const i=t.dot(this.x,this.y),r=this.radius*t.length;return e.set(i-r,i+r)}contains(t,e){return vt(re.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Rt(t.getBounds(),this);case 2:return Rt(t,this);case 5:return Gt(this,t);case 3:return kt(this,t);case 4:return Lt(this,t);case 1:return Mt(t,this);case 0:return vt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return qt(this,t.getBounds());case 2:return qt(this,t);case 5:return Ht(t,this,!0);case 3:return Wt(this,t);default:return null}}destroy(){this._position.destroy()}getCollisionVertices(){if(null===this._collisionVertices){this._collisionVertices=[];for(let t=0;t<ps.collisionSegments;t++)this._collisionVertices.push(this.getCollisionVertex(t))}return this._collisionVertices}getCollisionVertex(t){const e=2*t*Math.PI/ps.collisionSegments-Math.PI/2,i=Math.cos(e)*this._radius,r=Math.sin(e)*this._radius;return new re(this._radius+i,this._radius+r)}static get temp(){return null===cs&&(cs=new ps),cs}}ps.collisionSegments=32;class _s{constructor(t=0,e=0,i=0,r=i){this.collisionType=4,this._position=new re(t,e),this._radius=new re(i,r)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius.copy(t)}get rx(){return this._radius.x}set rx(t){this._radius.x=t}get ry(){return this._radius.y}set ry(t){this._radius.y=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t,e=t){return this._radius.set(t,e),this}set(t,e,i,r){return this._position.set(t,e),this._radius.set(i,r),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new _s(this.x,this.y,this.rx,this.ry)}getBounds(){return new Kt(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new st){return e}intersectsWith(t){switch(t.collisionType){case 6:return At(t.getBounds(),this);case 2:return At(t,this);case 5:return Vt(this,t);case 3:return Lt(t,this);case 4:return Ut(this,t);case 1:return Pt(t,this);case 0:return bt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e){return bt(re.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:r}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==r&&this.ry!==r)}destroy(){this._position.destroy(),this._radius.destroy()}}let fs=null;class ms{constructor(t=[],e=0,i=0){this.collisionType=5,this._points=[],this._edges=[],this._normals=[],this._position=new re(e,i),this.setPoints(t)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}get normals(){return this._normals}setPosition(t,e){return this._position.set(t,e),this}setPoints(t){const e=this._points.length,i=t.length,r=e-i,s=Math.min(e,i);for(let e=0;e<s;e++)this._points[e].copy(t[e]);if(r>0)this._points.splice(i).forEach(t=>t.destroy()),this._edges.splice(i).forEach(t=>t.destroy()),this._normals.splice(i).forEach(t=>t.destroy());else if(r<0)for(let r=e;r<i;r++)this._points.push(t[r].clone()),this._edges.push(t[r].clone()),this._normals.push(t[r].clone());for(let t=0;t<i;t++){const e=this._points[t],r=this._points[(t+1)%i];this._edges[t].set(r.x-e.x,r.y-e.y),this._normals[t].copy(this._edges[t]).rperp().normalize()}return this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this}clone(){return new ms(this.points,this.x,this.y)}equals({x:t,y:e,points:i}={}){return(void 0===t||this.x===t)&&(void 0===e||this.y===e)&&(void 0===i||this.points.length===i.length&&this.points.every((t,e)=>t.equals(i[e])))}getBounds(){let t=1/0,e=1/0,i=-1/0,r=-1/0;for(const s of this._points)t=Math.min(s.x,t),e=Math.min(s.y,e),i=Math.max(s.x,i),r=Math.max(s.y,r);return new Kt(this.x+t,this.y+e,i-t,r-e)}getNormals(){return this._normals}project(t,e=new st){const i=t.clone().normalize(),r=this._points.map(t=>i.dot(t.x,t.y));return e.set(Math.min(...r),Math.max(...r))}contains(t,e){return St(re.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Ft(t.getBounds(),this);case 2:return Ft(t,this);case 5:return Ot(this,t);case 3:return Gt(t,this);case 4:return Vt(t,this);case 1:return Bt(t,this);case 0:return St(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:case 2:case 5:return Xt(this,t);case 3:return Ht(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();this._position.destroy(),this._points.length=0}static get temp(){return null===fs&&(fs=new ms),fs}}let gs=null;class ys{constructor(t=0,e=0,i=0,r=0){this._startPoint=new re(t,e),this._endPoint=new re(i,r)}get startPoint(){return this._startPoint}set startPoint(t){this._startPoint.copy(t)}get startX(){return this._startPoint.x}set startX(t){this._startPoint.x=t}get startY(){return this._startPoint.y}set startY(t){this._startPoint.y=t}get endPoint(){return this._endPoint}set endPoint(t){this._endPoint.copy(t)}get endX(){return this._endPoint.x}set endX(t){this._endPoint.x=t}get endY(){return this._endPoint.y}set endY(t){this._endPoint.y=t}set(t,e,i,r){return this._startPoint.set(t,e),this._endPoint.set(i,r),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new ys(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:r}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==r&&this.endY!==r)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===gs&&(gs=new ys),gs}}class xs{constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new xs(t.length,0)}toVector(){return re.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}class ws{constructor(t={}){const{totalLifetime:e,elapsedLifetime:i,position:r,velocity:s,scale:o,rotation:a,rotationSpeed:h,textureIndex:l,tint:u}=t;this._totalLifetime=(e??n.oneSecond).clone(),this._elapsedLifetime=(i??n.zero).clone(),this._position=(r??re.zero).clone(),this._velocity=(s??re.zero).clone(),this._scale=(o??re.one).clone(),this._tint=(u??z.white).clone(),this._rotation=a??0,this._rotationSpeed=h??0,this._textureIndex=l??0}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=k(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get tint(){return this._tint}set tint(t){this._tint.copy(t)}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class vs extends de{constructor(t,e,i){const r=Math.floor(15*Math.sqrt(i+i)),s=2*Math.PI/r,n=[],o=[],a=[];let h=n.length/6;o.push(h);for(let l=0;l<r+1;l++){const r=t+Math.sin(s*l)*i,u=e+Math.cos(s*l)*i;a.push(r,u),n.push(t,e),n.push(r,u),o.push(h++,h++)}o.push(h-1),super({vertices:n,indices:o,points:a})}}class bs extends Or{constructor(){super(...arguments),this._lineWidth=0,this._lineColor=new z,this._fillColor=new z,this._currentPoint=new re(0,0)}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this._lineColor.copy(t)}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor.copy(t)}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof ue))throw new Error("Graphics can only contain DrawableShape children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof ue))throw new Error("Graphics can only contain DrawableShape children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:r}=this._currentPoint;return this.drawPath([i,r,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,r){const{x:s,y:n}=this._currentPoint;return this.drawPath(O(s,n,t,e,i,r)),this.moveTo(i,r),this}bezierCurveTo(t,e,i,r,s,n){const{x:o,y:a}=this._currentPoint;return this.drawPath(V(o,a,t,e,i,r,s,n)),this.moveTo(s,n),this}arcTo(t,e,i,r,s){const{x:n,y:o}=this._currentPoint,a=Math.abs(s);if(0===a||n===t&&o===e||t===i&&e===r)return this.lineTo(t,e);const h=t-n,l=e-o,u=i-t,d=r-e,c=Math.hypot(h,l),p=Math.hypot(u,d);if(0===c||0===p)return this.lineTo(t,e);const _=h/c,f=l/c,m=u/p,g=d/p,y=D(_*m+f*g,-1,1),x=Math.acos(y);if(0===x||x===Math.PI)return this.lineTo(t,e);const w=a/Math.tan(x/2);if(!Number.isFinite(w)||w>c||w>p)return this.lineTo(t,e);const v=t-_*w,b=e-f*w,S=t+m*w,T=e+g*w,C=_*g-f*m>0,M=v+(C?-f:f)*a,P=b+(C?_:-_)*a,B=Math.atan2(b-P,v-M),E=Math.atan2(T-P,S-M);return this.lineTo(v,b),this.drawArc(M,P,a,B,E,C)}drawArc(t,e,i,r,s,n=!1){const o=Math.abs(i);if(0===o)return this;let a=s-r;if(!n&&a<0?a+=R:n&&a>0&&(a-=R),0===a)return this;const h=Math.max(2,Math.ceil(Math.abs(a)/(Math.PI/16))),l=[];for(let i=0;i<=h;i++){const s=r+a*(i/h);l.push(t+Math.cos(s)*o,e+Math.sin(s)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(e,i,r,s){return this.addChild(new ue(ss(e,i,r,s,this._lineWidth),this._lineColor,t.RenderingPrimitives.TriangleStrip)),this}drawPath(e){return this.addChild(new ue(ns(e,this._lineWidth),this._lineColor,t.RenderingPrimitives.TriangleStrip)),this}drawPolygon(e){const i=as(e);return this.addChild(new ue(i,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(i.points),this}drawCircle(e,i,r){const s=new vs(e,i,r);return this.addChild(new ue(s,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawEllipse(e,i,r,s){const n=os(e,i,r,s);return this.addChild(new ue(n,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(n.points),this}drawRectangle(e,i,r,s){const n=hs(e,i,r,s);return this.addChild(new ue(n,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(n.points),this}drawStar(e,i,r,s,n=s/2,o=0){const a=ls(e,i,r,s,n,o);return this.addChild(new ue(a,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(a.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._lineColor.copy(z.black),this._fillColor.copy(z.black),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}}class Ss extends Ie{constructor(t,e){super(t),this._clips=new Map,this._currentClipName=null,this._currentFrameIndex=0,this._playing=!1,this._loopOverride=null,this._elapsedFrameTimeMs=0,this.onComplete=new E,this.onFrame=new E,e&&this.setClips(e)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get loop(){return null!==this._loopOverride?this._loopOverride:!!this._currentClipName&&(this._clips.get(this._currentClipName)?.loop??!1)}set loop(t){this._loopOverride=t}setClips(t){this._clips.clear();for(const[e,i]of Object.entries(t))this.defineClip(e,i);return this}defineClip(t,e){if(0===t.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");if(!Array.isArray(e.frames)||0===e.frames.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const i=e.fps??12;if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${i}).`);return this._clips.set(t,{frames:e.frames.map(t=>t.clone()),frameDurationMs:1e3/i,loop:e.loop??!0}),this}removeClip(t){return this._currentClipName===t&&this.stop(),this._clips.delete(t),this}play(t,e={}){const i=this._clips.get(t);if(!i)throw new Error(`AnimatedSprite clip "${t}" is not defined.`);const r=this._currentClipName===t,s=e.restart??!0;return r&&!s||(this._currentClipName=t,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._applyFrame(i.frames[0]),this.onFrame.dispatch(t,0)),this._loopOverride=e.loop??this._loopOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const t=this._clips.get(this._currentClipName);return t&&t.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(t.frames[0]),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(t){if(!this._playing||null===this._currentClipName)return this;const e=this._clips.get(this._currentClipName);if(!e||e.frames.length<=1)return this;const i="number"==typeof t?t:t.milliseconds;if(i<=0)return this;for(this._elapsedFrameTimeMs+=i;this._elapsedFrameTimeMs>=e.frameDurationMs;){this._elapsedFrameTimeMs-=e.frameDurationMs;const t=this._currentFrameIndex+1;if(t>=e.frames.length){if(this.loop){this._currentFrameIndex=0,this._applyFrame(e.frames[0]),this.onFrame.dispatch(this._currentClipName,0);continue}this._currentFrameIndex=e.frames.length-1,this._applyFrame(e.frames[this._currentFrameIndex]),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=t,this._applyFrame(e.frames[this._currentFrameIndex]),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex)}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const t of this._clips.values())for(const e of t.frames)e.destroy();this._clips.clear()}static fromSpritesheet(t){const e={};for(const[i,r]of t.animations)e[i]={frames:r.map(e=>t.getFrame(e)),loop:!0};return new Ss(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}class Ts{constructor(t={}){this._dirty=!0,this._align=t.align??"left",this._fill=t.fill??"black",this._stroke=t.stroke??"black",this._strokeThickness=t.strokeThickness??1,this._fontSize=t.fontSize??20,this._fontWeight=t.fontWeight??"bold",this._fontFamily=t.fontFamily??"Arial",this._wordWrap=t.wordWrap??!1,this._wordWrapWidth=t.wordWrapWidth??100,this._baseline=t.baseline??"alphabetic",this._lineJoin=t.lineJoin??"miter",this._miterLimit=t.miterLimit??10,this._padding=t.padding??0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._dirty=!0)}get fill(){return this._fill}set fill(t){this._fill!==t&&(this._fill=t,this._dirty=!0)}get stroke(){return this._stroke}set stroke(t){this._stroke!==t&&(this._stroke=t,this._dirty=!0)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this._dirty=!0)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._dirty=!0)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._dirty=!0)}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this._dirty=!0)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this._dirty=!0)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this._dirty=!0)}get baseline(){return this._baseline}set baseline(t){this._baseline!==t&&(this._baseline=t,this._dirty=!0)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this._dirty=!0)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this._dirty=!0)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this._dirty=!0)}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get font(){return`${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}apply(t){return t.font=this.font,t.fillStyle=this.fill,t.strokeStyle=this.stroke,t.lineWidth=this.strokeThickness,t.textBaseline=this.baseline,t.lineJoin=this.lineJoin,t.miterLimit=this.miterLimit,this}copy(t){return t!==this&&(this.align=t.align,this.fill=t.fill,this.stroke=t.stroke,this.strokeThickness=t.strokeThickness,this.fontSize=t.fontSize,this.fontWeight=t.fontWeight,this.fontFamily=t.fontFamily,this.wordWrap=t.wordWrap,this.wordWrapWidth=t.wordWrapWidth,this.baseline=t.baseline,this.lineJoin=t.lineJoin,this.miterLimit=t.miterLimit,this.padding=t.padding,this.dirty=t.dirty),this}clone(){return(new Ts).copy(this)}}const Cs=/(?:\r\n|\r|\n)/;class Ms{}const Ps=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"];class Bs{get connected(){return this._connected}constructor(t,e=1,i=Ps,r){if(this._onCloseHandler=this.disconnect.bind(this),this._connected=!1,this._database=null,!y)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=r}async getObjectStore(t,e="readonly"){return await this.connect(),this._database.transaction([t],e).objectStore(t)}async connect(){return!(!this._connected||!this._database)||new Promise((t,e)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",t=>{const r=i.result,s=i.transaction,n=[...s.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(r.addEventListener("error",()=>e(Error("An error occurred while opening the database."))),r.addEventListener("abort",()=>e(Error("The database opening was aborted."))),this._migrations){const t=Object.keys(this._migrations).map(Number).filter(t=>t>o&&t<=(a??this.version)).sort((t,e)=>t-e);for(const e of t){if(!this._migrations[e](r,s))return void s.abort()}}else{for(const t of n)this._storeNames.includes(t)||r.deleteObjectStore(t);for(const t of this._storeNames)n.includes(t)||r.createObjectStore(t,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,t(!0)}),i.addEventListener("error",()=>e(Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(Error("The request for the database connection has been blocked.")))})}async disconnect(){return this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close(),this._database=null,this._connected=!1),!0}async load(t,e){const i=await this.getObjectStore(t);return new Promise((t,r)=>{const s=i.get(e);s.addEventListener("success",()=>t(s.result?.data??null)),s.addEventListener("error",()=>r(Error("An error occurred while loading an item.")))})}async save(t,e,i){const r=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const n=r.put({name:e,data:i});n.addEventListener("success",()=>t()),n.addEventListener("error",()=>s(Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,r)=>{const s=i.delete(e);s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>r(Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const r=e.clear();r.addEventListener("success",()=>t(!0)),r.addEventListener("error",()=>i(Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((t,e)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>t(!0)),i.addEventListener("error",()=>e(Error("An error occurred while deleting a storage.")))})}destroy(){this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close()),this._database=null,this._connected=!1}}const Es="@dimforge/rapier2d-compat",Rs=65535,As=1/60,Fs={lineWidth:1,solidLineColor:new z(64,196,255,1),solidFillColor:new z(64,196,255,.12),triggerLineColor:new z(255,180,48,1),triggerFillColor:new z(255,180,48,.08)},ks=async()=>await import(Es),Ls=(t,e)=>{if(!Number.isFinite(t))throw new Error(`${e} must be a finite number.`)},Ds=(t,e)=>{if(Ls(t,e),t<=0)throw new Error(`${e} must be greater than zero.`)},Is=(t,e)=>{if(!Number.isInteger(t)||t<0||t>15)throw new Error(`${e} must be an integer between 0 and 15.`)},Ns=(t,e)=>void 0===t?e:"number"==typeof t?(Is(t,"collision group"),1<<t):0===t.length?0:t.reduce((t,e,i)=>(Is(e,`collision groups[${i}]`),t|1<<e),0),Gs=t=>{const e=Ns(t?.membership,1),i=Ns(t?.collidesWith,Rs);return(e&Rs)<<16|i&Rs},Us=t=>({x:t.offsetX??0,y:t.offsetY??0}),Vs=(t,e,i)=>{const r=Math.cos(i),s=Math.sin(i);return{x:t*r-e*s,y:t*s+e*r}},Os=t=>{(t=>{if("box"===t.type)return Ds(t.width,"Box width"),Ds(t.height,"Box height"),Ls(t.offsetX??0,"Box offsetX"),Ls(t.offsetY??0,"Box offsetY"),void Ls(t.offsetRotation??0,"Box offsetRotation");Ds(t.radius,"Circle radius"),Ls(t.offsetX??0,"Circle offsetX"),Ls(t.offsetY??0,"Circle offsetY")})(t.shape),Ls(t.friction??0,"friction"),Ls(t.restitution??0,"restitution"),Ls(t.density??0,"density"),Ls(t.gravityScale??1,"gravityScale"),Ls(t.linearDamping??0,"linearDamping"),Ls(t.angularDamping??0,"angularDamping"),Gs(t.collisionFilter)};class zs{constructor(t,e,i,r,s){this._world=t,this.node=e,this._body=i,this._collider=r,this.bodyType=s.type??"dynamic",this.shape=s.shape,this.trigger=s.trigger??!1,this._syncMode=s.syncMode??"physicsToNode"}get bodyHandle(){return this._body.handle}get colliderHandle(){return this._collider.handle}getBody(){return this._body}get syncMode(){return this._syncMode}set syncMode(t){this._syncMode=t}get x(){return this._body.translation().x}get y(){return this._body.translation().y}get rotation(){return this._body.rotation()}setSyncMode(t){return this._syncMode=t,this}teleport(t,e,i=this.node.rotation){return this._world.writeBodyTransform(this._body,t,e,i,!0),this.node.setPosition(t,e),this.node.setRotation(i),this}syncBodyFromNode(t=!0){return this._world.writeBodyTransform(this._body,this.node.x,this.node.y,this.node.rotation,t),this}syncNodeFromBody(){const t=this._body.translation();return this.node.setPosition(t.x,t.y),this.node.setRotation(this._body.rotation()),this}setCollisionFilter(t){const e=Gs(t);return this._collider.setCollisionGroups(e),this._collider.setSolverGroups(e),this}destroy(){this._world.removeBinding(this)}}class Ws{constructor(t,e,i){this.onCollisionEnter=new E,this.onCollisionExit=new E,this.onTriggerEnter=new E,this.onTriggerExit=new E,this._bindings=new Set,this._nodeBindings=new Map,this._colliderBindings=new Map,this._rapier=t,this._world=e,this._eventQueue=i}static async create(t={}){const e=t.moduleLoader??ks;let i=null;try{i=await e()}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Rapier physics module is unavailable. Install "${Es}" or provide a custom module loader. Original error: ${e}`)}const r=(t=>{const e=t,i=e.Vector2,r=e.World,s=e.EventQueue,n=e.RigidBodyDesc,o=e.ColliderDesc;if("function"!=typeof i||"function"!=typeof r||"function"!=typeof s)throw new Error("Invalid Rapier module loader result. Expected Vector2, World, and EventQueue exports.");if("object"!=typeof n||null===n||"object"!=typeof o||null===o)throw new Error("Invalid Rapier module loader result. Expected RigidBodyDesc and ColliderDesc exports.");const a=e.ActiveEvents,h="number"==typeof a?.COLLISION_EVENTS?a.COLLISION_EVENTS:void 0;return{init:"function"==typeof e.init?e.init:void 0,vector2:i,worldConstructor:r,eventQueueConstructor:s,rigidBodyDescFactory:n,colliderDescFactory:o,activeCollisionEvents:h}})(i);"function"==typeof r.init&&await r.init();const s=t.gravityX??0,n=t.gravityY??9.81;Ls(s,"gravityX"),Ls(n,"gravityY");const o=new r.worldConstructor(new r.vector2(s,n)),a=new r.eventQueueConstructor(!0);return new Ws(r,o,a)}get gravity(){return{x:this._world.gravity.x,y:this._world.gravity.y}}setGravity(t,e){return Ls(t,"gravityX"),Ls(e,"gravityY"),this._world.gravity.x=t,this._world.gravity.y=e,this}hasNode(t){return this._nodeBindings.has(t)}getBinding(t){return this._nodeBindings.get(t)??null}attachNode(t,e){if(this._nodeBindings.has(t))throw new Error("This SceneNode is already attached to a physics body.");Os(e);const i=this.createBodyDescriptor(t,e),r=this._world.createRigidBody(i),s=this.createColliderDescriptor(e),n=this._world.createCollider(s,r),o=new zs(this,t,r,n,e);return this._bindings.add(o),this._nodeBindings.set(t,o),this._colliderBindings.set(n.handle,o),o}detachNode(t){const e=this._nodeBindings.get(t);return e&&this.removeBinding(e),this}step(t=As){if(Ls(t,"deltaSeconds"),t<0)throw new Error("deltaSeconds must be zero or greater.");return this.applyStepDelta(t),this._world.step(this._eventQueue),this.drainCollisionEvents(),this.syncNodeTransforms(),this}syncNodeTransforms(){for(const t of this._bindings)"physicsToNode"===t.syncMode&&t.syncNodeFromBody();return this}createDebugGraphics(t={}){const e=new bs;return e.setCullable(!1),this.updateDebugGraphics(e,t),e}updateDebugGraphics(t,e={}){const i=e.lineWidth??Fs.lineWidth,r=e.solidLineColor??Fs.solidLineColor,s=e.solidFillColor??Fs.solidFillColor,n=e.triggerLineColor??Fs.triggerLineColor,o=e.triggerFillColor??Fs.triggerFillColor;t.clear(),t.lineWidth=i;for(const e of this._bindings){const i={x:e.x,y:e.y},a=e.rotation,h=e.trigger?n:r,l=e.trigger?o:s;if(t.lineColor=h,t.fillColor=l,"box"===e.shape.type){const r=this.buildBoxPath(e.shape,i.x,i.y,a);t.drawPolygon(r)}else{const r=Us(e.shape),s=Vs(r.x,r.y,a);t.drawCircle(i.x+s.x,i.y+s.y,e.shape.radius)}}return t}destroy(){for(const t of Array.from(this._bindings))this.removeBinding(t);this.onCollisionEnter.destroy(),this.onCollisionExit.destroy(),this.onTriggerEnter.destroy(),this.onTriggerExit.destroy()}writeBodyTransform(t,e,i,r,s){t.setTranslation(new this._rapier.vector2(e,i),s),t.setRotation(r,s)}removeBinding(t){this._bindings.has(t)&&(this._bindings.delete(t),this._nodeBindings.delete(t.node),this._colliderBindings.delete(t.colliderHandle),this._world.removeRigidBody(t.getBody()))}createBodyDescriptor(t,e){const i=e.type??"dynamic";let r=this._rapier.rigidBodyDescFactory.dynamic();switch(i){case"static":r=this._rapier.rigidBodyDescFactory.fixed();break;case"kinematic":if("function"==typeof this._rapier.rigidBodyDescFactory.kinematicPositionBased)r=this._rapier.rigidBodyDescFactory.kinematicPositionBased();else{if("function"!=typeof this._rapier.rigidBodyDescFactory.kinematicVelocityBased)throw new Error("Rapier module does not expose a kinematic rigid-body descriptor.");r=this._rapier.rigidBodyDescFactory.kinematicVelocityBased()}break;default:r=this._rapier.rigidBodyDescFactory.dynamic()}return r.setTranslation(t.x,t.y).setRotation(t.rotation).setLinearDamping(e.linearDamping??0).setAngularDamping(e.angularDamping??0).setGravityScale(e.gravityScale??1).lockRotations(e.lockRotation??!1),r}createColliderDescriptor(t){const e=t.shape,i="box"===e.type?this._rapier.colliderDescFactory.cuboid(e.width/2,e.height/2):this._rapier.colliderDescFactory.ball(e.radius),r=Us(e),s=Gs(t.collisionFilter);i.setTranslation(r.x,r.y).setRotation("box"===e.type?e.offsetRotation??0:0).setSensor(t.trigger??!1).setFriction(t.friction??.5).setRestitution(t.restitution??0).setDensity(t.density??1).setCollisionGroups(s).setSolverGroups(s);const n=this._rapier.activeCollisionEvents;return"number"==typeof n&&i.setActiveEvents(n),i}applyStepDelta(t){const e=this._world;"number"==typeof e.timestep&&(e.timestep=t),e.integrationParameters&&"number"==typeof e.integrationParameters.dt&&(e.integrationParameters.dt=t)}drainCollisionEvents(){this._eventQueue.drainCollisionEvents((t,e,i)=>{const r=this._colliderBindings.get(t),s=this._colliderBindings.get(e);if(!r||!s)return;const n=r.trigger||s.trigger,o={started:i,trigger:n,first:r,second:s};n?i?this.onTriggerEnter.dispatch(o):this.onTriggerExit.dispatch(o):i?this.onCollisionEnter.dispatch(o):this.onCollisionExit.dispatch(o)})}buildBoxPath(t,e,i,r){const s=t.width/2,n=t.height/2,o=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}],a=Us(t),h=t.offsetRotation??0,l=[];for(const t of o){const s=Vs(t.x,t.y,h),n={x:s.x+a.x,y:s.y+a.y},o=Vs(n.x,n.y,r);l.push(e+o.x,i+o.y)}return l}}return t.AbstractAssetFactory=pr,t.AbstractMedia=Vi,t.AbstractWebGl2BatchedRenderer=Ae,t.AbstractWebGl2Renderer=ge,t.AbstractWebGpuRenderer=Xe,t.AnimatedSprite=Ss,t.Application=class{constructor(e){this.onResize=new E,this._startupClock=new B,this._activeClock=new B,this._frameClock=new B,this._status=t.ApplicationStatus.Stopped,this._frameCount=0,this._frameRequest=0,this.options={canvas:e?.canvas??document.createElement("canvas"),...Ur,...e,backend:e?.backend??Gr},this.canvas=this.options.canvas,this.canvas.hasAttribute("tabindex")||this.canvas.setAttribute("tabindex","-1"),this.loader=new Ir({resourcePath:this.options.resourcePath,requestOptions:this.options.requestOptions,cache:this.options.cache}),this._backendType=this.resolveInitialBackendType(),this._renderManager=this.createRenderManager(this._backendType),this.inputManager=new Ui(this),this.sceneManager=new pe(this),this._updateHandler=this.update.bind(this),this._startupClock.start()}get status(){return this._status}get startupTime(){return this._startupClock.elapsedTime}get activeTime(){return this._activeClock.elapsedTime}get frameTime(){return this._frameClock.elapsedTime}get frameCount(){return this._frameCount}get renderManager(){return this._renderManager}async start(e){if(this._status===t.ApplicationStatus.Stopped){this._status=t.ApplicationStatus.Loading;try{await this.initializeRenderManager(),await this.sceneManager.setScene(e),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._activeClock.start(),this._status=t.ApplicationStatus.Running}catch(e){throw this._status=t.ApplicationStatus.Stopped,e}}return this}update(){if(this._status===t.ApplicationStatus.Running){const t=this._frameClock.elapsedTime,e=performance.now();this.renderManager.resetStats(),this.inputManager.update();const i=this.renderManager.view;i&&"function"==typeof i.update&&i.update(t.milliseconds),this.sceneManager.update(t),this.renderManager.flush(),this.renderManager.stats.frameTimeMs=performance.now()-e,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===t.ApplicationStatus.Running&&(this._status=t.ApplicationStatus.Halting,cancelAnimationFrame(this._frameRequest),this.sceneManager.setScene(null).catch(t=>{console.error("Application.stop() failed to unload the active scene.",t)}),this._activeClock.stop(),this._frameClock.stop(),this._status=t.ApplicationStatus.Stopped),this}resize(t,e){return this.renderManager.resize(t,e),this.onResize.dispatch(t,e,this),this}destroy(){this.stop(),this.loader.destroy(),this.inputManager.destroy(),this._renderManager.destroy(),this.sceneManager.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy()}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createRenderManager(t){return"webgpu"===t?new ii(this):new He(this)}async initializeRenderManager(){try{await this._renderManager.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._renderManager.destroy(),this._backendType="webgl2",this._renderManager=this.createRenderManager(this._backendType),await this._renderManager.initialize()}}canUseWebGpu(){return!!navigator.gpu}},t.ArcadeStickGamepadMapping=_i,t.AudioAnalyser=class{constructor(t,e={}){this._analyser=null,this._audioContext=null,this._analyserTarget=null;const{fftSize:i,minDecibels:r,maxDecibels:s,smoothingTimeConstant:n}=e;this._media=t,this._fftSize=i??2048,this._minDecibels=r??-100,this._maxDecibels=s??-30,this._smoothingTimeConstant=n??.8,this._frequencyBinCount=this._fftSize/2,this._timeDomainData=new Uint8Array(this._frequencyBinCount),this._frequencyData=new Uint8Array(this._frequencyBinCount),this._preciseTimeDomainData=new Float32Array(this._frequencyBinCount),this._preciseFrequencyData=new Float32Array(this._frequencyBinCount),rr()?this.setupWithAudioContext(ir()):er.once(this.setupWithAudioContext,this)}connect(){if(!this._analyser||null!==this._analyserTarget)return this;const t=this._media.analyserTarget;if(!t)throw new Error("No AudioNode on property analyserTarget.");return this._analyserTarget=t,t.connect(this._analyser),this}get timeDomainData(){return this._analyser&&(this.connect(),this._analyser.getByteTimeDomainData(this._timeDomainData)),this._timeDomainData}get frequencyData(){return this._analyser&&(this.connect(),this._analyser.getByteFrequencyData(this._frequencyData)),this._frequencyData}get preciseTimeDomainData(){return this._analyser&&(this.connect(),this._analyser.getFloatTimeDomainData(this._preciseTimeDomainData)),this._preciseTimeDomainData}get preciseFrequencyData(){return this._analyser&&(this.connect(),this._analyser.getFloatFrequencyData(this._preciseFrequencyData)),this._preciseFrequencyData}destroy(){er.clearByContext(this),this._analyserTarget?.disconnect(),this._analyser?.disconnect()}setupWithAudioContext(t){this._audioContext=t,this._analyser=t.createAnalyser(),this._analyser.fftSize=this._fftSize,this._analyser.minDecibels=this._minDecibels,this._analyser.maxDecibels=this._maxDecibels,this._analyser.smoothingTimeConstant=this._smoothingTimeConstant}},t.BinaryFactory=Pr,t.BlurFilter=class extends Ms{constructor(t={}){super(),this._sprite=new Ie(null),this._sampleTint=z.white.clone(),this._radius=2,this._quality=1,this._radius=Math.max(0,t.radius??2),this._quality=Math.max(1,Math.floor(t.quality??1))}get radius(){return this._radius}set radius(t){this._radius=Math.max(0,t)}get quality(){return this._quality}set quality(t){this._quality=Math.max(1,Math.floor(t))}apply(e,i,r){const s=this._radius,n=this._quality,o=Math.max(1,2*n+1),a=1/(s<=0?1:2*o);this._sampleTint.set(255,255,255,a),this._sprite.setTexture(i).setBlendMode(t.BlendModes.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=r.width,this._sprite.height=r.height,e.execute(new oe(()=>{if(s<=0)this._sprite.setPosition(0,0).render(e);else for(let t=0;t<o;t++){const i=(2*(1===o?0:t/(o-1))-1)*s;this._sprite.setPosition(i,0).render(e),this._sprite.setPosition(0,i).render(e)}},{target:r,view:r.view,clearColor:z.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}},t.Bounds=Qt,t.BundleLoadError=Ar,t.CacheFirstStrategy=class{async resolve(t,e){const{storageName:i,key:r,url:s,requestOptions:n,factory:o}=t;for(const t of e){const e=await t.load(i,r);if(null!=e)try{return await o.create(e),e}catch{await t.delete(i,r)}}const a=await fetch(s,n);if(!a.ok)throw new Error(`Failed to fetch "${s}" (${a.status} ${a.statusText}).`);const h=await o.process(a);for(const t of e)try{await t.save(i,r,h)}catch{}return h}},t.CallbackRenderPass=class{constructor(t){this._callback=t}execute(t){this._callback(t)}},t.Circle=ps,t.CircleGeometry=vs,t.Clock=B,t.Color=z,t.ColorAffector=class{constructor(t,e){this._fromColor=t.clone(),this._toColor=e.clone()}get fromColor(){return this._fromColor}set fromColor(t){this.setFromColor(t)}get toColor(){return this._toColor}set toColor(t){this.setToColor(t)}setFromColor(t){return this._fromColor.copy(t),this}setToColor(t){return this._toColor.copy(t),this}apply(t,e){const i=t.elapsedRatio,{r:r,g:s,b:n,a:o}=this._fromColor,{r:a,g:h,b:l,a:u}=this._toColor;return t.tint.set((a-r)*i+r,(h-s)*i+s,(l-n)*i+n,(u-o)*i+o),this}destroy(){this._fromColor.destroy(),this._toColor.destroy()}},t.ColorFilter=class extends Ms{constructor(t=z.white){super(),this._sprite=new Ie(null),this._color=t.clone()}get color(){return this._color}apply(e,i,r){this._sprite.setTexture(i).setBlendMode(t.BlendModes.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=r.width,this._sprite.height=r.height,e.execute(new oe(()=>{this._sprite.render(e)},{target:r,view:r.view,clearColor:z.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}},t.Container=Or,t.Drawable=le,t.DrawableShape=ue,t.Ellipse=_s,t.FactoryRegistry=cr,t.Filter=Ms,t.Flags=tt,t.FontFactory=_r,t.ForceAffector=class{constructor(t,e){this._acceleration=new re(t,e)}get acceleration(){return this._acceleration}set acceleration(t){this.setAcceleration(t)}setAcceleration(t){return this._acceleration.copy(t),this}apply(t,e){return t.velocity.add(e.seconds*this._acceleration.x,e.seconds*this._acceleration.y),this}destroy(){this._acceleration.destroy()}},t.GameCubeGamepadMapping=yi,t.Gamepad=li,t.GamepadControl=di,t.GamepadMapping=ci,t.GamepadPromptLayouts=Qr,t.GenericDualAnalogGamepadMapping=gi,t.Geometry=de,t.Graphics=bs,t.ImageFactory=gr,t.IndexedDbDatabase=Bs,t.IndexedDbStore=class{constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new Bs(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"],e.migrations)}async load(t,e){return this._db.load(t,e)}async save(t,e,i){return this._db.save(t,e,i)}async delete(t,e){return this._db.delete(t,e)}async clear(t){return this._db.clearStorage(t)}destroy(){this._db.destroy()}},t.Input=Zr,t.InputManager=Ui,t.Interval=st,t.JoyConLeftGamepadMapping=xi,t.JoyConRightGamepadMapping=wi,t.Json=hr,t.JsonFactory=yr,t.Line=ds,t.Loader=Ir,t.Matrix=J,t.Music=nr,t.MusicFactory=wr,t.NetworkOnlyStrategy=class{async resolve(t,e){const i=await fetch(t.url,t.requestOptions);if(!i.ok)throw new Error(`Failed to fetch "${t.url}" (${i.status} ${i.statusText}).`);return t.factory.process(i)}},t.ObservableSize=Jt,t.ObservableVector=Q,t.Particle=Ne,t.ParticleOptions=ws,t.ParticleSystem=Ge,t.PlayStationGamepadMapping=vi,t.Pointer=ui,t.PolarVector=xs,t.Polygon=ms,t.Quadtree=Vr,t.Random=r,t.RapierPhysicsBinding=zs,t.RapierPhysicsWorld=Ws,t.Rectangle=Kt,t.RenderNode=he,t.RenderTarget=se,t.RenderTargetPass=oe,t.RenderTexture=ne,t.RendererRegistry=Ve,t.Sampler=class{constructor(t,e){const{scaleMode:i,wrapMode:r,premultiplyAlpha:s,generateMipMap:n,flipY:o}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=n,this._flipY=o,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this.updateScaleModeParameters()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this.updateWrapModeParameters()),this}bind(t){return this._context.bindSampler(t,this._sampler),this}destroy(){this._context.deleteSampler(this._sampler)}updateScaleModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_MAG_FILTER,this._scaleMode),t.samplerParameteri(this._sampler,t.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_S,this._wrapMode),t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_T,this._wrapMode)}},t.ScaleAffector=class{constructor(t,e){this._scaleFactor=new re(t,e)}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this.setScaleFactor(t)}setScaleFactor(t){return this._scaleFactor.copy(t),this}apply(t,e){return t.scale.add(e.seconds*this._scaleFactor.x,e.seconds*this._scaleFactor.y),this}destroy(){this._scaleFactor.destroy()}},t.Scene=zr,t.SceneManager=pe,t.SceneNode=Zt,t.Segment=ys,t.Shader=ye,t.ShaderAttribute=be,t.ShaderUniform=Se,t.Signal=E,t.Size=i,t.Sound=or,t.SoundFactory=vr,t.Sprite=Ie,t.Spritesheet=class{constructor(t,e){this.frames=new Map,this.sprites=new Map,this.animations=new Map,this.texture=t,this.parse(e)}parse(t,e=!1){e||this.clear();for(const[e,i]of Object.entries(t.frames))this.addFrame(e,i);if(t.animations)for(const[e,i]of Object.entries(t.animations))this.defineAnimation(e,i)}addFrame(t,e){const{x:i,y:r,w:s,h:n}=e.frame,o=new Kt(i,r,s,n),a=new Ie(this.texture);a.setTextureFrame(o),this.frames.set(t,o),this.sprites.set(t,a)}defineAnimation(t,e){if(0===t.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(!Array.isArray(e)||0===e.length)throw new Error(`Spritesheet animation "${t}" must reference at least one frame.`);for(const i of e)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${t}" references missing frame "${i}".`);return this.animations.set(t,[...e]),this}getFrame(t){const e=this.frames.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}getAnimationFrameNames(t){const e=this.animations.get(t);if(!e)throw new Error(`Spritesheet animation named ${t} is not available!`);return e}getFrameSprite(t){const e=this.sprites.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}clear(){for(const t of this.frames.values())t.destroy();this.frames.clear();for(const t of this.sprites.values())t.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}},t.SteamControllerGamepadMapping=bi,t.SvgAsset=ur,t.SvgFactory=Mr,t.SwitchProGamepadMapping=Si,t.Text=class extends Ie{constructor(t,e,i,r=document.createElement("canvas")){super(new Ue(r,i)),this._dirty=!0,this._text=t,this._style=e&&e instanceof Ts?e:new Ts(e),this._canvas=r,this._context=r.getContext("2d"),this.updateTexture()}get text(){return this._text}set text(t){this.setText(t)}get style(){return this._style}set style(t){this.setStyle(t)}get canvas(){return this._canvas}set canvas(t){this.setCanvas(t)}setText(t){return this._text!==t&&(this._text=t,this._dirty=!0),this}setStyle(t){return this._style=t instanceof Ts?t:new Ts(t),this._dirty=!0,this}setCanvas(t){return this._canvas!==t&&(this._canvas=t,this._context=this._getContext(t),this._dirty=!0,this.texture.setSource.call(this.texture,t),this.setTextureFrame(Kt.temp.set(0,0,t.width,t.height))),this}updateTexture(){if(this._style&&(this._dirty||this._style.dirty)){const t=this._canvas,e=this._context,i=this._style.apply(e),r=i.wordWrap?this.getWordWrappedText():this._text,s=(t=>{if(!Re.has(t)){const e=document.body,i=document.createElement("div");i.appendChild(document.createTextNode("M")),i.setAttribute("style",`font: ${t};position:absolute;top:0;left:0`),e.appendChild(i),Re.set(t,i.offsetHeight),e.removeChild(i)}return Re.get(t)})(e.font)+i.strokeThickness,n=r.split(Cs),o=n.map(t=>e.measureText(t)),a=o.reduce((t,e)=>Math.max(t,e.width),0),h=Math.ceil(a+i.strokeThickness+2*i.padding),l=Math.ceil(s*n.length+2*i.padding);h!==t.width||l!==t.height?(t.width=h,t.height=l,this.setTextureFrame(Kt.temp.set(0,0,h,l))):e.clearRect(0,0,h,l),i.apply(e);for(let t=0;t<n.length;t++){const r=o[t],h=a-r.width,l="right"===i.align?h:h/2,u=i.padding+i.strokeThickness/2,d=r.actualBoundingBoxLeft+("left"===i.align?0:l)+u,c=r.actualBoundingBoxAscent+s*t+u;i.stroke&&i.strokeThickness&&e.strokeText(n[t],d,c),i.fill&&e.fillText(n[t],d,c)}this.texture.updateSource(),this._dirty=!1,this._style.dirty=!1}return this}getWordWrappedText(){const t=this._context,e=this._style.wordWrapWidth,i=this._text.split("\n"),r=t.measureText(" ").width;let s=e,n="";for(let o=0;o<i.length;o++){const a=i[o].split(" ");o>0&&(n+="\n");for(let i=0;i<a.length;i++){const o=a[i],h=t.measureText(o).width+r;h>s?(i>0&&(n+="\n"),s=e):s-=h,n+=`${o} `}}return n}render(t){return this.visible&&(this.updateTexture(),super.render(t)),this}_getContext(t){const e=t.getContext("2d");if(null===e)throw new Error("Could not create a 2D canvas context.");return e}},t.TextAsset=lr,t.TextFactory=br,t.TextStyle=Ts,t.Texture=Ue,t.TextureFactory=Sr,t.Time=n,t.Timer=Wr,t.TorqueAffector=class{constructor(t){this._angularAcceleration=t}get angularAcceleration(){return this._angularAcceleration}set angularAcceleration(t){this.setAngularAcceleration(t)}setAngularAcceleration(t){return this._angularAcceleration=t,this}apply(t,e){return t.rotationSpeed+=e.seconds*this._angularAcceleration,this}destroy(){}},t.Transformable=it,t.UniversalEmitter=class{constructor(t,e){this._emissionDelta=0,this._emissionRate=t,this._particleOptions=e??new ws}get emissionRate(){return this._emissionRate}set emissionRate(t){this._emissionRate=t}get particleOptions(){return this._particleOptions}set particleOptions(t){this._particleOptions=t}computeParticleCount(t){const e=this._emissionRate*t.seconds+this._emissionDelta,i=0|e;return this._emissionDelta=e-i,i}apply(t,e){const i=this.computeParticleCount(e),r=this._particleOptions;for(let e=0;e<i;e++){const e=t.requestParticle();e.applyOptions(r),t.emitParticle(e)}return this}destroy(){this._particleOptions.destroy()}},t.Vector=re,t.Video=ar,t.VideoFactory=Cr,t.View=ee,t.VttAsset=dr,t.VttFactory=Rr,t.WasmFactory=Br,t.WebGl2ParticleRenderer=ke,t.WebGl2PrimitiveRenderer=Le,t.WebGl2RenderBuffer=Be,t.WebGl2RenderManager=He,t.WebGl2ShaderBlock=Te,t.WebGl2SpriteRenderer=Fe,t.WebGl2VertexArrayObject=fe,t.WebGpuParticleRenderer=ti,t.WebGpuPrimitiveRenderer=Ye,t.WebGpuRenderManager=ii,t.WebGpuSpriteRenderer=Ke,t.XboxGamepadMapping=Ti,t.bezierCurveTo=V,t.buildCircle=(t,e,i,r=[],s=[])=>{const n=Math.floor(15*Math.sqrt(i+i)),o=2*Math.PI/n,a=[];let h=r.length/6;s.push(h);for(let l=0;l<n+1;l++){const n=t+Math.sin(o*l)*i,u=e+Math.cos(o*l)*i;a.push(n,u),r.push(t,e),r.push(n,u),s.push(h++,h++)}return s.push(h-1),new de({vertices:r,indices:s,points:a})},t.buildEllipse=os,t.buildLine=ss,t.buildPath=ns,t.buildPolygon=as,t.buildRectangle=hs,t.buildStar=ls,t.builtInGamepadDefinitions=Ni,t.canvasSourceToDataUrl=P,t.clamp=D,t.createRapierPhysicsWorld=async(t={})=>await Ws.create(t),t.createRenderStats=Oe,t.createWebGl2ShaderRuntime=Me,t.decodeAudioData=sr,t.defineAssetManifest=Fr,t.degreesPerRadian=F,t.degreesToRadians=L,t.determineMimeType=mr,t.emptyArrayBuffer=S,t.getAudioContext=ir,t.getCanvasSourceSize=C,t.getCollisionCircleCircle=Wt,t.getCollisionCircleRectangle=qt,t.getCollisionPolygonCircle=Ht,t.getCollisionRectangleRectangle=zt,t.getCollisionSat=Xt,t.getDistance=U,t.getOfflineAudioContext=()=>Ki(),t.getPreciseTime=v,t.getTextureSourceSize=M,t.getVoronoiRegion=(t,e)=>{const i=e.dot(t.x,t.y);return i<0?-1:i>t.lengthSq?1:0},t.getWebGpuBlendState=je,t.hours=t=>new n(t,n.hours),t.inRange=G,t.intersectionCircleCircle=kt,t.intersectionCircleEllipse=Lt,t.intersectionCirclePoly=Gt,t.intersectionEllipseEllipse=Ut,t.intersectionEllipsePoly=Vt,t.intersectionLineCircle=Mt,t.intersectionLineEllipse=Pt,t.intersectionLineLine=Tt,t.intersectionLinePoly=Bt,t.intersectionLineRect=Ct,t.intersectionPointCircle=vt,t.intersectionPointEllipse=bt,t.intersectionPointLine=xt,t.intersectionPointPoint=yt,t.intersectionPointPoly=St,t.intersectionPointRect=wt,t.intersectionPolyPoly=Ot,t.intersectionRectCircle=Rt,t.intersectionRectEllipse=At,t.intersectionRectPoly=Ft,t.intersectionRectRect=Et,t.intersectionSat=gt,t.isAudioContextReady=rr,t.isPowerOfTwo=N,t.lerp=I,t.matchesIds=ki,t.milliseconds=b,t.minutes=t=>new n(t,n.minutes),t.noop=f,t.normalizeIds=Fi,t.onAudioContextReady=er,t.parseGamepadDescriptor=Li,t.quadraticCurveTo=O,t.radiansPerDegree=A,t.radiansToDegrees=t=>t*F,t.rand=(t,e)=>(null===u&&(u=new r),u).next(t,e),t.removeArrayItems=T,t.resetRenderStats=ze,t.resolveDefinition=Di,t.resolveGamepadDefinition=Ii,t.seconds=t=>new n(t,n.seconds),t.sign=t=>t&&(t<0?-1:1),t.stopEvent=m,t.supportsCodec=(...t)=>t.some(t=>(()=>{if(!c())throw new Error("Audio codec detection requires a document context.");return null===a&&(a=document.createElement("audio")),a})().canPlayType(t).replace(o,"")),t.supportsEventOptions=()=>{if(null!==d)return d;if(!p())return d=!1,d;let t=!1;try{window.addEventListener("test",f,{get passive(){return t=!0,!1}}),window.removeEventListener("test",f)}catch(t){}return d=t,d},t.supportsIndexedDb=y,t.supportsPointerEvents=w,t.supportsTouchEvents=x,t.supportsWebAudio=g,t.tau=R,t.trimRotation=k,t.webGl2PrimitiveArrayConstructors=we,t.webGl2PrimitiveByteSizeMapping=xe,t.webGl2PrimitiveTypeNames=ve,t}({});
|
|
2
|
+
//# sourceMappingURL=exo.global.min.js.map
|