@codexo/exojs 0.4.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +464 -163
- package/README.md +156 -141
- package/dist/esm/audio/AudioAnalyser.d.ts +0 -1
- package/dist/esm/audio/AudioAnalyser.js +0 -2
- package/dist/esm/audio/AudioAnalyser.js.map +1 -1
- package/dist/esm/core/Application.d.ts +4 -4
- package/dist/esm/core/Application.js +19 -19
- package/dist/esm/core/Application.js.map +1 -1
- package/dist/esm/core/Scene.d.ts +59 -24
- package/dist/esm/core/Scene.js +60 -18
- package/dist/esm/core/Scene.js.map +1 -1
- package/dist/esm/core/SceneManager.js +15 -9
- package/dist/esm/core/SceneManager.js.map +1 -1
- package/dist/esm/core/SceneNode.d.ts +45 -5
- package/dist/esm/core/SceneNode.js +136 -7
- package/dist/esm/core/SceneNode.js.map +1 -1
- package/dist/esm/index.js +3 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/math/index.d.ts +0 -1
- package/dist/esm/rendering/CallbackRenderPass.d.ts +3 -3
- package/dist/esm/rendering/CallbackRenderPass.js +2 -2
- package/dist/esm/rendering/CallbackRenderPass.js.map +1 -1
- package/dist/esm/rendering/Container.d.ts +10 -11
- package/dist/esm/rendering/Container.js +5 -5
- package/dist/esm/rendering/Container.js.map +1 -1
- package/dist/esm/rendering/Drawable.d.ts +2 -2
- package/dist/esm/rendering/Drawable.js +5 -5
- package/dist/esm/rendering/Drawable.js.map +1 -1
- package/dist/esm/rendering/{SceneRenderRuntime.d.ts → RenderBackend.d.ts} +21 -3
- package/dist/esm/rendering/RenderNode.d.ts +41 -5
- package/dist/esm/rendering/RenderNode.js +89 -24
- package/dist/esm/rendering/RenderNode.js.map +1 -1
- package/dist/esm/rendering/RenderPass.d.ts +2 -2
- package/dist/esm/rendering/RenderTargetPass.d.ts +3 -3
- package/dist/esm/rendering/RenderTargetPass.js +9 -9
- package/dist/esm/rendering/RenderTargetPass.js.map +1 -1
- package/dist/esm/rendering/Renderer.d.ts +3 -3
- package/dist/esm/rendering/RendererRegistry.d.ts +13 -7
- package/dist/esm/rendering/RendererRegistry.js +18 -10
- package/dist/esm/rendering/RendererRegistry.js.map +1 -1
- package/dist/esm/rendering/filters/BlurFilter.d.ts +2 -2
- package/dist/esm/rendering/filters/BlurFilter.js +5 -5
- package/dist/esm/rendering/filters/BlurFilter.js.map +1 -1
- package/dist/esm/rendering/filters/ColorFilter.d.ts +2 -2
- package/dist/esm/rendering/filters/ColorFilter.js +3 -3
- package/dist/esm/rendering/filters/ColorFilter.js.map +1 -1
- package/dist/esm/rendering/filters/Filter.d.ts +2 -2
- package/dist/esm/rendering/index.d.ts +6 -6
- package/dist/esm/rendering/primitives/Graphics.d.ts +3 -3
- package/dist/esm/rendering/primitives/Graphics.js.map +1 -1
- package/dist/esm/rendering/shader/Shader.d.ts +3 -3
- package/dist/esm/rendering/shader/Shader.js +10 -10
- package/dist/esm/rendering/text/Text.d.ts +2 -2
- package/dist/esm/rendering/text/Text.js +2 -2
- package/dist/esm/rendering/text/Text.js.map +1 -1
- package/dist/esm/rendering/texture/Sampler.d.ts +0 -3
- package/dist/esm/rendering/texture/Sampler.js +5 -7
- package/dist/esm/rendering/texture/Sampler.js.map +1 -1
- package/dist/esm/rendering/types.d.ts +4 -0
- package/dist/esm/rendering/types.js +4 -0
- package/dist/esm/rendering/types.js.map +1 -1
- package/dist/esm/rendering/video/Video.d.ts +2 -2
- package/dist/esm/rendering/video/Video.js +2 -2
- package/dist/esm/rendering/video/Video.js.map +1 -1
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.d.ts +2 -2
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js +35 -11
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.d.ts +13 -13
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js +20 -20
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/{WebGl2RenderManager.d.ts → WebGl2Backend.d.ts} +15 -12
- package/dist/esm/rendering/webgl2/{WebGl2RenderManager.js → WebGl2Backend.js} +60 -38
- package/dist/esm/rendering/webgl2/WebGl2Backend.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2MaskCompositor.d.ts +31 -0
- package/dist/esm/rendering/webgl2/WebGl2MaskCompositor.js +186 -0
- package/dist/esm/rendering/webgl2/WebGl2MaskCompositor.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.d.ts +38 -7
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js +281 -90
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.d.ts +2 -2
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js +15 -10
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js +12 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2ShaderProgram.d.ts +2 -0
- package/dist/esm/rendering/webgl2/{WebGl2ShaderRuntime.js → WebGl2ShaderProgram.js} +58 -18
- package/dist/esm/rendering/webgl2/WebGl2ShaderProgram.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.d.ts +26 -7
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js +260 -62
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.d.ts +24 -1
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js +6 -2
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js.map +1 -1
- package/dist/esm/rendering/webgl2/glsl/mask-compose.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/mask-compose.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/mask-compose.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/mask-compose.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/particle.vert.js +1 -1
- package/dist/esm/rendering/webgl2/glsl/sprite.frag.js +1 -1
- package/dist/esm/rendering/webgl2/glsl/sprite.vert.js +1 -1
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.d.ts +9 -9
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js +18 -18
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/{WebGpuRenderManager.d.ts → WebGpuBackend.d.ts} +17 -14
- package/dist/esm/rendering/webgpu/{WebGpuRenderManager.js → WebGpuBackend.js} +74 -40
- package/dist/esm/rendering/webgpu/WebGpuBackend.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.d.ts +37 -0
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.js +279 -0
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.d.ts +2 -3
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js +65 -82
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.d.ts +2 -3
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js +24 -25
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.d.ts +28 -13
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js +410 -382
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js.map +1 -1
- package/dist/esm/resources/Loader.js +5 -3
- package/dist/esm/resources/Loader.js.map +1 -1
- package/dist/exo.esm.js +2500 -1399
- package/dist/exo.esm.js.map +1 -1
- package/package.json +20 -11
- package/dist/esm/math/Transformable.d.ts +0 -47
- package/dist/esm/math/Transformable.js +0 -140
- package/dist/esm/math/Transformable.js.map +0 -1
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.js.map +0 -1
- package/dist/esm/rendering/webgl2/WebGl2RendererRuntime.d.ts +0 -15
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.d.ts +0 -2
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js.map +0 -1
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js.map +0 -1
- package/dist/esm/rendering/webgpu/WebGpuRendererRuntime.d.ts +0 -8
- package/dist/exo.esm.min.js +0 -2
- package/dist/exo.esm.min.js.map +0 -1
- package/dist/exo.global.js +0 -17328
- package/dist/exo.global.js.map +0 -1
- package/dist/exo.global.min.js +0 -2
- package/dist/exo.global.min.js.map +0 -1
package/dist/exo.global.min.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var Exo=function(t){"use strict";let e=null;class i{_width;_height;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 zero=new i(0,0);static get temp(){return null===e&&(e=new i),e}}class r{_state=new Uint32Array(624);_iteration=0;_seed=0;_value=0;constructor(t=Date.now()){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{_milliseconds;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 milliseconds=1;static seconds=1e3;static minutes=6e4;static hours=36e5;static zero=new n(0);static oneMillisecond=new n(1);static oneSecond=new n(1,n.seconds);static oneMinute=new n(1,n.minutes);static oneHour=new n(1,n.hours);static get temp(){return null===s&&(s=new n),s}}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{_startTime;_elapsedTime=new n(0);_running=!1;constructor(t=n.zero,e=!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 R{_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){const e=this._bindings.slice();for(const i of e)if(!1===i.handler.call(i.context,...t))break}return this}destroy(){this.clear()}}const E=2*Math.PI,A=Math.PI/180,k=180/Math.PI;var F;t.VoronoiRegion=void 0,(F=t.VoronoiRegion||(t.VoronoiRegion={}))[F.left=-1]="left",F[F.middle=0]="middle",F[F.right=1]="right";const L=t=>{const e=t%360;return e<0?e+360:e},D=t=>t*A,I=(t,e,i)=>Math.min(i,Math.max(e,t)),N=(t,e,i)=>(1-i)*t+i*e,V=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)},O=(t,e,i,r,s,n,o,a,h=[],l=20)=>{h.push(t,e);for(let u=1;u<=l;u++){const 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},z=(t,e,i,r,s,n,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(N(N(t,i,l),N(i,s,l),l),N(N(e,r,l),N(r,n,l),l))}return o};class W{_r;_g;_b;_a;_rgba=null;_array=null;constructor(t=0,e=0,i=0,r=1){this._r=255&t,this._g=255&e,this._b=255&i,this._a=I(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=I(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=I(r,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new W(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)}static aliceBlue=new W(240,248,255,1);static antiqueWhite=new W(250,235,215,1);static aqua=new W(0,255,255,1);static aquamarine=new W(127,255,212,1);static azure=new W(240,255,255,1);static beige=new W(245,245,220,1);static bisque=new W(255,228,196,1);static black=new W(0,0,0,1);static blanchedAlmond=new W(255,235,205,1);static blue=new W(0,0,255,1);static blueViolet=new W(138,43,226,1);static brown=new W(165,42,42,1);static burlyWood=new W(222,184,135,1);static cadetBlue=new W(95,158,160,1);static chartreuse=new W(127,255,0,1);static chocolate=new W(210,105,30,1);static coral=new W(255,127,80,1);static cornflowerBlue=new W(100,149,237,1);static cornsilk=new W(255,248,220,1);static crimson=new W(220,20,60,1);static cyan=new W(0,255,255,1);static darkBlue=new W(0,0,139,1);static darkCyan=new W(0,139,139,1);static darkGoldenrod=new W(184,134,11,1);static darkGray=new W(169,169,169,1);static darkGreen=new W(0,100,0,1);static darkKhaki=new W(189,183,107,1);static darkMagenta=new W(139,0,139,1);static darkOliveGreen=new W(85,107,47,1);static darkOrange=new W(255,140,0,1);static darkOrchid=new W(153,50,204,1);static darkRed=new W(139,0,0,1);static darkSalmon=new W(233,150,122,1);static darkSeaGreen=new W(143,188,139,1);static darkSlateBlue=new W(72,61,139,1);static darkSlateGray=new W(47,79,79,1);static darkTurquoise=new W(0,206,209,1);static darkViolet=new W(148,0,211,1);static deepPink=new W(255,20,147,1);static deepSkyBlue=new W(0,191,255,1);static dimGray=new W(105,105,105,1);static dodgerBlue=new W(30,144,255,1);static firebrick=new W(178,34,34,1);static floralWhite=new W(255,250,240,1);static forestGreen=new W(34,139,34,1);static fuchsia=new W(255,0,255,1);static gainsboro=new W(220,220,220,1);static ghostWhite=new W(248,248,255,1);static gold=new W(255,215,0,1);static goldenrod=new W(218,165,32,1);static gray=new W(128,128,128,1);static green=new W(0,128,0,1);static greenYellow=new W(173,255,47,1);static honeydew=new W(240,255,240,1);static hotPink=new W(255,105,180,1);static indianRed=new W(205,92,92,1);static indigo=new W(75,0,130,1);static ivory=new W(255,255,240,1);static khaki=new W(240,230,140,1);static lavender=new W(230,230,250,1);static lavenderBlush=new W(255,240,245,1);static lawnGreen=new W(124,252,0,1);static lemonChiffon=new W(255,250,205,1);static lightBlue=new W(173,216,230,1);static lightCoral=new W(240,128,128,1);static lightCyan=new W(224,255,255,1);static lightGoldenrodYellow=new W(250,250,210,1);static lightGray=new W(211,211,211,1);static lightGreen=new W(144,238,144,1);static lightPink=new W(255,182,193,1);static lightSalmon=new W(255,160,122,1);static lightSeaGreen=new W(32,178,170,1);static lightSkyBlue=new W(135,206,250,1);static lightSlateGray=new W(119,136,153,1);static lightSteelBlue=new W(176,196,222,1);static lightYellow=new W(255,255,224,1);static lime=new W(0,255,0,1);static limeGreen=new W(50,205,50,1);static linen=new W(250,240,230,1);static magenta=new W(255,0,255,1);static maroon=new W(128,0,0,1);static mediumAquamarine=new W(102,205,170,1);static mediumBlue=new W(0,0,205,1);static mediumOrchid=new W(186,85,211,1);static mediumPurple=new W(147,112,219,1);static mediumSeaGreen=new W(60,179,113,1);static mediumSlateBlue=new W(123,104,238,1);static mediumSpringGreen=new W(0,250,154,1);static mediumTurquoise=new W(72,209,204,1);static mediumVioletRed=new W(199,21,133,1);static midnightBlue=new W(25,25,112,1);static mintCream=new W(245,255,250,1);static mistyRose=new W(255,228,225,1);static moccasin=new W(255,228,181,1);static navajoWhite=new W(255,222,173,1);static navy=new W(0,0,128,1);static oldLace=new W(253,245,230,1);static olive=new W(128,128,0,1);static oliveDrab=new W(107,142,35,1);static orange=new W(255,165,0,1);static orangeRed=new W(255,69,0,1);static orchid=new W(218,112,214,1);static paleGoldenrod=new W(238,232,170,1);static paleGreen=new W(152,251,152,1);static paleTurquoise=new W(175,238,238,1);static paleVioletRed=new W(219,112,147,1);static papayaWhip=new W(255,239,213,1);static peachPuff=new W(255,218,185,1);static peru=new W(205,133,63,1);static pink=new W(255,192,203,1);static plum=new W(221,160,221,1);static powderBlue=new W(176,224,230,1);static purple=new W(128,0,128,1);static red=new W(255,0,0,1);static rosyBrown=new W(188,143,143,1);static royalBlue=new W(65,105,225,1);static saddleBrown=new W(139,69,19,1);static salmon=new W(250,128,114,1);static sandyBrown=new W(244,164,96,1);static seaGreen=new W(46,139,87,1);static seaShell=new W(255,245,238,1);static sienna=new W(160,82,45,1);static silver=new W(192,192,192,1);static skyBlue=new W(135,206,235,1);static slateBlue=new W(106,90,205,1);static slateGray=new W(112,128,144,1);static snow=new W(255,250,250,1);static springGreen=new W(0,255,127,1);static steelBlue=new W(70,130,180,1);static tan=new W(210,180,140,1);static teal=new W(0,128,128,1);static thistle=new W(216,191,216,1);static tomato=new W(255,99,71,1);static transparentBlack=new W(0,0,0,0);static transparentWhite=new W(255,255,255,0);static turquoise=new W(64,224,208,1);static violet=new W(238,130,238,1);static wheat=new W(245,222,179,1);static white=new W(255,255,255,1);static whiteSmoke=new W(245,245,245,1);static yellow=new W(255,255,0,1);static yellowGreen=new W(154,205,50,1)}var q,H,Y,X,j,$,K;t.BlendModes=void 0,(q=t.BlendModes||(t.BlendModes={}))[q.Normal=0]="Normal",q[q.Additive=1]="Additive",q[q.Subtract=2]="Subtract",q[q.Multiply=3]="Multiply",q[q.Screen=4]="Screen",t.ScaleModes=void 0,(H=t.ScaleModes||(t.ScaleModes={}))[H.Nearest=9728]="Nearest",H[H.Linear=9729]="Linear",H[H.NearestMipmapNearest=9984]="NearestMipmapNearest",H[H.LinearMipmapNearest=9985]="LinearMipmapNearest",H[H.NearestMipmapLinear=9986]="NearestMipmapLinear",H[H.LinearMipmapLinear=9987]="LinearMipmapLinear",t.WrapModes=void 0,(Y=t.WrapModes||(t.WrapModes={}))[Y.Repeat=10497]="Repeat",Y[Y.ClampToEdge=33071]="ClampToEdge",Y[Y.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,($=t.BufferUsage||(t.BufferUsage={}))[$.StaticDraw=35044]="StaticDraw",$[$.StaticRead=35045]="StaticRead",$[$.StaticCopy=35046]="StaticCopy",$[$.DynamicDraw=35048]="DynamicDraw",$[$.DynamicRead=35049]="DynamicRead",$[$.DynamicCopy=35050]="DynamicCopy",$[$.StreamDraw=35040]="StreamDraw",$[$.StreamRead=35041]="StreamRead",$[$.StreamCopy=35042]="StreamCopy",t.ShaderPrimitives=void 0,(K=t.ShaderPrimitives||(t.ShaderPrimitives={}))[K.Int=5124]="Int",K[K.IntVec2=35667]="IntVec2",K[K.IntVec3=35668]="IntVec3",K[K.IntVec4=35669]="IntVec4",K[K.Float=5126]="Float",K[K.FloatVec2=35664]="FloatVec2",K[K.FloatVec3=35665]="FloatVec3",K[K.FloatVec4=35666]="FloatVec4",K[K.Bool=35670]="Bool",K[K.BoolVec2=35671]="BoolVec2",K[K.BoolVec3=35672]="BoolVec3",K[K.BoolVec4=35673]="BoolVec4",K[K.FloatMat2=35674]="FloatMat2",K[K.FloatMat3=35675]="FloatMat3",K[K.FloatMat4=35676]="FloatMat4",K[K.Sampler2D=35678]="Sampler2D";class Q{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 Z extends Q{_x;_y;_callback;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 Z(this._callback,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){}}let J=null;class tt{a;b;x;c;d;y;e;f;z;_array=null;constructor(t=1,e=0,i=0,r=0,s=1,n=0,o=0,a=0,h=1){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 tt(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(tt.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(tt.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const r=D(t),s=Math.cos(r),n=Math.sin(r);return this.combine(tt.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(tt.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 identity=new tt(1,0,0,0,1,0,0,0,1);static get temp(){return null===J&&(J=new tt),J}}class et{_value=0;get value(){return this._value}constructor(...t){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 it;t.TransformableFlags=void 0,(it=t.TransformableFlags||(t.TransformableFlags={}))[it.None=0]="None",it[it.Translation=1]="Translation",it[it.Rotation=2]="Rotation",it[it.Scaling=4]="Scaling",it[it.Origin=8]="Origin",it[it.Transform=15]="Transform",it[it.TransformInverse=16]="TransformInverse";class rt{flags=new et(t.TransformableFlags.Transform);_transform=new tt;_position=new Z(this._setPositionDirty.bind(this),0,0);_scale=new Z(this._setScalingDirty.bind(this),1,1);_origin=new Z(this._setOriginDirty.bind(this),0,0);_rotation=0;_sin=0;_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=L(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=D(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 st=null;class nt{min;max;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 nt(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 zero=new nt(0,0);static get temp(){return null===st&&(st=new nt),st}}var ot;t.CollisionType=void 0,(ot=t.CollisionType||(t.CollisionType={}))[ot.Point=0]="Point",ot[ot.Line=1]="Line",ot[ot.Rectangle=2]="Rectangle",ot[ot.Circle=3]="Circle",ot[ot.Ellipse=4]="Ellipse",ot[ot.Polygon=5]="Polygon",ot[ot.SceneNode=6]="SceneNode";const at=1e-10,ht=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),lt=({x:t,y:e,rx:i,ry:r})=>{if(i<=0||r<=0)return[];const s=ht(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},ut=({x:t,y:e},{x:i,y:r},{x:s,y:n})=>t<=Math.max(i,s)+at&&t>=Math.min(i,s)-at&&e<=Math.max(r,n)+at&&e>=Math.min(r,n)-at,dt=({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)<=at?0:o>0?1:2},ct=(t,e,i,r)=>{const s=dt(t,e,i),n=dt(t,e,r),o=dt(i,r,t),a=dt(i,r,e);return s!==n&&o!==a||(!(0!==s||!ut(i,t,e))||(!(0!==n||!ut(r,t,e))||(!(0!==o||!ut(t,i,r))||!(0!==a||!ut(e,i,r)))))},pt=({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},_t=(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(ct(r,s,i,n))return!0}}return pt(t[0],e)||pt(e[0],t)},ft=({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},mt=(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)<=at)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},gt=(t,e)=>Math.sqrt(t*t+e*e),yt=(e,i,r,s)=>{const n=r*e+s*i;const o=(a=e)*a+(h=i)*h;var a,h;return n<0?t.VoronoiRegion.left:n>o?t.VoronoiRegion.right:t.VoronoiRegion.middle},xt=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=new nt,n=new nt;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},wt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:r},s=0)=>U(t,e,i,r)<=s)(t,e,i),vt=(t,e,i=.1)=>ft(t,e.fromPosition,e.toPosition,i),bt=(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),St=(t,e)=>(({x:t,y:e},{x:i,y:r,radius:s})=>s>0&&U(t,e,i,r)<=s)(t,e),Tt=(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),Ct=(t,e)=>((t,{points:e})=>pt(t,e))(t,e),Mt=(t,e)=>mt(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Pt=(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 mt(t.fromPosition,t.toPosition,o,h)||mt(t.fromPosition,t.toPosition,a,l)||mt(t.fromPosition,t.toPosition,o,a)||mt(t.fromPosition,t.toPosition,h,l)},Bt=(t,e)=>{if(St(t.fromPosition,e)||St(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!!ft({x:d,y:c},t.fromPosition,t.toPosition)&&U(d,c,o,a)<=h},Rt=(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},Et=(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(mt(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+r},{x:a.x+i,y:a.y+r}))return!0}return!1},At=(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),kt=({x:t,y:e,width:i,height:r},{x:s,y:n,radius:o})=>{const a=I(s,t,t+i),h=I(n,e,e+r);return U(s,n,a,h)<=o},Ft=(t,e)=>_t((({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),lt(e)),Lt=(t,e)=>xt(t,e),Dt=({x:t,y:e,radius:i},{x:r,y:s,radius:n})=>U(t,e,r,s)<=i+n,It=(t,e)=>_t((({x:t,y:e,radius:i})=>{if(i<=0)return[];const r=ht(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),lt(e)),Nt=(e,i,r,s,n,o,a,h,l)=>{if(yt(h,l,n,o)!==t.VoronoiRegion.left)return!1;return yt(s.x,s.y,e-r.x,i-r.y)===t.VoronoiRegion.right&>(n,o)>a},Vt=(e,i,r,s,n,o,a,h,l)=>{if(yt(h,l,n,o)!==t.VoronoiRegion.right)return!1;return yt(s.x,s.y,e-r.x,i-r.y)===t.VoronoiRegion.left&>(n,o)>a},Gt=(t,e,i,r,s)=>{const n=s,o=-r,a=gt(n,o);if(0===a)return!1;const h=(t*n+e*o)/a;return h>0&&Math.abs(h)>i},Ut=({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(Nt(a,h,n[u],o[u],r,s,i,c.x,c.y))return!1;if(Vt(a,h,n[d],o[d],r,s,i,c.x,c.y))return!1;if(Gt(r,s,i,c.x,c.y))return!1}return!0},Ot=(t,e)=>_t(lt(t),lt(e)),zt=(t,e)=>_t(lt(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:r})=>({x:i+t,y:r+e})))(e)),Wt=(t,e)=>xt(t,e),qt=(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}},Ht=(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}},Yt=(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}},Xt=(e,i,r=!1)=>{const s=i.radius,n=e.points,o=i.x-e.x,a=i.y-e.y,h=i.position.clone().set(0,0),l=n.length;let u=!0,d=!0,c=1/0;for(let e=0;e<l;e++){const i=n[e],r=n[(e+1)%l],p=r.x-i.x,_=r.y-i.y,f=o-i.x,m=a-i.y,g=yt(p,_,f,m),y=gt(f,m);if(y>s&&(u=!1),g===t.VoronoiRegion.left){const r=n[0===e?l-1:e-1],u=i.x-r.x,p=i.y-r.y,_=o-r.x,g=a-r.y;if(yt(u,p,_,g)===t.VoronoiRegion.right){if(y>s)return h.destroy(),null;const t=s-y;Math.abs(t)<Math.abs(c)&&(c=t,h.set(f,m).normalize()),d=!1}}else if(g===t.VoronoiRegion.right){const i=n[(e+2)%l],u=i.x-r.x,p=i.y-r.y,_=o-r.x,f=a-r.y,m=gt(_,f);if(yt(u,p,_,f)===t.VoronoiRegion.left){if(m>s)return h.destroy(),null;const t=s-m;Math.abs(t)<Math.abs(c)&&(c=t,h.set(_,f).normalize()),d=!1}}else{const t=_,e=-p,i=gt(t,e),r=0===i?0:(f*t+m*e)/i;if(r>0&&Math.abs(r)>s)return h.destroy(),null;(r>=0||s-r<2*s)&&(d=!1);const n=s-r;Math.abs(n)<Math.abs(c)&&(c=n,h.set(t,e).normalize())}}const p=h.clone().multiply(c);return{shapeA:r?i:e,shapeB:r?e:i,overlap:c,shapeAinB:r?d:u,shapeBinA:r?u:d,projectionN:h,projectionV:p}},jt=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=(i[0]||r[0]).clone(),n=new nt,o=new nt;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 $t=null;const Kt=()=>{},Qt=new Z(Kt);class Zt{collisionType=t.CollisionType.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(t=0,e=t,r=0,s=r){this._position=new Z(()=>{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 Zt(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 Z(Kt),new Z(Kt),new Z(Kt),new Z(Kt)])),this._normalsDirty=!1),this._normals}project(t,e=new nt){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=Qt.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 bt(Qt.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(e){switch(e.collisionType){case t.CollisionType.SceneNode:return e.isAlignedBox?At(this,e.getBounds()):xt(this,e);case t.CollisionType.Rectangle:return At(this,e);case t.CollisionType.Polygon:return Lt(this,e);case t.CollisionType.Circle:return kt(this,e);case t.CollisionType.Ellipse:return Ft(this,e);case t.CollisionType.Line:return Pt(e,this);case t.CollisionType.Point:return bt(e,this);default:return!1}}collidesWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return e.isAlignedBox?qt(this,e.getBounds()):jt(this,e);case t.CollisionType.Rectangle:return qt(this,e);case t.CollisionType.Polygon:return jt(this,e);case t.CollisionType.Circle:return Yt(e,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===$t&&($t=new Zt),$t}}class Jt{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new Zt;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,Zt.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 te extends rt{collisionType=t.CollisionType.SceneNode;_bounds=new Jt;_visible=!0;_globalTransform=new tt;_localBounds=new Zt;_anchor=new Z(this._updateOrigin.bind(this),0,0);_parentNode=null;_zIndex=0;_childOrder=0;_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 nt){return this.getBounds().project(t,e)}intersectsWith(e){if(this.isAlignedBox)return this.getBounds().intersectsWith(e);switch(e.collisionType){case t.CollisionType.SceneNode:case t.CollisionType.Rectangle:case t.CollisionType.Polygon:return xt(this,e);case t.CollisionType.Circle:return kt(this.getBounds(),e);case t.CollisionType.Ellipse:return Ft(this.getBounds(),e);case t.CollisionType.Line:return Pt(e,this.getBounds());case t.CollisionType.Point:return bt(e,this.getBounds());default:return!1}}collidesWith(e){if(this.isAlignedBox)return this.getBounds().collidesWith(e);switch(e.collisionType){case t.CollisionType.SceneNode:case t.CollisionType.Rectangle:case t.CollisionType.Polygon:case t.CollisionType.Circle:return jt(this,e);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 ee extends i{_callback;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 ee(this._callback,this._width,this._height)}}var ie;t.ViewFlags=void 0,(ie=t.ViewFlags||(t.ViewFlags={}))[ie.None=0]="None",ie[ie.Translation=1]="Translation",ie[ie.Rotation=2]="Rotation",ie[ie.Scaling=4]="Scaling",ie[ie.Origin=8]="Origin",ie[ie.Transform=15]="Transform",ie[ie.TransformInverse=16]="TransformInverse",ie[ie.BoundingBox=32]="BoundingBox",ie[ie.TextureCoords=64]="TextureCoords",ie[ie.VertexTint=128]="VertexTint";class re{_center;_size;_viewport=new Zt(0,0,1,1);_transform=new tt;_inverseTransform=new tt;_bounds=new Jt;_flags=new et;_rotation=0;_sin=0;_cos=1;_zoomLevel=1;_zoomBaseWidth;_zoomBaseHeight;_followTarget=null;_followLerp=1;_followOffsetX=0;_followOffsetY=0;_boundsConstraint=null;_shakeIntensity=0;_shakeDurationMs=0;_shakeElapsedMs=0;_shakeFrequency=16;_shakeDecay=!0;_shakePhase=0;_shakeOffsetX=0;_shakeOffsetY=0;_updateId=0;constructor(e,i,r,s){this._center=new Z(this._setPositionDirty.bind(this),e,i),this._size=new ee(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=L(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=I(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=D(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:I(this._center.x,r,s),h=n>o?(t.top+t.bottom)/2:I(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 se=null;class ne extends Q{collisionType=t.CollisionType.Point;x;y;constructor(t=0,e=0){super(),this.x=t,this.y=e}clone(){return new ne(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return bt(this,e.getBounds());case t.CollisionType.Rectangle:return bt(this,e);case t.CollisionType.Polygon:return Ct(this,e);case t.CollisionType.Circle:return St(this,e);case t.CollisionType.Ellipse:return Tt(this,e);case t.CollisionType.Line:return vt(this,e);case t.CollisionType.Point:return wt(this,e);default:return!1}}collidesWith(t){return null}getBounds(){return Zt.temp.set(this.x,this.y,0,0)}contains(t,e){return wt(ne.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new nt){return e}destroy(){}static get temp(){return null===se&&(se=new ne),se}static zero=new ne(0,0);static one=new ne(1,1);static add(t,e){return new ne(t.x+e.x,t.y+e.y)}static subtract(t,e){return new ne(t.x-e.x,t.y-e.y)}static multiply(t,e){return new ne(t.x*e.x,t.y*e.y)}static divide(t,e){return new ne(t.x/e.x,t.y/e.y)}}class oe{_root;_destroyListeners=new Set;_version=0;_size;_viewport=new Zt;_defaultView;_view;constructor(t,e,r=!1){this._size=new i(t,e),this._root=r,this._defaultView=new re(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 ne(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 ae extends oe{static defaultSamplerOptions={scaleMode:t.ScaleModes.Linear,wrapMode:t.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};_source=null;_textureVersion=0;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(t,e,i){super(t,e,!1);const{scaleMode:r,wrapMode:s,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...ae.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 V(this.width)&&V(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++}}class he{_callback;_target;_view;_clearColor;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 le=t=>"destroy"in t&&"function"==typeof t.destroy;class ue extends te{static _spriteFactory=null;_filters=[];_cacheBounds=new Zt;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_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){ue._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)le(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 re(i+s/2,r+n/2,s,n):this._captureView.reset(i+s/2,r+n/2,s,n),t.execute(new he(()=>{o()},{target:e,view:this._captureView,clearColor:W.transparentBlack}))}_drawTexture(t,e,i,r,s,n,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(W.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 ae(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===ue._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=ue._spriteFactory()}return this._cacheSprite}}class de extends ue{_tint=W.white.clone();_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 ce extends de{geometry;drawMode;color;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 pe{vertices;indices;points;constructor({vertices:t=[],indices:e=[],points:i=[]}={}){this.vertices=new Float32Array(t),this.indices=new Uint16Array(e),this.points=i}destroy(){}}class _e extends ce{render(t){return this.visible&&t.draw(this),this}}class fe{_app;_stack=[];_transitionOverlay=new _e((()=>new pe({vertices:[0,0,1,0,0,1,1,1],indices:[0,1,2,3],points:[0,0,1,0,0,1,1,1]}))(),W.black,t.RenderingPrimitives.TriangleStrip);_transition=null;onChangeScene=new R;onStartScene=new R;onUpdateScene=new R;onStopScene=new R;constructor(t){this._app=t,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}.`,{cause:e})}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}}_handleKeyDown=t=>{this._dispatchInput({type:"keyDown",channel:t})};_handleKeyUp=t=>{this._dispatchInput({type:"keyUp",channel:t})};_handlePointerEnter=t=>{this._dispatchInput({type:"pointerEnter",pointer:t})};_handlePointerLeave=t=>{this._dispatchInput({type:"pointerLeave",pointer:t})};_handlePointerDown=t=>{this._dispatchInput({type:"pointerDown",pointer:t})};_handlePointerMove=t=>{this._dispatchInput({type:"pointerMove",pointer:t})};_handlePointerUp=t=>{this._dispatchInput({type:"pointerUp",pointer:t})};_handlePointerTap=t=>{this._dispatchInput({type:"pointerTap",pointer:t})};_handlePointerSwipe=t=>{this._dispatchInput({type:"pointerSwipe",pointer:t})};_handlePointerCancel=t=>{this._dispatchInput({type:"pointerCancel",pointer:t})};_handleMouseWheel=t=>{this._dispatchInput({type:"mouseWheel",wheel:t})};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??W.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:W.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 me=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 ge{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(e=t.RenderingPrimitives.Triangles){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 ye;t.RenderBackendType=void 0,(ye=t.RenderBackendType||(t.RenderBackendType={}))[ye.WebGl2=0]="WebGl2",ye[ye.WebGpu=1]="WebGpu";class xe{backendType=t.RenderBackendType.WebGl2;_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 we{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_runtime=null;constructor(t,e){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 ve={[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},be={[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},Se={[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 Te{index;name;type;size;location=-1;constructor(t,e,i){this.index=t,this.name=e,this.type=i,this.size=ve[i]}destroy(){}}class Ce{index;type;size;name;_value;_dirty=!0;constructor(t,e,i,r,s){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 Me{index;name;binding;dataSize;_context;_program;_blockData;_uniformBuffer;_uniforms=new Map;constructor(t,e,i){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 be[n](i,s[o],ve[n]*a),u=new Ce(r[o],n,a,h,l);this._uniforms.set(u.propName,u)}}}const Pe={[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 Be(t){let e=null,i=null,r=null;const s=[],n=[];function o(o){e||(i=Re(t,t.VERTEX_SHADER,o.vertexSource),r=Re(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 Te(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 be[n.type](ve[n.type]*n.size),a=new Ce(s,n.type,n.size,n.name,o),h=t.getUniformLocation(e,a.name),l=Pe[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 Me(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:()=>{t.useProgram(e),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 Re(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 Ee{_type;_usage;_runtime=null;_data=S;_version=0;constructor(t,e,i){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 Ae=(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},ke=new Map;class Fe extends xe{attributeCount;batchSize;indexData;vertexData;float32View;uint32View;shader;batchIndex=0;currentTexture=null;currentBlendMode=null;currentView=null;currentViewId=-1;vao=null;indexBuffer=null;vertexBuffer=null;connection=null;constructor(t,e,i,r){super(),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 we(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(Be(i)),this.connection=this.createConnection(i),this.indexBuffer=new Ee(t.BufferTypes.ElementArrayBuffer,this.indexData,t.BufferUsage.StaticDraw).connect(this.createBufferRuntime(this.connection)),this.vertexBuffer=new Ee(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 Le extends Fe{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 ge).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 De extends Fe{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 ge).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 Ie extends xe{_vertexCapacity;_indexCapacity;_vertexData;_indexData;_float32View;_uint32View;_shader=new we("#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");_connection=null;_currentBlendMode=null;_currentView=null;_viewId=-1;constructor(t){super(),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(Be(i)),null===r)throw new Error("Could not create vertex array object.");const s=new Map,n=new Ee(t.BufferTypes.ElementArrayBuffer,this._indexData,t.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,s)),o=new Ee(t.BufferTypes.ArrayBuffer,this._vertexData,t.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,s)),a=(new ge).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 Ne;t.SpriteFlags=void 0,(Ne=t.SpriteFlags||(t.SpriteFlags={}))[Ne.None=0]="None",Ne[Ne.Translation=1]="Translation",Ne[Ne.Rotation=2]="Rotation",Ne[Ne.Scaling=4]="Scaling",Ne[Ne.Origin=8]="Origin",Ne[Ne.Transform=15]="Transform",Ne[Ne.TransformInverse=16]="TransformInverse",Ne[Ne.BoundingBox=32]="BoundingBox",Ne[Ne.TextureCoords=64]="TextureCoords",Ne[Ne.VertexTint=128]="VertexTint";class Ve extends de{_texture=null;_textureFrame=new Zt;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);constructor(t){super(),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(Zt.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){const[t,e,i,r,s,n,o,a]=this.vertices;return[new ne(i-t,r-e).rperp().normalize(),new ne(s-i,n-r).rperp().normalize(),new ne(o-s,a-n).rperp().normalize(),new ne(t-o,e-a).rperp().normalize()]}project(t,e=new nt){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=ne.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}}ue.setInternalSpriteFactory(()=>new Ve(null));class Ge{_totalLifetime=n.oneSecond.clone();_elapsedLifetime=n.zero.clone();_position=ne.zero.clone();_velocity=ne.zero.clone();_scale=ne.one.clone();_rotation=0;_rotationSpeed=0;_textureIndex=0;_tint=W.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=L(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 Ue extends de{_emitters=[];_affectors=[];_particles=[];_graveyard=[];_texture;_textureFrame=new Zt;_vertices=new Float32Array(4);_texCoords=new Uint32Array(4);_updateTexCoords=!0;_updateVertices=!0;constructor(t){super(),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(Zt.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 Ge}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 Oe{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:t.ScaleModes.Linear,wrapMode:t.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1};static empty=new Oe(null);static get black(){return null===Oe._black&&(Oe._black=new Oe(Ae({fillStyle:"#000"}))),Oe._black}static get white(){return null===Oe._white&&(Oe._white=new Oe(Ae({fillStyle:"#fff"}))),Oe._white}_version=0;_source=null;_size=new i(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(t=null,e){const{scaleMode:i,wrapMode:r,premultiplyAlpha:s,generateMipMap:n,flipY:o}={...Oe.defaultSamplerOptions,...e};this._scaleMode=i,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=n,this._flipY=o,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 V(this.width)&&V(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++}}class ze{_renderers=new Map;_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 We=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0}),qe=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),He=(t,e)=>{throw`${me.glEnumToString(t)} was caused by call to: ${e}`},Ye=(t,e)=>{((t,e)=>{console.log(`gl.${t}(${me.glFunctionArgsToString(t,e)})`)})(t,e),((t,e)=>{for(const i of e)void 0===i&&console.error(`undefined passed to gl.${t}(${me.glFunctionArgsToString(t,e)})`)})(t,e)};class Xe{backendType=t.RenderBackendType.WebGl2;rendererRegistry=new ze;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_maskStack=[];_maskPixelStack=[];_maskPointA=new ne;_maskPointB=new ne;_canvas;_contextLost;_renderTarget;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new W;_cursor;_boundFramebuffer=null;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};constructor(e){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?me.makeDebugContext(u,He,Ye,u):u,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),s&&this.clearColor.copy(s),this._rootRenderTarget=new oe(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(Ve,new Le(a)),this.rendererRegistry.registerRenderer(Ue,new De(h)),this.rendererRegistry.registerRenderer(ce,new Ie(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 qe(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 ae(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 Oe?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 ae&&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 ae&&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 ae?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 ae?-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 ae||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 je{backendType=t.RenderBackendType.WebGpu;_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 $e(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"}}}}const Ke=20,Qe=Ke/Uint32Array.BYTES_PER_ELEMENT;class Ze extends je{_combinedTransform=new tt;_drawCalls=[];_drawCallCount=0;_pipelines=new Map;_renderManager=null;_device=null;_shaderModule=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_vertexBufferCapacity=0;_indexBufferCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_packedIndexData=new Uint16Array(0);_generatedIndexData=new Uint16Array(0);_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;if(!t||!e)return;if(0===this._drawCallCount&&!t.clearRequested)return;const i=t.getScissorRect(),r=null!==i&&(i.width<=0||i.height<=0),s=[],n=[];let o=0,a=0;if(this._drawCallCount>0&&!r)for(let e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e],r=i.shape,h=this._resolveDrawCall(r);if(n.push(h),null===h)continue;const l=this._getPipeline({topology:h.topology,usesStripIndex:h.usesStripIndex,blendMode:i.blendMode,format:t.renderTargetFormat});s.push({pipeline:l,vertexByteOffset:o*Ke,vertexCount:h.vertexCount,indexByteOffset:a*Uint16Array.BYTES_PER_ELEMENT,indexCount:h.indexCount}),o+=h.vertexCount,a+=h.indexCount}if(0===s.length){if(t.clearRequested){const i=e.createCommandEncoder(),r=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,r.end(),t.submit(i.finish())}return void(this._drawCallCount=0)}this._ensureVertexCapacity(o),a>0&&(this._ensureIndexCapacity(a),this._packedIndexData.length<a&&(this._packedIndexData=new Uint16Array(Math.max(a,0===this._packedIndexData.length?1:2*this._packedIndexData.length))));{let e=0,i=0;for(let r=0;r<this._drawCallCount;r++){const s=n[r];if(null===s)continue;const o=this._drawCalls[r].shape;this._writeShapeVertices(t,o,e),null!==s.indices&&s.indexCount>0&&(this._packedIndexData.set(s.indices.subarray(0,s.indexCount),i),i+=s.indexCount),e+=s.vertexCount}}e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,o*Ke),a>0&&e.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,a*Uint16Array.BYTES_PER_ELEMENT);const h=e.createCommandEncoder(),l=h.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==i&&l.setScissorRect(i.x,i.y,i.width,i.height);for(const e of s)l.setPipeline(e.pipeline),l.setVertexBuffer(0,this._vertexBuffer,e.vertexByteOffset),e.indexCount>0?(l.setIndexBuffer(this._indexBuffer,"uint16",e.indexByteOffset),l.drawIndexed(e.indexCount)):l.draw(e.vertexCount),t.stats.batches++,t.stats.drawCalls++;l.end(),t.submit(h.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 VertexInput {\n @location(0) position: vec4<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 = input.position;\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._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[]})}onDisconnect(){this.flush(),this._destroyBuffers(),this._pipelines.clear(),this._pipelineLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._drawCallCount=0}_writeShapeVertices(t,e,i){const r=this._combinedTransform.copy(e.getGlobalTransform()).combine(t.view.getTransform()),s=r.a,n=r.b,o=r.c,a=r.d,h=r.x,l=r.y,u=r.z,d=e.color.toRgba(),c=e.geometry.vertices,p=c.length/2;for(let t=0;t<p;t++){const e=2*t,r=(i+t)*Qe,p=c[e],_=c[e+1];this._float32View[r+0]=s*p+n*_+h,this._float32View[r+1]=o*p+a*_+l,this._float32View[r+2]=0,this._float32View[r+3]=u,this._uint32View[r+4]=d}}_ensureVertexCapacity(t){const e=t*Ke;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?Ke: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?Ke: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:Ke,attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t.format,blend:$e(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 Je=28/Uint32Array.BYTES_PER_ELEMENT;class ti extends je{_drawCalls=[];_drawCallCount=0;_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_renderManager=null;_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_uniformBindGroup=null;_vertexBuffer=null;_indexBuffer=null;_vertexCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_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>, ddx: vec2<f32>, ddy: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSampleGrad(spriteTexture0, spriteSampler0, uv, ddx, ddy);\n }\n case 1u: {\n return textureSampleGrad(spriteTexture1, spriteSampler1, uv, ddx, ddy);\n }\n case 2u: {\n return textureSampleGrad(spriteTexture2, spriteSampler2, uv, ddx, ddy);\n }\n case 3u: {\n return textureSampleGrad(spriteTexture3, spriteSampler3, uv, ddx, ddy);\n }\n case 4u: {\n return textureSampleGrad(spriteTexture4, spriteSampler4, uv, ddx, ddy);\n }\n case 5u: {\n return textureSampleGrad(spriteTexture5, spriteSampler5, uv, ddx, ddy);\n }\n case 6u: {\n return textureSampleGrad(spriteTexture6, spriteSampler6, uv, ddx, ddy);\n }\n default: {\n return textureSampleGrad(spriteTexture7, spriteSampler7, uv, ddx, ddy);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n // Compute screen-space derivatives in uniform control flow before the\n // per-slot switch. WGSL requires textureSample (implicit LOD) to run in\n // uniform control flow, which multi-texture batching breaks because the\n // slot varies per fragment. textureSampleGrad takes explicit derivatives\n // and is valid regardless of control-flow uniformity, while preserving\n // mipmap-correct LOD when sprites use mipmapped textures.\n let ddx = dpdx(input.texcoord);\n let ddy = dpdy(input.texcoord);\n let sample = sampleTexture(input.textureSlot, input.texcoord, ddx, ddy);\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 Oe)&&!(i instanceof ae)||0===i.width||0===i.height||i instanceof Oe&&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;this._drawCallCount>0&&this._ensureBatchCapacity(this._drawCallCount);const o=[];let a=0;for(let t=0;t<this._drawCallCount;){const e=this._getBatchRange(t),i=e.end-e.start;this._writeBatchVertexData(e,a),o.push({firstSprite:a,spriteCount:i,blendMode:e.blendMode,textures:e.textures}),a+=i,t=e.end}const h=t.view.getTransform();this._projectionData.set([h.a,h.c,0,0,h.b,h.d,0,0,0,0,1,0,h.x,h.y,0,h.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const l=e.createCommandEncoder(),u=l.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const d=t.getScissorRect(),c=null!==d&&(d.width<=0||d.height<=0);if(null===d||c||u.setScissorRect(d.x,d.y,d.width,d.height),this._drawCallCount>0&&!c){e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,4*a*28),u.setBindGroup(0,r),u.setVertexBuffer(0,this._vertexBuffer),u.setIndexBuffer(this._indexBuffer,"uint32");for(const i of o){const r=this._getPipeline(i.blendMode,t.renderTargetFormat),s=this._createTextureBindGroup(e,t,i.textures);u.setPipeline(r),u.setBindGroup(1,s),u.drawIndexed(6*i.spriteCount,1,6*i.firstSprite,0,0),t.stats.batches++,t.stats.drawCalls++}}u.end(),t.submit(l.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,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,e){const i=this._renderManager;if(!i)return;let r=4*e*Je;for(let e=t.start;e<t.end;e++){const s=this._drawCalls[e],n=t.textureSlots.get(s.texture)??0,o=i.shouldPremultiplyTextureSample(s.texture)?1:0,a=s.sprite.vertices,h=s.sprite.texCoords;for(let t=0;t<4;t++){const e=2*t,i=h[t];this._float32View[r]=a[e],this._float32View[r+1]=a[e+1],this._float32View[r+2]=(65535&i)/65535,this._float32View[r+3]=(i>>>16&65535)/65535,this._uint32View[r+4]=s.color,this._uint32View[r+5]=o,this._uint32View[r+6]=n,r+=Je}}}_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:$e(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const ei=56,ii=new Float32Array([0,0,1,0,1,1,0,1]),ri=new Uint16Array([0,1,2,0,2,3]);class si extends je{_drawCalls=[];_drawCallCount=0;_uniformData=new Float32Array(144/Float32Array.BYTES_PER_ELEMENT);_renderManager=null;_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_uniformBindGroup=null;_staticVertexBuffer=null;_instanceBuffer=null;_indexBuffer=null;_instanceBufferByteLength=0;_instanceData=new ArrayBuffer(56);_float32View=new Float32Array(this._instanceData);_uint32View=new Uint32Array(this._instanceData);_pipelines=new Map;render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof Oe)||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=t.getScissorRect(),a=null!==o&&(o.width<=0||o.height<=0);if(0===this._drawCallCount||a){if(t.clearRequested){const i=e.createCommandEncoder(),r=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,r.end(),t.submit(i.finish())}this._drawCallCount=0}else{for(let a=0;a<this._drawCallCount;a++){const h=this._drawCalls[a],l=h.system,u=l.particles.length;if(0===u)continue;const d=this._getPipeline(h.blendMode,t.renderTargetFormat),c=t.getTextureBinding(h.texture),p=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:c.view},{binding:1,resource:c.sampler}]});this._ensureCapacity(u),this._writeInstanceData(l.vertices,l.texCoords,l.particles),this._writeUniformData(t,l,h.texture),e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,u*ei),e.queue.writeBuffer(i,0,this._uniformData.buffer,this._uniformData.byteOffset,this._uniformData.byteLength);const _=e.createCommandEncoder(),f=_.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==o&&f.setScissorRect(o.x,o.y,o.width,o.height),f.setBindGroup(0,r),f.setPipeline(d),f.setBindGroup(1,p),f.setVertexBuffer(0,s),f.setVertexBuffer(1,this._instanceBuffer),f.setIndexBuffer(n,"uint16"),f.drawIndexed(6,u,0,0,0),t.stats.batches++,t.stats.drawCalls++,f.end(),t.submit(_.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:ii.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._staticVertexBuffer,0,ii.buffer,ii.byteOffset,ii.byteLength),this._indexBuffer=this._device.createBuffer({size:ri.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,ri.buffer,ri.byteOffset,ri.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*ei;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||ei;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:ei,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:$e(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const ni="rgba8unorm";class oi{backendType=t.RenderBackendType.WebGpu;rendererRegistry=new ze;_canvas;_rootRenderTarget;_clearColor=new W;_textureStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_maskStack=[];_maskPixelStack=[];_maskPointA=new ne;_maskPointB=new ne;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_renderer=null;_blendMode=null;_texture=null;_clearRequested=!1;_hasPresentedFrame=!1;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};constructor(t){const{width:e,height:i,clearColor:r}=t.options;this._canvas=t.canvas,this._rootRenderTarget=new oe(e,i,!0),this._renderTarget=this._rootRenderTarget,r&&this._clearColor.copy(r),this.rendererRegistry.registerRenderer(ce,new Ze),this.rendererRegistry.registerRenderer(Ve,new ti),this.rendererRegistry.registerRenderer(Ue,new si),this.resize(e,i)}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:ni}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 qe(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 oe&&!(t instanceof ae))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 ae))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 ae(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 ae))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 ae){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 ae)&&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.");let i=null;try{i=await e.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===i)throw new Error("Could not acquire a WebGPU adapter.");const r=this._canvas.getContext("webgpu");if(null===r)throw new Error("Could not create WebGPU canvas context.");if("function"!=typeof i.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");let s=null;try{s=await i.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{r.configure({device:s,format:n,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}return this._context=r,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:ni,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 ae||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 ae?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:ni,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 ae)){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 ae?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 // Y is flipped vs the position array: NDC Y points up, but texture UV\n // Y points down (UV (0,0) is the top-left of the source). Matching the\n // two ensures that the output texture's top-left pixel samples from the\n // source's top-left, so every mip level has the same orientation as the\n // level above it. Prior to this, odd mip levels were rendered upside\n // down, producing visible texture flips at view-size doublings.\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 1.0),\n vec2<f32>(2.0, 1.0),\n vec2<f32>(0.0, -1.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:ni,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 ai,hi,li,ui,di,ci,pi;t.ChannelSize=void 0,(ai=t.ChannelSize||(t.ChannelSize={}))[ai.Container=768]="Container",ai[ai.Category=256]="Category",ai[ai.Gamepad=64]="Gamepad",t.ChannelOffset=void 0,(hi=t.ChannelOffset||(t.ChannelOffset={}))[hi.Keyboard=0]="Keyboard",hi[hi.Pointers=256]="Pointers",hi[hi.Gamepads=512]="Gamepads",t.Keyboard=void 0,(li=t.Keyboard||(t.Keyboard={}))[li.Backspace=8]="Backspace",li[li.Tab=9]="Tab",li[li.Clear=12]="Clear",li[li.Enter=13]="Enter",li[li.Shift=16]="Shift",li[li.Control=17]="Control",li[li.Alt=18]="Alt",li[li.Pause=19]="Pause",li[li.CapsLock=20]="CapsLock",li[li.Escape=27]="Escape",li[li.Space=32]="Space",li[li.PageUp=33]="PageUp",li[li.PageDown=34]="PageDown",li[li.End=35]="End",li[li.Home=36]="Home",li[li.Left=37]="Left",li[li.Up=38]="Up",li[li.Right=39]="Right",li[li.Down=40]="Down",li[li.Insert=45]="Insert",li[li.Delete=46]="Delete",li[li.Help=47]="Help",li[li.Zero=48]="Zero",li[li.One=49]="One",li[li.Two=50]="Two",li[li.Three=51]="Three",li[li.Four=52]="Four",li[li.Five=53]="Five",li[li.Six=54]="Six",li[li.Seven=55]="Seven",li[li.Eight=56]="Eight",li[li.Nine=57]="Nine",li[li.A=65]="A",li[li.B=66]="B",li[li.C=67]="C",li[li.D=68]="D",li[li.E=69]="E",li[li.F=70]="F",li[li.G=71]="G",li[li.H=72]="H",li[li.I=73]="I",li[li.J=74]="J",li[li.K=75]="K",li[li.L=76]="L",li[li.M=77]="M",li[li.N=78]="N",li[li.O=79]="O",li[li.P=80]="P",li[li.Q=81]="Q",li[li.R=82]="R",li[li.S=83]="S",li[li.T=84]="T",li[li.U=85]="U",li[li.V=86]="V",li[li.W=87]="W",li[li.X=88]="X",li[li.Y=89]="Y",li[li.Z=90]="Z",li[li.NumPad0=96]="NumPad0",li[li.NumPad1=97]="NumPad1",li[li.NumPad2=98]="NumPad2",li[li.NumPad3=99]="NumPad3",li[li.NumPad4=100]="NumPad4",li[li.NumPad5=101]="NumPad5",li[li.NumPad6=102]="NumPad6",li[li.NumPad7=103]="NumPad7",li[li.NumPad8=104]="NumPad8",li[li.NumPad9=105]="NumPad9",li[li.NumPadMultiply=106]="NumPadMultiply",li[li.NumPadAdd=107]="NumPadAdd",li[li.NumPadEnter=108]="NumPadEnter",li[li.NumPadSubtract=109]="NumPadSubtract",li[li.NumPadDecimal=110]="NumPadDecimal",li[li.NumPadDivide=111]="NumPadDivide",li[li.F1=112]="F1",li[li.F2=113]="F2",li[li.F3=114]="F3",li[li.F4=115]="F4",li[li.F5=116]="F5",li[li.F6=117]="F6",li[li.F7=118]="F7",li[li.F8=119]="F8",li[li.F9=120]="F9",li[li.F10=121]="F10",li[li.F11=122]="F11",li[li.F12=123]="F12",li[li.NumLock=144]="NumLock",li[li.ScrollLock=145]="ScrollLock",li[li.Colon=186]="Colon",li[li.Equals=187]="Equals",li[li.Comma=188]="Comma",li[li.Dash=189]="Dash",li[li.Period=190]="Period",li[li.QuestionMark=191]="QuestionMark",li[li.Tilde=192]="Tilde",li[li.OpenBracket=219]="OpenBracket",li[li.BackwardSlash=220]="BackwardSlash",li[li.ClosedBracket=221]="ClosedBracket",li[li.Quotes=222]="Quotes";class _i{onConnect=new R;onDisconnect=new R;onUpdate=new R;indexValue;channelsValue;channelOffset;mappingValue;browserGamepad=null;info={name:"Generic Gamepad",label:"Generic Gamepad",vendorId:null,productId:null,productKey:null};constructor(e,i,r){const s="number"!=typeof e,n=s?e:null,o=s?e.index:e;if(this.indexValue=o,this.channelsValue=i,this.channelOffset=t.ChannelOffset.Gamepads+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(e){return this.channelOffset+(e^t.ChannelOffset.Gamepads)}static resolveChannelOffset(e,i){return t.ChannelOffset.Gamepads+e*t.ChannelSize.Gamepad+(i^t.ChannelOffset.Gamepads)}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,(ui=t.PointerStateFlag||(t.PointerStateFlag={}))[ui.None=0]="None",ui[ui.Over=1]="Over",ui[ui.Leave=2]="Leave",ui[ui.Down=4]="Down",ui[ui.Move=8]="Move",ui[ui.Up=16]="Up",ui[ui.Cancel=32]="Cancel",t.PointerState=void 0,(di=t.PointerState||(t.PointerState={}))[di.Unknown=0]="Unknown",di[di.InsideCanvas=1]="InsideCanvas",di[di.OutsideCanvas=2]="OutsideCanvas",di[di.Pressed=3]="Pressed",di[di.Moving=4]="Moving",di[di.Released=5]="Released",di[di.Cancelled=6]="Cancelled";class fi{id;type;position;startPos=new ne(-1,-1);size;tilt;stateFlags=new et;_canvas;_buttons;_pressure;_rotation;_currentState=t.PointerState.Unknown;constructor(e,r){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 ne(o-f,a-m),this.size=new i(h,l),this.tilt=new ne(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,(ci=t.GamepadChannel||(t.GamepadChannel={}))[ci.ButtonSouth=512]="ButtonSouth",ci[ci.ButtonWest=513]="ButtonWest",ci[ci.ButtonEast=514]="ButtonEast",ci[ci.ButtonNorth=515]="ButtonNorth",ci[ci.LeftShoulder=516]="LeftShoulder",ci[ci.RightShoulder=517]="RightShoulder",ci[ci.LeftTrigger=518]="LeftTrigger",ci[ci.RightTrigger=519]="RightTrigger",ci[ci.Select=520]="Select",ci[ci.Start=521]="Start",ci[ci.LeftStick=522]="LeftStick",ci[ci.RightStick=523]="RightStick",ci[ci.DPadUp=524]="DPadUp",ci[ci.DPadDown=525]="DPadDown",ci[ci.DPadLeft=526]="DPadLeft",ci[ci.DPadRight=527]="DPadRight",ci[ci.Guide=528]="Guide",ci[ci.Share=529]="Share",ci[ci.Capture=530]="Capture",ci[ci.Touchpad=531]="Touchpad",ci[ci.Paddle1=532]="Paddle1",ci[ci.LeftStickLeft=533]="LeftStickLeft",ci[ci.LeftStickRight=534]="LeftStickRight",ci[ci.LeftStickUp=535]="LeftStickUp",ci[ci.LeftStickDown=536]="LeftStickDown",ci[ci.RightStickLeft=537]="RightStickLeft",ci[ci.RightStickRight=538]="RightStickRight",ci[ci.RightStickUp=539]="RightStickUp",ci[ci.RightStickDown=540]="RightStickDown",ci[ci.AuxiliaryAxis0Negative=541]="AuxiliaryAxis0Negative",ci[ci.AuxiliaryAxis0Positive=542]="AuxiliaryAxis0Positive",ci[ci.AuxiliaryAxis1Negative=543]="AuxiliaryAxis1Negative",ci[ci.AuxiliaryAxis1Positive=544]="AuxiliaryAxis1Positive",ci[ci.AuxiliaryAxis2Negative=545]="AuxiliaryAxis2Negative",ci[ci.AuxiliaryAxis2Positive=546]="AuxiliaryAxis2Positive",ci[ci.AuxiliaryAxis3Negative=547]="AuxiliaryAxis3Negative",ci[ci.AuxiliaryAxis3Positive=548]="AuxiliaryAxis3Positive";class mi{index;channel;invert;normalize;threshold;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=I(i.threshold??.2,0,1)}transformValue(t){let e=I(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),e>this.threshold?e:0}}t.GamepadMappingFamily=void 0,(pi=t.GamepadMappingFamily||(t.GamepadMappingFamily={})).GenericDualAnalog="genericDualAnalog",pi.Xbox="xbox",pi.PlayStation="playStation",pi.SwitchPro="switchPro",pi.JoyConLeft="joyConLeft",pi.JoyConRight="joyConRight",pi.GameCube="gameCube",pi.SteamController="steamController",pi.ArcadeStick="arcadeStick";class gi{buttons;axes;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 mi(t,e,i))}}const yi=[[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 xi extends gi{family=t.GamepadMappingFamily.ArcadeStick;constructor(){super(gi.createControls(yi),[])}}const wi=[[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]],vi=[[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 bi extends gi{family=t.GamepadMappingFamily.GenericDualAnalog;constructor(){super(gi.createControls(wi),gi.createControls(vi))}}class Si extends bi{family=t.GamepadMappingFamily.GameCube}class Ti extends bi{family=t.GamepadMappingFamily.JoyConLeft}class Ci extends bi{family=t.GamepadMappingFamily.JoyConRight}class Mi extends bi{family=t.GamepadMappingFamily.PlayStation}class Pi extends bi{family=t.GamepadMappingFamily.SteamController}class Bi extends bi{family=t.GamepadMappingFamily.SwitchPro}class Ri extends bi{family=t.GamepadMappingFamily.Xbox}const Ei=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Ai=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,ki=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,Fi=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,Li=(t,e,i)=>({ids:i,name:t,resolve:()=>({name:t,mapping:e()})}),Di=t=>t.trim().toLowerCase(),Ii=t=>{const e=t.replace(Ai,"").replace(Ei,"").replace(Fi,"").replace(ki,"").replace(/\s+/g," ").trim();return e.length>0?e:null},Ni=t=>{if(!t)return[];return(Array.isArray(t)?t:[t]).map(Di)},Vi=(t,e)=>{if(!e)return!0;for(const i of Ni(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},Gi=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=Ai.exec(t)||Ei.exec(t)||Fi.exec(t)||ki.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:Ii(e)}},Ui=(t,e)=>Vi(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,Oi=(t,e=zi)=>{const i="connected"in t?Gi(t):t;for(const t of e){const e=Ui(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new bi}},zi=[...[Li("Xbox 360 Controller",()=>new Ri,"045e:028e"),Li("Xbox One Controller",()=>new Ri,["045e:02d1","045e:02dd"]),Li("Xbox Wireless Controller",()=>new Ri,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),Li("Xbox One Elite Controller",()=>new Ri,"045e:02e3"),Li("Xbox Elite Wireless Controller Series 2",()=>new Ri,["045e:0b00","045e:0b05","045e:0b22"]),Li("Xbox Series Controller",()=>new Ri,["045e:0b12","045e:0b13"]),Li("PlayStation 3 Controller",()=>new Mi,"054c:0268"),Li("DualShock 4 Controller",()=>new Mi,["054c:05c4","054c:09cc","054c:0ba0"]),Li("DualSense Controller",()=>new Mi,"054c:0ce6"),Li("DualSense Edge Controller",()=>new Mi,"054c:0df2"),Li("GameCube Controller Adapter",()=>new Si,"057e:0337"),Li("Joy-Con (L)",()=>new Ti,"057e:2006"),Li("Joy-Con (R)",()=>new Ci,"057e:2007"),Li("Joy-Con Charging Grip",()=>new Bi,"057e:200e"),Li("Switch Pro Controller",()=>new Bi,"057e:2009"),Li("Joy-Con 2 (L)",()=>new Ti,"057e:2066"),Li("Joy-Con 2 (R)",()=>new Ci,"057e:2067"),Li("Switch 2 Pro Controller",()=>new Bi,"057e:2069"),Li("Switch 2 GameCube Controller",()=>new Si,"057e:2073"),Li("Steam Controller",()=>new Pi,["28de:1102","28de:1142"]),Li("F310 Gamepad",()=>new bi,"046d:c216"),Li("F710 Gamepad",()=>new bi,["046d:c219","046d:c21f"]),Li("8BitDo P30 Controller",()=>new bi,["2dc8:5107","2dc8:5108"]),Li("8BitDo SF30 Pro Controller",()=>new Bi,["2dc8:3000","2dc8:6100","2dc8:6101"]),Li("8BitDo SN30 Controller",()=>new Bi,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),Li("8BitDo NES30 Controller",()=>new bi,"2dc8:ab12"),Li("PowerA Switch Controller",()=>new Bi,"20d6:a713"),Li("PowerA OPS Pro Wireless Controller",()=>new bi,"20d6:4033"),Li("PowerA OPS Wireless Controller",()=>new bi,"20d6:4026"),Li("Nacon Revolution 3 Controller",()=>new Mi,"146b:0611"),Li("Nacon Revolution Unlimited Pro Controller",()=>new Mi,"146b:0d08"),Li("Nacon Revolution Infinity Controller",()=>new Mi,"146b:0d10"),Li("Nacon Revolution 5 Pro Controller",()=>new Mi,["3285:0d17","3285:0d19"]),Li("Razer Raiju Controller",()=>new Mi,"1532:1000"),Li("Razer Raiju Mobile Controller",()=>new Mi,["1532:0705","1532:0707"]),Li("Razer Raiju Tournament Edition Controller",()=>new Mi,["1532:1007","1532:100a"]),Li("Razer Raiju Ultimate Controller",()=>new Mi,["1532:1004","1532:1009"]),Li("Razer Raion Controller",()=>new xi,"1532:1100")],...[Li("Microsoft Controller",()=>new Ri,"045e"),Li("Sony Controller",()=>new Mi,"054c")],Li("Generic Gamepad",()=>new bi)];var Wi;!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"}(Wi||(Wi={}));class qi{canvas;channels=new Float32Array(t.ChannelSize.Container);inputs=new Set;pointers={};gamepadsValue=[];gamepadsByIndex=new Map;gamepadSlotsActive=new Uint8Array(t.ChannelSize.Category/t.ChannelSize.Gamepad);wheelOffset=new ne;flags=new et;channelsPressed=[];channelsReleased=[];gamepadDefinitions;canvasFocusedValue;pointerDistanceThreshold;keyDownHandler=this.handleKeyDown.bind(this);keyUpHandler=this.handleKeyUp.bind(this);canvasFocusHandler=this.handleCanvasFocus.bind(this);canvasBlurHandler=this.handleCanvasBlur.bind(this);windowBlurHandler=this.handleWindowBlur.bind(this);mouseWheelHandler=this.handleMouseWheel.bind(this);pointerOverHandler=this.handlePointerOver.bind(this);pointerLeaveHandler=this.handlePointerLeave.bind(this);pointerDownHandler=this.handlePointerDown.bind(this);pointerMoveHandler=this.handlePointerMove.bind(this);pointerUpHandler=this.handlePointerUp.bind(this);pointerCancelHandler=this.handlePointerCancel.bind(this);onPointerEnter=new R;onPointerLeave=new R;onPointerDown=new R;onPointerMove=new R;onPointerUp=new R;onPointerTap=new R;onPointerSwipe=new R;onPointerCancel=new R;onMouseWheel=new R;onKeyDown=new R;onKeyUp=new R;onGamepadConnected=new R;onGamepadDisconnected=new R;onGamepadUpdated=new R;constructor(t){const{gamepadDefinitions:e=[],pointerDistanceThreshold:i}=t.options;this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=i,this.gamepadDefinitions=[...e,...zi],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!==Wi.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(e){const i=t.ChannelOffset.Keyboard+e.keyCode;this.channels[i]=1,this.channelsPressed.push(i),this.flags.push(Wi.KeyDown)}handleKeyUp(e){const i=t.ChannelOffset.Keyboard+e.keyCode;this.channels[i]=0,this.channelsReleased.push(i),this.flags.push(Wi.KeyUp)}handlePointerOver(t){this.pointers[t.pointerId]=new fi(t,this.canvas),this.flags.push(Wi.PointerUpdate)}handlePointerLeave(t){this.pointers[t.pointerId].handleLeave(t),this.flags.push(Wi.PointerUpdate)}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0,this.pointers[t.pointerId].handlePress(t),this.flags.push(Wi.PointerUpdate),t.preventDefault()}handlePointerMove(t){this.pointers[t.pointerId].handleMove(t),this.flags.push(Wi.PointerUpdate)}handlePointerUp(t){this.pointers[t.pointerId].handleRelease(t),this.flags.push(Wi.PointerUpdate),t.preventDefault()}handlePointerCancel(t){this.pointers[t.pointerId].handleCancel(t),this.flags.push(Wi.PointerUpdate)}handleMouseWheel(t){this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(Wi.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=Oi(e,this.gamepadDefinitions);i=new _i(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(Wi.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(Wi.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(Wi.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(Wi.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 Hi{onStart=new R;onStop=new R;_duration;_volume;_playbackRate;_loop;_muted;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){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 Yi=["mousedown","touchstart","touchend"];let Xi=null,ji=null,$i=!1,Ki=!1,Qi=!1;const Zi=()=>"undefined"!=typeof document,Ji=()=>Xi,tr=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===Xi&&(Xi=new AudioContext),Xi},er=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===ji){const t=tr();ji=new OfflineAudioContext(1,2,t.sampleRate)}return ji},ir=()=>{const t=Ji();t&&"running"===t.state&&!Qi&&(Qi=!0,(()=>{if($i&&Zi()){for(const t of Yi)document.removeEventListener(t,nr,!1);$i=!1}})(),or.dispatch(t))},rr=()=>{ir()},sr=()=>{const t=tr();Ki||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",rr),Ki=!0),ir(),Qi||(()=>{if(!$i&&Zi()){for(const t of Yi)document.addEventListener(t,nr,!1);$i=!0}})()},nr=()=>{const t=tr();"running"!==t.state?t.resume().then(()=>{ir()}):ir()};const or=new class extends R{add(t,e){return super.add(t,e),sr(),this}once(t,e){return super.once(t,e),sr(),this}},ar=()=>{const t=tr();return sr(),t},hr=()=>{const t=Ji();return null!==t&&"running"===t.state},lr=async t=>er().decodeAudioData(t);class ur extends Hi{_audioElement;_audioSetup=null;constructor(t,e){super(t),this._audioElement=t,e&&this.applyOptions(e),hr()?this.setupWithAudioContext(ar()):or.once(this.setupWithAudioContext,this)}setVolume(t){const e=I(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=I(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(),or.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 dr extends Hi{_audioBuffer;_pooledSources=[];_queuedPooledPlays=[];_sprites=new Map;_audioSetup=null;_paused=!0;_startTime=0;_currentTime=0;_sourceNode=null;_poolSize=1;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._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),hr()?this.setupWithAudioContext(ar()):or.once(this.setupWithAudioContext,this)}setVolume(t){const e=I(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=I(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=I(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=I(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(),or.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 cr extends Ve{onStart=new R;onStop=new R;_videoElement;_duration;_volume=1;_playbackRate=1;_loop=!1;_muted=!1;_audioSetup=null;_textureDirty=!0;_lastVideoTime=Number.NaN;_videoFrameCallbackHandle=null;_onMetadataHandler;_onResizeHandler;_onVideoFrameHandler;constructor(t,e,i){super(new Oe(t,i));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),hr()?this.setupWithAudioContext(ar()):or.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=I(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=I(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(Zt.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(),or.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 pr{}class _r{}class fr{}class mr{}class gr{_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 yr{_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 xr extends yr{storageName="font";_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 wr=[{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]}],vr=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of wr)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 br extends yr{storageName="image";async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??vr(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 Sr extends yr{storageName="json";async process(t){return await t.json()}async create(t){return t}}const Tr={once:!0};class Cr extends yr{storageName="music";_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??vr(t)});return new Promise((t,e)=>{const i=document.createElement("audio");this._audioElements.push(i),i.addEventListener("error",()=>e(Error("Error loading audio source.")),Tr),i.addEventListener("abort",()=>e(Error("Audio loading was canceled.")),Tr),i.addEventListener(r??"canplaythrough",()=>t(new ur(i,s)),Tr),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 Mr extends yr{storageName="sound";async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=await lr(t);return new dr(i,{...e.playbackOptions,poolSize:e.poolSize,sprites:e.sprites})}}class Pr extends yr{storageName="text";async process(t){return await t.text()}async create(t){return t}}class Br extends yr{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??vr(t)}),n=this.createObjectUrl(s);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{s(),t(new Oe(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 Rr={once:!0};class Er extends yr{storageName="video";_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??vr(t)});return new Promise((t,e)=>{const i=document.createElement("video");this._videoElements.push(i),i.addEventListener("error",()=>e(Error("Video loading error.")),Rr),i.addEventListener("abort",()=>e(Error("Video loading error: cancelled.")),Rr),i.addEventListener("emptied",()=>e(Error("Video loading error: emptied.")),Rr),i.addEventListener(r??"canplaythrough",()=>t(new cr(i,s,n)),Rr),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 Ar extends yr{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 kr extends yr{storageName="binary";async process(t){return t.arrayBuffer()}async create(t){return t}}class Fr extends yr{storageName="wasm";async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}const Lr=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 Dr extends yr{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=Lr(n),h=Lr(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 Ir extends Error{bundle;failures;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 Nr(t){return function(t){if(!Vr(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!Vr(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(!Vr(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.`);Gr(i.alias,`${s} has an invalid "alias".`),Gr(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 (${Ur(n)}, "${o}") in bundle "${e}".`);a.add(o)})}}(t),t}function Vr(t){return"object"==typeof t&&null!==t}function Gr(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function Ur(t){return t.name.length>0?t.name:"(anonymous type)"}class Or{_registry=new gr;_resources=new Map;_manifest=new Map;_bundles=new Map;_inFlight=new Map;_typeIds=new WeakMap;_preventStoreKeys=new Set;_stores;_resourcePath;_requestOptions;_concurrency;_nextTypeId=1;_backgroundQueue=[];_backgroundActive=0;_backgroundTotal=0;_backgroundLoaded=0;_backgroundResolve=null;onProgress=new R;onBundleProgress=new R;onLoaded=new R;onError=new R;constructor(t={}){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=Nr(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 Ir(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(Oe,new Br),this._registry.register(dr,new Mr),this._registry.register(ur,new Cr),this._registry.register(cr,new Er),this._registry.register(pr,new Sr),this._registry.register(_r,new Pr),this._registry.register(fr,new Ar),this._registry.register(mr,new Dr),this._registry.register(ArrayBuffer,new kr),"undefined"!=typeof FontFace&&this._registry.register(FontFace,new xr),"undefined"!=typeof HTMLImageElement&&this._registry.register(HTMLImageElement,new br),"undefined"!=typeof WebAssembly&&this._registry.register(WebAssembly.Module,new Fr)}}var zr;t.ApplicationStatus=void 0,(zr=t.ApplicationStatus||(t.ApplicationStatus={}))[zr.Loading=1]="Loading",zr[zr.Running=2]="Running",zr[zr.Halting=3]="Halting",zr[zr.Stopped=4]="Stopped";const Wr={type:"auto"},qr={width:800,height:600,clearColor:W.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:Wr};class Hr{static maxSceneNodes=50;static maxLevel=5;level;_bounds;_quadTrees=new Map;_sceneNodes=new Set;constructor(t,e=0){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>Hr.maxSceneNodes&&this.level<Hr.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 Hr(Zt.temp.set(e,t,s,n),o)),this._quadTrees.set(1,new Hr(Zt.temp.set(e+s,t,s,n),o)),this._quadTrees.set(2,new Hr(Zt.temp.set(e,t+n,s,n),o)),this._quadTrees.set(3,new Hr(Zt.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))}}}class Yr extends ue{_children=[];_sortableChildren=!1;_sortDirty=!1;_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){for(const e of t)this.addChildAt(e,this._children.length);return this}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 Xr{_app=null;_root=new Yr;_stackMode="overlay";_inputMode="capture";static create(t){return Object.assign(new Xr,t)}constructor(){}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 jr extends B{_limit;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 $r=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]]]),Kr=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]]),Qr=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"]]),Zr=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"]]),Jr=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"]]),ts=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"]]),es=new Map([[t.GamepadMappingFamily.GenericDualAnalog,Qr],[t.GamepadMappingFamily.Xbox,Zr],[t.GamepadMappingFamily.PlayStation,Jr],[t.GamepadMappingFamily.SwitchPro,ts],[t.GamepadMappingFamily.JoyConLeft,ts],[t.GamepadMappingFamily.JoyConRight,ts],[t.GamepadMappingFamily.GameCube,Qr],[t.GamepadMappingFamily.SteamController,Qr],[t.GamepadMappingFamily.ArcadeStick,Qr]]);class is{static triggerThreshold=300;channels=new Set;triggerTimer;valueState=0;onStart=new R;onStop=new R;onActive=new R;onTrigger=new R;constructor(t,{onStart:e,onStop:i,onActive:r,onTrigger:s,context:n,threshold:o}={}){this.channels=new Set(Array.isArray(t)?t:[t]),this.triggerTimer=new jr(b(o??is.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 rs(t,e,i=2){const r=e&&e.length,s=r?e[0]*i:t.length;let n=ss(t,0,s,i,!0);const o=[];if(!n||n.next===n.prev)return o;let a,h,l;if(r&&(n=function(t,e,i,r){const s=[];for(let i=0,n=e.length;i<n;i++){const o=ss(t,e[i]*r,i<n-1?e[i+1]*r:t.length,r,!1);o===o.next&&(o.steiner=!0),s.push(fs(o))}s.sort(ds);for(let t=0;t<s.length;t++)i=cs(s[t],i);return i}(t,e,n,i)),t.length>80*i){a=t[0],h=t[1];let e=a,r=h;for(let n=i;n<s;n+=i){const i=t[n],s=t[n+1];i<a&&(a=i),s<h&&(h=s),i>e&&(e=i),s>r&&(r=s)}l=Math.max(e-a,r-h),l=0!==l?32767/l:0}return os(n,o,i,a,h,l,0),o}function ss(t,e,i,r,s){let n;if(s===function(t,e,i,r){let s=0;for(let n=e,o=i-r;n<i;n+=r)s+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return s}(t,e,i,r)>0)for(let s=e;s<i;s+=r)n=Ms(s/r|0,t[s],t[s+1],n);else for(let s=i-r;s>=e;s-=r)n=Ms(s/r|0,t[s],t[s+1],n);return n&&ws(n,n.next)&&(Ps(n),n=n.next),n}function ns(t,e){if(!t)return t;e||(e=t);let i,r=t;do{if(i=!1,r.steiner||!ws(r,r.next)&&0!==xs(r.prev,r,r.next))r=r.next;else{if(Ps(r),r=e=r.prev,r===r.next)break;i=!0}}while(i||r!==e);return e}function os(t,e,i,r,s,n,o){if(!t)return;!o&&n&&function(t,e,i,r){let s=t;do{0===s.z&&(s.z=_s(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){let e,i=1;do{let r,s=t;t=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let t=0;t<i&&(a++,o=o.nextZ,o);t++);let h=i;for(;a>0||h>0&&o;)0!==a&&(0===h||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,h--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;s=o}n.nextZ=null,i*=2}while(e>1)}(s)}(t,r,s,n);let a=t;for(;t.prev!==t.next;){const h=t.prev,l=t.next;if(n?hs(t,r,s,n):as(t))e.push(h.i,t.i,l.i),Ps(t),t=l.next,a=l.next;else if((t=l)===a){o?1===o?os(t=ls(ns(t),e),e,i,r,s,n,2):2===o&&us(t,e,i,r,s,n):os(ns(t),e,i,r,s,n,1);break}}}function as(t){const e=t.prev,i=t,r=t.next;if(xs(e,i,r)>=0)return!1;const s=e.x,n=i.x,o=r.x,a=e.y,h=i.y,l=r.y,u=Math.min(s,n,o),d=Math.min(a,h,l),c=Math.max(s,n,o),p=Math.max(a,h,l);let _=r.next;for(;_!==e;){if(_.x>=u&&_.x<=c&&_.y>=d&&_.y<=p&&gs(s,a,n,h,o,l,_.x,_.y)&&xs(_.prev,_,_.next)>=0)return!1;_=_.next}return!0}function hs(t,e,i,r){const s=t.prev,n=t,o=t.next;if(xs(s,n,o)>=0)return!1;const a=s.x,h=n.x,l=o.x,u=s.y,d=n.y,c=o.y,p=Math.min(a,h,l),_=Math.min(u,d,c),f=Math.max(a,h,l),m=Math.max(u,d,c),g=_s(p,_,e,i,r),y=_s(f,m,e,i,r);let x=t.prevZ,w=t.nextZ;for(;x&&x.z>=g&&w&&w.z<=y;){if(x.x>=p&&x.x<=f&&x.y>=_&&x.y<=m&&x!==s&&x!==o&&gs(a,u,h,d,l,c,x.x,x.y)&&xs(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,w.x>=p&&w.x<=f&&w.y>=_&&w.y<=m&&w!==s&&w!==o&&gs(a,u,h,d,l,c,w.x,w.y)&&xs(w.prev,w,w.next)>=0)return!1;w=w.nextZ}for(;x&&x.z>=g;){if(x.x>=p&&x.x<=f&&x.y>=_&&x.y<=m&&x!==s&&x!==o&&gs(a,u,h,d,l,c,x.x,x.y)&&xs(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;w&&w.z<=y;){if(w.x>=p&&w.x<=f&&w.y>=_&&w.y<=m&&w!==s&&w!==o&&gs(a,u,h,d,l,c,w.x,w.y)&&xs(w.prev,w,w.next)>=0)return!1;w=w.nextZ}return!0}function ls(t,e){let i=t;do{const r=i.prev,s=i.next.next;!ws(r,s)&&vs(r,i,i.next,s)&&Ts(r,s)&&Ts(s,r)&&(e.push(r.i,i.i,s.i),Ps(i),Ps(i.next),i=t=s),i=i.next}while(i!==t);return ns(i)}function us(t,e,i,r,s,n){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&ys(o,t)){let a=Cs(o,t);return o=ns(o,o.next),a=ns(a,a.next),os(o,e,i,r,s,n,0),void os(a,e,i,r,s,n,0)}t=t.next}o=o.next}while(o!==t)}function ds(t,e){let i=t.x-e.x;if(0===i&&(i=t.y-e.y,0===i)){i=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)}return i}function cs(t,e){const i=function(t,e){let i=e;const r=t.x,s=t.y;let n,o=-1/0;if(ws(t,i))return i;do{if(ws(t,i.next))return i.next;if(s<=i.y&&s>=i.next.y&&i.next.y!==i.y){const t=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=r&&t>o&&(o=t,n=i.x<i.next.x?i:i.next,t===r))return n}i=i.next}while(i!==e);if(!n)return null;const a=n,h=n.x,l=n.y;let u=1/0;i=n;do{if(r>=i.x&&i.x>=h&&r!==i.x&&ms(s<l?r:o,s,h,l,s<l?o:r,s,i.x,i.y)){const e=Math.abs(s-i.y)/(r-i.x);Ts(i,t)&&(e<u||e===u&&(i.x>n.x||i.x===n.x&&ps(n,i)))&&(n=i,u=e)}i=i.next}while(i!==a);return n}(t,e);if(!i)return e;const r=Cs(i,t);return ns(r,r.next),ns(i,i.next)}function ps(t,e){return xs(t.prev,t,e.prev)<0&&xs(e.next,t,t.next)<0}function _s(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 fs(t){let 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 ms(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 gs(t,e,i,r,s,n,o,a){return!(t===o&&e===a)&&ms(t,e,i,r,s,n,o,a)}function ys(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&vs(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(Ts(t,e)&&Ts(e,t)&&function(t,e){let i=t,r=!1;const 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)&&(xs(t.prev,t,e.prev)||xs(t,e.prev,e))||ws(t,e)&&xs(t.prev,t,t.next)>0&&xs(e.prev,e,e.next)>0)}function xs(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function ws(t,e){return t.x===e.x&&t.y===e.y}function vs(t,e,i,r){const s=Ss(xs(t,e,i)),n=Ss(xs(t,e,r)),o=Ss(xs(i,r,t)),a=Ss(xs(i,r,e));return s!==n&&o!==a||(!(0!==s||!bs(t,i,e))||(!(0!==n||!bs(t,r,e))||(!(0!==o||!bs(i,t,r))||!(0!==a||!bs(i,e,r)))))}function bs(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 Ss(t){return t>0?1:t<0?-1:0}function Ts(t,e){return xs(t.prev,t,t.next)<0?xs(t,e,t.next)>=0&&xs(t,t.prev,e)>=0:xs(t,e,t.prev)<0||xs(t,t.next,e)<0}function Cs(t,e){const i=Bs(t.i,t.x,t.y),r=Bs(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 Ms(t,e,i,r){const s=Bs(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 Ps(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 Bs(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const Rs=(t,e,i,r,s,n=[],o=[])=>{const a=[t,e,i,r],h=s/2,l=n.length/6,u=new ne(t-i,e-r).perp().normalize().multiply(h),d=new ne(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 pe({vertices:n,indices:o,points:a})},Es=(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 ne(t[0],t[1]),o=new ne(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 pe({vertices:i,indices:r,points:t})},As=(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 pe({vertices:s,indices:n,points:h})},ks=(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 pe({vertices:e,indices:i,points:t})},Fs=(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 pe({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=E/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 ks(l)};let Ds=null;class Is{collisionType=t.CollisionType.Line;_fromPosition;_toPosition;constructor(t=0,e=0,i=0,r=0){this._fromPosition=new ne(t,e),this._toPosition=new ne(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 Is(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 Zt(s,n,Math.max(t,i)-s,Math.max(e,r)-n)}getNormals(){return[]}project(t,e=new nt){return e}intersectsWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return Pt(this,e.getBounds());case t.CollisionType.Rectangle:return Pt(this,e);case t.CollisionType.Polygon:return Et(this,e);case t.CollisionType.Circle:return Bt(this,e);case t.CollisionType.Ellipse:return Rt(this,e);case t.CollisionType.Line:return Mt(this,e);case t.CollisionType.Point:return vt(e,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return vt(ne.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===Ds&&(Ds=new Is),Ds}}let Ns=null;class Vs{static collisionSegments=32;collisionType=t.CollisionType.Circle;_position;_collisionVertices=null;_radius;constructor(t=0,e=0,i=0){this._position=new ne(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 Vs(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 Zt(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 nt){const i=t.dot(this.x,this.y),r=this.radius*t.length;return e.set(i-r,i+r)}contains(t,e){return St(ne.temp.set(t,e),this)}intersectsWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return kt(e.getBounds(),this);case t.CollisionType.Rectangle:return kt(e,this);case t.CollisionType.Polygon:return Ut(this,e);case t.CollisionType.Circle:return Dt(this,e);case t.CollisionType.Ellipse:return It(this,e);case t.CollisionType.Line:return Bt(e,this);case t.CollisionType.Point:return St(e,this);default:return!1}}collidesWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return Yt(this,e.getBounds());case t.CollisionType.Rectangle:return Yt(this,e);case t.CollisionType.Polygon:return Xt(e,this,!0);case t.CollisionType.Circle:return Ht(this,e);default:return null}}destroy(){this._position.destroy()}getCollisionVertices(){if(null===this._collisionVertices){this._collisionVertices=[];for(let t=0;t<Vs.collisionSegments;t++)this._collisionVertices.push(this.getCollisionVertex(t))}return this._collisionVertices}getCollisionVertex(t){const e=2*t*Math.PI/Vs.collisionSegments-Math.PI/2,i=Math.cos(e)*this._radius,r=Math.sin(e)*this._radius;return new ne(this._radius+i,this._radius+r)}static get temp(){return null===Ns&&(Ns=new Vs),Ns}}class Gs{collisionType=t.CollisionType.Ellipse;_position;_radius;constructor(t=0,e=0,i=0,r=i){this._position=new ne(t,e),this._radius=new ne(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 Gs(this.x,this.y,this.rx,this.ry)}getBounds(){return new Zt(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new nt){return e}intersectsWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return Ft(e.getBounds(),this);case t.CollisionType.Rectangle:return Ft(e,this);case t.CollisionType.Polygon:return zt(this,e);case t.CollisionType.Circle:return It(e,this);case t.CollisionType.Ellipse:return Ot(this,e);case t.CollisionType.Line:return Rt(e,this);case t.CollisionType.Point:return Tt(e,this);default:return!1}}collidesWith(t){return null}contains(t,e){return Tt(ne.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 Us=null;class Os{collisionType=t.CollisionType.Polygon;_position;_points=[];_edges=[];_normals=[];constructor(t=[],e=0,i=0){this._position=new ne(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 Os(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 Zt(this.x+t,this.y+e,i-t,r-e)}getNormals(){return this._normals}project(t,e=new nt){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 Ct(ne.temp.set(t,e),this)}intersectsWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:return Lt(e.getBounds(),this);case t.CollisionType.Rectangle:return Lt(e,this);case t.CollisionType.Polygon:return Wt(this,e);case t.CollisionType.Circle:return Ut(e,this);case t.CollisionType.Ellipse:return zt(e,this);case t.CollisionType.Line:return Et(e,this);case t.CollisionType.Point:return Ct(e,this);default:return!1}}collidesWith(e){switch(e.collisionType){case t.CollisionType.SceneNode:case t.CollisionType.Rectangle:case t.CollisionType.Polygon:return jt(this,e);case t.CollisionType.Circle:return Xt(this,e);default:return null}}destroy(){for(const t of this._points)t.destroy();this._position.destroy(),this._points.length=0}static get temp(){return null===Us&&(Us=new Os),Us}}let zs=null;class Ws{_startPoint;_endPoint;constructor(t=0,e=0,i=0,r=0){this._startPoint=new ne(t,e),this._endPoint=new ne(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 Ws(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===zs&&(zs=new Ws),zs}}class qs{radius;phi;constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new qs(t.length,0)}toVector(){return ne.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}class Hs{_totalLifetime;_elapsedLifetime;_position;_velocity;_scale;_tint;_rotation;_rotationSpeed;_textureIndex;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??ne.zero).clone(),this._velocity=(s??ne.zero).clone(),this._scale=(o??ne.one).clone(),this._tint=(u??W.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=L(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 Ys extends pe{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 Xs extends Yr{_lineWidth=0;_lineColor=new W;_fillColor=new W;_currentPoint=new ne(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 ce))throw new Error("Graphics can only contain DrawableShape children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof ce))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(z(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(O(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=I(_*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),R=Math.atan2(T-P,S-M);return this.lineTo(v,b),this.drawArc(M,P,a,B,R,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+=E:n&&a>0&&(a-=E),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 ce(Rs(e,i,r,s,this._lineWidth),this._lineColor,t.RenderingPrimitives.TriangleStrip)),this}drawPath(e){return this.addChild(new ce(Es(e,this._lineWidth),this._lineColor,t.RenderingPrimitives.TriangleStrip)),this}drawPolygon(e){const i=ks(e);return this.addChild(new ce(i,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(i.points),this}drawCircle(e,i,r){const s=new Ys(e,i,r);return this.addChild(new ce(s,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawEllipse(e,i,r,s){const n=As(e,i,r,s);return this.addChild(new ce(n,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(n.points),this}drawRectangle(e,i,r,s){const n=Fs(e,i,r,s);return this.addChild(new ce(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 ce(a,this._fillColor,t.RenderingPrimitives.TriangleStrip)),this._lineWidth>0&&this.drawPath(a.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._lineColor.copy(W.black),this._fillColor.copy(W.black),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}}class js extends Ve{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_playing=!1;_loopOverride=null;_elapsedFrameTimeMs=0;onComplete=new R;onFrame=new R;constructor(t,e){super(t),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 js(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}class $s{_align;_fill;_stroke;_strokeThickness;_fontSize;_fontWeight;_fontFamily;_wordWrap;_wordWrapWidth;_baseline;_lineJoin;_miterLimit;_padding;_dirty=!0;constructor(t={}){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 $s).copy(this)}}const Ks=/(?:\r\n|\r|\n)/;class Qs{}const Zs=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"];class Js{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(t,e=1,i=Zs,r){if(!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 tn="@dimforge/rapier2d-compat",en=65535,rn=1/60,sn={lineWidth:1,solidLineColor:new W(64,196,255,1),solidFillColor:new W(64,196,255,.12),triggerLineColor:new W(255,180,48,1),triggerFillColor:new W(255,180,48,.08)},nn=async()=>await import(tn),on=(t,e)=>{if(!Number.isFinite(t))throw new Error(`${e} must be a finite number.`)},an=(t,e)=>{if(on(t,e),t<=0)throw new Error(`${e} must be greater than zero.`)},hn=(t,e)=>{if(!Number.isInteger(t)||t<0||t>15)throw new Error(`${e} must be an integer between 0 and 15.`)},ln=(t,e)=>void 0===t?e:"number"==typeof t?(hn(t,"collision group"),1<<t):0===t.length?0:t.reduce((t,e,i)=>(hn(e,`collision groups[${i}]`),t|1<<e),0),un=t=>{const e=ln(t?.membership,1),i=ln(t?.collidesWith,en);return(e&en)<<16|i&en},dn=t=>({x:t.offsetX??0,y:t.offsetY??0}),cn=(t,e,i)=>{const r=Math.cos(i),s=Math.sin(i);return{x:t*r-e*s,y:t*s+e*r}},pn=t=>{(t=>{if("box"===t.type)return an(t.width,"Box width"),an(t.height,"Box height"),on(t.offsetX??0,"Box offsetX"),on(t.offsetY??0,"Box offsetY"),void on(t.offsetRotation??0,"Box offsetRotation");an(t.radius,"Circle radius"),on(t.offsetX??0,"Circle offsetX"),on(t.offsetY??0,"Circle offsetY")})(t.shape),on(t.friction??0,"friction"),on(t.restitution??0,"restitution"),on(t.density??0,"density"),on(t.gravityScale??1,"gravityScale"),on(t.linearDamping??0,"linearDamping"),on(t.angularDamping??0,"angularDamping"),un(t.collisionFilter)};class _n{_world;_body;_collider;_syncMode;node;bodyType;shape;trigger;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=un(t);return this._collider.setCollisionGroups(e),this._collider.setSolverGroups(e),this}destroy(){this._world.removeBinding(this)}}class fn{onCollisionEnter=new R;onCollisionExit=new R;onTriggerEnter=new R;onTriggerExit=new R;_rapier;_world;_eventQueue;_bindings=new Set;_nodeBindings=new Map;_colliderBindings=new Map;constructor(t,e,i){this._rapier=t,this._world=e,this._eventQueue=i}static async create(t={}){const e=t.moduleLoader??nn;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 "${tn}" or provide a custom module loader. Original error: ${e}`,{cause:t})}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;on(s,"gravityX"),on(n,"gravityY");const o=new r.worldConstructor(new r.vector2(s,n)),a=new r.eventQueueConstructor(!0);return new fn(r,o,a)}get gravity(){return{x:this._world.gravity.x,y:this._world.gravity.y}}setGravity(t,e){return on(t,"gravityX"),on(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.");pn(e);const i=this.createBodyDescriptor(t,e),r=this._world.createRigidBody(i),s=this.createColliderDescriptor(e),n=this._world.createCollider(s,r),o=new _n(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=rn){if(on(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 Xs;return e.setCullable(!1),this.updateDebugGraphics(e,t),e}updateDebugGraphics(t,e={}){const i=e.lineWidth??sn.lineWidth,r=e.solidLineColor??sn.solidLineColor,s=e.solidFillColor??sn.solidFillColor,n=e.triggerLineColor??sn.triggerLineColor,o=e.triggerFillColor??sn.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=dn(e.shape),s=cn(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=dn(e),s=un(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=dn(t),h=t.offsetRotation??0,l=[];for(const t of o){const s=cn(t.x,t.y,h),n={x:s.x+a.x,y:s.y+a.y},o=cn(n.x,n.y,r);l.push(e+o.x,i+o.y)}return l}}return t.AbstractAssetFactory=yr,t.AbstractMedia=Hi,t.AbstractWebGl2BatchedRenderer=Fe,t.AbstractWebGl2Renderer=xe,t.AbstractWebGpuRenderer=je,t.AnimatedSprite=js,t.Application=class{options;canvas;loader;inputManager;sceneManager;onResize=new R;_updateHandler;_startupClock=new B;_activeClock=new B;_frameClock=new B;_status=t.ApplicationStatus.Stopped;_frameCount=0;_frameRequest=0;_backendType;_renderManager;constructor(t){this.options={canvas:t?.canvas??document.createElement("canvas"),...qr,...t,backend:t?.backend??Wr},this.canvas=this.options.canvas,this.canvas.hasAttribute("tabindex")||this.canvas.setAttribute("tabindex","-1"),this.loader=new Or({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 qi(this),this.sceneManager=new fe(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 oi(this):new Xe(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=xi,t.AudioAnalyser=class{_media;_fftSize;_minDecibels;_maxDecibels;_smoothingTimeConstant;_frequencyBinCount;_timeDomainData;_frequencyData;_preciseTimeDomainData;_preciseFrequencyData;_analyser=null;_audioContext=null;_analyserTarget=null;constructor(t,e={}){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),hr()?this.setupWithAudioContext(ar()):or.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(){or.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=kr,t.BlurFilter=class extends Qs{_sprite=new Ve(null);_sampleTint=W.white.clone();_radius=2;_quality=1;constructor(t={}){super(),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 he(()=>{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:W.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}},t.Bounds=Jt,t.BundleLoadError=Ir,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{_callback;constructor(t){this._callback=t}execute(t){this._callback(t)}},t.Circle=Vs,t.CircleGeometry=Ys,t.Clock=B,t.Color=W,t.ColorAffector=class{_fromColor;_toColor;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 Qs{_color;_sprite=new Ve(null);constructor(t=W.white){super(),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 he(()=>{this._sprite.render(e)},{target:r,view:r.view,clearColor:W.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}},t.Container=Yr,t.Drawable=de,t.DrawableShape=ce,t.Ellipse=Gs,t.FactoryRegistry=gr,t.Filter=Qs,t.Flags=et,t.FontFactory=xr,t.ForceAffector=class{_acceleration;constructor(t,e){this._acceleration=new ne(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=Si,t.Gamepad=_i,t.GamepadControl=mi,t.GamepadMapping=gi,t.GamepadPromptLayouts=class{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(t){return $r.get(t)??[.5,.5]}static getControlLabels(t){return es.get(t)??Qr}static buildControlChannelMap(){return Kr}},t.GenericDualAnalogGamepadMapping=bi,t.Geometry=pe,t.Graphics=Xs,t.ImageFactory=br,t.IndexedDbDatabase=Js,t.IndexedDbStore=class{_db;constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new Js(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=is,t.InputManager=qi,t.Interval=nt,t.JoyConLeftGamepadMapping=Ti,t.JoyConRightGamepadMapping=Ci,t.Json=pr,t.JsonFactory=Sr,t.Line=Is,t.Loader=Or,t.Matrix=tt,t.Music=ur,t.MusicFactory=Cr,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=ee,t.ObservableVector=Z,t.Particle=Ge,t.ParticleOptions=Hs,t.ParticleSystem=Ue,t.PlayStationGamepadMapping=Mi,t.Pointer=fi,t.PolarVector=qs,t.Polygon=Os,t.Quadtree=Hr,t.Random=r,t.RapierPhysicsBinding=_n,t.RapierPhysicsWorld=fn,t.Rectangle=Zt,t.RenderNode=ue,t.RenderTarget=oe,t.RenderTargetPass=he,t.RenderTexture=ae,t.RendererRegistry=ze,t.Sampler=class{_context;_sampler;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;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{_scaleFactor;constructor(t,e){this._scaleFactor=new ne(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=Xr,t.SceneManager=fe,t.SceneNode=te,t.Segment=Ws,t.Shader=we,t.ShaderAttribute=Te,t.ShaderUniform=Ce,t.Signal=R,t.Size=i,t.Sound=dr,t.SoundFactory=Mr,t.Sprite=Ve,t.Spritesheet=class{texture;frames=new Map;sprites=new Map;animations=new Map;constructor(t,e){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 Zt(i,r,s,n),a=new Ve(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=Pi,t.SvgAsset=fr,t.SvgFactory=Ar,t.SwitchProGamepadMapping=Bi,t.Text=class extends Ve{_text;_style;_canvas;_context;_dirty=!0;constructor(t,e,i,r=document.createElement("canvas")){super(new Oe(r,i)),this._text=t,this._style=e&&e instanceof $s?e:new $s(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 $s?t:new $s(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(Zt.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(!ke.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),ke.set(t,i.offsetHeight),e.removeChild(i)}return ke.get(t)})(e.font)+i.strokeThickness,n=r.split(Ks),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(Zt.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=_r,t.TextFactory=Pr,t.TextStyle=$s,t.Texture=Oe,t.TextureFactory=Br,t.Time=n,t.Timer=jr,t.TorqueAffector=class{_angularAcceleration;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=rt,t.UniversalEmitter=class{_emissionRate;_particleOptions;_emissionDelta=0;constructor(t,e){this._emissionRate=t,this._particleOptions=e??new Hs}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=ne,t.Video=cr,t.VideoFactory=Er,t.View=re,t.VttAsset=mr,t.VttFactory=Dr,t.WasmFactory=Fr,t.WebGl2ParticleRenderer=De,t.WebGl2PrimitiveRenderer=Ie,t.WebGl2RenderBuffer=Ee,t.WebGl2RenderManager=Xe,t.WebGl2ShaderBlock=Me,t.WebGl2SpriteRenderer=Le,t.WebGl2VertexArrayObject=ge,t.WebGpuParticleRenderer=si,t.WebGpuPrimitiveRenderer=Ze,t.WebGpuRenderManager=oi,t.WebGpuSpriteRenderer=ti,t.XboxGamepadMapping=Ri,t.bezierCurveTo=O,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 pe({vertices:r,indices:s,points:a})},t.buildEllipse=As,t.buildLine=Rs,t.buildPath=Es,t.buildPolygon=ks,t.buildRectangle=Fs,t.buildStar=Ls,t.builtInGamepadDefinitions=zi,t.canvasSourceToDataUrl=P,t.clamp=I,t.createRapierPhysicsWorld=async(t={})=>await fn.create(t),t.createRenderStats=We,t.createWebGl2ShaderRuntime=Be,t.decodeAudioData=lr,t.defineAssetManifest=Nr,t.degreesPerRadian=k,t.degreesToRadians=D,t.determineMimeType=vr,t.emptyArrayBuffer=S,t.getAudioContext=ar,t.getCanvasSourceSize=C,t.getCollisionCircleCircle=Ht,t.getCollisionCircleRectangle=Yt,t.getCollisionPolygonCircle=Xt,t.getCollisionRectangleRectangle=qt,t.getCollisionSat=jt,t.getDistance=U,t.getOfflineAudioContext=()=>er(),t.getPreciseTime=v,t.getTextureSourceSize=M,t.getVoronoiRegion=(e,i)=>{const r=i.dot(e.x,e.y);return r<0?t.VoronoiRegion.left:r>e.lengthSq?t.VoronoiRegion.right:t.VoronoiRegion.middle},t.getWebGpuBlendState=$e,t.hours=t=>new n(t,n.hours),t.inRange=G,t.intersectionCircleCircle=Dt,t.intersectionCircleEllipse=It,t.intersectionCirclePoly=Ut,t.intersectionEllipseEllipse=Ot,t.intersectionEllipsePoly=zt,t.intersectionLineCircle=Bt,t.intersectionLineEllipse=Rt,t.intersectionLineLine=Mt,t.intersectionLinePoly=Et,t.intersectionLineRect=Pt,t.intersectionPointCircle=St,t.intersectionPointEllipse=Tt,t.intersectionPointLine=vt,t.intersectionPointPoint=wt,t.intersectionPointPoly=Ct,t.intersectionPointRect=bt,t.intersectionPolyPoly=Wt,t.intersectionRectCircle=kt,t.intersectionRectEllipse=Ft,t.intersectionRectPoly=Lt,t.intersectionRectRect=At,t.intersectionSat=xt,t.isAudioContextReady=hr,t.isPowerOfTwo=V,t.lerp=N,t.matchesIds=Vi,t.milliseconds=b,t.minutes=t=>new n(t,n.minutes),t.noop=f,t.normalizeIds=Ni,t.onAudioContextReady=or,t.parseGamepadDescriptor=Gi,t.quadraticCurveTo=z,t.radiansPerDegree=A,t.radiansToDegrees=t=>t*k,t.rand=(t,e)=>(null===u&&(u=new r),u).next(t,e),t.removeArrayItems=T,t.resetRenderStats=qe,t.resolveDefinition=Ui,t.resolveGamepadDefinition=Oi,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=E,t.trimRotation=L,t.webGl2PrimitiveArrayConstructors=be,t.webGl2PrimitiveByteSizeMapping=ve,t.webGl2PrimitiveTypeNames=Se,t}({});
|
|
2
|
-
//# sourceMappingURL=exo.global.min.js.map
|