holostaff-widget 2.2.0 → 3.0.0-alpha.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/dist/{BufferResource-C1ruXQTX.js → BufferResource-BfMo11sZ.js} +2 -2
- package/dist/{BufferResource-C1ruXQTX.js.map → BufferResource-BfMo11sZ.js.map} +1 -1
- package/dist/{CanvasRenderer-DbChYDOl.js → CanvasRenderer-BKOijV4O.js} +3 -3
- package/dist/{CanvasRenderer-DbChYDOl.js.map → CanvasRenderer-BKOijV4O.js.map} +1 -1
- package/dist/{Filter-D2L1V9fN.js → Filter-CINkTga6.js} +2 -2
- package/dist/{Filter-D2L1V9fN.js.map → Filter-CINkTga6.js.map} +1 -1
- package/dist/{RenderTargetSystem-DPwhMcpZ.js → RenderTargetSystem-DPqzypKt.js} +3 -3
- package/dist/{RenderTargetSystem-DPwhMcpZ.js.map → RenderTargetSystem-DPqzypKt.js.map} +1 -1
- package/dist/{WebGLRenderer-Cp6XondT.js → WebGLRenderer-b8Q9AmN0.js} +4 -4
- package/dist/{WebGLRenderer-Cp6XondT.js.map → WebGLRenderer-b8Q9AmN0.js.map} +1 -1
- package/dist/{WebGPURenderer-BDmK_KWD.js → WebGPURenderer-Ccxwx7Mk.js} +4 -4
- package/dist/{WebGPURenderer-BDmK_KWD.js.map → WebGPURenderer-Ccxwx7Mk.js.map} +1 -1
- package/dist/{browserAll-CjLyYNcB.js → browserAll-BYMbGfMT.js} +3 -3
- package/dist/{browserAll-CjLyYNcB.js.map → browserAll-BYMbGfMT.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +124 -104
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-CgKgBdpC.js → index-Xz_eejjc.js} +8212 -5390
- package/dist/index-Xz_eejjc.js.map +1 -0
- package/dist/{webworkerAll-BGJHmEXB.js → webworkerAll-Bcdpmg6h.js} +3 -3
- package/dist/{webworkerAll-BGJHmEXB.js.map → webworkerAll-Bcdpmg6h.js.map} +1 -1
- package/package.json +5 -2
- package/dist/index-CgKgBdpC.js.map +0 -1
package/dist/hs-widget.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(ri,Kt){typeof exports=="object"&&typeof module<"u"?Kt(exports):typeof define=="function"&&define.amd?define(["exports"],Kt):(ri=typeof globalThis<"u"?globalThis:ri||self,Kt(ri.HolostaffWidget={}))})(this,(function(ri){"use strict";const Kt={position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net"};function vu(s){const t=s.dataset.staffId;if(!t)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:t,position:s.dataset.position??Kt.position,trigger:s.dataset.trigger??Kt.trigger,scrollThreshold:parseFloat(s.dataset.scrollThreshold??"")||Kt.scrollThreshold,delayMs:parseInt(s.dataset.delayMs??"",10)||Kt.delayMs,theme:s.dataset.theme??Kt.theme,accentColor:s.dataset.accentColor??Kt.accentColor,language:s.dataset.language??Kt.language,backendUrl:s.dataset.backendUrl??Kt.backendUrl}}const Eu=["bottom-center","bottom-left","bottom-right"],Tu=["scroll","delay","immediate"],Su=["light","dark","auto"];function Cu(s,t,e){const i={...s};return!t.dataset.trigger&&e.trigger&&Tu.includes(e.trigger)&&(i.trigger=e.trigger),!t.dataset.position&&e.position&&Eu.includes(e.position)&&(i.position=e.position),!t.dataset.theme&&e.theme&&Su.includes(e.theme)&&(i.theme=e.theme),!t.dataset.scrollThreshold&&e.scrollThreshold!=null&&(i.scrollThreshold=e.scrollThreshold),!t.dataset.delayMs&&e.delayMs!=null&&(i.delayMs=e.delayMs),i}const Ks="https://us-central1-holostaff-ai.cloudfunctions.net";async function wu(s,t=Ks){const e=await fetch(`${t}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s})});if(!e.ok){const i=await e.json().catch(()=>({error:e.statusText}));throw new Error(i.error||`Session request failed: ${e.status}`)}return e.json()}async function Au(s,t=Ks){const e=await fetch(`${t}/widgetConfig?staffId=${encodeURIComponent(s)}`);if(!e.ok){const i=await e.json().catch(()=>({error:e.statusText}));throw new Error(i.error||`Config request failed: ${e.status}`)}return e.json()}async function Ru(s,t,e,i=Ks){const r=await fetch(`${i}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,domSnapshot:t,instruction:e})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var w=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(w||{});const Zs=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},cs=(s,t)=>Zs(s).priority??t,J={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(Zs).forEach(t=>{t.type.forEach(e=>{var i,r;return(r=(i=this._removeHandlers)[e])==null?void 0:r.call(i,t)})}),this},add(...s){return s.map(Zs).forEach(t=>{t.type.forEach(e=>{var n,o;const i=this._addHandlers,r=this._queue;i[e]?(o=i[e])==null||o.call(i,t):(r[e]=r[e]||[],(n=r[e])==null||n.push(t))})}),this},handle(s,t,e){var o;const i=this._addHandlers,r=this._removeHandlers;if(i[s]||r[s])throw new Error(`Extension type ${s} already has a handler`);i[s]=t,r[s]=e;const n=this._queue;return n[s]&&((o=n[s])==null||o.forEach(a=>t(a)),delete n[s]),this},handleByMap(s,t){return this.handle(s,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(s,t,e=-1){return this.handle(s,i=>{t.findIndex(n=>n.name===i.name)>=0||(t.push({name:i.name,value:i.ref}),t.sort((n,o)=>cs(o.value,e)-cs(n.value,e)))},i=>{const r=t.findIndex(n=>n.name===i.name);r!==-1&&t.splice(r,1)})},handleByList(s,t,e=-1){return this.handle(s,i=>{t.includes(i.ref)||(t.push(i.ref),t.sort((r,n)=>cs(n,e)-cs(r,e)))},i=>{const r=t.indexOf(i.ref);r!==-1&&t.splice(r,1)})},mixin(s,...t){for(const e of t)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(e))}},Iu={extension:{type:w.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>Vx)}},Pu={extension:{type:w.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>zx)}};class Ot{constructor(t,e,i){this._x=e||0,this._y=i||0,this._observer=t}clone(t){return new Ot(t??this._observer,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this._observer._onUpdate(this)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this._observer._onUpdate(this)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._observer._onUpdate(this))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._observer._onUpdate(this))}}function no(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Js={exports:{}},oo;function Mu(){return oo||(oo=1,(function(s){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function r(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,u,m){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,m),g=e?e+h:h;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)t.call(c,u)&&h.push(e?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=e?e+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var m=0,f=u.length,g=new Array(f);m<f;m++)g[m]=u[m].fn;return g},a.prototype.listenerCount=function(h){var c=e?e+h:h,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(h,c,u,m,f,g){var y=e?e+h:h;if(!this._events[y])return!1;var x=this._events[y],v=arguments.length,E,T;if(x.fn){switch(x.once&&this.removeListener(h,x.fn,void 0,!0),v){case 1:return x.fn.call(x.context),!0;case 2:return x.fn.call(x.context,c),!0;case 3:return x.fn.call(x.context,c,u),!0;case 4:return x.fn.call(x.context,c,u,m),!0;case 5:return x.fn.call(x.context,c,u,m,f),!0;case 6:return x.fn.call(x.context,c,u,m,f,g),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];x.fn.apply(x.context,E)}else{var C=x.length,R;for(T=0;T<C;T++)switch(x[T].once&&this.removeListener(h,x[T].fn,void 0,!0),v){case 1:x[T].fn.call(x[T].context);break;case 2:x[T].fn.call(x[T].context,c);break;case 3:x[T].fn.call(x[T].context,c,u);break;case 4:x[T].fn.call(x[T].context,c,u,m);break;default:if(!E)for(R=1,E=new Array(v-1);R<v;R++)E[R-1]=arguments[R];x[T].fn.apply(x[T].context,E)}}return!0},a.prototype.on=function(h,c,u){return n(this,h,c,u,!1)},a.prototype.once=function(h,c,u){return n(this,h,c,u,!0)},a.prototype.removeListener=function(h,c,u,m){var f=e?e+h:h;if(!this._events[f])return this;if(!c)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!m||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var y=0,x=[],v=g.length;y<v;y++)(g[y].fn!==c||m&&!g[y].once||u&&g[y].context!==u)&&x.push(g[y]);x.length?this._events[f]=x.length===1?x[0]:x:o(this,f)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=e?e+h:h,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,s.exports=a})(Js)),Js.exports}var ku=Mu();const Zt=no(ku),Bu=Math.PI*2,Ou=180/Math.PI,Du=Math.PI/180;class mt{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new mt(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Qs.x=0,Qs.y=0,Qs}}const Qs=new mt;class W{constructor(t=1,e=0,i=0,r=1,n=0,o=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=r,this.tx=n,this.ty=o}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,r,n,o){return this.a=t,this.b=e,this.c=i,this.d=r,this.tx=n,this.ty=o,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(t,e){e=e||new mt;const i=t.x,r=t.y;return e.x=this.a*i+this.c*r+this.tx,e.y=this.b*i+this.d*r+this.ty,e}applyInverse(t,e){e=e||new mt;const i=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(i*o+n*-r),c=t.x,u=t.y;return e.x=o*h*c+-n*h*u+(l*n-a*o)*h,e.y=i*h*u+-r*h*c+(-l*i+a*r)*h,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),r=this.a,n=this.c,o=this.tx;return this.a=r*e-this.b*i,this.b=r*i+this.b*e,this.c=n*e-this.d*i,this.d=n*i+this.d*e,this.tx=o*e-this.ty*i,this.ty=o*i+this.ty*e,this}append(t){const e=this.a,i=this.b,r=this.c,n=this.d;return this.a=t.a*e+t.b*r,this.b=t.a*i+t.b*n,this.c=t.c*e+t.d*r,this.d=t.c*i+t.d*n,this.tx=t.tx*e+t.ty*r+this.tx,this.ty=t.tx*i+t.ty*n+this.ty,this}appendFrom(t,e){const i=t.a,r=t.b,n=t.c,o=t.d,a=t.tx,l=t.ty,h=e.a,c=e.b,u=e.c,m=e.d;return this.a=i*h+r*u,this.b=i*c+r*m,this.c=n*h+o*u,this.d=n*c+o*m,this.tx=a*h+l*u+e.tx,this.ty=a*c+l*m+e.ty,this}setTransform(t,e,i,r,n,o,a,l,h){return this.a=Math.cos(a+h)*n,this.b=Math.sin(a+h)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=t-(i*this.a+r*this.c),this.ty=e-(i*this.b+r*this.d),this}prepend(t){const e=this.tx;if(t.a!==1||t.b!==0||t.c!==0||t.d!==1){const i=this.a,r=this.c;this.a=i*t.a+this.b*t.c,this.b=i*t.b+this.b*t.d,this.c=r*t.a+this.d*t.c,this.d=r*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,r=this.c,n=this.d,o=t.pivot,a=-Math.atan2(-r,n),l=Math.atan2(i,e),h=Math.abs(a+l);return h<1e-5||Math.abs(Bu-h)<1e-5?(t.rotation=l,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=a,t.skew.y=l),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(r*r+n*n),t.position.x=this.tx+(o.x*e+o.y*r),t.position.y=this.ty+(o.x*i+o.y*n),t}invert(){const t=this.a,e=this.b,i=this.c,r=this.d,n=this.tx,o=t*r-e*i;return this.a=r/o,this.b=-e/o,this.c=-i/o,this.d=t/o,this.tx=(i*this.ty-r*n)/o,this.ty=-(t*this.ty-e*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new W;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}equals(t){return t.a===this.a&&t.b===this.b&&t.c===this.c&&t.d===this.d&&t.tx===this.tx&&t.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Uu.identity()}static get shared(){return Gu.identity()}}const Gu=new W,Uu=new W,He=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],We=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ve=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ze=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],tr=[],ao=[],us=Math.sign;function Lu(){for(let s=0;s<16;s++){const t=[];tr.push(t);for(let e=0;e<16;e++){const i=us(He[s]*He[e]+Ve[s]*We[e]),r=us(We[s]*He[e]+ze[s]*We[e]),n=us(He[s]*Ve[e]+Ve[s]*ze[e]),o=us(We[s]*Ve[e]+ze[s]*ze[e]);for(let a=0;a<16;a++)if(He[a]===i&&We[a]===r&&Ve[a]===n&&ze[a]===o){t.push(a);break}}}for(let s=0;s<16;s++){const t=new W;t.set(He[s],We[s],Ve[s],ze[s],0,0),ao.push(t)}}Lu();const it={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:s=>He[s],uY:s=>We[s],vX:s=>Ve[s],vY:s=>ze[s],inv:s=>s&8?s&15:-s&7,add:(s,t)=>tr[s][t],sub:(s,t)=>tr[s][it.inv(t)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,t)=>Math.abs(s)*2<=Math.abs(t)?t>=0?it.S:it.N:Math.abs(t)*2<=Math.abs(s)?s>0?it.E:it.W:t>0?s>0?it.SE:it.SW:s>0?it.NE:it.NW,matrixAppendRotationInv:(s,t,e=0,i=0,r=0,n=0)=>{const o=ao[it.inv(t)],a=o.a,l=o.b,h=o.c,c=o.d,u=e-Math.min(0,a*r,h*n,a*r+h*n),m=i-Math.min(0,l*r,c*n,l*r+c*n),f=s.a,g=s.b,y=s.c,x=s.d;s.a=a*f+l*y,s.b=a*g+l*x,s.c=h*f+c*y,s.d=h*g+c*x,s.tx=u*f+m*y+s.tx,s.ty=u*g+m*x+s.ty},transformRectCoords:(s,t,e,i)=>{const{x:r,y:n,width:o,height:a}=s,{x:l,y:h,width:c,height:u}=t;return e===it.E?(i.set(r+l,n+h,o,a),i):e===it.S?i.set(c-n-a+l,r+h,a,o):e===it.W?i.set(c-r-o+l,u-n-a+h,o,a):e===it.N?i.set(n+l,u-r-o+h,a,o):i.set(r+l,n+h,o,a)}},ds=[new mt,new mt,new mt,new mt];class ct{constructor(t=0,e=0,i=0,r=0){this.type="rectangle",this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new ct(0,0,0,0)}clone(){return new ct(this.x,this.y,this.width,this.height)}copyFromBounds(t){return this.x=t.minX,this.y=t.minY,this.width=t.maxX-t.minX,this.height=t.maxY-t.minY,this}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){return this.width<=0||this.height<=0?!1:t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height}strokeContains(t,e,i,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,h=i*(1-r),c=i-h,u=a-h,m=a+n+h,f=l-h,g=l+o+h,y=a+c,x=a+n-c,v=l+c,E=l+o-c;return t>=u&&t<=m&&e>=f&&e<=g&&!(t>y&&t<x&&e>v&&e<E)}intersects(t,e){if(!e){const F=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=F)return!1;const k=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>k}const i=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=i||o<=n)return!1;const a=ds[0].set(t.left,t.top),l=ds[1].set(t.left,t.bottom),h=ds[2].set(t.right,t.top),c=ds[3].set(t.right,t.bottom);if(h.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(u===0||(e.apply(a,a),e.apply(l,l),e.apply(h,h),e.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=i||Math.min(a.x,l.x,h.x,c.x)>=r||Math.max(a.y,l.y,h.y,c.y)<=n||Math.min(a.y,l.y,h.y,c.y)>=o))return!1;const m=u*(l.y-a.y),f=u*(a.x-l.x),g=m*i+f*n,y=m*r+f*n,x=m*i+f*o,v=m*r+f*o;if(Math.max(g,y,x,v)<=m*a.x+f*a.y||Math.min(g,y,x,v)>=m*c.x+f*c.y)return!1;const E=u*(a.y-h.y),T=u*(h.x-a.x),C=E*i+T*n,R=E*r+T*n,A=E*i+T*o,P=E*r+T*o;return!(Math.max(C,R,A,P)<=E*a.x+T*a.y||Math.min(C,R,A,P)>=E*c.x+T*c.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=t*2,this.height+=e*2,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),r=Math.max(this.y,t.y),n=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,r=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=r-this.y,this}scale(t,e=t){return this.x*=t,this.y*=e,this.width*=t,this.height*=e,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),r=Math.min(this.y,t.y),n=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=r,this.height=n-r,this}getBounds(t){return t||(t=new ct),t.copyFrom(this),t}containsRect(t){if(this.width<=0||this.height<=0)return!1;const e=t.x,i=t.y,r=t.x+t.width,n=t.y+t.height;return e>=this.x&&e<this.x+this.width&&i>=this.y&&i<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(t,e,i,r){return this.x=t,this.y=e,this.width=i,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const er={default:-1};function dt(s="default"){return er[s]===void 0&&(er[s]=-1),++er[s]}const lo=new Set,vt="8.0.0",Nu="8.3.4",ni={quiet:!1,noColor:!1},K=((s,t,e=3)=>{if(ni.quiet||lo.has(t))return;let i=new Error().stack;const r=`${t}
|
|
2
|
-
Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!
|
|
3
|
-
`).splice(
|
|
4
|
-
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(i))),lo.add(t)});Object.defineProperties(K,{quiet:{get:()=>ni.quiet,set:s=>{ni.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>ni.noColor,set:s=>{ni.noColor=s},enumerable:!0,configurable:!1}});const ho=()=>{};function oi(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function co(s){return!(s&s-1)&&!!s}function uo(s){const t={};for(const e in s)s[e]!==void 0&&(t[e]=s[e]);return t}const fo=Object.create(null);function Fu(s){const t=fo[s];return t===void 0&&(fo[s]=dt("resource")),t}const po=class su extends Zt{constructor(t={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,t={...su.defaultOptions,...t},this.addressMode=t.addressMode,this.addressModeU=t.addressModeU??this.addressModeU,this.addressModeV=t.addressModeV??this.addressModeV,this.addressModeW=t.addressModeW??this.addressModeW,this.scaleMode=t.scaleMode,this.magFilter=t.magFilter??this.magFilter,this.minFilter=t.minFilter??this.minFilter,this.mipmapFilter=t.mipmapFilter??this.mipmapFilter,this.lodMinClamp=t.lodMinClamp,this.lodMaxClamp=t.lodMaxClamp,this.compare=t.compare,this.maxAnisotropy=t.maxAnisotropy??1}set addressMode(t){this.addressModeU=t,this.addressModeV=t,this.addressModeW=t}get addressMode(){return this.addressModeU}set wrapMode(t){K(vt,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=t}get wrapMode(){return this.addressMode}set scaleMode(t){this.magFilter=t,this.minFilter=t,this.mipmapFilter=t}get scaleMode(){return this.magFilter}set maxAnisotropy(t){this._maxAnisotropy=Math.min(t,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const t=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Fu(t),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};po.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let $e=po;const mo=class ru extends Zt{constructor(t={}){super(),this.options=t,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=dt("textureSource"),this._resourceType="textureSource",this._resourceId=dt("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,t={...ru.defaultOptions,...t},this.label=t.label??"",this.resource=t.resource,this.autoGarbageCollect=t.autoGarbageCollect,this._resolution=t.resolution,t.width?this.pixelWidth=t.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,t.height?this.pixelHeight=t.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=t.format,this.dimension=t.dimensions,this.viewDimension=t.viewDimension??t.dimensions,this.arrayLayerCount=t.arrayLayerCount,this.mipLevelCount=t.mipLevelCount,this.autoGenerateMipmaps=t.autoGenerateMipmaps,this.sampleCount=t.sampleCount,this.antialias=t.antialias,this.alphaMode=t.alphaMode,this.style=new $e(uo(t)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(t){var e,i;this.style!==t&&((e=this._style)==null||e.off("change",this._onStyleChange,this),this._style=t,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(t){this._style.maxAnisotropy=t}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(t){this._style.addressMode=t}get repeatMode(){return this._style.addressMode}set repeatMode(t){this._style.addressMode=t}get magFilter(){return this._style.magFilter}set magFilter(t){this._style.magFilter=t}get minFilter(){return this._style.minFilter}set minFilter(t){this._style.minFilter=t}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(t){this._style.mipmapFilter=t}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(t){this._style.lodMinClamp=t}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(t){this._style.lodMaxClamp=t}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const t=this._resolution;if(this.resize(this.resourceWidth/t,this.resourceHeight/t))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var t,e;this._resourceId=dt("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(e=(t=this._gpuData[i])==null?void 0:t.destroy)==null||e.call(t);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:t}=this;return t.naturalWidth||t.videoWidth||t.displayWidth||t.width}get resourceHeight(){const{resource:t}=this;return t.naturalHeight||t.videoHeight||t.displayHeight||t.height}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this.width=this.pixelWidth/t,this.height=this.pixelHeight/t)}resize(t,e,i){i||(i=this._resolution),t||(t=this.width),e||(e=this.height);const r=Math.round(t*i),n=Math.round(e*i);return this.width=r/i,this.height=n/i,this._resolution=i,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=dt("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(t){this._style.wrapMode=t}get wrapMode(){return this._style.wrapMode}set scaleMode(t){this._style.scaleMode=t}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=co(this.pixelWidth)&&co(this.pixelHeight)}static test(t){throw new Error("Unimplemented")}};mo.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let At=mo;class ir extends At{constructor(t){const e=t.resource||new Float32Array(t.width*t.height*4);let i=t.format;i||(e instanceof Float32Array?i="rgba32float":e instanceof Int32Array||e instanceof Uint32Array?i="rgba32uint":e instanceof Int16Array||e instanceof Uint16Array?i="rgba16uint":(e instanceof Int8Array,i="bgra8unorm")),super({...t,resource:e,format:i}),this.uploadMethodId="buffer"}static test(t){return t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}ir.extension=w.TextureSource;const go=new W;class _o{constructor(t,e){this.mapCoord=new W,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof e>"u"?this.clampMargin=t.width<10?0:.5:this.clampMargin=e,this.isSimple=!1,this.texture=t}get texture(){return this._texture}set texture(t){var e;this.texture!==t&&((e=this._texture)==null||e.removeListener("update",this.update,this),this._texture=t,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(t,e){e===void 0&&(e=t);const i=this.mapCoord;for(let r=0;r<t.length;r+=2){const n=t[r],o=t[r+1];e[r]=n*i.a+o*i.c+i.tx,e[r+1]=n*i.b+o*i.d+i.ty}return e}update(){const t=this._texture;this._updateID++;const e=t.uvs;this.mapCoord.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0);const i=t.orig,r=t.trim;r&&(go.set(i.width/r.width,0,0,i.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(go));const n=t.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(t.frame.x+a+l)/n.width,o[1]=(t.frame.y+a+l)/n.height,o[2]=(t.frame.x+t.frame.width-a+l)/n.width,o[3]=(t.frame.y+t.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=t.frame.width===n.width&&t.frame.height===n.height&&t.rotate===0,!0}}class $ extends Zt{constructor({source:t,label:e,frame:i,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:h}={}){if(super(),this.uid=dt("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new ct,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=e,this.source=(t==null?void 0:t.source)??new At,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:c,height:u}=this._source;this.frame.width=c,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=h||!1,this.updateUvs()}set source(t){this._source&&this._source.off("resize",this.update,this),this._source=t,t.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new _o(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:t,frame:e}=this,{width:i,height:r}=this._source,n=e.x/i,o=e.y/r,a=e.width/i,l=e.height/r;let h=this.rotate;if(h){const c=a/2,u=l/2,m=n+c,f=o+u;h=it.add(h,it.NW),t.x0=m+c*it.uX(h),t.y0=f+u*it.uY(h),h=it.add(h,2),t.x1=m+c*it.uX(h),t.y1=f+u*it.uY(h),h=it.add(h,2),t.x2=m+c*it.uX(h),t.y2=f+u*it.uY(h),h=it.add(h,2),t.x3=m+c*it.uX(h),t.y3=f+u*it.uY(h)}else t.x0=n,t.y0=o,t.x1=n+a,t.y1=o,t.x2=n+a,t.y2=o+l,t.x3=n,t.y3=o+l}destroy(t=!1){this._source&&(this._source.off("resize",this.update,this),t&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return K(vt,"Texture.baseTexture is now Texture.source"),this._source}}$.EMPTY=new $({label:"EMPTY",source:new At({label:"EMPTY"})}),$.EMPTY.destroy=ho,$.WHITE=new $({source:new ir({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),$.WHITE.destroy=ho;function yo(s,t,e){const{width:i,height:r}=e.orig,n=e.trim;if(n){const o=n.width,a=n.height;s.minX=n.x-t._x*i,s.maxX=s.minX+o,s.minY=n.y-t._y*r,s.maxY=s.minY+a}else s.minX=-t._x*i,s.maxX=s.minX+i,s.minY=-t._y*r,s.maxY=s.minY+r}const xo=new W;class Lt{constructor(t=1/0,e=1/0,i=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=xo,this.minX=t,this.minY=e,this.maxX=i,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new ct);const t=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(t.x=0,t.y=0,t.width=0,t.height=0):t.copyFromBounds(this),t}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=xo,this}set(t,e,i,r){this.minX=t,this.minY=e,this.maxX=i,this.maxY=r}addFrame(t,e,i,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,h=n.d,c=n.tx,u=n.ty;let m=this.minX,f=this.minY,g=this.maxX,y=this.maxY,x=o*t+l*e+c,v=a*t+h*e+u;x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*i+l*e+c,v=a*i+h*e+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*t+l*r+c,v=a*t+h*r+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*i+l*r+c,v=a*i+h*r+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),this.minX=m,this.minY=f,this.maxX=g,this.maxY=y}addRect(t,e){this.addFrame(t.x,t.y,t.x+t.width,t.y+t.height,e)}addBounds(t,e){this.addFrame(t.minX,t.minY,t.maxX,t.maxY,e)}addBoundsMask(t){this.minX=this.minX>t.minX?this.minX:t.minX,this.minY=this.minY>t.minY?this.minY:t.minY,this.maxX=this.maxX<t.maxX?this.maxX:t.maxX,this.maxY=this.maxY<t.maxY?this.maxY:t.maxY}applyMatrix(t){const e=this.minX,i=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:h,tx:c,ty:u}=t;let m=o*e+l*i+c,f=a*e+h*i+u;this.minX=m,this.minY=f,this.maxX=m,this.maxY=f,m=o*r+l*i+c,f=a*r+h*i+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY,m=o*e+l*n+c,f=a*e+h*n+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY,m=o*r+l*n+c,f=a*r+h*n+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY}fit(t){return this.minX<t.left&&(this.minX=t.left),this.maxX>t.right&&(this.maxX=t.right),this.minY<t.top&&(this.minY=t.top),this.maxY>t.bottom&&(this.maxY=t.bottom),this}fitBounds(t,e,i,r){return this.minX<t&&(this.minX=t),this.maxX>e&&(this.maxX=e),this.minY<i&&(this.minY=i),this.maxY>r&&(this.maxY=r),this}pad(t,e=t){return this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Lt(this.minX,this.minY,this.maxX,this.maxY)}scale(t,e=t){return this.minX*=t,this.minY*=e,this.maxX*=t,this.maxY*=e,this}get x(){return this.minX}set x(t){const e=this.maxX-this.minX;this.minX=t,this.maxX=t+e}get y(){return this.minY}set y(t){const e=this.maxY-this.minY;this.minY=t,this.maxY=t+e}get width(){return this.maxX-this.minX}set width(t){this.maxX=this.minX+t}get height(){return this.maxY-this.minY}set height(t){this.maxY=this.minY+t}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(t,e,i,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const h=r.a,c=r.b,u=r.c,m=r.d,f=r.tx,g=r.ty;for(let y=e;y<i;y+=2){const x=t[y],v=t[y+1],E=h*x+u*v+f,T=c*x+m*v+g;n=E<n?E:n,o=T<o?T:o,a=E>a?E:a,l=T>l?T:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(t,e){return this.minX<=t&&this.minY<=e&&this.maxX>=t&&this.maxY>=e}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(t){return this.minX=t.minX,this.minY=t.minY,this.maxX=t.maxX,this.maxY=t.maxY,this}}var Hu={grad:.9,turn:360,rad:360/(2*Math.PI)},ge=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},Pt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=Math.pow(10,t)),Math.round(e*s)/e+0},Jt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=1),s>e?e:s>t?s:t},bo=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},vo=function(s){return{r:Jt(s.r,0,255),g:Jt(s.g,0,255),b:Jt(s.b,0,255),a:Jt(s.a)}},sr=function(s){return{r:Pt(s.r),g:Pt(s.g),b:Pt(s.b),a:Pt(s.a,3)}},Wu=/^#([0-9a-f]{3,8})$/i,fs=function(s){var t=s.toString(16);return t.length<2?"0"+t:t},Eo=function(s){var t=s.r,e=s.g,i=s.b,r=s.a,n=Math.max(t,e,i),o=n-Math.min(t,e,i),a=o?n===t?(e-i)/o:n===e?2+(i-t)/o:4+(t-e)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},To=function(s){var t=s.h,e=s.s,i=s.v,r=s.a;t=t/360*6,e/=100,i/=100;var n=Math.floor(t),o=i*(1-e),a=i*(1-(t-n)*e),l=i*(1-(1-t+n)*e),h=n%6;return{r:255*[i,a,o,o,l,i][h],g:255*[l,i,i,a,o,o][h],b:255*[o,o,l,i,i,a][h],a:r}},So=function(s){return{h:bo(s.h),s:Jt(s.s,0,100),l:Jt(s.l,0,100),a:Jt(s.a)}},Co=function(s){return{h:Pt(s.h),s:Pt(s.s),l:Pt(s.l),a:Pt(s.a,3)}},wo=function(s){return To((e=(t=s).s,{h:t.h,s:(e*=((i=t.l)<50?i:100-i)/100)>0?2*e/(i+e)*100:0,v:i+e,a:t.a}));var t,e,i},Mi=function(s){return{h:(t=Eo(s)).h,s:(r=(200-(e=t.s))*(i=t.v)/100)>0&&r<200?e*i/100/(r<=100?r:200-r)*100:0,l:r/2,a:t.a};var t,e,i,r},Vu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,zu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,$u=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ju=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,rr={string:[[function(s){var t=Wu.exec(s);return t?(s=t[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?Pt(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?Pt(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var t=$u.exec(s)||ju.exec(s);return t?t[2]!==t[4]||t[4]!==t[6]?null:vo({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(s){var t=Vu.exec(s)||zu.exec(s);if(!t)return null;var e,i,r=So({h:(e=t[1],i=t[2],i===void 0&&(i="deg"),Number(e)*(Hu[i]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return wo(r)},"hsl"]],object:[[function(s){var t=s.r,e=s.g,i=s.b,r=s.a,n=r===void 0?1:r;return ge(t)&&ge(e)&&ge(i)?vo({r:Number(t),g:Number(e),b:Number(i),a:Number(n)}):null},"rgb"],[function(s){var t=s.h,e=s.s,i=s.l,r=s.a,n=r===void 0?1:r;if(!ge(t)||!ge(e)||!ge(i))return null;var o=So({h:Number(t),s:Number(e),l:Number(i),a:Number(n)});return wo(o)},"hsl"],[function(s){var t=s.h,e=s.s,i=s.v,r=s.a,n=r===void 0?1:r;if(!ge(t)||!ge(e)||!ge(i))return null;var o=(function(a){return{h:bo(a.h),s:Jt(a.s,0,100),v:Jt(a.v,0,100),a:Jt(a.a)}})({h:Number(t),s:Number(e),v:Number(i),a:Number(n)});return To(o)},"hsv"]]},Ao=function(s,t){for(var e=0;e<t.length;e++){var i=t[e][0](s);if(i)return[i,t[e][1]]}return[null,void 0]},Xu=function(s){return typeof s=="string"?Ao(s.trim(),rr.string):typeof s=="object"&&s!==null?Ao(s,rr.object):[null,void 0]},nr=function(s,t){var e=Mi(s);return{h:e.h,s:Jt(e.s+100*t,0,100),l:e.l,a:e.a}},or=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},Ro=function(s,t){var e=Mi(s);return{h:e.h,s:e.s,l:Jt(e.l+100*t,0,100),a:e.a}},ar=(function(){function s(t){this.parsed=Xu(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return Pt(or(this.rgba),2)},s.prototype.isDark=function(){return or(this.rgba)<.5},s.prototype.isLight=function(){return or(this.rgba)>=.5},s.prototype.toHex=function(){return t=sr(this.rgba),e=t.r,i=t.g,r=t.b,o=(n=t.a)<1?fs(Pt(255*n)):"","#"+fs(e)+fs(i)+fs(r)+o;var t,e,i,r,n,o},s.prototype.toRgb=function(){return sr(this.rgba)},s.prototype.toRgbString=function(){return t=sr(this.rgba),e=t.r,i=t.g,r=t.b,(n=t.a)<1?"rgba("+e+", "+i+", "+r+", "+n+")":"rgb("+e+", "+i+", "+r+")";var t,e,i,r,n},s.prototype.toHsl=function(){return Co(Mi(this.rgba))},s.prototype.toHslString=function(){return t=Co(Mi(this.rgba)),e=t.h,i=t.s,r=t.l,(n=t.a)<1?"hsla("+e+", "+i+"%, "+r+"%, "+n+")":"hsl("+e+", "+i+"%, "+r+"%)";var t,e,i,r,n},s.prototype.toHsv=function(){return t=Eo(this.rgba),{h:Pt(t.h),s:Pt(t.s),v:Pt(t.v),a:Pt(t.a,3)};var t},s.prototype.invert=function(){return oe({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},s.prototype.saturate=function(t){return t===void 0&&(t=.1),oe(nr(this.rgba,t))},s.prototype.desaturate=function(t){return t===void 0&&(t=.1),oe(nr(this.rgba,-t))},s.prototype.grayscale=function(){return oe(nr(this.rgba,-1))},s.prototype.lighten=function(t){return t===void 0&&(t=.1),oe(Ro(this.rgba,t))},s.prototype.darken=function(t){return t===void 0&&(t=.1),oe(Ro(this.rgba,-t))},s.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},s.prototype.alpha=function(t){return typeof t=="number"?oe({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Pt(this.rgba.a,3);var e},s.prototype.hue=function(t){var e=Mi(this.rgba);return typeof t=="number"?oe({h:t,s:e.s,l:e.l,a:e.a}):Pt(e.h)},s.prototype.isEqual=function(t){return this.toHex()===oe(t).toHex()},s})(),oe=function(s){return s instanceof ar?s:new ar(s)},Io=[],Yu=function(s){s.forEach(function(t){Io.indexOf(t)<0&&(t(ar,rr),Io.push(t))})};function qu(s,t){var e={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var r in e)i[e[r]]=r;var n={};s.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,h=i[this.toHex()];if(h)return h;if(o!=null&&o.closest){var c=this.toRgb(),u=1/0,m="black";if(!n.length)for(var f in e)n[f]=new s(e[f]).toRgb();for(var g in e){var y=(a=c,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));y<u&&(u=y,m=g)}return m}},t.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":e[a];return l?new s(l).toRgb():null},"name"])}Yu([qu]);const ai=class ls{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(t){if(t instanceof ls)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else{if(t===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}}get value(){return this._value}_cloneSource(t){return typeof t=="string"||typeof t=="number"||t instanceof Number||t===null?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):typeof t=="object"&&t!==null?{...t}:t}_isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if(i==="number"||i==="string"||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length!==e.length?!1:t.every((n,o)=>n===e[o]);if(t!==null&&e!==null){const n=Object.keys(t),o=Object.keys(e);return n.length!==o.length?!1:n.every(a=>t[a]===e[a])}return t===e}toRgba(){const[t,e,i,r]=this._components;return{r:t,g:e,b:i,a:r}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb),t[0]=Math.round(e*255),t[1]=Math.round(i*255),t[2]=Math.round(r*255),t}toArray(t){this._arrayRgba||(this._arrayRgba=[]),t||(t=this._arrayRgba);const[e,i,r,n]=this._components;return t[0]=e,t[1]=i,t[2]=r,t[3]=n,t}toRgbArray(t){this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb);const[e,i,r]=this._components;return t[0]=e,t[1]=i,t[2]=r,t}toNumber(){return this._int}toBgrNumber(){const[t,e,i]=this.toUint8RgbArray();return(i<<16)+(e<<8)+t}toLittleEndianNumber(){const t=this._int;return(t>>16)+(t&65280)+((t&255)<<16)}multiply(t){const[e,i,r,n]=ls._temp.setValue(t)._components;return this._components[0]*=e,this._components[1]*=i,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this._refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(t===1)return(255<<24)+this._int;if(t===0)return e?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return e&&(i=i*t+.5|0,r=r*t+.5|0,n=n*t+.5|0),(t*255<<24)+(i<<16)+(r<<8)+n}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const e=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-e.length)+e}setAlpha(t){return this._components[3]=this._clamp(t),this._value=null,this}_normalize(t){let e,i,r,n;if((typeof t=="number"||t instanceof Number)&&t>=0&&t<=16777215){const o=t;e=(o>>16&255)/255,i=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[e,i,r,n=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[e,i,r,n=255]=t,e/=255,i/=255,r/=255,n/=255;else if(typeof t=="string"||typeof t=="object"){if(typeof t=="string"){const a=ls.HEX_PATTERN.exec(t);a&&(t=`#${a[2]}`)}const o=oe(t);o.isValid()&&({r:e,g:i,b:r,a:n}=o.rgba,e/=255,i/=255,r/=255)}if(e!==void 0)this._components[0]=e,this._components[1]=i,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(t*255<<16)+(e*255<<8)+(i*255|0)}_clamp(t,e=0,i=1){return typeof t=="number"?Math.min(Math.max(t,e),i):(t.forEach((r,n)=>{t[n]=Math.min(Math.max(r,e),i)}),t)}static isColorLike(t){return typeof t=="number"||typeof t=="string"||t instanceof Number||t instanceof ls||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}};ai.shared=new ai,ai._temp=new ai,ai.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ut=ai;const Ku={cullArea:null,cullable:!1,cullableChildren:!0};let lr=0;const Po=500;function tt(...s){lr!==Po&&(lr++,lr===Po?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}const li={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Zu{constructor(t,e){this._pool=[],this._count=0,this._index=0,this._classType=t,e&&this.prepopulate(e)}prepopulate(t){for(let e=0;e<t;e++)this._pool[this._index++]=new this._classType;this._count+=t}get(t){var i;let e;return this._index>0?e=this._pool[--this._index]:(e=new this._classType,this._count++),(i=e.init)==null||i.call(e,t),e}return(t){var e;(e=t.reset)==null||e.call(t),this._pool[this._index++]=t}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let t=0;t<this._index;t++)this._pool[t].destroy();this._pool.length=0,this._count=0,this._index=0}}class Ju{constructor(){this._poolsByClass=new Map}prepopulate(t,e){this.getPool(t).prepopulate(e)}get(t,e){return this.getPool(t).get(e)}return(t){this.getPool(t.constructor).return(t)}getPool(t){return this._poolsByClass.has(t)||this._poolsByClass.set(t,new Zu(t)),this._poolsByClass.get(t)}stats(){const t={};return this._poolsByClass.forEach(e=>{const i=t[e._classType.name]?e._classType.name+e._classType.ID:e._classType.name;t[i]={free:e.totalFree,used:e.totalUsed,size:e.totalSize}}),t}clear(){this._poolsByClass.forEach(t=>t.clear()),this._poolsByClass.clear()}}const Mt=new Ju;li.register(Mt);const Qu={get isCachedAsTexture(){var s;return!!((s=this.renderGroup)!=null&&s.isCachedAsTexture)},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){var s;(s=this.renderGroup)==null||s.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){K("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function Mo(s,t,e){const i=s.length;let r;if(t>=i||e===0)return;e=t+e>i?i-t:e;const n=i-e;for(r=t;r<n;++r)s[r]=s[r+e];s.length=n}const td={allowChildren:!0,removeChildren(s=0,t){var n;const e=t??this.children.length,i=e-s,r=[];if(i>0&&i<=e){for(let a=e-1;a>=s;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}Mo(this.children,s,e);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(i===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const t=this.getChildAt(s);return this.removeChild(t)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,t){if(t<0||t>=this.children.length)throw new Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,t)},getChildIndex(s){const t=this.children.indexOf(s);if(t===-1)throw new Error("The supplied Container must be a child of the caller");return t},addChildAt(s,t){this.allowChildren||K(vt,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:e}=this;if(t<0||t>e.length)throw new Error(`${s}addChildAt: The index ${t} supplied is out of bounds ${e.length}`);const i=s.parent===this;if(s.parent){const n=s.parent.children.indexOf(s);if(i){if(n===t)return s;s.parent.children.splice(n,1)}else s.removeFromParent()}t===e.length?e.push(s):e.splice(t,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),i||(this.emit("childAdded",s,this,t),s.emit("added",this)),s},swapChildren(s,t){if(s===t)return;const e=this.getChildIndex(s),i=this.getChildIndex(t);this.children[e]=t,this.children[i]=s;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var s;(s=this.parent)==null||s.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(t=>this.reparentChildAt(t,this.children.length)),s[0])},reparentChildAt(s,t){if(s.parent===this)return this.setChildIndex(s,t),s;const e=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,t);const i=this.worldTransform.clone();return i.invert(),e.prepend(i),s.setFromMatrix(e),s},replaceChild(s,t){s.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(s)),t.setFromMatrix(s.localTransform),t.updateLocalTransform(),this.removeChild(s)}},ed={collectRenderables(s,t,e){this.parentRenderLayer&&this.parentRenderLayer!==e||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,t,e):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,t,e))},collectRenderablesSimple(s,t,e){const i=this.children,r=i.length;for(let n=0;n<r;n++)i[n].collectRenderables(s,t,e)},collectRenderablesWithEffects(s,t,e){const{renderPipes:i}=t;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];i[n.pipe].push(n,this,s)}this.collectRenderablesSimple(s,t,e);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];i[n.pipe].pop(n,this,s)}}};class ps{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let t=0;t<this.filters.length;t++)this.filters[t].destroy();this.filters=null,this.filterArea=null}}class id{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(t=>{this.add({test:t.test,maskClass:t})}))}add(t){this._tests.push(t)}getMaskEffect(t){this._initialized||this.init();for(let e=0;e<this._tests.length;e++){const i=this._tests[e];if(i.test(t))return Mt.get(i.maskClass,t)}return t}returnMaskEffect(t){Mt.return(t)}}const hr=new id;J.handleByList(w.MaskEffect,hr._effectClasses);const sd={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((e,i)=>e.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const t=this.effects.indexOf(s);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const t=this._maskEffect;(t==null?void 0:t.mask)!==s&&(t&&(this.removeEffect(t),hr.returnMaskEffect(t),this._maskEffect=null),s!=null&&(this._maskEffect=hr.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){var s;return(s=this._maskEffect)==null?void 0:s.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){var n;!Array.isArray(s)&&s&&(s=[s]);const t=this._filterEffect||(this._filterEffect=new ps);s=s;const e=(s==null?void 0:s.length)>0,i=((n=t.filters)==null?void 0:n.length)>0,r=e!==i;s=Array.isArray(s)?s.slice(0):s,t.filters=Object.freeze(s),r&&(e?this.addEffect(t):(this.removeEffect(t),t.filters=s??null))},get filters(){var s;return(s=this._filterEffect)==null?void 0:s.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new ps),this._filterEffect.filterArea=s},get filterArea(){var s;return(s=this._filterEffect)==null?void 0:s.filterArea}},rd={label:null,get name(){return K(vt,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){K(vt,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,t=!1){return this.getChildByLabel(s,t)},getChildByLabel(s,t=!1){const e=this.children;for(let i=0;i<e.length;i++){const r=e[i];if(r.label===s||s instanceof RegExp&&s.test(r.label))return r}if(t)for(let i=0;i<e.length;i++){const n=e[i].getChildByLabel(s,!0);if(n)return n}return null},getChildrenByLabel(s,t=!1,e=[]){const i=this.children;for(let r=0;r<i.length;r++){const n=i[r];(n.label===s||s instanceof RegExp&&s.test(n.label))&&e.push(n)}if(t)for(let r=0;r<i.length;r++)i[r].getChildrenByLabel(s,!0,e);return e}},Ht=Mt.getPool(W),_e=Mt.getPool(Lt),nd=new W,od={getFastGlobalBounds(s,t){t||(t=new Lt),t.clear(),this._getGlobalBoundsRecursive(!!s,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);const e=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(e.worldTransform),t},_getGlobalBoundsRecursive(s,t,e){let i=t;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==e||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(i=_e.get().clear()),this.boundsArea)t.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(s,i,e)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));n&&i.applyMatrix(o.worldTransform.copyTo(nd).invert()),t.addBounds(i),_e.return(i)}else this.renderGroup&&(t.addBounds(i,this.relativeGroupTransform),_e.return(i))}};function cr(s,t,e){e.clear();let i,r;return s.parent?t?i=s.parent.worldTransform:(r=Ht.get().identity(),i=ur(s,r)):i=W.IDENTITY,ko(s,e,i,t),r&&Ht.return(r),e.isValid||e.set(0,0,0,0),e}function ko(s,t,e,i){var a,l;if(!s.visible||!s.measurable)return;let r;i?r=s.worldTransform:(s.updateLocalTransform(),r=Ht.get(),r.appendFrom(s.localTransform,e));const n=t,o=!!s.effects.length;if(o&&(t=_e.get().clear()),s.boundsArea)t.addRect(s.boundsArea,r);else{const h=s.bounds;h&&!h.isEmpty()&&(t.matrix=r,t.addBounds(h));for(let c=0;c<s.children.length;c++)ko(s.children[c],t,r,i)}if(o){for(let h=0;h<s.effects.length;h++)(l=(a=s.effects[h]).addBounds)==null||l.call(a,t);n.addBounds(t,W.IDENTITY),_e.return(t)}i||Ht.return(r)}function ur(s,t){const e=s.parent;return e&&(ur(e,t),e.updateLocalTransform(),t.append(e.localTransform)),t}function hi(s,t){if(s===16777215||!t)return t;if(t===16777215||!s)return s;const e=s>>16&255,i=s>>8&255,r=s&255,n=t>>16&255,o=t>>8&255,a=t&255,l=e*n/255|0,h=i*o/255|0,c=r*a/255|0;return(l<<16)+(h<<8)+c}const Bo=16777215;function ms(s,t){return s===Bo?t:t===Bo?s:hi(s,t)}function ci(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const ad={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let t=this.alpha,e=this.parent;for(;e;)t*=e.alpha,e=e.parent;return t},getGlobalTransform(s=new W,t){if(t)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const e=ur(this,Ht.get().identity());return s.appendFrom(this.localTransform,e),Ht.return(e),s},getGlobalTint(s){if(s)return this.renderGroup?ci(this.renderGroup.worldColor):this.parentRenderGroup?ci(ms(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,e=this.parent;for(;e;)t=ms(t,e.localColor),e=e.parent;return ci(t)}};function dr(s,t,e){return t.clear(),e||(e=W.IDENTITY),Oo(s,t,e,s,!0),t.isValid||t.set(0,0,0,0),t}function Oo(s,t,e,i,r){var l,h;let n;if(r)n=Ht.get(),n=e.copyTo(n);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const c=s.localTransform;n=Ht.get(),n.appendFrom(c,e)}const o=t,a=!!s.effects.length;if(a&&(t=_e.get().clear()),s.boundsArea)t.addRect(s.boundsArea,n);else{s.renderPipeId&&(t.matrix=n,t.addBounds(s.bounds));const c=s.children;for(let u=0;u<c.length;u++)Oo(c[u],t,n,i,!1)}if(a){for(let c=0;c<s.effects.length;c++)(h=(l=s.effects[c]).addLocalBounds)==null||h.call(l,t,i);o.addBounds(t,W.IDENTITY),_e.return(t)}Ht.return(n)}function Do(s,t){const e=s.children;for(let i=0;i<e.length;i++){const r=e[i],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=t.index;(t.data[a]!==n||t.data[a+1]!==o)&&(t.data[t.index]=n,t.data[t.index+1]=o,t.didChange=!0),t.index=a+2,r.children.length&&Do(r,t)}return t.didChange}const ld=new W,hd={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,t){const e=Math.sign(this.scale.x)||1;t!==0?this.scale.x=s/t*e:this.scale.x=e},_setHeight(s,t){const e=Math.sign(this.scale.y)||1;t!==0?this.scale.y=s/t*e:this.scale.y=e},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Lt});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),Do(this,s),s.didChange&&dr(this,s.localBounds,ld),s.localBounds},getBounds(s,t){return cr(this,s,t||new Lt)}},cd={_onRender:null,set onRender(s){const t=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&(t==null||t.removeOnRender(this)),this._onRender=null;return}this._onRender||t==null||t.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},ud={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(dd))}};function dd(s,t){return s._zIndex-t._zIndex}const fd={getGlobalPosition(s=new mt,t=!1){return this.parent?this.parent.toGlobal(this._position,s,t):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,t,e=!1){const i=this.getGlobalTransform(Ht.get(),e);return t=i.apply(s,t),Ht.return(i),t},toLocal(s,t,e,i){t&&(s=t.toGlobal(s,e,i));const r=this.getGlobalTransform(Ht.get(),i);return e=r.applyInverse(s,e),Ht.return(r),e}};class fr{constructor(){this.uid=dt("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(t){this.instructions[this.instructionSize++]=t}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let pd=0;class md{constructor(t){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this.textureStyle=new $e(this.textureOptions)}createTexture(t,e,i,r){const n=new At({...this.textureOptions,width:t,height:e,resolution:1,antialias:i,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new $({source:n,label:`texturePool_${pd++}`})}getOptimalTexture(t,e,i=1,r,n=!1){let o=Math.ceil(t*i-1e-6),a=Math.ceil(e*i-1e-6);o=oi(o),a=oi(a);const l=r?1:0,h=n?1:0,c=(o<<17)+(a<<2)+(h<<1)+l;this._texturePool[c]||(this._texturePool[c]=[]);let u=this._texturePool[c].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=i,u.source.width=o/i,u.source.height=a/i,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=t,u.frame.height=e,u.updateUvs(),this._poolKeyHash[u.uid]=c,u}getSameSizeTexture(t,e=!1){const i=t.source;return this.getOptimalTexture(t.width,t.height,i._resolution,e)}returnTexture(t,e=!1){const i=this._poolKeyHash[t.uid];e&&(t.source.style=this.textureStyle),this._texturePool[i].push(t)}clear(t){if(t=t!==!1,t)for(const e in this._texturePool){const i=this._texturePool[e];if(i)for(let r=0;r<i.length;r++)i[r].destroy(!0)}this._texturePool={}}}const Nt=new md;li.register(Nt);class pr{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new W,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new fr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(t){this.root=t,t._onRender&&this.addOnRender(t),t.didChange=!0;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(t={}){this.textureOptions=t,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Nt.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const t=this._parentCacheAsTextureRenderGroup;t&&!t.textureNeedsUpdate&&t.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const t in this.childrenToUpdate){const e=this.childrenToUpdate[t];e.list.fill(null),e.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(t){t.renderGroupParent&&t.renderGroupParent._removeRenderGroupChild(t),t.renderGroupParent=this,this.renderGroupChildren.push(t)}_removeRenderGroupChild(t){const e=this.renderGroupChildren.indexOf(t);e>-1&&this.renderGroupChildren.splice(e,1),t.renderGroupParent=null}addChild(t){if(this.structureDidChange=!0,t.parentRenderGroup=this,t.updateTick=-1,t.parent===this.root?t.relativeRenderGroupDepth=1:t.relativeRenderGroupDepth=t.parent.relativeRenderGroupDepth+1,t.didChange=!0,this.onChildUpdate(t),t.renderGroup){this.addRenderGroupChild(t.renderGroup);return}t._onRender&&this.addOnRender(t);const e=t.children;for(let i=0;i<e.length;i++)this.addChild(e[i])}removeChild(t){if(this.structureDidChange=!0,t._onRender&&(t.renderGroup||this.removeOnRender(t)),t.parentRenderGroup=null,t.renderGroup){this._removeRenderGroupChild(t.renderGroup);return}const e=t.children;for(let i=0;i<e.length;i++)this.removeChild(e[i])}removeChildren(t){for(let e=0;e<t.length;e++)this.removeChild(t[e])}onChildUpdate(t){let e=this.childrenToUpdate[t.relativeRenderGroupDepth];e||(e=this.childrenToUpdate[t.relativeRenderGroupDepth]={index:0,list:[]}),e.list[e.index++]=t}updateRenderable(t){t.globalDisplayStatus<7||(this.instructionSet.renderPipes[t.renderPipeId].updateRenderable(t),t.didViewUpdate=!1)}onChildViewUpdate(t){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=t}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(t){this._onRenderContainers.push(t)}removeOnRender(t){this._onRenderContainers.splice(this._onRenderContainers.indexOf(t),1)}runOnRender(t){for(let e=0;e<this._onRenderContainers.length;e++)this._onRenderContainers[e]._onRender(t)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(t=[]){const e=this.root.children;for(let i=0;i<e.length;i++)this._getChildren(e[i],t);return t}_getChildren(t,e=[]){if(e.push(t),t.renderGroup)return e;const i=t.children;for(let r=0;r<i.length;r++)this._getChildren(i[r],e);return e}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new W),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new W),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const t=this._parentCacheAsTextureRenderGroup;return t?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new W),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(t.inverseWorldTransform).translate(-t._textureBounds.x,-t._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function gd(s,t,e={}){for(const i in t)!e[i]&&t[i]!==void 0&&(s[i]=t[i])}const mr=new Ot(null),gs=new Ot(null),gr=new Ot(null,1,1),_s=new Ot(null),ys=1,_r=2,ki=4;class kt extends Zt{constructor(t={}){var e,i;super(),this.uid=dt("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new W,this.relativeGroupTransform=new W,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Ot(this,0,0),this._scale=gr,this._pivot=gs,this._origin=_s,this._skew=mr,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],gd(this,t,{children:!0,parent:!0,effects:!0}),(e=t.children)==null||e.forEach(r=>this.addChild(r)),(i=t.parent)==null||i.addChild(this)}static mixin(t){K("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),J.mixin(kt,t)}set _didChangeId(t){this._didViewChangeTick=t>>12&4095,this._didContainerChangeTick=t&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...t){if(this.allowChildren||K(vt,"addChild: Only Containers will be allowed to add children in v8.0.0"),t.length>1){for(let r=0;r<t.length;r++)this.addChild(t[r]);return t[0]}const e=t[0],i=this.renderGroup||this.parentRenderGroup;return e.parent===this?(this.children.splice(this.children.indexOf(e),1),this.children.push(e),i&&(i.structureDidChange=!0),e):(e.parent&&e.parent.removeChild(e),this.children.push(e),this.sortableChildren&&(this.sortDirty=!0),e.parent=this,e.didChange=!0,e._updateFlags=15,i&&i.addChild(e),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this),this._didViewChangeTick++,e._zIndex!==0&&e.depthOfChildModified(),e)}removeChild(...t){if(t.length>1){for(let r=0;r<t.length;r++)this.removeChild(t[r]);return t[0]}const e=t[0],i=this.children.indexOf(e);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(e):this.parentRenderGroup&&this.parentRenderGroup.removeChild(e),e.parentRenderLayer&&e.parentRenderLayer.detach(e),e.parent=null,this.emit("childRemoved",e,this,i),e.emit("removed",this)),e}_onUpdate(t){t&&t===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(t){!!this.renderGroup!==t&&(t?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const t=this.parentRenderGroup;t==null||t.removeChild(this),this.renderGroup=Mt.get(pr,this),this.groupTransform=W.IDENTITY,t==null||t.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const t=this.parentRenderGroup;t==null||t.removeChild(this),Mt.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,t==null||t.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new W),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}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 position(){return this._position}set position(t){this._position.copyFrom(t)}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this._onUpdate(this._skew))}get angle(){return this.rotation*Ou}set angle(t){this.rotation=t*Du}get pivot(){return this._pivot===gs&&(this._pivot=new Ot(this,0,0)),this._pivot}set pivot(t){this._pivot===gs&&(this._pivot=new Ot(this,0,0),this._origin!==_s&&tt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._pivot.set(t):this._pivot.copyFrom(t)}get skew(){return this._skew===mr&&(this._skew=new Ot(this,0,0)),this._skew}set skew(t){this._skew===mr&&(this._skew=new Ot(this,0,0)),this._skew.copyFrom(t)}get scale(){return this._scale===gr&&(this._scale=new Ot(this,1,1)),this._scale}set scale(t){this._scale===gr&&(this._scale=new Ot(this,0,0)),typeof t=="string"&&(t=parseFloat(t)),typeof t=="number"?this._scale.set(t):this._scale.copyFrom(t)}get origin(){return this._origin===_s&&(this._origin=new Ot(this,0,0)),this._origin}set origin(t){this._origin===_s&&(this._origin=new Ot(this,0,0),this._pivot!==gs&&tt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._origin.set(t):this._origin.copyFrom(t)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(t){const e=this.getLocalBounds().width;this._setWidth(t,e)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(t){const e=this.getLocalBounds().height;this._setHeight(t,e)}getSize(t){t||(t={});const e=this.getLocalBounds();return t.width=Math.abs(this.scale.x*e.width),t.height=Math.abs(this.scale.y*e.height),t}setSize(t,e){const i=this.getLocalBounds();typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,i.width),e!==void 0&&this._setHeight(e,i.height)}_updateSkew(){const t=this._rotation,e=this._skew;this._cx=Math.cos(t+e._y),this._sx=Math.sin(t+e._y),this._cy=-Math.sin(t-e._x),this._sy=Math.cos(t-e._x)}updateTransform(t){return this.position.set(typeof t.x=="number"?t.x:this.position.x,typeof t.y=="number"?t.y:this.position.y),this.scale.set(typeof t.scaleX=="number"?t.scaleX||1:this.scale.x,typeof t.scaleY=="number"?t.scaleY||1:this.scale.y),this.rotation=typeof t.rotation=="number"?t.rotation:this.rotation,this.skew.set(typeof t.skewX=="number"?t.skewX:this.skew.x,typeof t.skewY=="number"?t.skewY:this.skew.y),this.pivot.set(typeof t.pivotX=="number"?t.pivotX:this.pivot.x,typeof t.pivotY=="number"?t.pivotY:this.pivot.y),this.origin.set(typeof t.originX=="number"?t.originX:this.origin.x,typeof t.originY=="number"?t.originY:this.origin.y),this}setFromMatrix(t){t.decompose(this)}updateLocalTransform(){const t=this._didContainerChangeTick;if(this._didLocalTransformChangeId===t)return;this._didLocalTransformChangeId=t;const e=this.localTransform,i=this._scale,r=this._pivot,n=this._origin,o=this._position,a=i._x,l=i._y,h=r._x,c=r._y,u=-n._x,m=-n._y;e.a=this._cx*a,e.b=this._sx*a,e.c=this._cy*l,e.d=this._sy*l,e.tx=o._x-(h*e.a+c*e.c)+(u*e.a+m*e.c)-u,e.ty=o._y-(h*e.b+c*e.d)+(u*e.b+m*e.d)-m}set alpha(t){t!==this.localAlpha&&(this.localAlpha=t,this._updateFlags|=ys,this._onUpdate())}get alpha(){return this.localAlpha}set tint(t){const i=ut.shared.setValue(t??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=ys,this._onUpdate())}get tint(){return ci(this.localColor)}set blendMode(t){this.localBlendMode!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=_r,this.localBlendMode=t,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(t){const e=t?2:0;(this.localDisplayStatus&2)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ki,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",t))}get culled(){return!(this.localDisplayStatus&4)}set culled(t){const e=t?0:4;(this.localDisplayStatus&4)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ki,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(t){const e=t?1:0;(this.localDisplayStatus&1)!==e&&(this._updateFlags|=ki,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(t=!1){var r;if(this.destroyed)return;this.destroyed=!0;let e;if(this.children.length&&(e=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof t=="boolean"?t:t==null?void 0:t.children)&&e)for(let n=0;n<e.length;++n)e[n].destroy(t);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}J.mixin(kt,td,od,fd,cd,hd,sd,rd,ud,Ku,Qu,ad,ed);class yr extends kt{constructor(t){super(t),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Lt(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=t.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(t){this._roundPixels=t?1:0}containsPoint(t){const e=this.bounds,{x:i,y:r}=t;return i>=e.minX&&i<=e.maxX&&r>=e.minY&&r<=e.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const t=this.renderGroup||this.parentRenderGroup;t&&t.onChildViewUpdate(this)}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(t){this.unload(),super.destroy(t),this._bounds=null}collectRenderablesSimple(t,e,i){const{renderPipes:r}=e;r.blendMode.pushBlendMode(this,this.groupBlendMode,t);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,t),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let h=0;h<l;h++)a[h].collectRenderables(t,e,i);r.blendMode.popBlendMode(t)}}class ye extends yr{constructor(t=$.EMPTY){t instanceof $&&(t={texture:t});const{texture:e=$.EMPTY,anchor:i,roundPixels:r,width:n,height:o,...a}=t;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new Ot({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:e.defaultAnchor&&(this.anchor=e.defaultAnchor),this.texture=e,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(t,e=!1){return t instanceof $?new ye(t):new ye($.from(t,e))}set texture(t){t||(t=$.EMPTY);const e=this._texture;e!==t&&(e&&e.dynamic&&e.off("update",this.onViewUpdate,this),t.dynamic&&t.on("update",this.onViewUpdate,this),this._texture=t,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return yo(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return K("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const t=this._anchor,e=this._texture,i=this._bounds,{width:r,height:n}=e.orig;i.minX=-t._x*r,i.maxX=i.minX+r,i.minY=-t._y*n,i.maxY=i.minY+n}destroy(t=!1){if(super.destroy(t),typeof t=="boolean"?t:t==null?void 0:t.texture){const i=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this._setWidth(t,this._texture.orig.width),this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this._setHeight(t,this._texture.orig.height),this._height=t}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this._texture.orig.width,t.height=Math.abs(this.scale.y)*this._texture.orig.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this._texture.orig.width),e!==void 0&&this._setHeight(e,this._texture.orig.height)}}const _d=new Lt;function Go(s,t,e){const i=_d;s.measurable=!0,cr(s,e,i),t.addBoundsMask(i),s.measurable=!1}function Uo(s,t,e){const i=_e.get();s.measurable=!0;const r=Ht.get().identity(),n=Lo(s,e,r);dr(s,i,n),s.measurable=!1,t.addBoundsMask(i),Ht.return(r),_e.return(i)}function Lo(s,t,e){return s?(s!==t&&(Lo(s.parent,t,e),s.updateLocalTransform(),e.append(s.localTransform)),e):(tt("Mask bounds, renderable is not inside the root container"),e)}class No{constructor(t){this.priority=0,this.inverse=!1,this.pipe="alphaMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t,this.renderMaskToTexture=!(t instanceof ye),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(t,e){this.inverse||Go(this.mask,t,e)}addLocalBounds(t,e){Uo(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof ye}}No.extension=w.MaskEffect;class Fo{constructor(t){this.priority=0,this.pipe="colorMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t}destroy(){}static test(t){return typeof t=="number"}}Fo.extension=w.MaskEffect;class Ho{constructor(t){this.priority=0,this.pipe="stencilMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(t,e){Go(this.mask,t,e)}addLocalBounds(t,e){Uo(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof kt}}Ho.extension=w.MaskEffect;let Wo={createCanvas:(s,t)=>{const e=document.createElement("canvas");return e.width=s,e.height=t,e},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,t)=>fetch(s,t),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const rt={get(){return Wo},set(s){Wo=s}};class ae extends At{constructor(t){t.resource||(t.resource=rt.get().createCanvas()),t.width||(t.width=t.resource.width,t.autoDensity||(t.width/=t.resolution)),t.height||(t.height=t.resource.height,t.autoDensity||(t.height/=t.resolution)),super(t),this.uploadMethodId="image",this.autoDensity=t.autoDensity,this.resizeCanvas(),this.transparent=!!t.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(t=this.width,e=this.height,i=this._resolution){const r=super.resize(t,e,i);return r&&this.resizeCanvas(),r}static test(t){return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&t instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}ae.extension=w.TextureSource;class xs extends At{constructor(t){super(t),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(t){return globalThis.HTMLImageElement&&t instanceof HTMLImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||globalThis.VideoFrame&&t instanceof VideoFrame}}xs.extension=w.TextureSource;var ui=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(ui||{});class xr{constructor(t,e=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=t,this._context=e,this.priority=i,this._once=r}match(t,e=null){return this._fn===t&&this._context===e}emit(t){this._fn&&(this._context?this._fn.call(this._context,t):this._fn(t));const e=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const Vo=class qt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new xr(null,null,1/0),this.deltaMS=1/qt.targetFPMS,this.elapsedMS=1/qt.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=ui.NORMAL){return this._addListener(new xr(t,e,i))}addOnce(t,e,i=ui.NORMAL){return this._addListener(new xr(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(!e)t.connect(i);else{for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i.match(t,e)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let e;if(t>this.lastTime){if(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),e*=this.speed,this._minElapsedMS){const n=t-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=t-n%this._minElapsedMS}this.deltaMS=e,this.deltaTime=this.deltaMS*qt.targetFPMS;const i=this._head;let r=i.next;for(;r;)r=r.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){const e=Math.min(Math.max(0,t)/1e3,qt.targetFPMS);this._maxElapsedMS=1/e,this._minElapsedMS&&t>this.maxFPS&&(this.maxFPS=t)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){t===0?this._minElapsedMS=0:(t<this.minFPS&&(this.minFPS=t),this._minElapsedMS=1/(t/1e3))}static get shared(){if(!qt._shared){const t=qt._shared=new qt;t.autoStart=!0,t._protected=!0}return qt._shared}static get system(){if(!qt._system){const t=qt._system=new qt;t.autoStart=!0,t._protected=!0}return qt._system}};Vo.targetFPMS=.06;let Qt=Vo,br;async function yd(){return br??(br=(async()=>{var o;const t=rt.get().createCanvas(1,1).getContext("webgl");if(!t)return"premultiply-alpha-on-upload";const e=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!e)return"premultiply-alpha-on-upload";const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const n=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,n),t.deleteFramebuffer(r),t.deleteTexture(i),(o=t.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),br}const bs=class nu extends At{constructor(t){super(t),this.isReady=!1,this.uploadMethodId="video",t={...nu.defaultOptions,...t},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=t.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=t.autoPlay!==!1,this.alphaMode=t.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),t.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const t=Qt.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const t=this.resource,e=this.options;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(e.preload||t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlayThrough),t.addEventListener("error",this._onError,!0)),this.alphaMode=await yd(),this._load=new Promise((i,r)=>{this.isValid?i(this):(this._resolve=i,this._reject=r,e.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${e.preloadTimeoutMs}ms`))})),t.load())}),this._load}_onError(t){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.resource;return!t.paused&&!t.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const t=this.resource;this.isValid&&(this.isReady=!0,this.resize(t.videoWidth,t.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const t=this.resource;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlayThrough),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Qt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Qt.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Qt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(t){return globalThis.HTMLVideoElement&&t instanceof HTMLVideoElement}};bs.extension=w.TextureSource,bs.defaultOptions={...At.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},bs.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let xd=bs;const di=(s,t,e=!1)=>(Array.isArray(s)||(s=[s]),t?s.map(i=>typeof i=="string"||e?t(i):i):s);class bd{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(t){return this._cache.has(t)}get(t){const e=this._cache.get(t);return e||tt(`[Assets] Asset id ${t} was not found in the Cache`),e}set(t,e){const i=di(t);let r;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.test(e)){r=h.getCacheableAssets(i,e);break}}const n=new Map(Object.entries(r||{}));r||i.forEach(l=>{n.set(l,e)});const o=[...n.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const h=r?r[l]:e;this._cache.has(l)&&this._cache.get(l)!==h&&tt("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(t){if(!this._cacheMap.has(t)){tt(`[Assets] Asset id ${t} was not found in the Cache`);return}const e=this._cacheMap.get(t);e.cacheKeys.forEach(r=>{this._cache.delete(r)}),e.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const fi=new bd,vr=[];J.handleByList(w.TextureSource,vr);function zo(s={}){const t=s&&s.resource,e=t?s.resource:s,i=t?s:{resource:s};for(let r=0;r<vr.length;r++){const n=vr[r];if(n.test(e))return new n(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function vd(s={},t=!1){const e=s&&s.resource,i=e?s.resource:s,r=e?s:{resource:s};if(!t&&fi.has(i))return fi.get(i);const n=new $({source:zo(r)});return n.on("destroy",()=>{fi.has(i)&&fi.remove(i)}),t||fi.set(i,n),n}function Ed(s,t=!1){return typeof s=="string"?fi.get(s):s instanceof At?new $({source:s}):vd(s,t)}$.from=Ed,At.from=zo,J.add(No,Fo,Ho,xd,xs,ae,ir);var $o=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))($o||{});function ee(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function Bi(s){return s.split("?")[0].split("#")[0]}function Td(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sd(s,t,e){return s.replace(new RegExp(Td(t),"g"),e)}function Cd(s,t){let e="",i=0,r=-1,n=0,o=-1;for(let a=0;a<=s.length;++a){if(a<s.length)o=s.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(e.length<2||i!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const l=e.lastIndexOf("/");if(l!==e.length-1){l===-1?(e="",i=0):(e=e.slice(0,l),i=e.length-1-e.lastIndexOf("/")),r=a,n=0;continue}}else if(e.length===2||e.length===1){e="",i=0,r=a,n=0;continue}}}else e.length>0?e+=`/${s.slice(r+1,a)}`:e=s.slice(r+1,a),i=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return e}const Oi={toPosix(s){return Sd(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){ee(s),s=this.toPosix(s);const t=/^file:\/\/\//.exec(s);if(t)return t[0];const e=/^[^/:]+:\/{0,2}/.exec(s);return e?e[0]:""},toAbsolute(s,t,e){if(ee(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const i=Bi(this.toPosix(t??rt.get().getBaseUrl())),r=Bi(this.toPosix(e??this.rootname(i)));return s=this.toPosix(s),s.startsWith("/")?Oi.join(r,s.slice(1)):this.isAbsolute(s)?s:this.join(i,s)},normalize(s){if(ee(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let t="";const e=s.startsWith("/");this.hasProtocol(s)&&(t=this.rootname(s),s=s.slice(t.length));const i=s.endsWith("/");return s=Cd(s),s.length>0&&i&&(s+="/"),e?`/${s}`:t+s},isAbsolute(s){return ee(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let t;for(let e=0;e<s.length;++e){const i=s[e];if(ee(i),i.length>0)if(t===void 0)t=i;else{const r=s[e-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?t+=`/../${i}`:t+=`/${i}`}}return t===void 0?".":this.normalize(t)},dirname(s){if(ee(s),s.length===0)return".";s=this.toPosix(s);let t=s.charCodeAt(0);const e=t===47;let i=-1,r=!0;const n=this.getProtocol(s),o=s;s=s.slice(n.length);for(let a=s.length-1;a>=1;--a)if(t=s.charCodeAt(a),t===47){if(!r){i=a;break}}else r=!1;return i===-1?e?"/":this.isUrl(o)?n+s:n:e&&i===1?"//":n+s.slice(0,i)},rootname(s){ee(s),s=this.toPosix(s);let t="";if(s.startsWith("/")?t="/":t=this.getProtocol(s),this.isUrl(s)){const e=s.indexOf("/",t.length);e!==-1?t=s.slice(0,e):t=s,t.endsWith("/")||(t+="/")}return t},basename(s,t){ee(s),t&&ee(t),s=Bi(this.toPosix(s));let e=0,i=-1,r=!0,n;if(t!==void 0&&t.length>0&&t.length<=s.length){if(t.length===s.length&&t===s)return"";let o=t.length-1,a=-1;for(n=s.length-1;n>=0;--n){const l=s.charCodeAt(n);if(l===47){if(!r){e=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===t.charCodeAt(o)?--o===-1&&(i=n):(o=-1,i=a))}return e===i?i=a:i===-1&&(i=s.length),s.slice(e,i)}for(n=s.length-1;n>=0;--n)if(s.charCodeAt(n)===47){if(!r){e=n+1;break}}else i===-1&&(r=!1,i=n+1);return i===-1?"":s.slice(e,i)},extname(s){ee(s),s=Bi(this.toPosix(s));let t=-1,e=0,i=-1,r=!0,n=0;for(let o=s.length-1;o>=0;--o){const a=s.charCodeAt(o);if(a===47){if(!r){e=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?t===-1?t=o:n!==1&&(n=1):t!==-1&&(n=-1)}return t===-1||i===-1||n===0||n===1&&t===i-1&&t===e+1?"":s.slice(t,i)},parse(s){ee(s);const t={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return t;s=Bi(this.toPosix(s));let e=s.charCodeAt(0);const i=this.isAbsolute(s);let r;t.root=this.rootname(s),i||this.hasProtocol(s)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,h=s.length-1,c=0;for(;h>=r;--h){if(e=s.charCodeAt(h),e===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),e===46?n===-1?n=h:c!==1&&(c=1):n!==-1&&(c=-1)}return n===-1||a===-1||c===0||c===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&i?t.base=t.name=s.slice(1,a):t.base=t.name=s.slice(o,a)):(o===0&&i?(t.name=s.slice(1,n),t.base=s.slice(1,a)):(t.name=s.slice(o,n),t.base=s.slice(o,a)),t.ext=s.slice(n,a)),t.dir=this.dirname(s),t},sep:"/",delimiter:":",joinExtensions:[".html"]};function jo(s,t,e,i,r){const n=t[e];for(let o=0;o<n.length;o++){const a=n[o];e<t.length-1?jo(s.replace(i[e],a),t,e+1,i,r):r.push(s.replace(i[e],a))}}function wd(s){const t=/\{(.*?)\}/g,e=s.match(t),i=[];if(e){const r=[];e.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),jo(s,r,0,e,i)}else i.push(s);return i}const Xo=s=>!Array.isArray(s);class Yo{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(t,e)=>`${t}${this._bundleIdConnector}${e}`,extractAssetIdFromBundle:(t,e)=>e.replace(`${t}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(t){if(this._bundleIdConnector=t.connector??this._bundleIdConnector,this._createBundleAssetId=t.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=t.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...t){t.forEach(e=>{this._preferredOrder.push(e),e.priority||(e.priority=Object.keys(e.params))}),this._resolverHash={}}set basePath(t){this._basePath=t}get basePath(){return this._basePath}set rootPath(t){this._rootPath=t}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(t){if(typeof t=="string")this._defaultSearchParams=t;else{const e=t;this._defaultSearchParams=Object.keys(e).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(e[i])}`).join("&")}}getAlias(t){const{alias:e,src:i}=t;return di(e||i,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(t,e){this._assetMap[t]&&(e&&e!==this._resolverHash[t]||(delete this._resolverHash[t],delete this._assetMap[t]))}addManifest(t){this._manifest&&tt("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=t,t.bundles.forEach(e=>{this.addBundle(e.name,e.assets)})}addBundle(t,e){const i=[];let r=e;Array.isArray(e)||(r=Object.entries(e).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const h=this._createBundleAssetId(t,a);i.push(h),l=[a,h]}else{const h=a.map(c=>this._createBundleAssetId(t,c));i.push(...h),l=[...a,...h]}this.add({...n,alias:l,src:o})}),this._bundles[t]=i}add(t){const e=[];Array.isArray(t)?e.push(...t):e.push(t);let i;i=n=>{this.hasKey(n)&&tt(`[Resolver] already has key: ${n} overwriting`)},di(e).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:h,parser:c}=n;const u=di(o).map(y=>typeof y=="string"?wd(y):Array.isArray(y)?y:[y]),m=this.getAlias(n);Array.isArray(m)?m.forEach(i):i(m);const f=[],g=y=>{const x=this._parsers.find(v=>v.test(y));return{src:y,...x==null?void 0:x.parse(y)}};u.forEach(y=>{y.forEach(x=>{let v={};if(typeof x!="object"?v=g(x):(a=x.data??a,l=x.format??l,(x.loadParser||x.parser)&&(h=x.loadParser??h,c=x.parser??c),v={...g(x.src),...x}),!m)throw new Error(`[Resolver] alias is undefined for this asset: ${v.src}`);v=this._buildResolvedAsset(v,{aliases:m,data:a,format:l,loadParser:h,parser:c,progressSize:n.progressSize}),f.push(v)})}),m.forEach(y=>{this._assetMap[y]=f})})}resolveBundle(t){const e=Xo(t);t=di(t);const i={};return t.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const h=o[l];a[this._extractAssetIdFromBundle(r,l)]=h}i[r]=a}}),e?i[t[0]]:i}resolveUrl(t){const e=this.resolve(t);if(typeof t!="string"){const i={};for(const r in e)i[r]=e[r].src;return i}return e.src}resolve(t){const e=Xo(t);t=di(t);const i={};return t.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const h=n.filter(c=>c[a]?c[a]===l:!1);h.length&&(n=h)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});i[r]=this._resolverHash[r]}),e?i[t[0]]:i}hasKey(t){return!!this._assetMap[t]}hasBundle(t){return!!this._bundles[t]}_getPreferredOrder(t){for(let e=0;e<t.length;e++){const i=t[e],r=this._preferredOrder.find(n=>n.params.format.includes(i.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(t){if(!this._defaultSearchParams)return t;const e=/\?/.test(t)?"&":"?";return`${t}${e}${this._defaultSearchParams}`}_buildResolvedAsset(t,e){const{aliases:i,data:r,loadParser:n,parser:o,format:a,progressSize:l}=e;return(this._basePath||this._rootPath)&&(t.src=Oi.toAbsolute(t.src,this._basePath,this._rootPath)),t.alias=i??t.alias??[t.src],t.src=this._appendDefaultSearchParams(t.src),t.data={...r||{},...t.data},t.loadParser=n??t.loadParser,t.parser=o??t.parser,t.format=a??t.format??Ad(t.src),l!==void 0&&(t.progressSize=l),t}}Yo.RETINA_PREFIX=/@([0-9\.]+)x/;function Ad(s){return s.split(".").pop().split("?").shift().split("#").shift()}const qo=(s,t)=>{const e=t.split("?")[1];return e&&(s+=`?${e}`),s},Ko=class hs{constructor(t,e){this.linkedSheets=[];let i=t;(t==null?void 0:t.source)instanceof At&&(i={texture:t,data:e});const{texture:r,data:n,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=r instanceof $?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=hs.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(t,e=!1){let i=t;const r=e?1/0:hs.BATCH_SIZE;for(;i-t<r&&i<this._frameKeys.length;){const n=this._frameKeys[i],o=this._frames[n],a=o.frame;if(a){let l=null,h=null;const c=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new ct(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?l=new ct(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new ct(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(h=new ct(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new $({source:this.textureSource,frame:l,orig:u,trim:h,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}i++}}_processAnimations(){const t=this.data.animations||{};for(const e in t){this.animations[e]=[];for(let i=0;i<t[e].length;i++){const r=t[e][i];this.animations[e].push(this.textures[r])}}}_parseComplete(){const t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*hs.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*hs.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(t=!1){var e;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&((e=this._texture)==null||e.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Ko.BATCH_SIZE=1e3;let Zo=Ko;const Rd=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Jo(s,t,e){const i={};if(s.forEach(r=>{i[r]=t}),Object.keys(t.textures).forEach(r=>{i[`${t.cachePrefix}${r}`]=t.textures[r]}),!e){const r=Oi.dirname(s[0]);t.linkedSheets.forEach((n,o)=>{const a=Jo([`${r}/${t.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(i,a)})}return i}const Id={extension:w.Asset,cache:{test:s=>s instanceof Zo,getCacheableAssets:(s,t)=>Jo(s,t,!1)},resolver:{extension:{type:w.ResolveParser,name:"resolveSpritesheet"},test:s=>{const e=s.split("?")[0].split("."),i=e.pop(),r=e.pop();return i==="json"&&Rd.includes(r)},parse:s=>{var e;const t=s.split(".");return{resolution:parseFloat(((e=Yo.RETINA_PREFIX.exec(s))==null?void 0:e[1])??"1"),format:t[t.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:w.LoadParser,priority:$o.Normal,name:"spritesheetLoader"},async testParse(s,t){return Oi.extname(t.src).toLowerCase()===".json"&&!!s.frames},async parse(s,t,e){var u,m;const{texture:i,imageFilename:r,textureOptions:n,cachePrefix:o}=(t==null?void 0:t.data)??{};let a=Oi.dirname(t.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof $)l=i;else{const f=qo(a+(r??s.meta.image),t.src);l=(await e.load([{src:f,data:n}]))[f]}const h=new Zo({texture:l.source,data:s,cachePrefix:o});await h.parse();const c=(u=s==null?void 0:s.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(c)){const f=[];for(const y of c){if(typeof y!="string")continue;let x=a+y;(m=t.data)!=null&&m.ignoreMultiPack||(x=qo(x,t.src),f.push(e.load({src:x,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(f);h.linkedSheets=g,g.forEach(y=>{y.linkedSheets=[h].concat(h.linkedSheets.filter(x=>x!==y))})}return h},async unload(s,t,e){await e.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};J.add(Id);class Qo{constructor(t){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const e=this._canvas.getBoundingClientRect(),i=this._canvas.width,r=this._canvas.height,n=e.width/i*this._renderer.resolution,o=e.height/r*this._renderer.resolution,a=e.left,l=e.top,h=`translate(${a}px, ${l}px) scale(${n}, ${o})`;h!==this._lastTransform&&(this._domElement.style.transform=h,this._lastTransform=h)},this._domElement=t.domElement,this._renderer=t.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(t=>{for(const e of t){if(e.target!==this._canvas)continue;const i=this.canvas.width,r=this.canvas.height,n=e.contentRect.width/i*this._renderer.resolution,o=e.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||Qt.shared.add(this.updateTranslation,this,ui.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Qt.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class Di{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Di.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new mt,this.page=new mt,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,i,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Er=/iPhone/i,ta=/iPod/i,ea=/iPad/i,ia=/\biOS-universal(?:.+)Mac\b/i,Tr=/\bAndroid(?:.+)Mobile\b/i,sa=/Android/i,pi=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,vs=/Silk/i,xe=/Windows Phone/i,ra=/\bWindows(?:.+)ARM\b/i,na=/BlackBerry/i,oa=/BB10/i,aa=/Opera Mini/i,la=/\b(CriOS|Chrome)(?:.+)Mobile/i,ha=/Mobile(?:.+)Firefox\b/i,ca=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function Pd(s){return function(t){return t.test(s)}}function ua(s){var t={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?t.userAgent=s:s&&s.userAgent&&(t={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var e=t.userAgent,i=e.split("[FBAN");typeof i[1]<"u"&&(e=i[0]),i=e.split("Twitter"),typeof i[1]<"u"&&(e=i[0]);var r=Pd(e),n={apple:{phone:r(Er)&&!r(xe),ipod:r(ta),tablet:!r(Er)&&(r(ea)||ca(t))&&!r(xe),universal:r(ia),device:(r(Er)||r(ta)||r(ea)||r(ia)||ca(t))&&!r(xe)},amazon:{phone:r(pi),tablet:!r(pi)&&r(vs),device:r(pi)||r(vs)},android:{phone:!r(xe)&&r(pi)||!r(xe)&&r(Tr),tablet:!r(xe)&&!r(pi)&&!r(Tr)&&(r(vs)||r(sa)),device:!r(xe)&&(r(pi)||r(vs)||r(Tr)||r(sa))||r(/\bokhttp\b/i)},windows:{phone:r(xe),tablet:r(ra),device:r(xe)||r(ra)},other:{blackberry:r(na),blackberry10:r(oa),opera:r(aa),firefox:r(ha),chrome:r(la),device:r(na)||r(oa)||r(aa)||r(ha)||r(la)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Md=(ua.default??ua)(globalThis.navigator),kd=9,da=100,Bd=0,Od=0,fa=2,pa=1,Dd=-1e3,Gd=-1e3,Ud=2,Sr=class ou{constructor(t,e=Md){this._mobileInfo=e,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(e.tablet||e.phone)&&this._createTouchHook(),this._renderer=t}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const t=document.createElement("button");t.style.width=`${pa}px`,t.style.height=`${pa}px`,t.style.position="absolute",t.style.top=`${Dd}px`,t.style.left=`${Gd}px`,t.style.zIndex=Ud.toString(),t.style.backgroundColor="#FF0000",t.title="select to enable accessibility for this content",t.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(t),this._hookDiv=t}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Bd}px`,this._div.style.left=`${Od}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=fa.toString(),this._canvasObserver=new Qo({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const t=this._renderer.view.canvas;if(t.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const e=new MutationObserver(()=>{t.parentNode&&(e.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});e.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var t,e;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const i of this._children)(t=i._accessibleDiv)!=null&&t.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1;for(const i in this._pools)this._pools[i].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[i];(e=this._div)!=null&&e.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(t){if(!t.visible||!t.accessibleChildren)return;t.accessible&&(t._accessibleActive||this._addChild(t),t._renderId=this._renderId);const e=t.children;if(e)for(let i=0;i<e.length;i++)this._updateAccessibleObjects(e[i])}init(t){const i={accessibilityOptions:{...ou.defaultOptions,...(t==null?void 0:t.accessibilityOptions)||{}}};this.debug=i.accessibilityOptions.debug,this._activateOnTab=i.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=i.accessibilityOptions.deactivateOnMouseMove,i.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const t=performance.now();if(this._mobileInfo.android.device&&t<this._androidUpdateCount||(this._androidUpdateCount=t+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const e=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const i of this._children)i._renderId===this._renderId&&e.add(this._children.indexOf(i))}for(let i=this._children.length-1;i>=0;i--){const r=this._children[i];e.has(i)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,Mo(this._children,i,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let i=0;i<this._children.length;i++){const r=this._children[i];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(t){t.innerHTML=`type: ${t.type}</br> title : ${t.title}</br> tabIndex: ${t.tabIndex}`}_capHitArea(t){t.x<0&&(t.width+=t.x,t.x=0),t.y<0&&(t.height+=t.y,t.y=0);const{width:e,height:i}=this._renderer;t.x+t.width>e&&(t.width=e-t.x),t.y+t.height>i&&(t.height=i-t.y)}_addChild(t){let i=this._getPool(t.accessibleType).pop();i?(i.innerHTML="",i.removeAttribute("title"),i.removeAttribute("aria-label"),i.tabIndex=0):(t.accessibleType==="button"?i=document.createElement("button"):(i=document.createElement(t.accessibleType),i.style.cssText=`
|
|
1
|
+
(function(gi,tt){typeof exports=="object"&&typeof module<"u"?tt(exports):typeof define=="function"&&define.amd?define(["exports"],tt):(gi=typeof globalThis<"u"?globalThis:gi||self,tt(gi.HolostaffWidget={}))})(this,(function(gi){"use strict";const tt={position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net",visionWsUrl:null};function Vd(s){const e=s.dataset.staffId;if(!e)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:e,position:s.dataset.position??tt.position,trigger:s.dataset.trigger??tt.trigger,scrollThreshold:parseFloat(s.dataset.scrollThreshold??"")||tt.scrollThreshold,delayMs:parseInt(s.dataset.delayMs??"",10)||tt.delayMs,theme:s.dataset.theme??tt.theme,accentColor:s.dataset.accentColor??tt.accentColor,language:s.dataset.language??tt.language,backendUrl:s.dataset.backendUrl??tt.backendUrl,visionWsUrl:s.dataset.visionWsUrl??tt.visionWsUrl}}const zd=["bottom-center","bottom-left","bottom-right"],$d=["scroll","delay","immediate"],jd=["light","dark","auto"];function Xd(s,e,t){const i={...s};return!e.dataset.trigger&&t.trigger&&$d.includes(t.trigger)&&(i.trigger=t.trigger),!e.dataset.position&&t.position&&zd.includes(t.position)&&(i.position=t.position),!e.dataset.theme&&t.theme&&jd.includes(t.theme)&&(i.theme=t.theme),!e.dataset.scrollThreshold&&t.scrollThreshold!=null&&(i.scrollThreshold=t.scrollThreshold),!e.dataset.delayMs&&t.delayMs!=null&&(i.delayMs=t.delayMs),i}const Rr="https://us-central1-holostaff-ai.cloudfunctions.net";async function Yd(s,e=Rr){const t=await fetch(`${e}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s})});if(!t.ok){const i=await t.json().catch(()=>({error:t.statusText}));throw new Error(i.error||`Session request failed: ${t.status}`)}return t.json()}async function Kd(s,e=Rr){const t=await fetch(`${e}/widgetConfig?staffId=${encodeURIComponent(s)}`);if(!t.ok){const i=await t.json().catch(()=>({error:t.statusText}));throw new Error(i.error||`Config request failed: ${t.status}`)}return t.json()}async function qd(s,e,t,i=Rr){const r=await fetch(`${i}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,domSnapshot:e,instruction:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var I=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(I||{});const Mr=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},Os=(s,e)=>Mr(s).priority??e,ie={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(Mr).forEach(e=>{e.type.forEach(t=>{var i,r;return(r=(i=this._removeHandlers)[t])==null?void 0:r.call(i,e)})}),this},add(...s){return s.map(Mr).forEach(e=>{e.type.forEach(t=>{var n,o;const i=this._addHandlers,r=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(r[t]=r[t]||[],(n=r[t])==null||n.push(e))})}),this},handle(s,e,t){var o;const i=this._addHandlers,r=this._removeHandlers;if(i[s]||r[s])throw new Error(`Extension type ${s} already has a handler`);i[s]=e,r[s]=t;const n=this._queue;return n[s]&&((o=n[s])==null||o.forEach(a=>e(a)),delete n[s]),this},handleByMap(s,e){return this.handle(s,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(s,e,t=-1){return this.handle(s,i=>{e.findIndex(n=>n.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((n,o)=>Os(o.value,t)-Os(n.value,t)))},i=>{const r=e.findIndex(n=>n.name===i.name);r!==-1&&e.splice(r,1)})},handleByList(s,e,t=-1){return this.handle(s,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((r,n)=>Os(n,t)-Os(r,t)))},i=>{const r=e.indexOf(i.ref);r!==-1&&e.splice(r,1)})},mixin(s,...e){for(const t of e)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(t))}},Zd={extension:{type:I.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>P0)}},Jd={extension:{type:I.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>k0)}};class ze{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new ze(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}function jo(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Pr={exports:{}},Xo;function Qd(){return Xo||(Xo=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,p){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new r(h,u||l,p),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],d]:l._events[g].push(d):(l._events[g]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var p=0,d=u.length,g=new Array(d);p<d;p++)g[p]=u[p].fn;return g},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,p,d,g){var _=t?t+c:c;if(!this._events[_])return!1;var y=this._events[_],x=arguments.length,v,C;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),x){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,p),!0;case 5:return y.fn.call(y.context,h,u,p,d),!0;case 6:return y.fn.call(y.context,h,u,p,d,g),!0}for(C=1,v=new Array(x-1);C<x;C++)v[C-1]=arguments[C];y.fn.apply(y.context,v)}else{var T=y.length,A;for(C=0;C<T;C++)switch(y[C].once&&this.removeListener(c,y[C].fn,void 0,!0),x){case 1:y[C].fn.call(y[C].context);break;case 2:y[C].fn.call(y[C].context,h);break;case 3:y[C].fn.call(y[C].context,h,u);break;case 4:y[C].fn.call(y[C].context,h,u,p);break;default:if(!v)for(A=1,v=new Array(x-1);A<x;A++)v[A-1]=arguments[A];y[C].fn.apply(y[C].context,v)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,p){var d=t?t+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var g=this._events[d];if(g.fn)g.fn===h&&(!p||g.once)&&(!u||g.context===u)&&o(this,d);else{for(var _=0,y=[],x=g.length;_<x;_++)(g[_].fn!==h||p&&!g[_].once||u&&g[_].context!==u)&&y.push(g[_]);y.length?this._events[d]=y.length===1?y[0]:y:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,s.exports=a})(Pr)),Pr.exports}var ef=Qd();const nt=jo(ef),tf=Math.PI*2,sf=180/Math.PI,rf=Math.PI/180;class Ce{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new Ce(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return kr.x=0,kr.y=0,kr}}const kr=new Ce;class Y{constructor(e=1,t=0,i=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,r,n,o){return this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new Ce;const i=e.x,r=e.y;return t.x=this.a*i+this.c*r+this.tx,t.y=this.b*i+this.d*r+this.ty,t}applyInverse(e,t){t=t||new Ce;const i=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(i*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=i*c*u+-r*c*h+(-l*i+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*i,this.b=r*i+this.b*t,this.c=n*t-this.d*i,this.d=n*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*i+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*i+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*i+e.ty*n+this.ty,this}appendFrom(e,t){const i=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,p=t.d;return this.a=i*c+r*u,this.b=i*h+r*p,this.c=n*c+o*u,this.d=n*h+o*p,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*p+t.ty,this}setTransform(e,t,i,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(i*this.a+r*this.c),this.ty=t-(i*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,r=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(i,t),c=Math.abs(a+l);return c<1e-5||Math.abs(tf-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*i+o.y*n),e}invert(){const e=this.a,t=this.b,i=this.c,r=this.d,n=this.tx,o=e*r-t*i;return this.a=r/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new Y;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return of.identity()}static get shared(){return nf.identity()}}const nf=new Y,of=new Y,Qt=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ei=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ti=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ii=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Br=[],Yo=[],Ds=Math.sign;function af(){for(let s=0;s<16;s++){const e=[];Br.push(e);for(let t=0;t<16;t++){const i=Ds(Qt[s]*Qt[t]+ti[s]*ei[t]),r=Ds(ei[s]*Qt[t]+ii[s]*ei[t]),n=Ds(Qt[s]*ti[t]+ti[s]*ii[t]),o=Ds(ei[s]*ti[t]+ii[s]*ii[t]);for(let a=0;a<16;a++)if(Qt[a]===i&&ei[a]===r&&ti[a]===n&&ii[a]===o){e.push(a);break}}}for(let s=0;s<16;s++){const e=new Y;e.set(Qt[s],ei[s],ti[s],ii[s],0,0),Yo.push(e)}}af();const ce={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:s=>Qt[s],uY:s=>ei[s],vX:s=>ti[s],vY:s=>ii[s],inv:s=>s&8?s&15:-s&7,add:(s,e)=>Br[s][e],sub:(s,e)=>Br[s][ce.inv(e)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,e)=>Math.abs(s)*2<=Math.abs(e)?e>=0?ce.S:ce.N:Math.abs(e)*2<=Math.abs(s)?s>0?ce.E:ce.W:e>0?s>0?ce.SE:ce.SW:s>0?ce.NE:ce.NW,matrixAppendRotationInv:(s,e,t=0,i=0,r=0,n=0)=>{const o=Yo[ce.inv(e)],a=o.a,l=o.b,c=o.c,h=o.d,u=t-Math.min(0,a*r,c*n,a*r+c*n),p=i-Math.min(0,l*r,h*n,l*r+h*n),d=s.a,g=s.b,_=s.c,y=s.d;s.a=a*d+l*_,s.b=a*g+l*y,s.c=c*d+h*_,s.d=c*g+h*y,s.tx=u*d+p*_+s.tx,s.ty=u*g+p*y+s.ty},transformRectCoords:(s,e,t,i)=>{const{x:r,y:n,width:o,height:a}=s,{x:l,y:c,width:h,height:u}=e;return t===ce.E?(i.set(r+l,n+c,o,a),i):t===ce.S?i.set(h-n-a+l,r+c,a,o):t===ce.W?i.set(h-r-o+l,u-n-a+c,o,a):t===ce.N?i.set(n+l,u-r-o+c,a,o):i.set(r+l,n+c,o,a)}},Ns=[new Ce,new Ce,new Ce,new Ce];class ye{constructor(e=0,t=0,i=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(i),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new ye(0,0,0,0)}clone(){return new ye(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=i*(1-r),h=i-c,u=a-c,p=a+n+c,d=l-c,g=l+o+c,_=a+h,y=a+n-h,x=l+h,v=l+o-h;return e>=u&&e<=p&&t>=d&&t<=g&&!(e>_&&e<y&&t>x&&t<v)}intersects(e,t){if(!t){const D=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=D)return!1;const k=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>k}const i=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=i||o<=n)return!1;const a=Ns[0].set(e.left,e.top),l=Ns[1].set(e.left,e.bottom),c=Ns[2].set(e.right,e.top),h=Ns[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=i||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const p=u*(l.y-a.y),d=u*(a.x-l.x),g=p*i+d*n,_=p*r+d*n,y=p*i+d*o,x=p*r+d*o;if(Math.max(g,_,y,x)<=p*a.x+d*a.y||Math.min(g,_,y,x)>=p*h.x+d*h.y)return!1;const v=u*(a.y-c.y),C=u*(c.x-a.x),T=v*i+C*n,A=v*r+C*n,w=v*i+C*o,R=v*r+C*o;return!(Math.max(T,A,w,R)<=v*a.x+C*a.y||Math.min(T,A,w,R)>=v*h.x+C*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new ye),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&i>=this.y&&i<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,i,r){return this.x=e,this.y=t,this.width=i,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Or={default:-1};function xe(s="default"){return Or[s]===void 0&&(Or[s]=-1),++Or[s]}const Ko=new Set,Ie="8.0.0",lf="8.3.4",_i={quiet:!1,noColor:!1},J=((s,e,t=3)=>{if(_i.quiet||Ko.has(e))return;let i=new Error().stack;const r=`${e}
|
|
2
|
+
Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!_i.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",r):(i=i.split(`
|
|
3
|
+
`).splice(t).join(`
|
|
4
|
+
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(i))),Ko.add(e)});Object.defineProperties(J,{quiet:{get:()=>_i.quiet,set:s=>{_i.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>_i.noColor,set:s=>{_i.noColor=s},enumerable:!0,configurable:!1}});const qo=()=>{};function yi(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function Zo(s){return!(s&s-1)&&!!s}function Jo(s){const e={};for(const t in s)s[t]!==void 0&&(e[t]=s[t]);return e}const Qo=Object.create(null);function cf(s){const e=Qo[s];return e===void 0&&(Qo[s]=xe("resource")),e}const ea=class Ed extends nt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...Ed.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){J(Ie,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=cf(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};ea.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let si=ea;const ta=class wd extends nt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=xe("textureSource"),this._resourceType="textureSource",this._resourceId=xe("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...wd.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new si(Jo(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,i;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=xe("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(t=(e=this._gpuData[i])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,i){i||(i=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*i),n=Math.round(t*i);return this.width=r/i,this.height=n/i,this._resolution=i,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=xe("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=Zo(this.pixelWidth)&&Zo(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};ta.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let De=ta;class Dr extends De{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let i=e.format;i||(t instanceof Float32Array?i="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?i="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?i="rgba16uint":(t instanceof Int8Array,i="bgra8unorm")),super({...e,resource:t,format:i}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}Dr.extension=I.TextureSource;const ia=new Y;class sa{constructor(e,t){this.mapCoord=new Y,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const i=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*i.a+o*i.c+i.tx,t[r+1]=n*i.b+o*i.d+i.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const i=e.orig,r=e.trim;r&&(ia.set(i.width/r.width,0,0,i.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(ia));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class q extends nt{constructor({source:e,label:t,frame:i,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=xe("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new ye,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new De,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new sa(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:i,height:r}=this._source,n=t.x/i,o=t.y/r,a=t.width/i,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,p=n+h,d=o+u;c=ce.add(c,ce.NW),e.x0=p+h*ce.uX(c),e.y0=d+u*ce.uY(c),c=ce.add(c,2),e.x1=p+h*ce.uX(c),e.y1=d+u*ce.uY(c),c=ce.add(c,2),e.x2=p+h*ce.uX(c),e.y2=d+u*ce.uY(c),c=ce.add(c,2),e.x3=p+h*ce.uX(c),e.y3=d+u*ce.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return J(Ie,"Texture.baseTexture is now Texture.source"),this._source}}q.EMPTY=new q({label:"EMPTY",source:new De({label:"EMPTY"})}),q.EMPTY.destroy=qo,q.WHITE=new q({source:new Dr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),q.WHITE.destroy=qo;function ra(s,e,t){const{width:i,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;s.minX=n.x-e._x*i,s.maxX=s.minX+o,s.minY=n.y-e._y*r,s.maxY=s.minY+a}else s.minX=-e._x*i,s.maxX=s.minX+i,s.minY=-e._y*r,s.maxY=s.minY+r}const na=new Y;class je{constructor(e=1/0,t=1/0,i=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=na,this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new ye);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=na,this}set(e,t,i,r){this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}addFrame(e,t,i,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let p=this.minX,d=this.minY,g=this.maxX,_=this.maxY,y=o*e+l*t+h,x=a*e+c*t+u;y<p&&(p=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*i+l*t+h,x=a*i+c*t+u,y<p&&(p=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*e+l*r+h,x=a*e+c*r+u,y<p&&(p=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*i+l*r+h,x=a*i+c*r+u,y<p&&(p=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),this.minX=p,this.minY=d,this.maxX=g,this.maxY=_}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,i=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let p=o*t+l*i+h,d=a*t+c*i+u;this.minX=p,this.minY=d,this.maxX=p,this.maxY=d,p=o*r+l*i+h,d=a*r+c*i+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*t+l*n+h,d=a*t+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*r+l*n+h,d=a*r+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,i,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<i&&(this.minY=i),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new je(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,i,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,p=r.d,d=r.tx,g=r.ty;for(let _=t;_<i;_+=2){const y=e[_],x=e[_+1],v=c*y+u*x+d,C=h*y+p*x+g;n=v<n?v:n,o=C<o?C:o,a=v>a?v:a,l=C>l?C:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var hf={grad:.9,turn:360,rad:360/(2*Math.PI)},Tt=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},Le=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*s)/t+0},ot=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),s>t?t:s>e?s:e},oa=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},aa=function(s){return{r:ot(s.r,0,255),g:ot(s.g,0,255),b:ot(s.b,0,255),a:ot(s.a)}},Nr=function(s){return{r:Le(s.r),g:Le(s.g),b:Le(s.b),a:Le(s.a,3)}},uf=/^#([0-9a-f]{3,8})$/i,Fs=function(s){var e=s.toString(16);return e.length<2?"0"+e:e},la=function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=Math.max(e,t,i),o=n-Math.min(e,t,i),a=o?n===e?(t-i)/o:n===t?2+(i-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},ca=function(s){var e=s.h,t=s.s,i=s.v,r=s.a;e=e/360*6,t/=100,i/=100;var n=Math.floor(e),o=i*(1-t),a=i*(1-(e-n)*t),l=i*(1-(1-e+n)*t),c=n%6;return{r:255*[i,a,o,o,l,i][c],g:255*[l,i,i,a,o,o][c],b:255*[o,o,l,i,i,a][c],a:r}},ha=function(s){return{h:oa(s.h),s:ot(s.s,0,100),l:ot(s.l,0,100),a:ot(s.a)}},ua=function(s){return{h:Le(s.h),s:Le(s.s),l:Le(s.l),a:Le(s.a,3)}},da=function(s){return ca((t=(e=s).s,{h:e.h,s:(t*=((i=e.l)<50?i:100-i)/100)>0?2*t/(i+t)*100:0,v:i+t,a:e.a}));var e,t,i},qi=function(s){return{h:(e=la(s)).h,s:(r=(200-(t=e.s))*(i=e.v)/100)>0&&r<200?t*i/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,i,r},df=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ff=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,pf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,mf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Fr={string:[[function(s){var e=uf.exec(s);return e?(s=e[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?Le(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?Le(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var e=pf.exec(s)||mf.exec(s);return e?e[2]!==e[4]||e[4]!==e[6]?null:aa({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(s){var e=df.exec(s)||ff.exec(s);if(!e)return null;var t,i,r=ha({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(hf[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return da(r)},"hsl"]],object:[[function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=r===void 0?1:r;return Tt(e)&&Tt(t)&&Tt(i)?aa({r:Number(e),g:Number(t),b:Number(i),a:Number(n)}):null},"rgb"],[function(s){var e=s.h,t=s.s,i=s.l,r=s.a,n=r===void 0?1:r;if(!Tt(e)||!Tt(t)||!Tt(i))return null;var o=ha({h:Number(e),s:Number(t),l:Number(i),a:Number(n)});return da(o)},"hsl"],[function(s){var e=s.h,t=s.s,i=s.v,r=s.a,n=r===void 0?1:r;if(!Tt(e)||!Tt(t)||!Tt(i))return null;var o=(function(a){return{h:oa(a.h),s:ot(a.s,0,100),v:ot(a.v,0,100),a:ot(a.a)}})({h:Number(e),s:Number(t),v:Number(i),a:Number(n)});return ca(o)},"hsv"]]},fa=function(s,e){for(var t=0;t<e.length;t++){var i=e[t][0](s);if(i)return[i,e[t][1]]}return[null,void 0]},gf=function(s){return typeof s=="string"?fa(s.trim(),Fr.string):typeof s=="object"&&s!==null?fa(s,Fr.object):[null,void 0]},Gr=function(s,e){var t=qi(s);return{h:t.h,s:ot(t.s+100*e,0,100),l:t.l,a:t.a}},Lr=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},pa=function(s,e){var t=qi(s);return{h:t.h,s:t.s,l:ot(t.l+100*e,0,100),a:t.a}},Ur=(function(){function s(e){this.parsed=gf(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return Le(Lr(this.rgba),2)},s.prototype.isDark=function(){return Lr(this.rgba)<.5},s.prototype.isLight=function(){return Lr(this.rgba)>=.5},s.prototype.toHex=function(){return e=Nr(this.rgba),t=e.r,i=e.g,r=e.b,o=(n=e.a)<1?Fs(Le(255*n)):"","#"+Fs(t)+Fs(i)+Fs(r)+o;var e,t,i,r,n,o},s.prototype.toRgb=function(){return Nr(this.rgba)},s.prototype.toRgbString=function(){return e=Nr(this.rgba),t=e.r,i=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+i+", "+r+", "+n+")":"rgb("+t+", "+i+", "+r+")";var e,t,i,r,n},s.prototype.toHsl=function(){return ua(qi(this.rgba))},s.prototype.toHslString=function(){return e=ua(qi(this.rgba)),t=e.h,i=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+i+"%, "+r+"%, "+n+")":"hsl("+t+", "+i+"%, "+r+"%)";var e,t,i,r,n},s.prototype.toHsv=function(){return e=la(this.rgba),{h:Le(e.h),s:Le(e.s),v:Le(e.v),a:Le(e.a,3)};var e},s.prototype.invert=function(){return mt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},s.prototype.saturate=function(e){return e===void 0&&(e=.1),mt(Gr(this.rgba,e))},s.prototype.desaturate=function(e){return e===void 0&&(e=.1),mt(Gr(this.rgba,-e))},s.prototype.grayscale=function(){return mt(Gr(this.rgba,-1))},s.prototype.lighten=function(e){return e===void 0&&(e=.1),mt(pa(this.rgba,e))},s.prototype.darken=function(e){return e===void 0&&(e=.1),mt(pa(this.rgba,-e))},s.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},s.prototype.alpha=function(e){return typeof e=="number"?mt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Le(this.rgba.a,3);var t},s.prototype.hue=function(e){var t=qi(this.rgba);return typeof e=="number"?mt({h:e,s:t.s,l:t.l,a:t.a}):Le(t.h)},s.prototype.isEqual=function(e){return this.toHex()===mt(e).toHex()},s})(),mt=function(s){return s instanceof Ur?s:new Ur(s)},ma=[],_f=function(s){s.forEach(function(e){ma.indexOf(e)<0&&(e(Ur,Fr),ma.push(e))})};function yf(s,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var r in t)i[t[r]]=r;var n={};s.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=i[this.toHex()];if(c)return c;if(o!=null&&o.closest){var h=this.toRgb(),u=1/0,p="black";if(!n.length)for(var d in t)n[d]=new s(t[d]).toRgb();for(var g in t){var _=(a=h,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));_<u&&(u=_,p=g)}return p}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new s(l).toRgb():null},"name"])}_f([yf]);const bi=class ks{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof ks)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const i=typeof e;if(i!==typeof t)return!1;if(i==="number"||i==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,i,r]=this._components;return{r:e,g:t,b:i,a:r}}toRgb(){const[e,t,i]=this._components;return{r:e,g:t,b:i}}toRgbaString(){const[e,t,i]=this.toUint8RgbArray();return`rgba(${e},${t},${i},${this.alpha})`}toUint8RgbArray(e){const[t,i,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(i*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,i,r,n]=this._components;return e[0]=t,e[1]=i,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,i,r]=this._components;return e[0]=t,e[1]=i,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,i]=this.toUint8RgbArray();return(i<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,i,r,n]=ks._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=i,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(i=i*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(i<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(e){let t,i,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,i=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,i,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,i,r,n=255]=e,t/=255,i/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=ks.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=mt(e);o.isValid()&&({r:t,g:i,b:r,a:n}=o.rgba,t/=255,i/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=i,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,i]=this._components;this._int=(e*255<<16)+(t*255<<8)+(i*255|0)}_clamp(e,t=0,i=1){return typeof e=="number"?Math.min(Math.max(e,t),i):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),i)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof ks||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};bi.shared=new bi,bi._temp=new bi,bi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let be=bi;const bf={cullArea:null,cullable:!1,cullableChildren:!0};let Wr=0;const ga=500;function ne(...s){Wr!==ga&&(Wr++,Wr===ga?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}const xi={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class xf{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var i;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(i=t.init)==null||i.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class vf{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new xf(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const i=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[i]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Ue=new vf;xi.register(Ue);const Sf={get isCachedAsTexture(){var s;return!!((s=this.renderGroup)!=null&&s.isCachedAsTexture)},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){var s;(s=this.renderGroup)==null||s.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){J("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function _a(s,e,t){const i=s.length;let r;if(e>=i||t===0)return;t=e+t>i?i-e:t;const n=i-t;for(r=e;r<n;++r)s[r]=s[r+t];s.length=n}const Cf={allowChildren:!0,removeChildren(s=0,e){var n;const t=e??this.children.length,i=t-s,r=[];if(i>0&&i<=t){for(let a=t-1;a>=s;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}_a(this.children,s,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(i===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const e=this.getChildAt(s);return this.removeChild(e)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,e)},getChildIndex(s){const e=this.children.indexOf(s);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(s,e){this.allowChildren||J(Ie,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${s}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const i=s.parent===this;if(s.parent){const n=s.parent.children.indexOf(s);if(i){if(n===e)return s;s.parent.children.splice(n,1)}else s.removeFromParent()}e===t.length?t.push(s):t.splice(e,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),i||(this.emit("childAdded",s,this,e),s.emit("added",this)),s},swapChildren(s,e){if(s===e)return;const t=this.getChildIndex(s),i=this.getChildIndex(e);this.children[t]=e,this.children[i]=s;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var s;(s=this.parent)==null||s.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(e=>this.reparentChildAt(e,this.children.length)),s[0])},reparentChildAt(s,e){if(s.parent===this)return this.setChildIndex(s,e),s;const t=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,e);const i=this.worldTransform.clone();return i.invert(),t.prepend(i),s.setFromMatrix(t),s},replaceChild(s,e){s.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(s)),e.setFromMatrix(s.localTransform),e.updateLocalTransform(),this.removeChild(s)}},Tf={collectRenderables(s,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,e,t))},collectRenderablesSimple(s,e,t){const i=this.children,r=i.length;for(let n=0;n<r;n++)i[n].collectRenderables(s,e,t)},collectRenderablesWithEffects(s,e,t){const{renderPipes:i}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];i[n.pipe].push(n,this,s)}this.collectRenderablesSimple(s,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];i[n.pipe].pop(n,this,s)}}};class Gs{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class Ef{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const i=this._tests[t];if(i.test(e))return Ue.get(i.maskClass,e)}return e}returnMaskEffect(e){Ue.return(e)}}const Hr=new Ef;ie.handleByList(I.MaskEffect,Hr._effectClasses);const wf={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((t,i)=>t.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const e=this.effects.indexOf(s);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const e=this._maskEffect;(e==null?void 0:e.mask)!==s&&(e&&(this.removeEffect(e),Hr.returnMaskEffect(e),this._maskEffect=null),s!=null&&(this._maskEffect=Hr.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){var s;return(s=this._maskEffect)==null?void 0:s.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){var n;!Array.isArray(s)&&s&&(s=[s]);const e=this._filterEffect||(this._filterEffect=new Gs);s=s;const t=(s==null?void 0:s.length)>0,i=((n=e.filters)==null?void 0:n.length)>0,r=t!==i;s=Array.isArray(s)?s.slice(0):s,e.filters=Object.freeze(s),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=s??null))},get filters(){var s;return(s=this._filterEffect)==null?void 0:s.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new Gs),this._filterEffect.filterArea=s},get filterArea(){var s;return(s=this._filterEffect)==null?void 0:s.filterArea}},If={label:null,get name(){return J(Ie,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){J(Ie,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,e=!1){return this.getChildByLabel(s,e)},getChildByLabel(s,e=!1){const t=this.children;for(let i=0;i<t.length;i++){const r=t[i];if(r.label===s||s instanceof RegExp&&s.test(r.label))return r}if(e)for(let i=0;i<t.length;i++){const n=t[i].getChildByLabel(s,!0);if(n)return n}return null},getChildrenByLabel(s,e=!1,t=[]){const i=this.children;for(let r=0;r<i.length;r++){const n=i[r];(n.label===s||s instanceof RegExp&&s.test(n.label))&&t.push(n)}if(e)for(let r=0;r<i.length;r++)i[r].getChildrenByLabel(s,!0,t);return t}},Ke=Ue.getPool(Y),Et=Ue.getPool(je),Af=new Y,Rf={getFastGlobalBounds(s,e){e||(e=new je),e.clear(),this._getGlobalBoundsRecursive(!!s,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(s,e,t){let i=e;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(i=Et.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(s,i,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));n&&i.applyMatrix(o.worldTransform.copyTo(Af).invert()),e.addBounds(i),Et.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),Et.return(i))}};function Vr(s,e,t){t.clear();let i,r;return s.parent?e?i=s.parent.worldTransform:(r=Ke.get().identity(),i=zr(s,r)):i=Y.IDENTITY,ya(s,t,i,e),r&&Ke.return(r),t.isValid||t.set(0,0,0,0),t}function ya(s,e,t,i){var a,l;if(!s.visible||!s.measurable)return;let r;i?r=s.worldTransform:(s.updateLocalTransform(),r=Ke.get(),r.appendFrom(s.localTransform,t));const n=e,o=!!s.effects.length;if(o&&(e=Et.get().clear()),s.boundsArea)e.addRect(s.boundsArea,r);else{const c=s.bounds;c&&!c.isEmpty()&&(e.matrix=r,e.addBounds(c));for(let h=0;h<s.children.length;h++)ya(s.children[h],e,r,i)}if(o){for(let c=0;c<s.effects.length;c++)(l=(a=s.effects[c]).addBounds)==null||l.call(a,e);n.addBounds(e,Y.IDENTITY),Et.return(e)}i||Ke.return(r)}function zr(s,e){const t=s.parent;return t&&(zr(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function vi(s,e){if(s===16777215||!e)return e;if(e===16777215||!s)return s;const t=s>>16&255,i=s>>8&255,r=s&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=i*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const ba=16777215;function Ls(s,e){return s===ba?e:e===ba?s:vi(s,e)}function Si(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const Mf={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(s=new Y,e){if(e)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const t=zr(this,Ke.get().identity());return s.appendFrom(this.localTransform,t),Ke.return(t),s},getGlobalTint(s){if(s)return this.renderGroup?Si(this.renderGroup.worldColor):this.parentRenderGroup?Si(Ls(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Ls(e,t.localColor),t=t.parent;return Si(e)}};function $r(s,e,t){return e.clear(),t||(t=Y.IDENTITY),xa(s,e,t,s,!0),e.isValid||e.set(0,0,0,0),e}function xa(s,e,t,i,r){var l,c;let n;if(r)n=Ke.get(),n=t.copyTo(n);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const h=s.localTransform;n=Ke.get(),n.appendFrom(h,t)}const o=e,a=!!s.effects.length;if(a&&(e=Et.get().clear()),s.boundsArea)e.addRect(s.boundsArea,n);else{s.renderPipeId&&(e.matrix=n,e.addBounds(s.bounds));const h=s.children;for(let u=0;u<h.length;u++)xa(h[u],e,n,i,!1)}if(a){for(let h=0;h<s.effects.length;h++)(c=(l=s.effects[h]).addLocalBounds)==null||c.call(l,e,i);o.addBounds(e,Y.IDENTITY),Et.return(e)}Ke.return(n)}function va(s,e){const t=s.children;for(let i=0;i<t.length;i++){const r=t[i],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&va(r,e)}return e.didChange}const Pf=new Y,kf={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=s/e*t:this.scale.x=t},_setHeight(s,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=s/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new je});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),va(this,s),s.didChange&&$r(this,s.localBounds,Pf),s.localBounds},getBounds(s,e){return Vr(this,s,e||new je)}},Bf={_onRender:null,set onRender(s){const e=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},Of={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(Df))}};function Df(s,e){return s._zIndex-e._zIndex}const Nf={getGlobalPosition(s=new Ce,e=!1){return this.parent?this.parent.toGlobal(this._position,s,e):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,e,t=!1){const i=this.getGlobalTransform(Ke.get(),t);return e=i.apply(s,e),Ke.return(i),e},toLocal(s,e,t,i){e&&(s=e.toGlobal(s,t,i));const r=this.getGlobalTransform(Ke.get(),i);return t=r.applyInverse(s,t),Ke.return(r),t}};class jr{constructor(){this.uid=xe("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let Ff=0;class Gf{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new si(this.textureOptions)}createTexture(e,t,i,r){const n=new De({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new q({source:n,label:`texturePool_${Ff++}`})}getOptimalTexture(e,t,i=1,r,n=!1){let o=Math.ceil(e*i-1e-6),a=Math.ceil(t*i-1e-6);o=yi(o),a=yi(a);const l=r?1:0,c=n?1:0,h=(o<<17)+(a<<2)+(c<<1)+l;this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=i,u.source.width=o/i,u.source.height=a/i,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=e,u.frame.height=t,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(e,t=!1){const i=e.source;return this.getOptimalTexture(e.width,e.height,i._resolution,t)}returnTexture(e,t=!1){const i=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[i].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const i=this._texturePool[t];if(i)for(let r=0;r<i.length;r++)i[r].destroy(!0)}this._texturePool={}}}const Xe=new Gf;xi.register(Xe);class Xr{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new Y,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new jr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let i=0;i<t.length;i++){const r=t[i];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Xe.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let i=0;i<t.length;i++)this.addChild(t[i])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let i=0;i<t.length;i++)this.removeChild(t[i])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let i=0;i<t.length;i++)this._getChildren(t[i],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const i=e.children;for(let r=0;r<i.length;r++)this._getChildren(i[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new Y),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new Y),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new Y),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function Lf(s,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(s[i]=e[i])}const Yr=new ze(null),Us=new ze(null),Kr=new ze(null,1,1),Ws=new ze(null),Hs=1,qr=2,Zi=4;class We extends nt{constructor(e={}){var t,i;super(),this.uid=xe("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new Y,this.relativeGroupTransform=new Y,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new ze(this,0,0),this._scale=Kr,this._pivot=Us,this._origin=Ws,this._skew=Yr,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],Lf(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(r=>this.addChild(r)),(i=e.parent)==null||i.addChild(this)}static mixin(e){J("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),ie.mixin(We,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||J(Ie,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],i=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),i&&(i.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,i&&i.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],i=this.children.indexOf(t);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,i),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Ue.get(Xr,this),this.groupTransform=Y.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Ue.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new Y),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*sf}set angle(e){this.rotation=e*rf}get pivot(){return this._pivot===Us&&(this._pivot=new ze(this,0,0)),this._pivot}set pivot(e){this._pivot===Us&&(this._pivot=new ze(this,0,0),this._origin!==Ws&&ne("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===Yr&&(this._skew=new ze(this,0,0)),this._skew}set skew(e){this._skew===Yr&&(this._skew=new ze(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===Kr&&(this._scale=new ze(this,1,1)),this._scale}set scale(e){this._scale===Kr&&(this._scale=new ze(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Ws&&(this._origin=new ze(this,0,0)),this._origin}set origin(e){this._origin===Ws&&(this._origin=new ze(this,0,0),this._pivot!==Us&&ne("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const i=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,i.width),t!==void 0&&this._setHeight(t,i.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,i=this._scale,r=this._pivot,n=this._origin,o=this._position,a=i._x,l=i._y,c=r._x,h=r._y,u=-n._x,p=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+p*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+p*t.d)-p}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Hs,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=be.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=Hs,this._onUpdate())}get tint(){return Si(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=qr,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Zi,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Zi,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=Zi,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var r;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}ie.mixin(We,Cf,Rf,Nf,Bf,kf,wf,If,Of,bf,Sf,Mf,Tf);class Zr extends We{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new je(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:i,y:r}=e;return i>=t.minX&&i<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,i){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let c=0;c<l;c++)a[c].collectRenderables(e,t,i);r.blendMode.popBlendMode(e)}}class Gt extends Zr{constructor(e=q.EMPTY){e instanceof q&&(e={texture:e});const{texture:t=q.EMPTY,anchor:i,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new ze({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof q?new Gt(e):new Gt(q.from(e,t))}set texture(e){e||(e=q.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return ra(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return J("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,i=this._bounds,{width:r,height:n}=t.orig;i.minX=-e._x*r,i.maxX=i.minX+r,i.minY=-e._y*n,i.maxY=i.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Uf=new je;function Sa(s,e,t){const i=Uf;s.measurable=!0,Vr(s,t,i),e.addBoundsMask(i),s.measurable=!1}function Ca(s,e,t){const i=Et.get();s.measurable=!0;const r=Ke.get().identity(),n=Ta(s,t,r);$r(s,i,n),s.measurable=!1,e.addBoundsMask(i),Ke.return(r),Et.return(i)}function Ta(s,e,t){return s?(s!==e&&(Ta(s.parent,e,t),s.updateLocalTransform(),t.append(s.localTransform)),t):(ne("Mask bounds, renderable is not inside the root container"),t)}class Ea{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Gt),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||Sa(this.mask,e,t)}addLocalBounds(e,t){Ca(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Gt}}Ea.extension=I.MaskEffect;class wa{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}wa.extension=I.MaskEffect;class Ia{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){Sa(this.mask,e,t)}addLocalBounds(e,t){Ca(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof We}}Ia.extension=I.MaskEffect;let Aa={createCanvas:(s,e)=>{const t=document.createElement("canvas");return t.width=s,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,e)=>fetch(s,e),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const de={get(){return Aa},set(s){Aa=s}};class gt extends De{constructor(e){e.resource||(e.resource=de.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,i=this._resolution){const r=super.resize(e,t,i);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}gt.extension=I.TextureSource;class Vs extends De{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}Vs.extension=I.TextureSource;var Ci=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(Ci||{});class Jr{constructor(e,t=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=i,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const Ra=class rt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new Jr(null,null,1/0),this.deltaMS=1/rt.targetFPMS,this.elapsedMS=1/rt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,i=Ci.NORMAL){return this._addListener(new Jr(e,t,i))}addOnce(e,t,i=Ci.NORMAL){return this._addListener(new Jr(e,t,i,!0))}_addListener(e){let t=this._head.next,i=this._head;if(!t)e.connect(i);else{for(;t;){if(e.priority>t.priority){e.connect(i);break}i=t,t=t.next}e.previous||e.connect(i)}return this._startIfPossible(),this}remove(e,t){let i=this._head.next;for(;i;)i.match(e,t)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*rt.targetFPMS;const i=this._head;let r=i.next;for(;r;)r=r.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(Math.max(0,e)/1e3,rt.targetFPMS);this._maxElapsedMS=1/t,this._minElapsedMS&&e>this.maxFPS&&(this.maxFPS=e)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!rt._shared){const e=rt._shared=new rt;e.autoStart=!0,e._protected=!0}return rt._shared}static get system(){if(!rt._system){const e=rt._system=new rt;e.autoStart=!0,e._protected=!0}return rt._system}};Ra.targetFPMS=.06;let at=Ra,Qr;async function Wf(){return Qr??(Qr=(async()=>{var o;const e=de.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(i),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),Qr}const zs=class Id extends De{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Id.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=at.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Wf(),this._load=new Promise((i,r)=>{this.isValid?i(this):(this._resolve=i,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(at.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};zs.extension=I.TextureSource,zs.defaultOptions={...De.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},zs.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Hf=zs;const Ti=(s,e,t=!1)=>(Array.isArray(s)||(s=[s]),e?s.map(i=>typeof i=="string"||t?e(i):i):s);class Vf{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||ne(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Ti(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(i,t);break}}const n=new Map(Object.entries(r||{}));r||i.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&ne("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){ne(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const Ei=new Vf,en=[];ie.handleByList(I.TextureSource,en);function Ma(s={}){const e=s&&s.resource,t=e?s.resource:s,i=e?s:{resource:s};for(let r=0;r<en.length;r++){const n=en[r];if(n.test(t))return new n(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function zf(s={},e=!1){const t=s&&s.resource,i=t?s.resource:s,r=t?s:{resource:s};if(!e&&Ei.has(i))return Ei.get(i);const n=new q({source:Ma(r)});return n.on("destroy",()=>{Ei.has(i)&&Ei.remove(i)}),e||Ei.set(i,n),n}function $f(s,e=!1){return typeof s=="string"?Ei.get(s):s instanceof De?new q({source:s}):zf(s,e)}q.from=$f,De.from=Ma,ie.add(Ea,wa,Ia,Hf,Vs,gt,Dr);var Pa=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(Pa||{});function ct(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function Ji(s){return s.split("?")[0].split("#")[0]}function jf(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xf(s,e,t){return s.replace(new RegExp(jf(e),"g"),t)}function Yf(s,e){let t="",i=0,r=-1,n=0,o=-1;for(let a=0;a<=s.length;++a){if(a<s.length)o=s.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",i=0,r=a,n=0;continue}}}else t.length>0?t+=`/${s.slice(r+1,a)}`:t=s.slice(r+1,a),i=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Qi={toPosix(s){return Xf(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){ct(s),s=this.toPosix(s);const e=/^file:\/\/\//.exec(s);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(s);return t?t[0]:""},toAbsolute(s,e,t){if(ct(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const i=Ji(this.toPosix(e??de.get().getBaseUrl())),r=Ji(this.toPosix(t??this.rootname(i)));return s=this.toPosix(s),s.startsWith("/")?Qi.join(r,s.slice(1)):this.isAbsolute(s)?s:this.join(i,s)},normalize(s){if(ct(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let e="";const t=s.startsWith("/");this.hasProtocol(s)&&(e=this.rootname(s),s=s.slice(e.length));const i=s.endsWith("/");return s=Yf(s),s.length>0&&i&&(s+="/"),t?`/${s}`:e+s},isAbsolute(s){return ct(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let e;for(let t=0;t<s.length;++t){const i=s[t];if(ct(i),i.length>0)if(e===void 0)e=i;else{const r=s[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${i}`:e+=`/${i}`}}return e===void 0?".":this.normalize(e)},dirname(s){if(ct(s),s.length===0)return".";s=this.toPosix(s);let e=s.charCodeAt(0);const t=e===47;let i=-1,r=!0;const n=this.getProtocol(s),o=s;s=s.slice(n.length);for(let a=s.length-1;a>=1;--a)if(e=s.charCodeAt(a),e===47){if(!r){i=a;break}}else r=!1;return i===-1?t?"/":this.isUrl(o)?n+s:n:t&&i===1?"//":n+s.slice(0,i)},rootname(s){ct(s),s=this.toPosix(s);let e="";if(s.startsWith("/")?e="/":e=this.getProtocol(s),this.isUrl(s)){const t=s.indexOf("/",e.length);t!==-1?e=s.slice(0,t):e=s,e.endsWith("/")||(e+="/")}return e},basename(s,e){ct(s),e&&ct(e),s=Ji(this.toPosix(s));let t=0,i=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=s.length){if(e.length===s.length&&e===s)return"";let o=e.length-1,a=-1;for(n=s.length-1;n>=0;--n){const l=s.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(i=n):(o=-1,i=a))}return t===i?i=a:i===-1&&(i=s.length),s.slice(t,i)}for(n=s.length-1;n>=0;--n)if(s.charCodeAt(n)===47){if(!r){t=n+1;break}}else i===-1&&(r=!1,i=n+1);return i===-1?"":s.slice(t,i)},extname(s){ct(s),s=Ji(this.toPosix(s));let e=-1,t=0,i=-1,r=!0,n=0;for(let o=s.length-1;o>=0;--o){const a=s.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||i===-1||n===0||n===1&&e===i-1&&e===t+1?"":s.slice(e,i)},parse(s){ct(s);const e={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return e;s=Ji(this.toPosix(s));let t=s.charCodeAt(0);const i=this.isAbsolute(s);let r;e.root=this.rootname(s),i||this.hasProtocol(s)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=s.length-1,h=0;for(;c>=r;--c){if(t=s.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&i?e.base=e.name=s.slice(1,a):e.base=e.name=s.slice(o,a)):(o===0&&i?(e.name=s.slice(1,n),e.base=s.slice(1,a)):(e.name=s.slice(o,n),e.base=s.slice(o,a)),e.ext=s.slice(n,a)),e.dir=this.dirname(s),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function ka(s,e,t,i,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?ka(s.replace(i[t],a),e,t+1,i,r):r.push(s.replace(i[t],a))}}function Kf(s){const e=/\{(.*?)\}/g,t=s.match(e),i=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),ka(s,r,0,t,i)}else i.push(s);return i}const Ba=s=>!Array.isArray(s);class Oa{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t[i])}`).join("&")}}getAlias(e){const{alias:t,src:i}=e;return Ti(t||i,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&ne("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const i=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);i.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));i.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=i}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let i;i=n=>{this.hasKey(n)&&ne(`[Resolver] already has key: ${n} overwriting`)},Ti(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=Ti(o).map(_=>typeof _=="string"?Kf(_):Array.isArray(_)?_:[_]),p=this.getAlias(n);Array.isArray(p)?p.forEach(i):i(p);const d=[],g=_=>{const y=this._parsers.find(x=>x.test(_));return{src:_,...y==null?void 0:y.parse(_)}};u.forEach(_=>{_.forEach(y=>{let x={};if(typeof y!="object"?x=g(y):(a=y.data??a,l=y.format??l,(y.loadParser||y.parser)&&(c=y.loadParser??c,h=y.parser??h),x={...g(y.src),...y}),!p)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:p,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),d.push(x)})}),p.forEach(_=>{this._assetMap[_]=d})})}resolveBundle(e){const t=Ba(e);e=Ti(e);const i={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}i[r]=a}}),t?i[e[0]]:i}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const i={};for(const r in t)i[r]=t[r].src;return i}return t.src}resolve(e){const t=Ba(e);e=Ti(e);const i={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});i[r]=this._resolverHash[r]}),t?i[e[0]]:i}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const i=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(i.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:i,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Qi.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=i??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??qf(e.src),l!==void 0&&(e.progressSize=l),e}}Oa.RETINA_PREFIX=/@([0-9\.]+)x/;function qf(s){return s.split(".").pop().split("?").shift().split("#").shift()}const Da=(s,e)=>{const t=e.split("?")[1];return t&&(s+=`?${t}`),s},Na=class Bs{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof De&&(i={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=r instanceof q?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Bs.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let i=e;const r=t?1/0:Bs.BATCH_SIZE;for(;i-e<r&&i<this._frameKeys.length;){const n=this._frameKeys[i],o=this._frames[n],a=o.frame;if(a){let l=null,c=null;const h=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new ye(0,0,Math.floor(h.w)/this.resolution,Math.floor(h.h)/this.resolution);o.rotated?l=new ye(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new ye(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(c=new ye(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new q({source:this.textureSource,frame:l,orig:u,trim:c,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}i++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let i=0;i<e[t].length;i++){const r=e[t][i];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Bs.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Bs.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Na.BATCH_SIZE=1e3;let Fa=Na;const Zf=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ga(s,e,t){const i={};if(s.forEach(r=>{i[r]=e}),Object.keys(e.textures).forEach(r=>{i[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=Qi.dirname(s[0]);e.linkedSheets.forEach((n,o)=>{const a=Ga([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(i,a)})}return i}const Jf={extension:I.Asset,cache:{test:s=>s instanceof Fa,getCacheableAssets:(s,e)=>Ga(s,e,!1)},resolver:{extension:{type:I.ResolveParser,name:"resolveSpritesheet"},test:s=>{const t=s.split("?")[0].split("."),i=t.pop(),r=t.pop();return i==="json"&&Zf.includes(r)},parse:s=>{var t;const e=s.split(".");return{resolution:parseFloat(((t=Oa.RETINA_PREFIX.exec(s))==null?void 0:t[1])??"1"),format:e[e.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:I.LoadParser,priority:Pa.Normal,name:"spritesheetLoader"},async testParse(s,e){return Qi.extname(e.src).toLowerCase()===".json"&&!!s.frames},async parse(s,e,t){var u,p;const{texture:i,imageFilename:r,textureOptions:n,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=Qi.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof q)l=i;else{const d=Da(a+(r??s.meta.image),e.src);l=(await t.load([{src:d,data:n}]))[d]}const c=new Fa({texture:l.source,data:s,cachePrefix:o});await c.parse();const h=(u=s==null?void 0:s.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(h)){const d=[];for(const _ of h){if(typeof _!="string")continue;let y=a+_;(p=e.data)!=null&&p.ignoreMultiPack||(y=Da(y,e.src),d.push(t.load({src:y,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(d);c.linkedSheets=g,g.forEach(_=>{_.linkedSheets=[c].concat(c.linkedSheets.filter(y=>y!==_))})}return c},async unload(s,e,t){await t.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};ie.add(Jf);class La{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),i=this._canvas.width,r=this._canvas.height,n=t.width/i*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const i=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/i*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||at.shared.add(this.updateTranslation,this,Ci.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&at.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class es{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=es.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new Ce,this.page=new Ce,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var tn=/iPhone/i,Ua=/iPod/i,Wa=/iPad/i,Ha=/\biOS-universal(?:.+)Mac\b/i,sn=/\bAndroid(?:.+)Mobile\b/i,Va=/Android/i,wi=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,$s=/Silk/i,wt=/Windows Phone/i,za=/\bWindows(?:.+)ARM\b/i,$a=/BlackBerry/i,ja=/BB10/i,Xa=/Opera Mini/i,Ya=/\b(CriOS|Chrome)(?:.+)Mobile/i,Ka=/Mobile(?:.+)Firefox\b/i,qa=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function Qf(s){return function(e){return e.test(s)}}function Za(s){var e={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?e.userAgent=s:s&&s.userAgent&&(e={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var r=Qf(t),n={apple:{phone:r(tn)&&!r(wt),ipod:r(Ua),tablet:!r(tn)&&(r(Wa)||qa(e))&&!r(wt),universal:r(Ha),device:(r(tn)||r(Ua)||r(Wa)||r(Ha)||qa(e))&&!r(wt)},amazon:{phone:r(wi),tablet:!r(wi)&&r($s),device:r(wi)||r($s)},android:{phone:!r(wt)&&r(wi)||!r(wt)&&r(sn),tablet:!r(wt)&&!r(wi)&&!r(sn)&&(r($s)||r(Va)),device:!r(wt)&&(r(wi)||r($s)||r(sn)||r(Va))||r(/\bokhttp\b/i)},windows:{phone:r(wt),tablet:r(za),device:r(wt)||r(za)},other:{blackberry:r($a),blackberry10:r(ja),opera:r(Xa),firefox:r(Ka),chrome:r(Ya),device:r($a)||r(ja)||r(Xa)||r(Ka)||r(Ya)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const ep=(Za.default??Za)(globalThis.navigator),tp=9,Ja=100,ip=0,sp=0,Qa=2,el=1,rp=-1e3,np=-1e3,op=2,rn=class Ad{constructor(e,t=ep){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${el}px`,e.style.height=`${el}px`,e.style.position="absolute",e.style.top=`${rp}px`,e.style.left=`${np}px`,e.style.zIndex=op.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${ip}px`,this._div.style.left=`${sp}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Qa.toString(),this._canvasObserver=new La({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var e,t;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const i of this._children)(e=i._accessibleDiv)!=null&&e.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1;for(const i in this._pools)this._pools[i].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[i];(t=this._div)!=null&&t.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let i=0;i<t.length;i++)this._updateAccessibleObjects(t[i])}init(e){const i={accessibilityOptions:{...Ad.defaultOptions,...(e==null?void 0:e.accessibilityOptions)||{}}};this.debug=i.accessibilityOptions.debug,this._activateOnTab=i.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=i.accessibilityOptions.deactivateOnMouseMove,i.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const i of this._children)i._renderId===this._renderId&&t.add(this._children.indexOf(i))}for(let i=this._children.length-1;i>=0;i--){const r=this._children[i];t.has(i)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,_a(this._children,i,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let i=0;i<this._children.length;i++){const r=this._children[i];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:i}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>i&&(e.height=i-e.y)}_addChild(e){let i=this._getPool(e.accessibleType).pop();i?(i.innerHTML="",i.removeAttribute("title"),i.removeAttribute("aria-label"),i.tabIndex=0):(e.accessibleType==="button"?i=document.createElement("button"):(i=document.createElement(e.accessibleType),i.style.cssText=`
|
|
5
5
|
color: transparent;
|
|
6
6
|
pointer-events: none;
|
|
7
7
|
padding: 0;
|
|
@@ -14,7 +14,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!ni.noColor
|
|
|
14
14
|
-webkit-user-select: none;
|
|
15
15
|
-moz-user-select: none;
|
|
16
16
|
-ms-user-select: none;
|
|
17
|
-
`,
|
|
17
|
+
`,e.accessibleText&&(i.innerText=e.accessibleText)),i.style.width=`${Ja}px`,i.style.height=`${Ja}px`,i.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",i.style.position="absolute",i.style.zIndex=Qa.toString(),i.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?i.setAttribute("aria-live","off"):i.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?i.setAttribute("aria-relevant","additions"):i.setAttribute("aria-relevant","text"),i.addEventListener("click",this._onClick.bind(this)),i.addEventListener("focus",this._onFocus.bind(this)),i.addEventListener("focusout",this._onFocusOut.bind(this))),i.style.pointerEvents=e.accessiblePointerEvents,i.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?i.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(i.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&i.setAttribute("aria-label",e.accessibleHint),e.interactive?i.tabIndex=e.tabIndex:i.tabIndex=0,this.debug&&this._updateDebugHTML(i),e._accessibleActive=!0,e._accessibleDiv=i,i.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:i}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new es(r),{target:i});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==tp||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){var e;this._deactivate(),this._destroyTouchHook(),(e=this._canvasObserver)==null||e.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}};rn.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"accessibility"},rn.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let ap=rn;const lp={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},nn=Object.create(null),tl=Object.create(null);function ts(s,e){let t=tl[s];return t===void 0&&(nn[e]===void 0&&(nn[e]=1),tl[s]=t=nn[e]++),t}let Ii;function il(){return(!Ii||Ii!=null&&Ii.isContextLost())&&(Ii=de.get().createCanvas().getContext("webgl",{})),Ii}let js;function cp(){if(!js){js="mediump";const s=il();s&&s.getShaderPrecisionFormat&&(js=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision?"highp":"mediump")}return js}function hp(s,e,t){return e?s:t?(s=s.replace("out vec4 finalColor;",""),`
|
|
18
18
|
|
|
19
19
|
#ifdef GL_ES // This checks if it is WebGL1
|
|
20
20
|
#define in varying
|
|
@@ -29,29 +29,29 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!ni.noColor
|
|
|
29
29
|
#define out varying
|
|
30
30
|
#endif
|
|
31
31
|
${s}
|
|
32
|
-
`}function
|
|
33
|
-
${s}`}else if(i!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function
|
|
34
|
-
${s}`:s}const
|
|
35
|
-
${s}`}function Xd(s,t){return t?s.replace("#version 300 es",""):s}const wr={stripVersion:Xd,ensurePrecision:Wd,addProgramDefines:Hd,setProgramName:jd,insertVersion:Vd},Ui=Object.create(null),_a=class Zn{constructor(t){t={...Zn.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Fd()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let r=t.fragment,n=t.vertex;Object.keys(wr).forEach(o=>{const a=i[o];r=wr[o](r,a,!0),n=wr[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=Gi(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,Ui[this._cacheKey]=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return Ui[e]||(Ui[e]=new Zn(t),Ui[e]._cacheKey=e),Ui[e]}};_a.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let gi=_a;const ya={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function Li(s){return ya[s]??ya.float32}const Yd={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},xa=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function ba(s,t){let e;for(;(e=xa.exec(s))!==null;){const i=Yd[e[3]]??"float32";t[e[2]]={location:parseInt(e[1],10),format:i,stride:Li(i).stride,offset:0,instance:!1,start:0}}xa.lastIndex=0}function qd(s){return s.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function Kd({source:s,entryPoint:t}){const e={},i=qd(s),r=i.indexOf(`fn ${t}(`);if(r===-1)return e;const n=i.indexOf("->",r);if(n===-1)return e;const o=i.substring(r,n);if(ba(o,e),Object.keys(e).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],h=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),c=i.match(h);c&&ba(c[1],e)}}return e}function Ar(s){var u,m;const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=(u=s.match(t))==null?void 0:u.map(f=>({group:parseInt(f.match(e)[1],10),binding:parseInt(f.match(i)[1],10),name:f.match(r)[2],isUniform:f.match(r)[1]==="<uniform>",type:f.match(n)[1]}));if(!h)return{groups:[],structs:[]};const c=((m=s.match(o))==null?void 0:m.map(f=>{const g=f.match(l)[1],y=f.match(a).reduce((x,v)=>{const[E,T]=v.split(":");return x[E.trim()]=T.trim(),x},{});return y?{name:g,members:y}:null}).filter(({name:f})=>h.some(g=>g.type===f||g.type.includes(`<${f}>`))))??[];return{groups:h,structs:c}}var je=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(je||{});function Zd({groups:s}){const t=[];for(let e=0;e<s.length;e++){const i=s[e];t[i.group]||(t[i.group]=[]),i.isUniform?t[i.group].push({binding:i.binding,visibility:je.VERTEX|je.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?t[i.group].push({binding:i.binding,visibility:je.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?t[i.group].push({binding:i.binding,visibility:je.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?t[i.group].push({binding:i.binding,visibility:je.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&t[i.group].push({binding:i.binding,visibility:je.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let e=0;e<t.length;e++)t[e]||(t[e]=[]);return t}function Jd({groups:s}){const t=[];for(let e=0;e<s.length;e++){const i=s[e];t[i.group]||(t[i.group]={}),t[i.group][i.name]=i.binding}return t}function Qd(s,t){const e=new Set,i=new Set,r=[...s.structs,...t.structs].filter(o=>e.has(o.name)?!1:(e.add(o.name),!0)),n=[...s.groups,...t.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:r,groups:n}}const Ni=Object.create(null);class Xe{constructor(t){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:e,vertex:i,layout:r,gpuLayout:n,name:o}=t;if(this.name=o,this.fragment=e,this.vertex=i,e.source===i.source){const h=Ar(e.source);this.structsAndGroups=h}else{const h=Ar(i.source),c=Ar(e.source);this.structsAndGroups=Qd(h,c)}this.layout=r??Jd(this.structsAndGroups),this.gpuLayout=n??Zd(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,i=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=Gi(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=Kd(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Ni[this._cacheKey]=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return Ni[e]||(Ni[e]=new Xe(t),Ni[e]._cacheKey=e),Ni[e]}}const va=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],tf=va.reduce((s,t)=>(s[t]=!0,s),{});function ef(s,t){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*t);case"vec3<f32>":return new Float32Array(3*t);case"vec4<f32>":return new Float32Array(4*t);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ea=class au{constructor(t,e){this._touched=0,this.uid=dt("uniform"),this._resourceType="uniformGroup",this._resourceId=dt("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...au.defaultOptions,...e},this.uniformStructures=t;const i={};for(const r in t){const n=t[r];if(n.name=r,n.size=n.size??1,!tf[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${va.join(", ")}`)}n.value??(n.value=ef(n.type,n.size)),i[r]=n.value}this.uniforms=i,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=Gi(Object.keys(i).map(r=>`${r}-${t[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Ea.defaultOptions={ubo:!1,isStatic:!1};let le=Ea;class Ie{constructor(t){this.resources=Object.create(null),this._dirty=!0;let e=0;for(const i in t){const r=t[i];this.setResource(r,e++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const t=[];let e=0;for(const i in this.resources)t[e++]=this.resources[i]._resourceId;this._key=t.join("|")}setResource(t,e){var r,n;const i=this.resources[e];t!==i&&((r=i==null?void 0:i.off)==null||r.call(i,"change",this.onResourceChange,this),(n=t.on)==null||n.call(t,"change",this.onResourceChange,this),this.resources[e]=t,this._dirty=!0)}getResource(t){return this.resources[t]}_touch(t,e){const i=this.resources;for(const r in i)i[r]._gcLastUsed=t,i[r]._touched=e}destroy(){var e;const t=this.resources;for(const i in t){const r=t[i];(e=r==null?void 0:r.off)==null||e.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(t){this._dirty=!0,t.destroyed?this.destroy():this._updateKey()}}var he=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.CANVAS=4]="CANVAS",s[s.BOTH=3]="BOTH",s))(he||{});class be extends Zt{constructor(t){super(),this.uid=dt("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:e,glProgram:i,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=t;this.gpuProgram=e,this.glProgram=i,o===void 0&&(o=0,e&&(o|=he.WEBGPU),i&&(o|=he.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&r&&a)for(const h in a)for(const c in a[h]){const u=a[h][c];l[u]={group:h,binding:c,name:u}}else if(e&&r&&!a){const h=e.structsAndGroups.groups;a={},h.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,l[c.name]=c})}else if(n){r={},a={},e&&e.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let h=0;for(const c in n)l[c]||(r[99]||(r[99]=new Ie,this._ownedBindGroups.push(r[99])),l[c]={group:99,binding:h,name:c},a[99]=a[99]||{},a[99][h]=c,h++);for(const c in n){const u=c;let m=n[c];!m.source&&!m._resourceType&&(m=new le(m));const f=l[u];f&&(r[f.group]||(r[f.group]=new Ie,this._ownedBindGroups.push(r[f.group])),r[f.group].setResource(m,f.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(t,e,i){var r,n;(r=this._uniformBindMap)[e]||(r[e]={}),(n=this._uniformBindMap[e])[i]||(n[i]=t),this.groups[e]||(this.groups[e]=new Ie,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const i={};for(const r in e){const n=e[r];Object.defineProperty(i,n.name,{get(){return t[n.group].getResource(n.binding)},set(o){t[n.group].setResource(o,n.binding)}})}return i}destroy(t=!1){var e,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),t&&((e=this.gpuProgram)==null||e.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(t){const{gpu:e,gl:i,...r}=t;let n,o;return e&&(n=Xe.from(e)),i&&(o=gi.from(i)),new be({gpuProgram:n,glProgram:o,...r})}}const sf={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Rr=0,Ir=1,Pr=2,Mr=3,kr=4,Br=5,Or=class lu{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Rr)}set blend(t){!!(this.data&1<<Rr)!==t&&(this.data^=1<<Rr)}get offsets(){return!!(this.data&1<<Ir)}set offsets(t){!!(this.data&1<<Ir)!==t&&(this.data^=1<<Ir)}set cullMode(t){if(t==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=t==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<Pr)}set culling(t){!!(this.data&1<<Pr)!==t&&(this.data^=1<<Pr)}get depthTest(){return!!(this.data&1<<Mr)}set depthTest(t){!!(this.data&1<<Mr)!==t&&(this.data^=1<<Mr)}get depthMask(){return!!(this.data&1<<Br)}set depthMask(t){!!(this.data&1<<Br)!==t&&(this.data^=1<<Br)}get clockwiseFrontFace(){return!!(this.data&1<<kr)}set clockwiseFrontFace(t){!!(this.data&1<<kr)!==t&&(this.data^=1<<kr)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!=="none",this._blendMode=t,this._blendModeId=sf[t]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const t=new lu;return t.depthTest=!1,t.blend=!0,t}};Or.default2d=Or.for2d();let ve=Or;const Ta=class Jn extends be{constructor(t){t={...Jn.defaultOptions,...t},super(t),this.enabled=!0,this._state=ve.for2d(),this.blendMode=t.blendMode,this.padding=t.padding,typeof t.antialias=="boolean"?this.antialias=t.antialias?"on":"off":this.antialias=t.antialias,this.resolution=t.resolution,this.blendRequired=t.blendRequired,this.clipToViewport=t.clipToViewport,this.addResource("uTexture",0,1),t.blendRequired&&this.addResource("uBackTexture",0,3)}apply(t,e,i,r){t.applyFilter(this,e,i,r)}get blendMode(){return this._state.blendMode}set blendMode(t){this._state.blendMode=t}static from(t){const{gpu:e,gl:i,...r}=t;let n,o;return e&&(n=Xe.from(e)),i&&(o=gi.from(i)),new Jn({gpuProgram:n,glProgram:o,...r})}};Ta.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Sa=Ta;const Dr=[];J.handleByNamedList(w.Environment,Dr);async function rf(s){if(!s)for(let t=0;t<Dr.length;t++){const e=Dr[t];if(e.value.test()){await e.value.load();return}}}let Fi;function Ca(){if(typeof Fi=="boolean")return Fi;try{Fi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Fi=!1}return Fi}function wa(s,t,e=2){const i=t&&t.length,r=i?t[0]*e:s.length;let n=Aa(s,0,r,e,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,h;if(i&&(n=hf(s,t,n,e)),s.length>80*e){a=s[0],l=s[1];let c=a,u=l;for(let m=e;m<r;m+=e){const f=s[m],g=s[m+1];f<a&&(a=f),g<l&&(l=g),f>c&&(c=f),g>u&&(u=g)}h=Math.max(c-a,u-l),h=h!==0?32767/h:0}return Hi(n,o,e,a,l,h,0),o}function Aa(s,t,e,i,r){let n;if(r===bf(s,t,e,i)>0)for(let o=t;o<e;o+=i)n=Ma(o/i|0,s[o],s[o+1],n);else for(let o=e-i;o>=t;o-=i)n=Ma(o/i|0,s[o],s[o+1],n);return n&&_i(n,n.next)&&(zi(n),n=n.next),n}function Ye(s,t){if(!s)return s;t||(t=s);let e=s,i;do if(i=!1,!e.steiner&&(_i(e,e.next)||Et(e.prev,e,e.next)===0)){if(zi(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function Hi(s,t,e,i,r,n,o){if(!s)return;!o&&n&&pf(s,i,r,n);let a=s;for(;s.prev!==s.next;){const l=s.prev,h=s.next;if(n?of(s,i,r,n):nf(s)){t.push(l.i,s.i,h.i),zi(s),s=h.next,a=h.next;continue}if(s=h,s===a){o?o===1?(s=af(Ye(s),t),Hi(s,t,e,i,r,n,2)):o===2&&lf(s,t,e,i,r,n):Hi(Ye(s),t,e,i,r,n,1);break}}}function nf(s){const t=s.prev,e=s,i=s.next;if(Et(t,e,i)>=0)return!1;const r=t.x,n=e.x,o=i.x,a=t.y,l=e.y,h=i.y,c=Math.min(r,n,o),u=Math.min(a,l,h),m=Math.max(r,n,o),f=Math.max(a,l,h);let g=i.next;for(;g!==t;){if(g.x>=c&&g.x<=m&&g.y>=u&&g.y<=f&&Wi(r,a,n,l,o,h,g.x,g.y)&&Et(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function of(s,t,e,i){const r=s.prev,n=s,o=s.next;if(Et(r,n,o)>=0)return!1;const a=r.x,l=n.x,h=o.x,c=r.y,u=n.y,m=o.y,f=Math.min(a,l,h),g=Math.min(c,u,m),y=Math.max(a,l,h),x=Math.max(c,u,m),v=Gr(f,g,t,e,i),E=Gr(y,x,t,e,i);let T=s.prevZ,C=s.nextZ;for(;T&&T.z>=v&&C&&C.z<=E;){if(T.x>=f&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&Wi(a,c,l,u,h,m,T.x,T.y)&&Et(T.prev,T,T.next)>=0||(T=T.prevZ,C.x>=f&&C.x<=y&&C.y>=g&&C.y<=x&&C!==r&&C!==o&&Wi(a,c,l,u,h,m,C.x,C.y)&&Et(C.prev,C,C.next)>=0))return!1;C=C.nextZ}for(;T&&T.z>=v;){if(T.x>=f&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&Wi(a,c,l,u,h,m,T.x,T.y)&&Et(T.prev,T,T.next)>=0)return!1;T=T.prevZ}for(;C&&C.z<=E;){if(C.x>=f&&C.x<=y&&C.y>=g&&C.y<=x&&C!==r&&C!==o&&Wi(a,c,l,u,h,m,C.x,C.y)&&Et(C.prev,C,C.next)>=0)return!1;C=C.nextZ}return!0}function af(s,t){let e=s;do{const i=e.prev,r=e.next.next;!_i(i,r)&&Ia(i,e,e.next,r)&&Vi(i,r)&&Vi(r,i)&&(t.push(i.i,e.i,r.i),zi(e),zi(e.next),e=s=r),e=e.next}while(e!==s);return Ye(e)}function lf(s,t,e,i,r,n){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&_f(o,a)){let l=Pa(o,a);o=Ye(o,o.next),l=Ye(l,l.next),Hi(o,t,e,i,r,n,0),Hi(l,t,e,i,r,n,0);return}a=a.next}o=o.next}while(o!==s)}function hf(s,t,e,i){const r=[];for(let n=0,o=t.length;n<o;n++){const a=t[n]*i,l=n<o-1?t[n+1]*i:s.length,h=Aa(s,a,l,i,!1);h===h.next&&(h.steiner=!0),r.push(gf(h))}r.sort(cf);for(let n=0;n<r.length;n++)e=uf(r[n],e);return e}function cf(s,t){let e=s.x-t.x;if(e===0&&(e=s.y-t.y,e===0)){const i=(s.next.y-s.y)/(s.next.x-s.x),r=(t.next.y-t.y)/(t.next.x-t.x);e=i-r}return e}function uf(s,t){const e=df(s,t);if(!e)return t;const i=Pa(e,s);return Ye(i,i.next),Ye(e,e.next)}function df(s,t){let e=t;const i=s.x,r=s.y;let n=-1/0,o;if(_i(s,e))return e;do{if(_i(s,e.next))return e.next;if(r<=e.y&&r>=e.next.y&&e.next.y!==e.y){const u=e.x+(r-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>n&&(n=u,o=e.x<e.next.x?e:e.next,u===i))return o}e=e.next}while(e!==t);if(!o)return null;const a=o,l=o.x,h=o.y;let c=1/0;e=o;do{if(i>=e.x&&e.x>=l&&i!==e.x&&Ra(r<h?i:n,r,l,h,r<h?n:i,r,e.x,e.y)){const u=Math.abs(r-e.y)/(i-e.x);Vi(e,s)&&(u<c||u===c&&(e.x>o.x||e.x===o.x&&ff(o,e)))&&(o=e,c=u)}e=e.next}while(e!==a);return o}function ff(s,t){return Et(s.prev,s,t.prev)<0&&Et(t.next,s,s.next)<0}function pf(s,t,e,i){let r=s;do r.z===0&&(r.z=Gr(r.x,r.y,t,e,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==s);r.prevZ.nextZ=null,r.prevZ=null,mf(r)}function mf(s){let t,e=1;do{let i=s,r;s=null;let n=null;for(t=0;i;){t++;let o=i,a=0;for(let h=0;h<e&&(a++,o=o.nextZ,!!o);h++);let l=e;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:s=r,r.prevZ=n,n=r;i=o}n.nextZ=null,e*=2}while(t>1);return s}function Gr(s,t,e,i,r){return s=(s-e)*r|0,t=(t-i)*r|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,s|t<<1}function gf(s){let t=s,e=s;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==s);return e}function Ra(s,t,e,i,r,n,o,a){return(r-o)*(t-a)>=(s-o)*(n-a)&&(s-o)*(i-a)>=(e-o)*(t-a)&&(e-o)*(n-a)>=(r-o)*(i-a)}function Wi(s,t,e,i,r,n,o,a){return!(s===o&&t===a)&&Ra(s,t,e,i,r,n,o,a)}function _f(s,t){return s.next.i!==t.i&&s.prev.i!==t.i&&!yf(s,t)&&(Vi(s,t)&&Vi(t,s)&&xf(s,t)&&(Et(s.prev,s,t.prev)||Et(s,t.prev,t))||_i(s,t)&&Et(s.prev,s,s.next)>0&&Et(t.prev,t,t.next)>0)}function Et(s,t,e){return(t.y-s.y)*(e.x-t.x)-(t.x-s.x)*(e.y-t.y)}function _i(s,t){return s.x===t.x&&s.y===t.y}function Ia(s,t,e,i){const r=Ss(Et(s,t,e)),n=Ss(Et(s,t,i)),o=Ss(Et(e,i,s)),a=Ss(Et(e,i,t));return!!(r!==n&&o!==a||r===0&&Ts(s,e,t)||n===0&&Ts(s,i,t)||o===0&&Ts(e,s,i)||a===0&&Ts(e,t,i))}function Ts(s,t,e){return t.x<=Math.max(s.x,e.x)&&t.x>=Math.min(s.x,e.x)&&t.y<=Math.max(s.y,e.y)&&t.y>=Math.min(s.y,e.y)}function Ss(s){return s>0?1:s<0?-1:0}function yf(s,t){let e=s;do{if(e.i!==s.i&&e.next.i!==s.i&&e.i!==t.i&&e.next.i!==t.i&&Ia(e,e.next,s,t))return!0;e=e.next}while(e!==s);return!1}function Vi(s,t){return Et(s.prev,s,s.next)<0?Et(s,t,s.next)>=0&&Et(s,s.prev,t)>=0:Et(s,t,s.prev)<0||Et(s,s.next,t)<0}function xf(s,t){let e=s,i=!1;const r=(s.x+t.x)/2,n=(s.y+t.y)/2;do e.y>n!=e.next.y>n&&e.next.y!==e.y&&r<(e.next.x-e.x)*(n-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==s);return i}function Pa(s,t){const e=Ur(s.i,s.x,s.y),i=Ur(t.i,t.x,t.y),r=s.next,n=t.prev;return s.next=t,t.prev=s,e.next=r,r.prev=e,i.next=e,e.prev=i,n.next=i,i.prev=n,i}function Ma(s,t,e,i){const r=Ur(s,t,e);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function zi(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function Ur(s,t,e){return{i:s,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function bf(s,t,e,i){let r=0;for(let n=t,o=e-i;n<e;n+=i)r+=(s[o]-s[n])*(s[n+1]+s[o+1]),o=n;return r}const vf=wa.default||wa;var Xt=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(Xt||{});class ka{constructor(t){this.items=[],this._name=t}emit(t,e,i,r,n,o,a,l){const{name:h,items:c}=this;for(let u=0,m=c.length;u<m;u++)c[u][h](t,e,i,r,n,o,a,l);return this}add(t){return t[this._name]&&(this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return e!==-1&&this.items.splice(e,1),this}contains(t){return this.items.indexOf(t)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const Ef=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Ba=class hu extends Zt{constructor(t){super(),this.tick=0,this.uid=dt("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=t.type,this.name=t.name,this.config=t;const e=[...Ef,...this.config.runners??[]];this._addRunners(...e),this._unsafeEvalCheck()}async init(t={}){const e=t.skipExtensionImports===!0?!0:t.manageImports===!1;await rf(e),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)t={...this._systemsHash[i].constructor.defaultOptions,...t};t={...hu.defaultOptions,...t},this._roundPixels=t.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(t);this._initOptions=t}render(t,e){this.tick++;let i=t;if(i instanceof kt&&(i={container:i},e&&(K(vt,"passing a second argument is deprecated, please use render options instead"),i.target=e.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const r=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=r?i.clearColor:ut.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(t,e,i){const r=this.view.resolution;this.view.resize(t,e,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==r&&this.runners.resolutionChange.emit(i)}clear(t={}){const e=this;t.target||(t.target=e.renderTarget.renderTarget),t.clearColor||(t.clearColor=this.background.colorRgba),t.clear??(t.clear=Xt.ALL);const{clear:i,clearColor:r,target:n,mipLevel:o,layer:a}=t;ut.shared.setValue(r??this.background.colorRgba),e.renderTarget.clear(n,i,ut.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(t){this.view.resolution=t,this.runners.resolutionChange.emit(t)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...t){t.forEach(e=>{this.runners[e]=new ka(e)})}_addSystems(t){let e;for(e in t){const i=t[e];this._addSystem(i.value,i.name)}}_addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const r in this.runners)this.runners[r].add(i);return this}_addPipes(t,e){const i=e.reduce((r,n)=>(r[n.name]=n.value,r),{});t.forEach(r=>{const n=r.value,o=r.name,a=i[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(t=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(t),(t===!0||typeof t=="object"&&t.releaseGlobalResources)&&li.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(t){return this.textureGenerator.generateTexture(t)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Ca())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};Ba.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let $i=Ba,Cs;function Tf(s){return Cs!==void 0||(Cs=(()=>{var e;const t={stencil:!0,failIfMajorPerformanceCaveat:s??$i.defaultOptions.failIfMajorPerformanceCaveat};try{if(!rt.get().getWebGLRenderingContext())return!1;let r=rt.get().createCanvas().getContext("webgl",t);const n=!!((e=r==null?void 0:r.getContextAttributes())!=null&&e.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Cs}let ws;async function Sf(s={}){return ws!==void 0||(ws=await(async()=>{const t=rt.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),ws}const Oa=["webgl","webgpu","canvas"];async function Cf(s){let t=[];s.preference?(t.push(s.preference),Oa.forEach(n=>{n!==s.preference&&t.push(n)})):t=Oa.slice();let e,i={};for(let n=0;n<t.length;n++){const o=t[n];if(o==="webgpu"&&await Sf()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>gy);e=a,i={...s,...s.webgpu};break}else if(o==="webgl"&&Tf(s.failIfMajorPerformanceCaveat??$i.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>Y_);e=a,i={...s,...s.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>Xg);e=a,i={...s,...s.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!e)throw new Error("No available renderer for the current environment");const r=new e;return await r.init(i),r}const As="8.17.1";class Da{static init(){var t;(t=globalThis.__PIXI_APP_INIT__)==null||t.call(globalThis,this,As)}static destroy(){}}Da.extension=w.Application;class Ga{constructor(t){this._renderer=t}init(){var t;(t=globalThis.__PIXI_RENDERER_INIT__)==null||t.call(globalThis,this._renderer,As)}destroy(){this._renderer=null}}Ga.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"initHook",priority:-10};class Ua{static init(t){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,i;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;e=r,i=n}this.renderer.resize(e,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=t.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Ua.extension=w.Application;class La{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,ui.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?Qt.shared:new Qt,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}La.extension=w.Application,J.add(Ua),J.add(La);const Na=class Qn{constructor(...t){this.stage=new kt,t[0]!==void 0&&K(vt,"Application constructor options are deprecated, please use Application.init() instead.")}async init(t){t={...t},this.stage||(this.stage=new kt),this.renderer=await Cf(t),Qn._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return K(vt,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(t=!1,e=!1){const i=Qn._plugins.slice(0);i.reverse(),i.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(e),this.stage=null,this.renderer.destroy(t),this.renderer=null}};Na._plugins=[];let Fa=Na;J.handleByList(w.Application,Fa._plugins),J.add(Da);var Lr,Ha;function wf(){if(Ha)return Lr;Ha=1,Lr=e;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},t=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function e(n){var o=[];return n.replace(t,function(a,l,h){var c=l.toLowerCase();for(h=r(h),c=="m"&&h.length>2&&(o.push([l].concat(h.splice(0,2))),c="l",l=l=="m"?"l":"L");;){if(h.length==s[c])return h.unshift(l),o.push(h);if(h.length<s[c])throw new Error("malformed path data");o.push([l].concat(h.splice(0,s[c])))}}),o}var i=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(i);return o?o.map(Number):[]}return Lr}var Af=wf();const Rf=no(Af);function If(s,t){const e=Rf(s),i=[];let r=null,n=0,o=0;for(let a=0;a<e.length;a++){const l=e[a],h=l[0],c=l;switch(h){case"M":n=c[1],o=c[2],t.moveTo(n,o);break;case"m":n+=c[1],o+=c[2],t.moveTo(n,o);break;case"H":n=c[1],t.lineTo(n,o);break;case"h":n+=c[1],t.lineTo(n,o);break;case"V":o=c[1],t.lineTo(n,o);break;case"v":o+=c[1],t.lineTo(n,o);break;case"L":n=c[1],o=c[2],t.lineTo(n,o);break;case"l":n+=c[1],o+=c[2],t.lineTo(n,o);break;case"C":n=c[5],o=c[6],t.bezierCurveTo(c[1],c[2],c[3],c[4],n,o);break;case"c":t.bezierCurveTo(n+c[1],o+c[2],n+c[3],o+c[4],n+c[5],o+c[6]),n+=c[5],o+=c[6];break;case"S":n=c[3],o=c[4],t.bezierCurveToShort(c[1],c[2],n,o);break;case"s":t.bezierCurveToShort(n+c[1],o+c[2],n+c[3],o+c[4]),n+=c[3],o+=c[4];break;case"Q":n=c[3],o=c[4],t.quadraticCurveTo(c[1],c[2],n,o);break;case"q":t.quadraticCurveTo(n+c[1],o+c[2],n+c[3],o+c[4]),n+=c[3],o+=c[4];break;case"T":n=c[1],o=c[2],t.quadraticCurveToShort(n,o);break;case"t":n+=c[1],o+=c[2],t.quadraticCurveToShort(n,o);break;case"A":n=c[6],o=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"a":n+=c[6],o+=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"Z":case"z":t.closePath(),i.length>0&&(r=i.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:tt(`Unknown SVG path command: ${h}`)}h!=="Z"&&h!=="z"&&r===null&&(r={startX:n,startY:o},i.push(r))}return t}class Nr{constructor(t=0,e=0,i=0){this.type="circle",this.x=t,this.y=e,this.radius=i}clone(){return new Nr(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-t,n=this.y-e;return r*=r,n*=n,r+n<=i}strokeContains(t,e,i,r=.5){if(this.radius===0)return!1;const n=this.x-t,o=this.y-e,a=this.radius,l=(1-r)*i,h=Math.sqrt(n*n+o*o);return h<=a+l&&h>a-(i-l)}getBounds(t){return t||(t=new ct),t.x=this.x-this.radius,t.y=this.y-this.radius,t.width=this.radius*2,t.height=this.radius*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.radius=t.radius,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Fr{constructor(t=0,e=0,i=0,r=0){this.type="ellipse",this.x=t,this.y=e,this.halfWidth=i,this.halfHeight=r}clone(){return new Fr(this.x,this.y,this.halfWidth,this.halfHeight)}contains(t,e){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(t-this.x)/this.halfWidth,r=(e-this.y)/this.halfHeight;return i*=i,r*=r,i+r<=1}strokeContains(t,e,i,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=i*(1-r),l=i-a,h=n-l,c=o-l,u=n+a,m=o+a,f=t-this.x,g=e-this.y,y=f*f/(h*h)+g*g/(c*c),x=f*f/(u*u)+g*g/(m*m);return y>1&&x<=1}getBounds(t){return t||(t=new ct),t.x=this.x-this.halfWidth,t.y=this.y-this.halfHeight,t.width=this.halfWidth*2,t.height=this.halfHeight*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.halfWidth=t.halfWidth,this.halfHeight=t.halfHeight,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Pf(s,t,e,i,r,n){const o=s-e,a=t-i,l=r-e,h=n-i,c=o*l+a*h,u=l*l+h*h;let m=-1;u!==0&&(m=c/u);let f,g;m<0?(f=e,g=i):m>1?(f=r,g=n):(f=e+m*l,g=i+m*h);const y=s-f,x=t-g;return y*y+x*x}let Mf,kf;class ji{constructor(...t){this.type="polygon";let e=Array.isArray(t[0])?t[0]:t;if(typeof e[0]!="number"){const i=[];for(let r=0,n=e.length;r<n;r++)i.push(e[r].x,e[r].y);e=i}this.points=e,this.closePath=!0}isClockwise(){let t=0;const e=this.points,i=e.length;for(let r=0;r<i;r+=2){const n=e[r],o=e[r+1],a=e[(r+2)%i],l=e[(r+3)%i];t+=(a-n)*(l+o)}return t<0}containsPolygon(t){const e=this.getBounds(Mf),i=t.getBounds(kf);if(!e.containsRect(i))return!1;const r=t.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const t=this.points.slice(),e=new ji(t);return e.closePath=this.closePath,e}contains(t,e){let i=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],h=this.points[o*2],c=this.points[o*2+1];l>e!=c>e&&t<(h-a)*((e-l)/(c-l))+a&&(i=!i)}return i}strokeContains(t,e,i,r=.5){const n=i*i,o=n*(1-r),a=n-o,{points:l}=this,h=l.length-(this.closePath?0:2);for(let c=0;c<h;c+=2){const u=l[c],m=l[c+1],f=l[(c+2)%l.length],g=l[(c+3)%l.length],y=Pf(t,e,u,m,f,g),x=Math.sign((f-u)*(e-m)-(g-m)*(t-u));if(y<=(x<0?a:o))return!0}return!1}getBounds(t){t||(t=new ct);const e=this.points;let i=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=e.length;a<l;a+=2){const h=e[a],c=e[a+1];i=h<i?h:i,r=h>r?h:r,n=c<n?c:n,o=c>o?c:o}return t.x=i,t.width=r-i,t.y=n,t.height=o-n,t}copyFrom(t){return this.points=t.points.slice(),this.closePath=t.closePath,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return K("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return K("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Rs=(s,t,e,i,r,n,o)=>{const a=s-e,l=t-i,h=Math.sqrt(a*a+l*l);return h>=r-n&&h<=r+o};class Hr{constructor(t=0,e=0,i=0,r=0,n=20){this.type="roundedRectangle",this.x=t,this.y=e,this.width=i,this.height=r,this.radius=n}getBounds(t){return t||(t=new ct),t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}clone(){return new Hr(this.x,this.y,this.width,this.height,this.radius)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let r=t-(this.x+i),n=e-(this.y+i);const o=i*i;if(r*r+n*n<=o||(r=t-(this.x+this.width-i),r*r+n*n<=o)||(n=e-(this.y+this.height-i),r*r+n*n<=o)||(r=t-(this.x+i),r*r+n*n<=o))return!0}return!1}strokeContains(t,e,i,r=.5){const{x:n,y:o,width:a,height:l,radius:h}=this,c=i*(1-r),u=i-c,m=n+h,f=o+h,g=a-h*2,y=l-h*2,x=n+a,v=o+l;return(t>=n-c&&t<=n+u||t>=x-u&&t<=x+c)&&e>=f&&e<=f+y||(e>=o-c&&e<=o+u||e>=v-u&&e<=v+c)&&t>=m&&t<=m+g?!0:t<m&&e<f&&Rs(t,e,m,f,h,u,c)||t>x-h&&e<f&&Rs(t,e,x-h,f,h,u,c)||t>x-h&&e>v-h&&Rs(t,e,x-h,v-h,h,u,c)||t<m&&e>v-h&&Rs(t,e,m,v-h,h,u,c)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Wa={};function Wr(s,t,e){let i=2166136261;for(let r=0;r<t;r++)i^=s[r].uid,i=Math.imul(i,16777619),i>>>=0;return Wa[i]||Bf(s,t,i,e)}function Bf(s,t,e,i){const r={};let n=0;for(let a=0;a<i;a++){const l=a<t?s[a]:$.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Ie(r);return Wa[e]=o,o}class Va{constructor(t){typeof t=="number"?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}function Vr(s,t,e,i){if(e??(e=0),i??(i=Math.min(s.byteLength-e,t.byteLength)),!(e&7)&&!(i&7)){const r=i/8;new Float64Array(t,0,r).set(new Float64Array(s,e,r))}else if(!(e&3)&&!(i&3)){const r=i/4;new Float32Array(t,0,r).set(new Float32Array(s,e,r))}else new Uint8Array(t).set(new Uint8Array(s,e,i))}const Of={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var wt=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(wt||{});function za(s,t){return t.alphaMode==="no-premultiply-alpha"&&Of[s]||s}const Df=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
36
|
-
`);function
|
|
37
|
-
else `),e<s-1&&(t+=`if(test == ${e}.0){}`);return t}function $a(s,t){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const e=t.createShader(t.FRAGMENT_SHADER);try{for(;;){const i=Df.replace(/%forloop%/gi,Gf(s));if(t.shaderSource(e,i),t.compileShader(e),!t.getShaderParameter(e,t.COMPILE_STATUS))s=s/2|0;else break}}finally{t.deleteShader(e)}return s}let yi=null;function Uf(){var t;if(yi)return yi;const s=ga();return yi=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),yi=$a(yi,s),(t=s.getExtension("WEBGL_lose_context"))==null||t.loseContext(),yi}class Lf{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let t=0;t<this.count;t++){const e=this.textures[t];this.textures[t]=null,this.ids[e.uid]=null}this.count=0}}class Nf{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Lf,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const Xi=[];let Is=0;li.register({clear:()=>{if(Xi.length>0)for(const s of Xi)s&&s.destroy();Xi.length=0,Is=0}});function ja(){return Is>0?Xi[--Is]:new Nf}function Xa(s){s.elements=null,Xi[Is++]=s}let Yi=0;const Ya=class cu{constructor(t){this.uid=dt("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...cu.defaultOptions,...t},t.maxTextures||(K("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),t.maxTextures=Uf());const{maxTextures:e,attributesInitialSize:i,indicesInitialSize:r}=t;this.attributeBuffer=new Va(i*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=e}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let t=0;t<this.batchIndex;t++)Xa(this.batches[t]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(t){this._elements[this.elementSize++]=t,t._indexStart=this.indexSize,t._attributeStart=this.attributeSize,t._batcher=this,this.indexSize+=t.indexSize,this.attributeSize+=t.attributeSize*this.vertexSize}checkAndUpdateTexture(t,e){const i=t._batch.textures.ids[e._source.uid];return!i&&i!==0?!1:(t._textureId=i,t.texture=e,!0)}updateElement(t){this.dirty=!0;const e=this.attributeBuffer;t.packAsQuad?this.packQuadAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId):this.packAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId)}break(t){const e=this._elements;if(!e[this.elementStart])return;let i=ja(),r=i.textures;r.clear();const n=e[this.elementStart];let o=za(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,h=this.attributeBuffer.uint32View,c=this.indexBuffer;let u=this._batchIndexSize,m=this._batchIndexStart,f="startBatch",g=[];const y=this.maxTextures;for(let x=this.elementStart;x<this.elementSize;++x){const v=e[x];e[x]=null;const T=v.texture._source,C=za(v.blendMode,T),R=o!==C||a!==v.topology;if(T._batchTick===Yi&&!R){v._textureId=T._textureBindLocation,u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,h,v._attributeStart,v._textureId),this.packQuadIndex(c,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,h,v._attributeStart,v._textureId),this.packIndex(v,c,v._indexStart,v._attributeStart/this.vertexSize)),v._batch=i,g.push(v);continue}T._batchTick=Yi,(r.count>=y||R)&&(this._finishBatch(i,m,u-m,r,o,a,t,f,g),f="renderBatch",m=u,o=C,a=v.topology,i=ja(),r=i.textures,r.clear(),g=[],++Yi),v._textureId=T._textureBindLocation=r.count,r.ids[T.uid]=r.count,r.textures[r.count++]=T,v._batch=i,g.push(v),u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,h,v._attributeStart,v._textureId),this.packQuadIndex(c,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,h,v._attributeStart,v._textureId),this.packIndex(v,c,v._indexStart,v._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(i,m,u-m,r,o,a,t,f,g),m=u,++Yi),this.elementStart=this.elementSize,this._batchIndexStart=m,this._batchIndexSize=u}_finishBatch(t,e,i,r,n,o,a,l,h){t.gpuBindGroup=null,t.bindGroup=null,t.action=l,t.batcher=this,t.textures=r,t.blendMode=n,t.topology=o,t.start=e,t.size=i,t.elements=h,++Yi,this.batches[this.batchIndex++]=t,a.add(t)}finish(t){this.break(t)}ensureAttributeBuffer(t){t*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(t*4)}ensureIndexBuffer(t){t<=this.indexBuffer.length||this._resizeIndexBuffer(t)}_resizeAttributeBuffer(t){const e=Math.max(t,this.attributeBuffer.size*2),i=new Va(e);Vr(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(t){const e=this.indexBuffer;let i=Math.max(t,e.length*1.5);i+=i%2;const r=i>65535?new Uint32Array(i):new Uint16Array(i);if(r.BYTES_PER_ELEMENT!==e.BYTES_PER_ELEMENT)for(let n=0;n<e.length;n++)r[n]=e[n];else Vr(e.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(t,e,i){t[e]=i+0,t[e+1]=i+1,t[e+2]=i+2,t[e+3]=i+0,t[e+4]=i+2,t[e+5]=i+3}packIndex(t,e,i,r){const n=t.indices,o=t.indexSize,a=t.indexOffset,l=t.attributeOffset;for(let h=0;h<o;h++)e[i++]=r+n[h+a]-l}destroy(t={}){var e;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)Xa(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,t.shader&&((e=this.shader)==null||e.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Ya.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Ff=Ya;var yt=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(yt||{});class Pe extends Zt{constructor(t){let{data:e,size:i}=t;const{usage:r,label:n,shrinkToFit:o}=t;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=dt("buffer"),this._resourceType="buffer",this._resourceId=dt("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,e instanceof Array&&(e=new Float32Array(e)),this._data=e,i??(i=e==null?void 0:e.byteLength);const a=!!e;this.descriptor={size:i,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(t){this.setDataWithSize(t,t.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&yt.STATIC)}set static(t){t?this.descriptor.usage|=yt.STATIC:this.descriptor.usage&=~yt.STATIC}setDataWithSize(t,e,i){if(this._updateID++,this._updateSize=e*t.BYTES_PER_ELEMENT,this._data===t){i&&this.emit("update",this);return}const r=this._data;if(this._data=t,this._dataInt32=null,!r||r.length!==t.length){!this.shrinkToFit&&r&&t.byteLength<r.byteLength?i&&this.emit("update",this):(this.descriptor.size=t.byteLength,this._resourceId=dt("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(t){this._updateSize=t??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function qa(s,t){if(!(s instanceof Pe)){let e=t?yt.INDEX:yt.VERTEX;s instanceof Array&&(t?(s=new Uint32Array(s),e=yt.INDEX|yt.COPY_DST):(s=new Float32Array(s),e=yt.VERTEX|yt.COPY_DST)),s=new Pe({data:s,label:t?"index-mesh-buffer":"vertex-mesh-buffer",usage:e})}return s}function Hf(s,t,e){const i=s.getAttribute(t);if(!i)return e.minX=0,e.minY=0,e.maxX=0,e.maxY=0,e;const r=i.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const h=r.BYTES_PER_ELEMENT,c=(i.offset||0)/h,u=(i.stride||8)/h;for(let m=c;m<r.length;m+=u){const f=r[m],g=r[m+1];f>a&&(a=f),g>l&&(l=g),f<n&&(n=f),g<o&&(o=g)}return e.minX=n,e.minY=o,e.maxX=a,e.maxY=l,e}function Wf(s){return(s instanceof Pe||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=qa(s.buffer,!1),s}class zr extends Zt{constructor(t={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Lt,this._boundsDirty=!0;const{attributes:e,indexBuffer:i,topology:r}=t;if(this.buffers=[],this.attributes={},e)for(const n in e)this.addAttribute(n,e[n]);this.instanceCount=t.instanceCount??1,i&&this.addIndex(i),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(t){return this.attributes[t]}getIndex(){return this.indexBuffer}getBuffer(t){return this.getAttribute(t).buffer}getSize(){for(const t in this.attributes){const e=this.attributes[t];return e.buffer.data.length/(e.stride/4||e.size)}return 0}addAttribute(t,e){const i=Wf(e);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[t]=i}addIndex(t){this.indexBuffer=qa(t,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Hf(this,"aPosition",this._bounds)):this._bounds}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(t=!1){var e;this.emit("destroy",this),this.removeAllListeners(),t&&this.buffers.forEach(i=>i.destroy()),this.unload(),(e=this.indexBuffer)==null||e.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Vf=new Float32Array(1),zf=new Uint32Array(1);class $f extends zr{constructor(){const e=new Pe({data:Vf,label:"attribute-batch-buffer",usage:yt.VERTEX|yt.COPY_DST,shrinkToFit:!1}),i=new Pe({data:zf,label:"index-batch-buffer",usage:yt.INDEX|yt.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:e,format:"float32x2",stride:r,offset:0},aUV:{buffer:e,format:"float32x2",stride:r,offset:8},aColor:{buffer:e,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:e,format:"uint16x2",stride:r,offset:20}},indexBuffer:i})}}function Ka(s,t,e){if(s)for(const i in s){const r=i.toLocaleLowerCase(),n=t[r];if(n){let o=s[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),e&&n.push(`//----${e}----//`),n.push(o)}else tt(`${i} placement hook does not exist in shader`)}}const jf=/\{\{(.*?)\}\}/g;function Za(s){var i;const t={};return(((i=s.match(jf))==null?void 0:i.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{t[r]=[]}),t}function Ja(s,t){let e;const i=/@in\s+([^;]+);/g;for(;(e=i.exec(s))!==null;)t.push(e[1])}function Qa(s,t,e=!1){const i=[];Ja(t,i),s.forEach(a=>{a.header&&Ja(a.header,i)});const r=i;e&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
38
|
-
`);let o=
|
|
32
|
+
`}function up(s,e,t){const i=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(s.substring(0,9)!=="precision"){let r=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return r==="highp"&&i!=="highp"&&(r="mediump"),`precision ${r} float;
|
|
33
|
+
${s}`}else if(i!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function dp(s,e){return e?`#version 300 es
|
|
34
|
+
${s}`:s}const fp={},pp={};function mp(s,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?fp:pp;return i[e]?(i[e]++,e+=`-${i[e]}`):i[e]=1,s.indexOf("#define SHADER_NAME")!==-1?s:`${`#define SHADER_NAME ${e}`}
|
|
35
|
+
${s}`}function gp(s,e){return e?s.replace("#version 300 es",""):s}const on={stripVersion:gp,ensurePrecision:up,addProgramDefines:hp,setProgramName:mp,insertVersion:dp},is=Object.create(null),sl=class Go{constructor(e){e={...Go.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:cp()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(on).forEach(o=>{const a=i[o];r=on[o](r,a,!0),n=on[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=ts(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,is[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return is[t]||(is[t]=new Go(e),is[t]._cacheKey=t),is[t]}};sl.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ai=sl;const rl={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function ss(s){return rl[s]??rl.float32}const _p={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},nl=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function ol(s,e){let t;for(;(t=nl.exec(s))!==null;){const i=_p[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:ss(i).stride,offset:0,instance:!1,start:0}}nl.lastIndex=0}function yp(s){return s.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function bp({source:s,entryPoint:e}){const t={},i=yp(s),r=i.indexOf(`fn ${e}(`);if(r===-1)return t;const n=i.indexOf("->",r);if(n===-1)return t;const o=i.substring(r,n);if(ol(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],c=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),h=i.match(c);h&&ol(h[1],t)}}return t}function an(s){var u,p;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=(u=s.match(e))==null?void 0:u.map(d=>({group:parseInt(d.match(t)[1],10),binding:parseInt(d.match(i)[1],10),name:d.match(r)[2],isUniform:d.match(r)[1]==="<uniform>",type:d.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=((p=s.match(o))==null?void 0:p.map(d=>{const g=d.match(l)[1],_=d.match(a).reduce((y,x)=>{const[v,C]=x.split(":");return y[v.trim()]=C.trim(),y},{});return _?{name:g,members:_}:null}).filter(({name:d})=>c.some(g=>g.type===d||g.type.includes(`<${d}>`))))??[];return{groups:c,structs:h}}var ri=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(ri||{});function xp({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:ri.VERTEX|ri.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:ri.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:ri.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:ri.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:ri.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function vp({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function Sp(s,e){const t=new Set,i=new Set,r=[...s.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...s.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:r,groups:n}}const rs=Object.create(null);class ni{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const c=an(t.source);this.structsAndGroups=c}else{const c=an(i.source),h=an(t.source);this.structsAndGroups=Sp(c,h)}this.layout=r??vp(this.structsAndGroups),this.gpuLayout=n??xp(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=ts(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=bp(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,rs[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return rs[t]||(rs[t]=new ni(e),rs[t]._cacheKey=t),rs[t]}}const al=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],Cp=al.reduce((s,e)=>(s[e]=!0,s),{});function Tp(s,e){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const ll=class Rd{constructor(e,t){this._touched=0,this.uid=xe("uniform"),this._resourceType="uniformGroup",this._resourceId=xe("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Rd.defaultOptions,...t},this.uniformStructures=e;const i={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!Cp[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${al.join(", ")}`)}n.value??(n.value=Tp(n.type,n.size)),i[r]=n.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=ts(Object.keys(i).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};ll.defaultOptions={ubo:!1,isStatic:!1};let _t=ll;class Lt{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const r=e[i];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var r,n;const i=this.resources[t];e!==i&&((r=i==null?void 0:i.off)==null||r.call(i,"change",this.onResourceChange,this),(n=e.on)==null||n.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const r in i)i[r]._gcLastUsed=e,i[r]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const r=e[i];(t=r==null?void 0:r.off)==null||t.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){this._dirty=!0,e.destroyed?this.destroy():this._updateKey()}}var yt=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.CANVAS=4]="CANVAS",s[s.BOTH=3]="BOTH",s))(yt||{});class It extends nt{constructor(e){super(),this.uid=xe("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=yt.WEBGPU),i&&(o|=yt.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Lt,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let p=n[h];!p.source&&!p._resourceType&&(p=new _t(p));const d=l[u];d&&(r[d.group]||(r[d.group]=new Lt,this._ownedBindGroups.push(r[d.group])),r[d.group].setResource(p,d.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,i){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[i]||(n[i]=e),this.groups[t]||(this.groups[t]=new Lt,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const r in t){const n=t[r];Object.defineProperty(i,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=ni.from(t)),i&&(o=Ai.from(i)),new It({gpuProgram:n,glProgram:o,...r})}}const Ep={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},ln=0,cn=1,hn=2,un=3,dn=4,fn=5,pn=class Md{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<ln)}set blend(e){!!(this.data&1<<ln)!==e&&(this.data^=1<<ln)}get offsets(){return!!(this.data&1<<cn)}set offsets(e){!!(this.data&1<<cn)!==e&&(this.data^=1<<cn)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<hn)}set culling(e){!!(this.data&1<<hn)!==e&&(this.data^=1<<hn)}get depthTest(){return!!(this.data&1<<un)}set depthTest(e){!!(this.data&1<<un)!==e&&(this.data^=1<<un)}get depthMask(){return!!(this.data&1<<fn)}set depthMask(e){!!(this.data&1<<fn)!==e&&(this.data^=1<<fn)}get clockwiseFrontFace(){return!!(this.data&1<<dn)}set clockwiseFrontFace(e){!!(this.data&1<<dn)!==e&&(this.data^=1<<dn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=Ep[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new Md;return e.depthTest=!1,e.blend=!0,e}};pn.default2d=pn.for2d();let At=pn;const cl=class Lo extends It{constructor(e){e={...Lo.defaultOptions,...e},super(e),this.enabled=!0,this._state=At.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,r){e.applyFilter(this,t,i,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=ni.from(t)),i&&(o=Ai.from(i)),new Lo({gpuProgram:n,glProgram:o,...r})}};cl.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let hl=cl;const mn=[];ie.handleByNamedList(I.Environment,mn);async function wp(s){if(!s)for(let e=0;e<mn.length;e++){const t=mn[e];if(t.value.test()){await t.value.load();return}}}let ns;function ul(){if(typeof ns=="boolean")return ns;try{ns=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{ns=!1}return ns}function dl(s,e,t=2){const i=e&&e.length,r=i?e[0]*t:s.length;let n=fl(s,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(i&&(n=Pp(s,e,n,t)),s.length>80*t){a=s[0],l=s[1];let h=a,u=l;for(let p=t;p<r;p+=t){const d=s[p],g=s[p+1];d<a&&(a=d),g<l&&(l=g),d>h&&(h=d),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return os(n,o,t,a,l,c,0),o}function fl(s,e,t,i,r){let n;if(r===Hp(s,e,t,i)>0)for(let o=e;o<t;o+=i)n=_l(o/i|0,s[o],s[o+1],n);else for(let o=t-i;o>=e;o-=i)n=_l(o/i|0,s[o],s[o+1],n);return n&&Ri(n,n.next)&&(cs(n),n=n.next),n}function oi(s,e){if(!s)return s;e||(e=s);let t=s,i;do if(i=!1,!t.steiner&&(Ri(t,t.next)||Ae(t.prev,t,t.next)===0)){if(cs(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function os(s,e,t,i,r,n,o){if(!s)return;!o&&n&&Np(s,i,r,n);let a=s;for(;s.prev!==s.next;){const l=s.prev,c=s.next;if(n?Ap(s,i,r,n):Ip(s)){e.push(l.i,s.i,c.i),cs(s),s=c.next,a=c.next;continue}if(s=c,s===a){o?o===1?(s=Rp(oi(s),e),os(s,e,t,i,r,n,2)):o===2&&Mp(s,e,t,i,r,n):os(oi(s),e,t,i,r,n,1);break}}}function Ip(s){const e=s.prev,t=s,i=s.next;if(Ae(e,t,i)>=0)return!1;const r=e.x,n=t.x,o=i.x,a=e.y,l=t.y,c=i.y,h=Math.min(r,n,o),u=Math.min(a,l,c),p=Math.max(r,n,o),d=Math.max(a,l,c);let g=i.next;for(;g!==e;){if(g.x>=h&&g.x<=p&&g.y>=u&&g.y<=d&&as(r,a,n,l,o,c,g.x,g.y)&&Ae(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function Ap(s,e,t,i){const r=s.prev,n=s,o=s.next;if(Ae(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,p=o.y,d=Math.min(a,l,c),g=Math.min(h,u,p),_=Math.max(a,l,c),y=Math.max(h,u,p),x=gn(d,g,e,t,i),v=gn(_,y,e,t,i);let C=s.prevZ,T=s.nextZ;for(;C&&C.z>=x&&T&&T.z<=v;){if(C.x>=d&&C.x<=_&&C.y>=g&&C.y<=y&&C!==r&&C!==o&&as(a,h,l,u,c,p,C.x,C.y)&&Ae(C.prev,C,C.next)>=0||(C=C.prevZ,T.x>=d&&T.x<=_&&T.y>=g&&T.y<=y&&T!==r&&T!==o&&as(a,h,l,u,c,p,T.x,T.y)&&Ae(T.prev,T,T.next)>=0))return!1;T=T.nextZ}for(;C&&C.z>=x;){if(C.x>=d&&C.x<=_&&C.y>=g&&C.y<=y&&C!==r&&C!==o&&as(a,h,l,u,c,p,C.x,C.y)&&Ae(C.prev,C,C.next)>=0)return!1;C=C.prevZ}for(;T&&T.z<=v;){if(T.x>=d&&T.x<=_&&T.y>=g&&T.y<=y&&T!==r&&T!==o&&as(a,h,l,u,c,p,T.x,T.y)&&Ae(T.prev,T,T.next)>=0)return!1;T=T.nextZ}return!0}function Rp(s,e){let t=s;do{const i=t.prev,r=t.next.next;!Ri(i,r)&&ml(i,t,t.next,r)&&ls(i,r)&&ls(r,i)&&(e.push(i.i,t.i,r.i),cs(t),cs(t.next),t=s=r),t=t.next}while(t!==s);return oi(t)}function Mp(s,e,t,i,r,n){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&Lp(o,a)){let l=gl(o,a);o=oi(o,o.next),l=oi(l,l.next),os(o,e,t,i,r,n,0),os(l,e,t,i,r,n,0);return}a=a.next}o=o.next}while(o!==s)}function Pp(s,e,t,i){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*i,l=n<o-1?e[n+1]*i:s.length,c=fl(s,a,l,i,!1);c===c.next&&(c.steiner=!0),r.push(Gp(c))}r.sort(kp);for(let n=0;n<r.length;n++)t=Bp(r[n],t);return t}function kp(s,e){let t=s.x-e.x;if(t===0&&(t=s.y-e.y,t===0)){const i=(s.next.y-s.y)/(s.next.x-s.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=i-r}return t}function Bp(s,e){const t=Op(s,e);if(!t)return e;const i=gl(t,s);return oi(i,i.next),oi(t,t.next)}function Op(s,e){let t=e;const i=s.x,r=s.y;let n=-1/0,o;if(Ri(s,t))return t;do{if(Ri(s,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=i&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(i>=t.x&&t.x>=l&&i!==t.x&&pl(r<c?i:n,r,l,c,r<c?n:i,r,t.x,t.y)){const u=Math.abs(r-t.y)/(i-t.x);ls(t,s)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&Dp(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function Dp(s,e){return Ae(s.prev,s,e.prev)<0&&Ae(e.next,s,s.next)<0}function Np(s,e,t,i){let r=s;do r.z===0&&(r.z=gn(r.x,r.y,e,t,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==s);r.prevZ.nextZ=null,r.prevZ=null,Fp(r)}function Fp(s){let e,t=1;do{let i=s,r;s=null;let n=null;for(e=0;i;){e++;let o=i,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:s=r,r.prevZ=n,n=r;i=o}n.nextZ=null,t*=2}while(e>1);return s}function gn(s,e,t,i,r){return s=(s-t)*r|0,e=(e-i)*r|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,s|e<<1}function Gp(s){let e=s,t=s;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==s);return t}function pl(s,e,t,i,r,n,o,a){return(r-o)*(e-a)>=(s-o)*(n-a)&&(s-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(i-a)}function as(s,e,t,i,r,n,o,a){return!(s===o&&e===a)&&pl(s,e,t,i,r,n,o,a)}function Lp(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!Up(s,e)&&(ls(s,e)&&ls(e,s)&&Wp(s,e)&&(Ae(s.prev,s,e.prev)||Ae(s,e.prev,e))||Ri(s,e)&&Ae(s.prev,s,s.next)>0&&Ae(e.prev,e,e.next)>0)}function Ae(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function Ri(s,e){return s.x===e.x&&s.y===e.y}function ml(s,e,t,i){const r=Ys(Ae(s,e,t)),n=Ys(Ae(s,e,i)),o=Ys(Ae(t,i,s)),a=Ys(Ae(t,i,e));return!!(r!==n&&o!==a||r===0&&Xs(s,t,e)||n===0&&Xs(s,i,e)||o===0&&Xs(t,s,i)||a===0&&Xs(t,e,i))}function Xs(s,e,t){return e.x<=Math.max(s.x,t.x)&&e.x>=Math.min(s.x,t.x)&&e.y<=Math.max(s.y,t.y)&&e.y>=Math.min(s.y,t.y)}function Ys(s){return s>0?1:s<0?-1:0}function Up(s,e){let t=s;do{if(t.i!==s.i&&t.next.i!==s.i&&t.i!==e.i&&t.next.i!==e.i&&ml(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function ls(s,e){return Ae(s.prev,s,s.next)<0?Ae(s,e,s.next)>=0&&Ae(s,s.prev,e)>=0:Ae(s,e,s.prev)<0||Ae(s,s.next,e)<0}function Wp(s,e){let t=s,i=!1;const r=(s.x+e.x)/2,n=(s.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==s);return i}function gl(s,e){const t=_n(s.i,s.x,s.y),i=_n(e.i,e.x,e.y),r=s.next,n=e.prev;return s.next=e,e.prev=s,t.next=r,r.prev=t,i.next=t,t.prev=i,n.next=i,i.prev=n,i}function _l(s,e,t,i){const r=_n(s,e,t);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function cs(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function _n(s,e,t){return{i:s,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Hp(s,e,t,i){let r=0;for(let n=e,o=t-i;n<t;n+=i)r+=(s[o]-s[n])*(s[n+1]+s[o+1]),o=n;return r}const Vp=dl.default||dl;var it=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(it||{});class yl{constructor(e){this.items=[],this._name=e}emit(e,t,i,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,p=h.length;u<p;u++)h[u][c](e,t,i,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const zp=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],bl=class Pd extends nt{constructor(e){super(),this.tick=0,this.uid=xe("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...zp,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await wp(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...Pd.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof We&&(i={container:i},t&&(J(Ie,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const r=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=r?i.clearColor:be.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const r=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==r&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=it.ALL);const{clear:i,clearColor:r,target:n,mipLevel:o,layer:a}=e;be.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,i,be.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new yl(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const r in this.runners)this.runners[r].add(i);return this}_addPipes(e,t){const i=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=i[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&xi.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!ul())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};bl.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let hs=bl,Ks;function $p(s){return Ks!==void 0||(Ks=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:s??hs.defaultOptions.failIfMajorPerformanceCaveat};try{if(!de.get().getWebGLRenderingContext())return!1;let r=de.get().createCanvas().getContext("webgl",e);const n=!!((t=r==null?void 0:r.getContextAttributes())!=null&&t.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Ks}let qs;async function jp(s={}){return qs!==void 0||(qs=await(async()=>{const e=de.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),qs}const xl=["webgl","webgpu","canvas"];async function Xp(s){let e=[];s.preference?(e.push(s.preference),xl.forEach(n=>{n!==s.preference&&e.push(n)})):e=xl.slice();let t,i={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await jp()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>Gb);t=a,i={...s,...s.webgpu};break}else if(o==="webgl"&&$p(s.failIfMajorPerformanceCaveat??hs.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>gb);t=a,i={...s,...s.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>my);t=a,i={...s,...s.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(i),r}const Zs="8.17.1";class vl{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,Zs)}static destroy(){}}vl.extension=I.Application;class Sl{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,Zs)}destroy(){this._renderer=null}}Sl.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"initHook",priority:-10};class Cl{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,i=n}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Cl.extension=I.Application;class Tl{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Ci.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?at.shared:new at,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}Tl.extension=I.Application,ie.add(Cl),ie.add(Tl);const El=class Uo{constructor(...e){this.stage=new We,e[0]!==void 0&&J(Ie,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new We),this.renderer=await Xp(e),Uo._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return J(Ie,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=Uo._plugins.slice(0);i.reverse(),i.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};El._plugins=[];let wl=El;ie.handleByList(I.Application,wl._plugins),ie.add(vl);var yn,Il;function Yp(){if(Il)return yn;Il=1,yn=t;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==s[h])return c.unshift(l),o.push(c);if(c.length<s[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,s[h])))}}),o}var i=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(i);return o?o.map(Number):[]}return yn}var Kp=Yp();const qp=jo(Kp);function Zp(s,e){const t=qp(s),i=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),i.length>0&&(r=i.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:ne(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},i.push(r))}return e}class bn{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new bn(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=i}strokeContains(e,t,i,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*i,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(i-l)}getBounds(e){return e||(e=new ye),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class xn{constructor(e=0,t=0,i=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=i,this.halfHeight=r}clone(){return new xn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return i*=i,r*=r,i+r<=1}strokeContains(e,t,i,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=i*(1-r),l=i-a,c=n-l,h=o-l,u=n+a,p=o+a,d=e-this.x,g=t-this.y,_=d*d/(c*c)+g*g/(h*h),y=d*d/(u*u)+g*g/(p*p);return _>1&&y<=1}getBounds(e){return e||(e=new ye),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Jp(s,e,t,i,r,n){const o=s-t,a=e-i,l=r-t,c=n-i,h=o*l+a*c,u=l*l+c*c;let p=-1;u!==0&&(p=h/u);let d,g;p<0?(d=t,g=i):p>1?(d=r,g=n):(d=t+p*l,g=i+p*c);const _=s-d,y=e-g;return _*_+y*y}let Qp,em;class us{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const i=[];for(let r=0,n=t.length;r<n;r++)i.push(t[r].x,t[r].y);t=i}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,i=t.length;for(let r=0;r<i;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%i],l=t[(r+3)%i];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Qp),i=e.getBounds(em);if(!t.containsRect(i))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new us(e);return t.closePath=this.closePath,t}contains(e,t){let i=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(i=!i)}return i}strokeContains(e,t,i,r=.5){const n=i*i,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],p=l[h+1],d=l[(h+2)%l.length],g=l[(h+3)%l.length],_=Jp(e,t,u,p,d,g),y=Math.sign((d-u)*(t-p)-(g-p)*(e-u));if(_<=(y<0?a:o))return!0}return!1}getBounds(e){e||(e=new ye);const t=this.points;let i=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];i=c<i?c:i,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=i,e.width=r-i,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return J("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return J("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Js=(s,e,t,i,r,n,o)=>{const a=s-t,l=e-i,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class vn{constructor(e=0,t=0,i=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=i,this.height=r,this.radius=n}getBounds(e){return e||(e=new ye),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new vn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+i&&t<=this.y+this.height-i||e>=this.x+i&&e<=this.x+this.width-i)return!0;let r=e-(this.x+i),n=t-(this.y+i);const o=i*i;if(r*r+n*n<=o||(r=e-(this.x+this.width-i),r*r+n*n<=o)||(n=t-(this.y+this.height-i),r*r+n*n<=o)||(r=e-(this.x+i),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,i,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=i*(1-r),u=i-h,p=n+c,d=o+c,g=a-c*2,_=l-c*2,y=n+a,x=o+l;return(e>=n-h&&e<=n+u||e>=y-u&&e<=y+h)&&t>=d&&t<=d+_||(t>=o-h&&t<=o+u||t>=x-u&&t<=x+h)&&e>=p&&e<=p+g?!0:e<p&&t<d&&Js(e,t,p,d,c,u,h)||e>y-c&&t<d&&Js(e,t,y-c,d,c,u,h)||e>y-c&&t>x-c&&Js(e,t,y-c,x-c,c,u,h)||e<p&&t>x-c&&Js(e,t,p,x-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Al={};function Sn(s,e,t){let i=2166136261;for(let r=0;r<e;r++)i^=s[r].uid,i=Math.imul(i,16777619),i>>>=0;return Al[i]||tm(s,e,i,t)}function tm(s,e,t,i){const r={};let n=0;for(let a=0;a<i;a++){const l=a<e?s[a]:q.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Lt(r);return Al[t]=o,o}class Rl{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function Cn(s,e,t,i){if(t??(t=0),i??(i=Math.min(s.byteLength-t,e.byteLength)),!(t&7)&&!(i&7)){const r=i/8;new Float64Array(e,0,r).set(new Float64Array(s,t,r))}else if(!(t&3)&&!(i&3)){const r=i/4;new Float32Array(e,0,r).set(new Float32Array(s,t,r))}else new Uint8Array(e).set(new Uint8Array(s,t,i))}const im={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var Be=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(Be||{});function Ml(s,e){return e.alphaMode==="no-premultiply-alpha"&&im[s]||s}const sm=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
36
|
+
`);function rm(s){let e="";for(let t=0;t<s;++t)t>0&&(e+=`
|
|
37
|
+
else `),t<s-1&&(e+=`if(test == ${t}.0){}`);return e}function Pl(s,e){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const i=sm.replace(/%forloop%/gi,rm(s));if(e.shaderSource(t,i),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))s=s/2|0;else break}}finally{e.deleteShader(t)}return s}let Mi=null;function nm(){var e;if(Mi)return Mi;const s=il();return Mi=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),Mi=Pl(Mi,s),(e=s.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Mi}class om{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class am{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new om,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const ds=[];let Qs=0;xi.register({clear:()=>{if(ds.length>0)for(const s of ds)s&&s.destroy();ds.length=0,Qs=0}});function kl(){return Qs>0?ds[--Qs]:new am}function Bl(s){s.elements=null,ds[Qs++]=s}let fs=0;const Ol=class kd{constructor(e){this.uid=xe("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...kd.defaultOptions,...e},e.maxTextures||(J("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=nm());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:r}=e;this.attributeBuffer=new Rl(i*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)Bl(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const i=e._batch.textures.ids[t._source.uid];return!i&&i!==0?!1:(e._textureId=i,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let i=kl(),r=i.textures;r.clear();const n=t[this.elementStart];let o=Ml(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,p=this._batchIndexStart,d="startBatch",g=[];const _=this.maxTextures;for(let y=this.elementStart;y<this.elementSize;++y){const x=t[y];t[y]=null;const C=x.texture._source,T=Ml(x.blendMode,C),A=o!==T||a!==x.topology;if(C._batchTick===fs&&!A){x._textureId=C._textureBindLocation,u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,g.push(x);continue}C._batchTick=fs,(r.count>=_||A)&&(this._finishBatch(i,p,u-p,r,o,a,e,d,g),d="renderBatch",p=u,o=T,a=x.topology,i=kl(),r=i.textures,r.clear(),g=[],++fs),x._textureId=C._textureBindLocation=r.count,r.ids[C.uid]=r.count,r.textures[r.count++]=C,x._batch=i,g.push(x),u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(i,p,u-p,r,o,a,e,d,g),p=u,++fs),this.elementStart=this.elementSize,this._batchIndexStart=p,this._batchIndexSize=u}_finishBatch(e,t,i,r,n,o,a,l,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=i,e.elements=c,++fs,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),i=new Rl(t);Cn(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(e){const t=this.indexBuffer;let i=Math.max(e,t.length*1.5);i+=i%2;const r=i>65535?new Uint32Array(i):new Uint16Array(i);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else Cn(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,i){e[t]=i+0,e[t+1]=i+1,e[t+2]=i+2,e[t+3]=i+0,e[t+4]=i+2,e[t+5]=i+3}packIndex(e,t,i,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[i++]=r+n[c+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)Bl(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Ol.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let lm=Ol;var Ee=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(Ee||{});let Ut=class extends nt{constructor(e){let{data:t,size:i}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=xe("buffer"),this._resourceType="buffer",this._resourceId=xe("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,i??(i=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:i,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&Ee.STATIC)}set static(e){e?this.descriptor.usage|=Ee.STATIC:this.descriptor.usage&=~Ee.STATIC}setDataWithSize(e,t,i){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){i&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?i&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=xe("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}};function Dl(s,e){if(!(s instanceof Ut)){let t=e?Ee.INDEX:Ee.VERTEX;s instanceof Array&&(e?(s=new Uint32Array(s),t=Ee.INDEX|Ee.COPY_DST):(s=new Float32Array(s),t=Ee.VERTEX|Ee.COPY_DST)),s=new Ut({data:s,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return s}function cm(s,e,t){const i=s.getAttribute(e);if(!i)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=i.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(i.offset||0)/c,u=(i.stride||8)/c;for(let p=h;p<r.length;p+=u){const d=r[p],g=r[p+1];d>a&&(a=d),g>l&&(l=g),d<n&&(n=d),g<o&&(o=g)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function hm(s){return(s instanceof Ut||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=Dl(s.buffer,!1),s}class Tn extends nt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=xe("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new je,this._boundsDirty=!0;const{attributes:t,indexBuffer:i,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,i&&this.addIndex(i),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const i=hm(t);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=i}addIndex(e){this.indexBuffer=Dl(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,cm(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(i=>i.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const um=new Float32Array(1),dm=new Uint32Array(1);class fm extends Tn{constructor(){const t=new Ut({data:um,label:"attribute-batch-buffer",usage:Ee.VERTEX|Ee.COPY_DST,shrinkToFit:!1}),i=new Ut({data:dm,label:"index-batch-buffer",usage:Ee.INDEX|Ee.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:i})}}function Nl(s,e,t){if(s)for(const i in s){const r=i.toLocaleLowerCase(),n=e[r];if(n){let o=s[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else ne(`${i} placement hook does not exist in shader`)}}const pm=/\{\{(.*?)\}\}/g;function Fl(s){var i;const e={};return(((i=s.match(pm))==null?void 0:i.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{e[r]=[]}),e}function Gl(s,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function Ll(s,e,t=!1){const i=[];Gl(e,i),s.forEach(a=>{a.header&&Gl(a.header,i)});const r=i;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
38
|
+
`);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
|
|
39
39
|
${n}
|
|
40
|
-
`),o}function
|
|
41
|
-
`),n=
|
|
40
|
+
`),o}function Ul(s,e){let t;const i=/@out\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function mm(s){const t=/\b(\w+)\s*:/g.exec(s);return t?t[1]:""}function gm(s){const e=/@.*?\s+/g;return s.replace(e,"")}function _m(s,e){const t=[];Ul(e,t),s.forEach(l=>{l.header&&Ul(l.header,t)});let i=0;const r=t.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${i++}) ${l}`).join(`,
|
|
41
|
+
`),n=t.sort().map(l=>` var ${gm(l)};`).join(`
|
|
42
42
|
`),o=`return VSOutput(
|
|
43
|
-
${
|
|
44
|
-
`)});`;let a=
|
|
43
|
+
${t.sort().map(l=>` ${mm(l)}`).join(`,
|
|
44
|
+
`)});`;let a=e.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
|
|
45
45
|
${r}
|
|
46
46
|
`),a=a.replace("{{start}}",`
|
|
47
47
|
${n}
|
|
48
48
|
`),a=a.replace("{{return}}",`
|
|
49
49
|
${o}
|
|
50
|
-
`),a}function
|
|
51
|
-
`).length?
|
|
50
|
+
`),a}function Wl(s,e){let t=s;for(const i in e){const r=e[i];r.join(`
|
|
51
|
+
`).length?t=t.replace(`{{${i}}}`,`//-----${i} START-----//
|
|
52
52
|
${r.join(`
|
|
53
53
|
`)}
|
|
54
|
-
//----${i} FINISH----//`):
|
|
54
|
+
//----${i} FINISH----//`):t=t.replace(`{{${i}}}`,"")}return t}const Wt=Object.create(null),En=new Map;let ym=0;function bm({template:s,bits:e}){const t=Hl(s,e);if(Wt[t])return Wt[t];const{vertex:i,fragment:r}=vm(s,e);return Wt[t]=Vl(i,r,e),Wt[t]}function xm({template:s,bits:e}){const t=Hl(s,e);return Wt[t]||(Wt[t]=Vl(s.vertex,s.fragment,e)),Wt[t]}function vm(s,e){const t=e.map(o=>o.vertex).filter(o=>!!o),i=e.map(o=>o.fragment).filter(o=>!!o);let r=Ll(t,s.vertex,!0);r=_m(t,r);const n=Ll(i,s.fragment,!0);return{vertex:r,fragment:n}}function Hl(s,e){return e.map(t=>(En.has(t)||En.set(t,ym++),En.get(t))).sort((t,i)=>t-i).join("-")+s.vertex+s.fragment}function Vl(s,e,t){const i=Fl(s),r=Fl(e);return t.forEach(n=>{Nl(n.vertex,i,n.name),Nl(n.fragment,r,n.name)}),{vertex:Wl(s,i),fragment:Wl(e,r)}}const Sm=`
|
|
55
55
|
@in aPosition: vec2<f32>;
|
|
56
56
|
@in aUV: vec2<f32>;
|
|
57
57
|
|
|
@@ -95,7 +95,7 @@ ${r.join(`
|
|
|
95
95
|
|
|
96
96
|
{{return}}
|
|
97
97
|
};
|
|
98
|
-
`,
|
|
98
|
+
`,Cm=`
|
|
99
99
|
@in vUV : vec2<f32>;
|
|
100
100
|
@in vColor : vec4<f32>;
|
|
101
101
|
|
|
@@ -118,7 +118,7 @@ ${r.join(`
|
|
|
118
118
|
|
|
119
119
|
return finalColor;
|
|
120
120
|
};
|
|
121
|
-
`,
|
|
121
|
+
`,Tm=`
|
|
122
122
|
in vec2 aPosition;
|
|
123
123
|
in vec2 aUV;
|
|
124
124
|
|
|
@@ -154,7 +154,7 @@ ${r.join(`
|
|
|
154
154
|
|
|
155
155
|
{{end}}
|
|
156
156
|
}
|
|
157
|
-
`,
|
|
157
|
+
`,Em=`
|
|
158
158
|
|
|
159
159
|
in vec4 vColor;
|
|
160
160
|
in vec2 vUV;
|
|
@@ -175,7 +175,7 @@ ${r.join(`
|
|
|
175
175
|
|
|
176
176
|
{{end}}
|
|
177
177
|
}
|
|
178
|
-
`,
|
|
178
|
+
`,wm={name:"global-uniforms-bit",vertex:{header:`
|
|
179
179
|
struct GlobalUniforms {
|
|
180
180
|
uProjectionMatrix:mat3x3<f32>,
|
|
181
181
|
uWorldTransformMatrix:mat3x3<f32>,
|
|
@@ -184,22 +184,22 @@ ${r.join(`
|
|
|
184
184
|
}
|
|
185
185
|
|
|
186
186
|
@group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
|
|
187
|
-
`}},
|
|
187
|
+
`}},Im={name:"global-uniforms-bit",vertex:{header:`
|
|
188
188
|
uniform mat3 uProjectionMatrix;
|
|
189
189
|
uniform mat3 uWorldTransformMatrix;
|
|
190
190
|
uniform vec4 uWorldColorAlpha;
|
|
191
191
|
uniform vec2 uResolution;
|
|
192
|
-
`}};function
|
|
192
|
+
`}};function wn({bits:s,name:e}){const t=bm({template:{fragment:Cm,vertex:Sm},bits:[wm,...s]});return ni.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function In({bits:s,name:e}){return new Ai({name:e,...xm({template:{vertex:Tm,fragment:Em},bits:[Im,...s]})})}const zl={name:"color-bit",vertex:{header:`
|
|
193
193
|
@in aColor: vec4<f32>;
|
|
194
194
|
`,main:`
|
|
195
195
|
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
196
|
-
`}}
|
|
196
|
+
`}},$l={name:"color-bit",vertex:{header:`
|
|
197
197
|
in vec4 aColor;
|
|
198
198
|
`,main:`
|
|
199
199
|
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
200
|
-
`}},
|
|
201
|
-
`)}function
|
|
202
|
-
`)}function
|
|
200
|
+
`}},An={};function Am(s){const e=[];if(s===1)e.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),e.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let t=0;for(let i=0;i<s;i++)e.push(`@group(1) @binding(${t++}) var textureSource${i+1}: texture_2d<f32>;`),e.push(`@group(1) @binding(${t++}) var textureSampler${i+1}: sampler;`)}return e.join(`
|
|
201
|
+
`)}function Rm(s){const e=[];if(s===1)e.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{e.push("switch vTextureId {");for(let t=0;t<s;t++)t===s-1?e.push(" default:{"):e.push(` case ${t}:{`),e.push(` outColor = textureSampleGrad(textureSource${t+1}, textureSampler${t+1}, vUV, uvDx, uvDy);`),e.push(" break;}");e.push("}")}return e.join(`
|
|
202
|
+
`)}function jl(s){return An[s]||(An[s]={name:"texture-batch-bit",vertex:{header:`
|
|
203
203
|
@in aTextureIdAndRound: vec2<u32>;
|
|
204
204
|
@out @interpolate(flat) vTextureId : u32;
|
|
205
205
|
`,main:`
|
|
@@ -212,14 +212,14 @@ ${r.join(`
|
|
|
212
212
|
`},fragment:{header:`
|
|
213
213
|
@in @interpolate(flat) vTextureId: u32;
|
|
214
214
|
|
|
215
|
-
${
|
|
215
|
+
${Am(s)}
|
|
216
216
|
`,main:`
|
|
217
217
|
var uvDx = dpdx(vUV);
|
|
218
218
|
var uvDy = dpdy(vUV);
|
|
219
219
|
|
|
220
|
-
${
|
|
221
|
-
`}}),
|
|
222
|
-
`)}function
|
|
220
|
+
${Rm(s)}
|
|
221
|
+
`}}),An[s]}const Rn={};function Mm(s){const e=[];for(let t=0;t<s;t++)t>0&&e.push("else"),t<s-1&&e.push(`if(vTextureId < ${t}.5)`),e.push("{"),e.push(` outColor = texture(uTextures[${t}], vUV);`),e.push("}");return e.join(`
|
|
222
|
+
`)}function Xl(s){return Rn[s]||(Rn[s]={name:"texture-batch-bit",vertex:{header:`
|
|
223
223
|
in vec2 aTextureIdAndRound;
|
|
224
224
|
out float vTextureId;
|
|
225
225
|
|
|
@@ -237,18 +237,18 @@ ${r.join(`
|
|
|
237
237
|
|
|
238
238
|
`,main:`
|
|
239
239
|
|
|
240
|
-
${
|
|
241
|
-
`}}),
|
|
240
|
+
${Mm(s)}
|
|
241
|
+
`}}),Rn[s]}const Mn={name:"round-pixels-bit",vertex:{header:`
|
|
242
242
|
fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
|
|
243
243
|
{
|
|
244
244
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
245
245
|
}
|
|
246
|
-
`}},
|
|
246
|
+
`}},Pn={name:"round-pixels-bit",vertex:{header:`
|
|
247
247
|
vec2 roundPixels(vec2 position, vec2 targetSize)
|
|
248
248
|
{
|
|
249
249
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
250
250
|
}
|
|
251
|
-
`}},ll={};function hl(s){let t=ll[s];if(t)return t;const e=new Int32Array(s);for(let i=0;i<s;i++)e[i]=i;return t=ll[s]=new le({uTextures:{value:e,type:"i32",size:s}},{isStatic:!0}),t}class cl extends be{constructor(t){const e=Xr({name:"batch",bits:[nl,al(t),Zr]}),i=jr({name:"batch",bits:[rl,ol(t),Kr]});super({glProgram:e,gpuProgram:i,resources:{batchSamplers:hl(t)}}),this.maxTextures=t}}let qi=null;const ul=class uu extends Ff{constructor(t){super(t),this.geometry=new $f,this.name=uu.extension.name,this.vertexSize=6,qi??(qi=new cl(t.maxTextures)),this.shader=qi}packAttributes(t,e,i,r,n){const o=n<<16|t.roundPixels&65535,a=t.transform,l=a.a,h=a.b,c=a.c,u=a.d,m=a.tx,f=a.ty,{positions:g,uvs:y}=t,x=t.color,v=t.attributeOffset,E=v+t.attributeSize;for(let T=v;T<E;T++){const C=T*2,R=g[C],A=g[C+1];e[r++]=l*R+c*A+m,e[r++]=u*A+h*R+f,e[r++]=y[C],e[r++]=y[C+1],i[r++]=x,i[r++]=o}}packQuadAttributes(t,e,i,r,n){const o=t.texture,a=t.transform,l=a.a,h=a.b,c=a.c,u=a.d,m=a.tx,f=a.ty,g=t.bounds,y=g.maxX,x=g.minX,v=g.maxY,E=g.minY,T=o.uvs,C=t.color,R=n<<16|t.roundPixels&65535;e[r+0]=l*x+c*E+m,e[r+1]=u*E+h*x+f,e[r+2]=T.x0,e[r+3]=T.y0,i[r+4]=C,i[r+5]=R,e[r+6]=l*y+c*E+m,e[r+7]=u*E+h*y+f,e[r+8]=T.x1,e[r+9]=T.y1,i[r+10]=C,i[r+11]=R,e[r+12]=l*y+c*v+m,e[r+13]=u*v+h*y+f,e[r+14]=T.x2,e[r+15]=T.y2,i[r+16]=C,i[r+17]=R,e[r+18]=l*x+c*v+m,e[r+19]=u*v+h*x+f,e[r+20]=T.x3,e[r+21]=T.y3,i[r+22]=C,i[r+23]=R}_updateMaxTextures(t){this.shader.maxTextures!==t&&(qi=new cl(t),this.shader=qi)}destroy(){this.shader=null,super.destroy()}};ul.extension={type:[w.Batcher],name:"default"};let Jr=ul;class ce{constructor(t){this.items=Object.create(null);const{renderer:e,type:i,onUnload:r,priority:n,name:o}=t;this._renderer=e,e.gc.addResourceHash(this,"items",i,n??0),this._onUnload=r,this.name=o}add(t){return this.items[t.uid]?!1:(this.items[t.uid]=t,t.once("unload",this.remove,this),t._gcLastUsed=this._renderer.gc.now,!0)}remove(t,...e){var r;if(!this.items[t.uid])return;const i=t._gpuData[this._renderer.uid];i&&((r=this._onUnload)==null||r.call(this,t,...e),i.destroy(),t._gpuData[this._renderer.uid]=null,this.items[t.uid]=null)}removeAll(...t){Object.values(this.items).forEach(e=>e&&this.remove(e,...t))}destroy(...t){this.removeAll(...t),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function hp(s,t,e,i,r,n,o,a=null){let l=0;e*=t,r*=n;const h=a.a,c=a.b,u=a.c,m=a.d,f=a.tx,g=a.ty;for(;l<o;){const y=s[e],x=s[e+1];i[r]=h*y+u*x+f,i[r+1]=c*y+m*x+g,r+=n,e+=t,l++}}function cp(s,t,e,i){let r=0;for(t*=e;r<i;)s[t]=0,s[t+1]=0,t+=e,r++}function dl(s,t,e,i,r){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,c=t.ty;e||(e=0),i||(i=2),r||(r=s.length/i-e);let u=e*i;for(let m=0;m<r;m++){const f=s[u],g=s[u+1];s[u]=n*f+a*g+h,s[u+1]=o*f+l*g+c,u+=i}}const up=new W;class Qr{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const t=this.baseColor,e=t>>16|t&65280|(t&255)<<16,i=this.renderable;return i?hi(e,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):e+(this.alpha*255<<24)}get transform(){var t;return((t=this.renderable)==null?void 0:t.groupTransform)||up}copyTo(t){t.indexOffset=this.indexOffset,t.indexSize=this.indexSize,t.attributeOffset=this.attributeOffset,t.attributeSize=this.attributeSize,t.baseColor=this.baseColor,t.alpha=this.alpha,t.texture=this.texture,t.geometryData=this.geometryData,t.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Ki={extension:{type:w.ShapeBuilder,name:"circle"},build(s,t){let e,i,r,n,o,a;if(s.type==="circle"){const C=s;if(o=a=C.radius,o<=0)return!1;e=C.x,i=C.y,r=n=0}else if(s.type==="ellipse"){const C=s;if(o=C.halfWidth,a=C.halfHeight,o<=0||a<=0)return!1;e=C.x,i=C.y,r=n=0}else{const C=s,R=C.width/2,A=C.height/2;e=C.x+R,i=C.y+A,o=a=Math.max(0,Math.min(C.radius,Math.min(R,A))),r=R-o,n=A-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),h=l*8+(r?4:0)+(n?4:0);if(h===0)return!1;if(l===0)return t[0]=t[6]=e+r,t[1]=t[3]=i+n,t[2]=t[4]=e-r,t[5]=t[7]=i-n,!0;let c=0,u=l*4+(r?2:0)+2,m=u,f=h,g=r+o,y=n,x=e+g,v=e-g,E=i+y;if(t[c++]=x,t[c++]=E,t[--u]=E,t[--u]=v,n){const C=i-y;t[m++]=v,t[m++]=C,t[--f]=C,t[--f]=x}for(let C=1;C<l;C++){const R=Math.PI/2*(C/l),A=r+Math.cos(R)*o,P=n+Math.sin(R)*a,F=e+A,B=e-A,k=i+P,O=i-P;t[c++]=F,t[c++]=k,t[--u]=k,t[--u]=B,t[m++]=B,t[m++]=O,t[--f]=O,t[--f]=F}g=r,y=n+a,x=e+g,v=e-g,E=i+y;const T=i-y;return t[c++]=x,t[c++]=E,t[--f]=T,t[--f]=x,r&&(t[c++]=v,t[c++]=E,t[--f]=T,t[--f]=v),!0},triangulate(s,t,e,i,r,n){if(s.length===0)return;let o=0,a=0;for(let c=0;c<s.length;c+=2)o+=s[c],a+=s[c+1];o/=s.length/2,a/=s.length/2;let l=i;t[l*e]=o,t[l*e+1]=a;const h=l++;for(let c=0;c<s.length;c+=2)t[l*e]=s[c],t[l*e+1]=s[c+1],c>0&&(r[n++]=l,r[n++]=h,r[n++]=l-1),l++;r[n++]=h+1,r[n++]=h,r[n++]=l-1}},dp={...Ki,extension:{...Ki.extension,name:"ellipse"}},fp={...Ki,extension:{...Ki.extension,name:"roundedRectangle"}},fl=1e-4,pl=1e-4;function pp(s){const t=s.length;if(t<6)return 1;let e=0;for(let i=0,r=s[t-2],n=s[t-1];i<t;i+=2){const o=s[i],a=s[i+1];e+=(o-r)*(a+n),r=o,n=a}return e<0?-1:1}function ml(s,t,e,i,r,n,o,a){const l=s-e*r,h=t-i*r,c=s+e*n,u=t+i*n;let m,f;o?(m=i,f=-e):(m=-i,f=e);const g=l+m,y=h+f,x=c+m,v=u+f;return a.push(g,y),a.push(x,v),2}function qe(s,t,e,i,r,n,o,a){const l=e-s,h=i-t;let c=Math.atan2(l,h),u=Math.atan2(r-s,n-t);a&&c<u?c+=Math.PI*2:!a&&c>u&&(u+=Math.PI*2);let m=c;const f=u-c,g=Math.abs(f),y=Math.sqrt(l*l+h*h),x=(15*g*Math.sqrt(y)/Math.PI>>0)+1,v=f/x;if(m+=v,a){o.push(s,t),o.push(e,i);for(let E=1,T=m;E<x;E++,T+=v)o.push(s,t),o.push(s+Math.sin(T)*y,t+Math.cos(T)*y);o.push(s,t),o.push(r,n)}else{o.push(e,i),o.push(s,t);for(let E=1,T=m;E<x;E++,T+=v)o.push(s+Math.sin(T)*y,t+Math.cos(T)*y),o.push(s,t);o.push(r,n),o.push(s,t)}return x*2}function gl(s,t,e,i,r,n){const o=fl;if(s.length===0)return;const a=t;let l=a.alignment;if(t.alignment!==.5){let D=pp(s);l=(l-.5)*D+.5}const h=new mt(s[0],s[1]),c=new mt(s[s.length-2],s[s.length-1]),u=i,m=Math.abs(h.x-c.x)<o&&Math.abs(h.y-c.y)<o;if(u){s=s.slice(),m&&(s.pop(),s.pop(),c.set(s[s.length-2],s[s.length-1]));const D=(h.x+c.x)*.5,z=(c.y+h.y)*.5;s.unshift(D,z),s.push(D,z)}const f=r,g=s.length/2;let y=s.length;const x=f.length/2,v=a.width/2,E=v*v,T=a.miterLimit*a.miterLimit;let C=s[0],R=s[1],A=s[2],P=s[3],F=0,B=0,k=-(R-P),O=C-A,L=0,N=0,H=Math.sqrt(k*k+O*O);k/=H,O/=H,k*=v,O*=v;const at=l,G=(1-at)*2,U=at*2;u||(a.cap==="round"?y+=qe(C-k*(G-U)*.5,R-O*(G-U)*.5,C-k*G,R-O*G,C+k*U,R+O*U,f,!0)+2:a.cap==="square"&&(y+=ml(C,R,k,O,G,U,!0,f))),f.push(C-k*G,R-O*G),f.push(C+k*U,R+O*U);for(let D=1;D<g-1;++D){C=s[(D-1)*2],R=s[(D-1)*2+1],A=s[D*2],P=s[D*2+1],F=s[(D+1)*2],B=s[(D+1)*2+1],k=-(R-P),O=C-A,H=Math.sqrt(k*k+O*O),k/=H,O/=H,k*=v,O*=v,L=-(P-B),N=A-F,H=Math.sqrt(L*L+N*N),L/=H,N/=H,L*=v,N*=v;const z=A-C,Y=R-P,j=A-F,V=B-P,ot=z*j+Y*V,lt=Y*j-V*z,gt=lt<0;if(Math.abs(lt)<.001*Math.abs(ot)){f.push(A-k*G,P-O*G),f.push(A+k*U,P+O*U),ot>=0&&(a.join==="round"?y+=qe(A,P,A-k*G,P-O*G,A-L*G,P-N*G,f,!1)+4:y+=2,f.push(A-L*U,P-N*U),f.push(A+L*G,P+N*G));continue}const ht=(-k+C)*(-O+P)-(-k+A)*(-O+R),_t=(-L+F)*(-N+P)-(-L+A)*(-N+B),Z=(z*_t-j*ht)/lt,Bt=(V*ht-Y*_t)/lt,zt=(Z-A)*(Z-A)+(Bt-P)*(Bt-P),xt=A+(Z-A)*G,Gt=P+(Bt-P)*G,Ut=A-(Z-A)*U,$t=P-(Bt-P)*U,Fe=Math.min(z*z+Y*Y,j*j+V*V),pe=gt?G:U,ei=Fe+pe*pe*E;zt<=ei?a.join==="bevel"||zt/E>T?(gt?(f.push(xt,Gt),f.push(A+k*U,P+O*U),f.push(xt,Gt),f.push(A+L*U,P+N*U)):(f.push(A-k*G,P-O*G),f.push(Ut,$t),f.push(A-L*G,P-N*G),f.push(Ut,$t)),y+=2):a.join==="round"?gt?(f.push(xt,Gt),f.push(A+k*U,P+O*U),y+=qe(A,P,A+k*U,P+O*U,A+L*U,P+N*U,f,!0)+4,f.push(xt,Gt),f.push(A+L*U,P+N*U)):(f.push(A-k*G,P-O*G),f.push(Ut,$t),y+=qe(A,P,A-k*G,P-O*G,A-L*G,P-N*G,f,!1)+4,f.push(A-L*G,P-N*G),f.push(Ut,$t)):(f.push(xt,Gt),f.push(Ut,$t)):(f.push(A-k*G,P-O*G),f.push(A+k*U,P+O*U),a.join==="round"?gt?y+=qe(A,P,A+k*U,P+O*U,A+L*U,P+N*U,f,!0)+2:y+=qe(A,P,A-k*G,P-O*G,A-L*G,P-N*G,f,!1)+2:a.join==="miter"&&zt/E<=T&&(gt?(f.push(Ut,$t),f.push(Ut,$t)):(f.push(xt,Gt),f.push(xt,Gt)),y+=2),f.push(A-L*G,P-N*G),f.push(A+L*U,P+N*U),y+=2)}C=s[(g-2)*2],R=s[(g-2)*2+1],A=s[(g-1)*2],P=s[(g-1)*2+1],k=-(R-P),O=C-A,H=Math.sqrt(k*k+O*O),k/=H,O/=H,k*=v,O*=v,f.push(A-k*G,P-O*G),f.push(A+k*U,P+O*U),u||(a.cap==="round"?y+=qe(A-k*(G-U)*.5,P-O*(G-U)*.5,A-k*G,P-O*G,A+k*U,P+O*U,f,!1)+2:a.cap==="square"&&(y+=ml(A,P,k,O,G,U,!1,f)));const X=pl*pl;for(let D=x;D<y+x-2;++D)C=f[D*2],R=f[D*2+1],A=f[(D+1)*2],P=f[(D+1)*2+1],F=f[(D+2)*2],B=f[(D+2)*2+1],!(Math.abs(C*(P-B)+A*(B-R)+F*(R-P))<X)&&n.push(D,D+1,D+2)}function mp(s,t,e,i){const r=fl;if(s.length===0)return;const n=s[0],o=s[1],a=s[s.length-2],l=s[s.length-1],h=t||Math.abs(n-a)<r&&Math.abs(o-l)<r,c=e,u=s.length/2,m=c.length/2;for(let f=0;f<u;f++)c.push(s[f*2]),c.push(s[f*2+1]);for(let f=0;f<u-1;f++)i.push(m+f,m+f+1);h&&i.push(m+u-1,m)}function _l(s,t,e,i,r,n,o){const a=vf(s,t,2);if(!a)return;for(let h=0;h<a.length;h+=3)n[o++]=a[h]+r,n[o++]=a[h+1]+r,n[o++]=a[h+2]+r;let l=r*i;for(let h=0;h<s.length;h+=2)e[l]=s[h],e[l+1]=s[h+1],l+=i}const gp=[],_p={extension:{type:w.ShapeBuilder,name:"polygon"},build(s,t){for(let e=0;e<s.points.length;e++)t[e]=s.points[e];return!0},triangulate(s,t,e,i,r,n){_l(s,gp,t,e,i,r,n)}},yp={extension:{type:w.ShapeBuilder,name:"rectangle"},build(s,t){const e=s,i=e.x,r=e.y,n=e.width,o=e.height;return n>0&&o>0?(t[0]=i,t[1]=r,t[2]=i+n,t[3]=r,t[4]=i+n,t[5]=r+o,t[6]=i,t[7]=r+o,!0):!1},triangulate(s,t,e,i,r,n){let o=0;i*=e,t[i+o]=s[0],t[i+o+1]=s[1],o+=e,t[i+o]=s[2],t[i+o+1]=s[3],o+=e,t[i+o]=s[6],t[i+o+1]=s[7],o+=e,t[i+o]=s[4],t[i+o+1]=s[5],o+=e;const a=i/e;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},xp={extension:{type:w.ShapeBuilder,name:"triangle"},build(s,t){return t[0]=s.x,t[1]=s.y,t[2]=s.x2,t[3]=s.y2,t[4]=s.x3,t[5]=s.y3,!0},triangulate(s,t,e,i,r,n){let o=0;i*=e,t[i+o]=s[0],t[i+o+1]=s[1],o+=e,t[i+o]=s[2],t[i+o+1]=s[3],o+=e,t[i+o]=s[4],t[i+o+1]=s[5];const a=i/e;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},yl=[{offset:0,color:"white"},{offset:1,color:"black"}],tn=class to{constructor(...t){this.uid=dt("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let e=bp(t);e={...e.type==="radial"?to.defaultRadialOptions:to.defaultLinearOptions,...uo(e)},this._textureSize=e.textureSize,this._wrapMode=e.wrapMode,e.type==="radial"?(this.center=e.center,this.outerCenter=e.outerCenter??this.center,this.innerRadius=e.innerRadius,this.outerRadius=e.outerRadius,this.scale=e.scale,this.rotation=e.rotation):(this.start=e.start,this.end=e.end),this.textureSpace=e.textureSpace,this.type=e.type,e.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(t,e){return this.colorStops.push({offset:t,color:ut.shared.setValue(e).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:t,y:e}=this.start,{x:i,y:r}=this.end,n=i-t,o=r-e;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const x=t;t=i,i=x,n*=-1}if(o<0){const x=e;e=r,r=x,o*=-1}}const l=this.colorStops.length?this.colorStops:yl,h=this._textureSize,{canvas:c,context:u}=bl(h,1),m=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);xl(m,l),u.fillStyle=m,u.fillRect(0,0,h,1),this.texture=new $({source:new xs({resource:c,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),y=new W;y.scale(f/h,1),y.rotate(g),y.translate(t,e),this.textureSpace==="local"&&y.scale(h,h),this.transform=y}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const t=this.colorStops.length?this.colorStops:yl,e=this._textureSize,{canvas:i,context:r}=bl(e,e),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,h=this.innerRadius,c=this.outerRadius,u=a-c,m=l-c,f=e/(c*2),g=(n-u)*f,y=(o-m)*f,x=r.createRadialGradient(g,y,h*f,(a-u)*f,(l-m)*f,c*f);xl(x,t),r.fillStyle=t[t.length-1].color,r.fillRect(0,0,e,e),r.fillStyle=x,r.translate(g,y),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-y),r.fillRect(0,0,e,e),this.texture=new $({source:new xs({resource:i,addressMode:this._wrapMode})});const v=new W;v.scale(1/f,1/f),v.translate(u,m),this.textureSpace==="local"&&v.scale(e,e),this.transform=v}destroy(){var t;(t=this.texture)==null||t.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};tn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},tn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let ue=tn;function xl(s,t){for(let e=0;e<t.length;e++){const i=t[e];s.addColorStop(i.offset,i.color)}}function bl(s,t){const e=rt.get().createCanvas(s,t),i=e.getContext("2d");return{canvas:e,context:i}}function bp(s){let t=s[0]??{};return(typeof t=="number"||s[1])&&(K("8.5.2","use options object instead"),t={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??ue.defaultLinearOptions.textureSize}),t}const vp=new W,Ep=new ct;function vl(s,t,e,i){const r=t.matrix?s.copyFrom(t.matrix).invert():s.identity();if(t.textureSpace==="local"){const o=e.getBounds(Ep);t.width&&o.pad(t.width);const{x:a,y:l}=o,h=1/o.width,c=1/o.height,u=-a*h,m=-l*c,f=r.a,g=r.b,y=r.c,x=r.d;r.a*=h,r.b*=h,r.c*=c,r.d*=c,r.tx=u*f+m*y+r.tx,r.ty=u*g+m*x+r.ty}else r.translate(t.texture.frame.x,t.texture.frame.y),r.scale(1/t.texture.source.width,1/t.texture.source.height);const n=t.texture.source.style;return!(t.fill instanceof ue)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),i&&r.append(vp.copyFrom(i).invert()),r}const Zi={};J.handleByMap(w.ShapeBuilder,Zi),J.add(yp,_p,xp,Ki,dp,fp);const Tp=new ct,Sp=new W;function Cp(s,t){const{geometryData:e,batches:i}=t;i.length=0,e.indices.length=0,e.vertices.length=0,e.uvs.length=0;for(let r=0;r<s.instructions.length;r++){const n=s.instructions[r];if(n.action==="texture")wp(n.data,i,e);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,h=n.data.hole;o&&h&&El(h.shapePath,l,!0,i,e),h&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=h.shapePath.shapePrimitives),El(a,l,o,i,e)}}}function wp(s,t,e){const i=[],r=Zi.rectangle,n=Tp;n.x=s.dx,n.y=s.dy,n.width=s.dw,n.height=s.dh;const o=s.transform;if(!r.build(n,i))return;const{vertices:a,uvs:l,indices:h}=e,c=h.length,u=a.length/2;o&&dl(i,o),r.triangulate(i,a,2,u,h,c);const m=s.image,f=m.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const g=Mt.get(Qr);g.indexOffset=c,g.indexSize=h.length-c,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=s.style,g.alpha=s.alpha,g.texture=m,g.geometryData=e,t.push(g)}function El(s,t,e,i,r){const{vertices:n,uvs:o,indices:a}=r;s.shapePrimitives.forEach(({shape:l,transform:h,holes:c})=>{const u=[],m=Zi[l.type];if(!m.build(l,u))return;const f=a.length,g=n.length/2;let y="triangle-list";if(h&&dl(u,h),e){const T=l.closePath??!0,C=t;C.pixelLine?(mp(u,T,n,a),y="line-list"):gl(u,C,!1,T,n,a)}else if(c){const T=[],C=u.slice();Ap(c).forEach(A=>{T.push(C.length/2),C.push(...A)}),_l(C,T,n,2,g,a,f)}else m.triangulate(u,n,2,g,a,f);const x=o.length/2,v=t.texture;if(v!==$.WHITE){const T=vl(Sp,t,l,h);hp(n,2,g,o,x,2,n.length/2-g,T)}else cp(o,x,2,n.length/2-g);const E=Mt.get(Qr);E.indexOffset=f,E.indexSize=a.length-f,E.attributeOffset=g,E.attributeSize=n.length/2-g,E.baseColor=t.color,E.alpha=t.alpha,E.texture=v,E.geometryData=r,E.topology=y,i.push(E)})}function Ap(s){const t=[];for(let e=0;e<s.length;e++){const i=s[e].shape,r=[];Zi[i.type].build(i,r)&&t.push(r)}return t}class Rp{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(t=>{Mt.return(t)}),this.graphicsData&&Mt.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class Ip{constructor(){this.instructions=new fr}init(t){const e=t.maxTextures;this.batcher?this.batcher._updateMaxTextures(e):this.batcher=new Jr({maxTextures:e}),this.instructions.reset()}get geometry(){return K(Nu,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const en=class eo{constructor(t){this._renderer=t,this._managedContexts=new ce({renderer:t,type:"resource",name:"graphicsContext"})}init(t){eo.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??eo.defaultOptions.bezierSmoothness}getContextRenderData(t){return t._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(t)}updateGpuContext(t){const e=!!t._gpuData[this._renderer.uid],i=t._gpuData[this._renderer.uid]||this._initContext(t);if(t.dirty||!e){e&&i.reset(),Cp(t,i);const r=t.batchMode;t.customShader||r==="no-batch"?i.isBatchable=!1:r==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,t.dirty=!1}return i}getGpuContext(t){return t._gpuData[this._renderer.uid]||this._initContext(t)}_initContextRenderData(t){const e=Mt.get(Ip,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=t._gpuData[this._renderer.uid],{batches:r,geometryData:n}=i;i.graphicsData=e;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=e.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const m=r[u];l.add(m)}l.finish(e.instructions);const h=l.geometry;h.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),h.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const c=l.batches;for(let u=0;u<c.length;u++){const m=c[u];m.bindGroup=Wr(m.textures.textures,m.textures.count,this._renderer.limits.maxBatchableTextures)}return e}_initContext(t){const e=new Rp;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};en.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"graphicsContext"},en.defaultOptions={bezierSmoothness:.5};let sn=en;const Pp=8,Ps=11920929e-14,Mp=1;function Tl(s,t,e,i,r,n,o,a,l,h){const u=Math.min(.99,Math.max(0,h??sn.defaultOptions.bezierSmoothness));let m=(Mp-u)/1;return m*=m,kp(t,e,i,r,n,o,a,l,s,m),s}function kp(s,t,e,i,r,n,o,a,l,h){rn(s,t,e,i,r,n,o,a,l,h,0),l.push(o,a)}function rn(s,t,e,i,r,n,o,a,l,h,c){if(c>Pp)return;const u=(s+e)/2,m=(t+i)/2,f=(e+r)/2,g=(i+n)/2,y=(r+o)/2,x=(n+a)/2,v=(u+f)/2,E=(m+g)/2,T=(f+y)/2,C=(g+x)/2,R=(v+T)/2,A=(E+C)/2;if(c>0){let P=o-s,F=a-t;const B=Math.abs((e-o)*F-(i-a)*P),k=Math.abs((r-o)*F-(n-a)*P);if(B>Ps&&k>Ps){if((B+k)*(B+k)<=h*(P*P+F*F)){l.push(R,A);return}}else if(B>Ps){if(B*B<=h*(P*P+F*F)){l.push(R,A);return}}else if(k>Ps){if(k*k<=h*(P*P+F*F)){l.push(R,A);return}}else if(P=R-(s+o)/2,F=A-(t+a)/2,P*P+F*F<=h){l.push(R,A);return}}rn(s,t,u,m,v,E,R,A,l,h,c+1),rn(R,A,T,C,y,x,o,a,l,h,c+1)}const Bp=8,Op=11920929e-14,Dp=1;function Gp(s,t,e,i,r,n,o,a){const h=Math.min(.99,Math.max(0,a??sn.defaultOptions.bezierSmoothness));let c=(Dp-h)/1;return c*=c,Up(t,e,i,r,n,o,s,c),s}function Up(s,t,e,i,r,n,o,a){nn(o,s,t,e,i,r,n,a,0),o.push(r,n)}function nn(s,t,e,i,r,n,o,a,l){if(l>Bp)return;const h=(t+i)/2,c=(e+r)/2,u=(i+n)/2,m=(r+o)/2,f=(h+u)/2,g=(c+m)/2;let y=n-t,x=o-e;const v=Math.abs((i-n)*x-(r-o)*y);if(v>Op){if(v*v<=a*(y*y+x*x)){s.push(f,g);return}}else if(y=f-(t+n)/2,x=g-(e+o)/2,y*y+x*x<=a){s.push(f,g);return}nn(s,t,e,h,c,f,g,a,l+1),nn(s,f,g,u,m,n,o,a,l+1)}function Sl(s,t,e,i,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(l/Math.PI)))),a=Math.max(a,3);let h=l/a,c=r;h*=o?-1:1;for(let u=0;u<a+1;u++){const m=Math.cos(c),f=Math.sin(c),g=t+m*i,y=e+f*i;s.push(g,y),c+=h}}function Lp(s,t,e,i,r,n){const o=s[s.length-2],l=s[s.length-1]-e,h=o-t,c=r-e,u=i-t,m=Math.abs(l*u-h*c);if(m<1e-8||n===0){(s[s.length-2]!==t||s[s.length-1]!==e)&&s.push(t,e);return}const f=l*l+h*h,g=c*c+u*u,y=l*c+h*u,x=n*Math.sqrt(f)/m,v=n*Math.sqrt(g)/m,E=x*y/f,T=v*y/g,C=x*u+v*h,R=x*c+v*l,A=h*(v+E),P=l*(v+E),F=u*(x+T),B=c*(x+T),k=Math.atan2(P-R,A-C),O=Math.atan2(B-R,F-C);Sl(s,C+t,R+e,n,k,O,h*c>u*l)}const Ji=Math.PI*2,on={centerX:0,centerY:0,ang1:0,ang2:0},an=({x:s,y:t},e,i,r,n,o,a,l)=>{s*=e,t*=i;const h=r*s-n*t,c=n*s+r*t;return l.x=h+o,l.y=c+a,l};function Np(s,t){const e=t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),i=t===1.5707963267948966?.551915024494:e,r=Math.cos(s),n=Math.sin(s),o=Math.cos(s+t),a=Math.sin(s+t);return[{x:r-n*i,y:n+r*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const Cl=(s,t,e,i)=>{const r=s*i-t*e<0?-1:1;let n=s*e+t*i;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},Fp=(s,t,e,i,r,n,o,a,l,h,c,u,m)=>{const f=Math.pow(r,2),g=Math.pow(n,2),y=Math.pow(c,2),x=Math.pow(u,2);let v=f*g-f*x-g*y;v<0&&(v=0),v/=f*x+g*y,v=Math.sqrt(v)*(o===a?-1:1);const E=v*r/n*u,T=v*-n/r*c,C=h*E-l*T+(s+e)/2,R=l*E+h*T+(t+i)/2,A=(c-E)/r,P=(u-T)/n,F=(-c-E)/r,B=(-u-T)/n,k=Cl(1,0,A,P);let O=Cl(A,P,F,B);a===0&&O>0&&(O-=Ji),a===1&&O<0&&(O+=Ji),m.centerX=C,m.centerY=R,m.ang1=k,m.ang2=O};function Hp(s,t,e,i,r,n,o,a=0,l=0,h=0){if(n===0||o===0)return;const c=Math.sin(a*Ji/360),u=Math.cos(a*Ji/360),m=u*(t-i)/2+c*(e-r)/2,f=-c*(t-i)/2+u*(e-r)/2;if(m===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(m,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),Fp(t,e,i,r,n,o,l,h,c,u,m,f,on);let{ang1:y,ang2:x}=on;const{centerX:v,centerY:E}=on;let T=Math.abs(x)/(Ji/4);Math.abs(1-T)<1e-7&&(T=1);const C=Math.max(Math.ceil(T),1);x/=C;let R=s[s.length-2],A=s[s.length-1];const P={x:0,y:0};for(let F=0;F<C;F++){const B=Np(y,x),{x:k,y:O}=an(B[0],n,o,u,c,v,E,P),{x:L,y:N}=an(B[1],n,o,u,c,v,E,P),{x:H,y:at}=an(B[2],n,o,u,c,v,E,P);Tl(s,R,A,k,O,L,N,H,at),R=H,A=at,y+=x}}function Wp(s,t,e){const i=(o,a)=>{const l=a.x-o.x,h=a.y-o.y,c=Math.sqrt(l*l+h*h),u=l/c,m=h/c;return{len:c,nx:u,ny:m}},r=(o,a)=>{o===0?s.moveTo(a.x,a.y):s.lineTo(a.x,a.y)};let n=t[t.length-1];for(let o=0;o<t.length;o++){const a=t[o%t.length],l=a.radius??e;if(l<=0){r(o,a),n=a;continue}const h=t[(o+1)%t.length],c=i(a,n),u=i(a,h);if(c.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let m=Math.asin(c.nx*u.ny-c.ny*u.nx),f=1,g=!1;c.nx*u.nx-c.ny*-u.ny<0?m<0?m=Math.PI+m:(m=Math.PI-m,f=-1,g=!0):m>0&&(f=-1,g=!0);const y=m/2;let x,v=Math.abs(Math.cos(y)*l/Math.sin(y));v>Math.min(c.len/2,u.len/2)?(v=Math.min(c.len/2,u.len/2),x=Math.abs(v*Math.sin(y)/Math.cos(y))):x=l;const E=a.x+u.nx*v+-u.ny*x*f,T=a.y+u.ny*v+u.nx*x*f,C=Math.atan2(c.ny,c.nx)+Math.PI/2*f,R=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&s.moveTo(E+Math.cos(C)*x,T+Math.sin(C)*x),s.arc(E,T,x,C,R,g),n=a}}function Vp(s,t,e,i){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,h)=>({x:a.x+(l.x-a.x)*h,y:a.y+(l.y-a.y)*h}),o=t.length;for(let a=0;a<o;a++){const l=t[(a+1)%o],h=l.radius??e;if(h<=0){a===0?s.moveTo(l.x,l.y):s.lineTo(l.x,l.y);continue}const c=t[a],u=t[(a+2)%o],m=r(c,l);let f;if(m<1e-4)f=l;else{const x=Math.min(m/2,h);f=n(l,c,x/m)}const g=r(u,l);let y;if(g<1e-4)y=l;else{const x=Math.min(g/2,h);y=n(l,u,x/g)}a===0?s.moveTo(f.x,f.y):s.lineTo(f.x,f.y),s.quadraticCurveTo(l.x,l.y,y.x,y.y,i)}}const zp=new ct;class $p{constructor(t){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Lt,this._graphicsPath2D=t,this.signed=t.checkForHoles}moveTo(t,e){return this.startPoly(t,e),this}lineTo(t,e){this._ensurePoly();const i=this._currentPoly.points,r=i[i.length-2],n=i[i.length-1];return(r!==t||n!==e)&&i.push(t,e),this}arc(t,e,i,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Sl(a,t,e,i,r,n,o),this}arcTo(t,e,i,r,n){this._ensurePoly();const o=this._currentPoly.points;return Lp(o,t,e,i,r,n),this}arcToSvg(t,e,i,r,n,o,a){const l=this._currentPoly.points;return Hp(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,t,e,i,r,n),this}bezierCurveTo(t,e,i,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Tl(this._currentPoly.points,l.lastX,l.lastY,t,e,i,r,n,o,a),this}quadraticCurveTo(t,e,i,r,n){this._ensurePoly();const o=this._currentPoly;return Gp(this._currentPoly.points,o.lastX,o.lastY,t,e,i,r,n),this}closePath(){return this.endPoly(!0),this}addPath(t,e){this.endPoly(),e&&!e.isIdentity()&&(t=t.clone(!0),t.transform(e));const i=this.shapePrimitives,r=i.length;for(let n=0;n<t.instructions.length;n++){const o=t.instructions[n];this[o.action](...o.data)}if(t.checkForHoles&&i.length-r>1){let n=null;for(let o=r;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const l=a.shape,h=n==null?void 0:n.shape;h&&h.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):n=a}}}return this}finish(t=!1){this.endPoly(t)}rect(t,e,i,r,n){return this.drawShape(new ct(t,e,i,r),n),this}circle(t,e,i,r){return this.drawShape(new Nr(t,e,i),r),this}poly(t,e,i){const r=new ji(t);return r.closePath=e,this.drawShape(r,i),this}regularPoly(t,e,i,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,h=[];for(let c=0;c<r;c++){const u=a-c*l;h.push(t+i*Math.cos(u),e+i*Math.sin(u))}return this.poly(h,!0,o),this}roundPoly(t,e,i,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(t,e,i,r,o);const l=i*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const h=-1*Math.PI/2+o,c=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let m=0;m<r;m++){const f=m*c+h,g=t+i*Math.cos(f),y=e+i*Math.sin(f),x=f+Math.PI+u,v=f-Math.PI-u,E=g+n*Math.cos(x),T=y+n*Math.sin(x),C=g+n*Math.cos(v),R=y+n*Math.sin(v);m===0?this.moveTo(E,T):this.lineTo(E,T),this.quadraticCurveTo(g,y,C,R,a)}return this.closePath()}roundShape(t,e,i=!1,r){return t.length<3?this:(i?Vp(this,t,e,r):Wp(this,t,e),this.closePath())}filletRect(t,e,i,r,n){if(n===0)return this.rect(t,e,i,r);const o=Math.min(i,r)/2,a=Math.min(o,Math.max(-o,n)),l=t+i,h=e+r,c=a<0?-a:0,u=Math.abs(a);return this.moveTo(t,e+u).arcTo(t+c,e+c,t+u,e,u).lineTo(l-u,e).arcTo(l-c,e+c,l,e+u,u).lineTo(l,h-u).arcTo(l-c,h-c,t+i-u,h,u).lineTo(t+u,h).arcTo(t+c,h-c,t,h-u,u).closePath()}chamferRect(t,e,i,r,n,o){if(n<=0)return this.rect(t,e,i,r);const a=Math.min(n,Math.min(i,r)/2),l=t+i,h=e+r,c=[t+a,e,l-a,e,l,e+a,l,h-a,l-a,h,t+a,h,t,h-a,t,e+a];for(let u=c.length-1;u>=2;u-=2)c[u]===c[u-2]&&c[u-1]===c[u-3]&&c.splice(u-1,2);return this.poly(c,!0,o)}ellipse(t,e,i,r,n){return this.drawShape(new Fr(t,e,i,r),n),this}roundRect(t,e,i,r,n,o){return this.drawShape(new Hr(t,e,i,r,n),o),this}drawShape(t,e){return this.endPoly(),this.shapePrimitives.push({shape:t,transform:e}),this}startPoly(t,e){let i=this._currentPoly;return i&&this.endPoly(),i=new ji,i.points.push(t,e),this._currentPoly=i,this}endPoly(t=!1){const e=this._currentPoly;return e&&e.points.length>2&&(e.closePath=t,this.shapePrimitives.push({shape:e})),this._currentPoly=null,this}_ensurePoly(t=!0){if(!this._currentPoly&&(this._currentPoly=new ji,t)){const e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let i=e.shape.x,r=e.shape.y;if(e.transform&&!e.transform.isIdentity()){const n=e.transform,o=i;i=n.a*i+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(i,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const t=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let e=0;e<t.instructions.length;e++){const i=t.instructions[e];this[i.action](...i.data)}this.finish()}get bounds(){const t=this._bounds;t.clear();const e=this.shapePrimitives;for(let i=0;i<e.length;i++){const r=e[i],n=r.shape.getBounds(zp);r.transform?t.addRect(n,r.transform):t.addRect(n)}return t}}class Ee{constructor(t,e=!1){this.instructions=[],this.uid=dt("graphicsPath"),this._dirty=!0,this.checkForHoles=e,typeof t=="string"?If(t,this):this.instructions=(t==null?void 0:t.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new $p(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(t,e){return t=t.clone(),this.instructions.push({action:"addPath",data:[t,e]}),this._dirty=!0,this}arc(...t){return this.instructions.push({action:"arc",data:t}),this._dirty=!0,this}arcTo(...t){return this.instructions.push({action:"arcTo",data:t}),this._dirty=!0,this}arcToSvg(...t){return this.instructions.push({action:"arcToSvg",data:t}),this._dirty=!0,this}bezierCurveTo(...t){return this.instructions.push({action:"bezierCurveTo",data:t}),this._dirty=!0,this}bezierCurveToShort(t,e,i,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(mt.shared);let l=0,h=0;if(!o||o.action!=="bezierCurveTo")l=a.x,h=a.y;else{l=o.data[2],h=o.data[3];const c=a.x,u=a.y;l=c+(c-l),h=u+(u-h)}return this.instructions.push({action:"bezierCurveTo",data:[l,h,t,e,i,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...t){return this.instructions.push({action:"ellipse",data:t}),this._dirty=!0,this}lineTo(...t){return this.instructions.push({action:"lineTo",data:t}),this._dirty=!0,this}moveTo(...t){return this.instructions.push({action:"moveTo",data:t}),this}quadraticCurveTo(...t){return this.instructions.push({action:"quadraticCurveTo",data:t}),this._dirty=!0,this}quadraticCurveToShort(t,e,i){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(mt.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,h=n.y;o=l+(l-o),a=h+(h-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,t,e,i]}),this._dirty=!0,this}rect(t,e,i,r,n){return this.instructions.push({action:"rect",data:[t,e,i,r,n]}),this._dirty=!0,this}circle(t,e,i,r){return this.instructions.push({action:"circle",data:[t,e,i,r]}),this._dirty=!0,this}roundRect(...t){return this.instructions.push({action:"roundRect",data:t}),this._dirty=!0,this}poly(...t){return this.instructions.push({action:"poly",data:t}),this._dirty=!0,this}regularPoly(...t){return this.instructions.push({action:"regularPoly",data:t}),this._dirty=!0,this}roundPoly(...t){return this.instructions.push({action:"roundPoly",data:t}),this._dirty=!0,this}roundShape(...t){return this.instructions.push({action:"roundShape",data:t}),this._dirty=!0,this}filletRect(...t){return this.instructions.push({action:"filletRect",data:t}),this._dirty=!0,this}chamferRect(...t){return this.instructions.push({action:"chamferRect",data:t}),this._dirty=!0,this}star(t,e,i,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,h=i*2,c=Math.PI*2/h,u=[];for(let m=0;m<h;m++){const f=m%2?n:r,g=m*c+l;u.push(t+f*Math.cos(g),e+f*Math.sin(g))}return this.poly(u,!0,a),this}clone(t=!1){const e=new Ee;if(e.checkForHoles=this.checkForHoles,!t)e.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const r=this.instructions[i];e.instructions.push({action:r.action,data:r.data.slice()})}return e}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(t){if(t.isIdentity())return this;const e=t.a,i=t.b,r=t.c,n=t.d,o=t.tx,a=t.ty;let l=0,h=0,c=0,u=0,m=0,f=0,g=0,y=0;for(let x=0;x<this.instructions.length;x++){const v=this.instructions[x],E=v.data;switch(v.action){case"moveTo":case"lineTo":l=E[0],h=E[1],E[0]=e*l+r*h+o,E[1]=i*l+n*h+a;break;case"bezierCurveTo":c=E[0],u=E[1],m=E[2],f=E[3],l=E[4],h=E[5],E[0]=e*c+r*u+o,E[1]=i*c+n*u+a,E[2]=e*m+r*f+o,E[3]=i*m+n*f+a,E[4]=e*l+r*h+o,E[5]=i*l+n*h+a;break;case"quadraticCurveTo":c=E[0],u=E[1],l=E[2],h=E[3],E[0]=e*c+r*u+o,E[1]=i*c+n*u+a,E[2]=e*l+r*h+o,E[3]=i*l+n*h+a;break;case"arcToSvg":l=E[5],h=E[6],g=E[0],y=E[1],E[0]=e*g+r*y,E[1]=i*g+n*y,E[5]=e*l+r*h+o,E[6]=i*l+n*h+a;break;case"circle":E[4]=Qi(E[3],t);break;case"rect":E[4]=Qi(E[4],t);break;case"ellipse":E[8]=Qi(E[8],t);break;case"roundRect":E[5]=Qi(E[5],t);break;case"addPath":E[0].transform(t);break;case"poly":E[2]=Qi(E[2],t);break;default:tt("unknown transform action",v.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(t){let e=this.instructions.length-1,i=this.instructions[e];if(!i)return t.x=0,t.y=0,t;for(;i.action==="closePath";){if(e--,e<0)return t.x=0,t.y=0,t;i=this.instructions[e]}switch(i.action){case"moveTo":case"lineTo":t.x=i.data[0],t.y=i.data[1];break;case"quadraticCurveTo":t.x=i.data[2],t.y=i.data[3];break;case"bezierCurveTo":t.x=i.data[4],t.y=i.data[5];break;case"arc":case"arcToSvg":t.x=i.data[5],t.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(t);break}return t}}function Qi(s,t){return s?s.prepend(t):t.clone()}function Tt(s,t,e){const i=s.getAttribute(t);return i?Number(i):e}function jp(s,t){const e=s.querySelectorAll("defs");for(let i=0;i<e.length;i++){const r=e[i];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":t.defs[o.id]=Xp(o);break;case"radialgradient":t.defs[o.id]=Yp();break}}}}function Xp(s){const t=Tt(s,"x1",0),e=Tt(s,"y1",0),i=Tt(s,"x2",1),r=Tt(s,"y2",0),n=s.getAttribute("gradientUnits")||"objectBoundingBox",o=new ue(t,e,i,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<s.children.length;a++){const l=s.children[a],h=Tt(l,"offset",0),c=ut.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(h,c)}return o}function Yp(s){return tt("[SVG Parser] Radial gradients are not yet supported"),new ue(0,0,1,0)}function wl(s){const t=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:""}const Al={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function Rl(s,t){const e=s.getAttribute("style"),i={},r={},n={strokeStyle:i,fillStyle:r,useFill:!1,useStroke:!1};for(const o in Al){const a=s.getAttribute(o);a&&Il(t,n,o,a.trim())}if(e){const o=e.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[h,c]=l.split(":");Al[h]&&Il(t,n,h,c.trim())}}return{strokeStyle:n.useStroke?i:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Il(s,t,e,i){switch(e){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const r=wl(i);t.strokeStyle.fill=s.defs[r]}else t.strokeStyle.color=ut.shared.setValue(i).toNumber();t.useStroke=!0}break;case"stroke-width":t.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const r=wl(i);t.fillStyle.fill=s.defs[r]}else t.fillStyle.color=ut.shared.setValue(i).toNumber();t.useFill=!0}break;case"fill-opacity":t.fillStyle.alpha=Number(i);break;case"stroke-opacity":t.strokeStyle.alpha=Number(i);break;case"opacity":t.fillStyle.alpha=Number(i),t.strokeStyle.alpha=Number(i);break}}function qp(s){if(s.length<=2)return!0;const t=s.map(a=>a.area).sort((a,l)=>l-a),[e,i]=t,r=t[t.length-1],n=e/i,o=i/r;return!(n>3&&o<2)}function Kp(s){return s.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function Zp(s){const t=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;const e=t.map(Number),i=[],r=[];for(let c=0;c<e.length;c+=2)c+1<e.length&&(i.push(e[c]),r.push(e[c+1]));if(i.length===0||r.length===0)return 0;const n=Math.min(...i),o=Math.max(...i),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Pl(s,t){const e=new Ee(s,!1);for(const i of e.instructions)t.instructions.push(i)}function Jp(s,t){if(typeof s=="string"){const o=document.createElement("div");o.innerHTML=s.trim(),s=o.querySelector("svg")}const e={context:t,defs:{},path:new Ee};jp(s,e);const i=s.children,{fillStyle:r,strokeStyle:n}=Rl(s,e);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Ml(a,e,r,n)}return t}function Ml(s,t,e,i){const r=s.children,{fillStyle:n,strokeStyle:o}=Rl(s,t);n&&e?e={...e,...n}:n&&(e=n),o&&i?i={...i,...o}:o&&(i=o);const a=!e&&!i;a&&(e={color:0});let l,h,c,u,m,f,g,y,x,v,E,T,C,R,A,P,F;switch(s.nodeName.toLowerCase()){case"path":{R=s.getAttribute("d");const B=s.getAttribute("fill-rule"),k=Kp(R),O=B==="evenodd",L=k.length>1;if(O&&L){const H=k.map(G=>({path:G,area:Zp(G)}));if(H.sort((G,U)=>U.area-G.area),k.length>3||!qp(H))for(let G=0;G<H.length;G++){const U=H[G],X=G===0;t.context.beginPath();const D=new Ee(void 0,!0);Pl(U.path,D),t.context.path(D),X?(e&&t.context.fill(e),i&&t.context.stroke(i)):t.context.cut()}else for(let G=0;G<H.length;G++){const U=H[G],X=G%2===1;t.context.beginPath();const D=new Ee(void 0,!0);Pl(U.path,D),t.context.path(D),X?t.context.cut():(e&&t.context.fill(e),i&&t.context.stroke(i))}}else{const H=B?B==="evenodd":!0;A=new Ee(R,H),t.context.path(A),e&&t.context.fill(e),i&&t.context.stroke(i)}break}case"circle":g=Tt(s,"cx",0),y=Tt(s,"cy",0),x=Tt(s,"r",0),t.context.ellipse(g,y,x,x),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"rect":l=Tt(s,"x",0),h=Tt(s,"y",0),P=Tt(s,"width",0),F=Tt(s,"height",0),v=Tt(s,"rx",0),E=Tt(s,"ry",0),v||E?t.context.roundRect(l,h,P,F,v||E):t.context.rect(l,h,P,F),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"ellipse":g=Tt(s,"cx",0),y=Tt(s,"cy",0),v=Tt(s,"rx",0),E=Tt(s,"ry",0),t.context.beginPath(),t.context.ellipse(g,y,v,E),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"line":c=Tt(s,"x1",0),u=Tt(s,"y1",0),m=Tt(s,"x2",0),f=Tt(s,"y2",0),t.context.beginPath(),t.context.moveTo(c,u),t.context.lineTo(m,f),i&&t.context.stroke(i);break;case"polygon":C=s.getAttribute("points"),T=C.match(/-?\d+/g).map(B=>parseInt(B,10)),t.context.poly(T,!0),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"polyline":C=s.getAttribute("points"),T=C.match(/-?\d+/g).map(B=>parseInt(B,10)),t.context.poly(T,!1),i&&t.context.stroke(i);break;case"g":case"svg":break;default:{tt(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}a&&(e=null);for(let B=0;B<r.length;B++)Ml(r[B],t,e,i)}const kl={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class ts{constructor(t,e){this.uid=dt("fillPattern"),this._tick=0,this.transform=new W,this.texture=t,this.transform.scale(1/t.frame.width,1/t.frame.height),e&&(t.source.style.addressModeU=kl[e].addressModeU,t.source.style.addressModeV=kl[e].addressModeV)}setTransform(t){const e=this.texture;this.transform.copyFrom(t),this.transform.invert(),this.transform.scale(1/e.frame.width,1/e.frame.height),this._tick++}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture=t,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function Qp(s){return ut.isColorLike(s)}function Bl(s){return s instanceof ts}function Ol(s){return s instanceof ue}function tm(s){return s instanceof $}function em(s,t,e){const i=ut.shared.setValue(t??0);return s.color=i.toNumber(),s.alpha=i.alpha===1?e.alpha:i.alpha,s.texture=$.WHITE,{...e,...s}}function im(s,t,e){return s.texture=t,{...e,...s}}function Dl(s,t,e){return s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,{...e,...s}}function Gl(s,t,e){return t.buildGradient(),s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,s.textureSpace=t.textureSpace,{...e,...s}}function sm(s,t){const e={...t,...s},i=ut.shared.setValue(e.color);return e.alpha*=i.alpha,e.color=i.toNumber(),e}function Ke(s,t){if(s==null)return null;const e={},i=s;return Qp(s)?em(e,s,t):tm(s)?im(e,s,t):Bl(s)?Dl(e,s,t):Ol(s)?Gl(e,s,t):i.fill&&Bl(i.fill)?Dl(i,i.fill,t):i.fill&&Ol(i.fill)?Gl(i,i.fill,t):sm(i,t)}function Ms(s,t){const{width:e,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=t,h=Ke(s,l);return h?{width:e,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...h}:null}function rm(s,t){let e=1;const i=s.shapePath.shapePrimitives;for(let r=0;r<i.length;r++){const n=i[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let h=0;h<a;h+=2){if(!l&&(h===0||h===a-2))continue;const c=(h-2+a)%a,u=(h+2)%a,m=o[c],f=o[c+1],g=o[h],y=o[h+1],x=o[u],v=o[u+1],E=m-g,T=f-y,C=x-g,R=v-y,A=E*E+T*T,P=C*C+R*R;if(A<1e-12||P<1e-12)continue;let k=(E*C+T*R)/Math.sqrt(A*P);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const L=Math.min(1/O,t);L>e&&(e=L)}}return e}const nm=new mt,Ul=new W,ln=class me extends Zt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Ee,this._transform=new W,this._fillStyle={...me.defaultFillStyle},this._strokeStyle={...me.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Lt,this._boundsDirty=!0}clone(){const t=new me;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=Ke(t,me.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=Ms(t,me.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=Ke(t,me.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=Ke(t,me.defaultStrokeStyle),this}texture(t,e,i,r,n,o){return this.instructions.push({action:"texture",data:{image:t,dx:i||0,dy:r||0,dw:n||t.frame.width,dh:o||t.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:e||e===0?ut.shared.setValue(e).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Ee,this}fill(t,e){let i;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?i=r.data.path:i=this._activePath.clone(),i?(t!=null&&(e!==void 0&&typeof t=="number"&&(K(vt,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),t={color:t,alpha:e}),this._fillStyle=Ke(t,me.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:t,y:e}=this._activePath.getLastPoint(mt.shared);this._activePath.clear(),this._activePath.moveTo(t,e)}stroke(t){let e;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?e=i.data.path:e=this._activePath.clone(),e?(t!=null&&(this._strokeStyle=Ms(t,me.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:e}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let t=0;t<2;t++){const e=this.instructions[this.instructions.length-1-t],i=this._activePath.clone();if(e&&(e.action==="stroke"||e.action==="fill"))if(e.data.hole)e.data.hole.addPath(i);else{e.data.hole=i;break}}return this._initNextPathLocation(),this}arc(t,e,i,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*t+a.c*e+a.tx,a.b*t+a.d*e+a.ty,i,r,n,o),this}arcTo(t,e,i,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*t+o.c*e+o.tx,o.b*t+o.d*e+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}arcToSvg(t,e,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(t,e,i,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(t,e,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*i+l.c*r+l.tx,l.b*i+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var t;return this._tick++,(t=this._activePath)==null||t.closePath(),this}ellipse(t,e,i,r){return this._tick++,this._activePath.ellipse(t,e,i,r,this._transform.clone()),this}circle(t,e,i){return this._tick++,this._activePath.circle(t,e,i,this._transform.clone()),this}path(t){return this._tick++,this._activePath.addPath(t,this._transform.clone()),this}lineTo(t,e){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*t+i.c*e+i.tx,i.b*t+i.d*e+i.ty),this}moveTo(t,e){this._tick++;const i=this._transform,r=this._activePath.instructions,n=i.a*t+i.c*e+i.tx,o=i.b*t+i.d*e+i.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(t,e,i,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*t+o.c*e+o.tx,o.b*t+o.d*e+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}rect(t,e,i,r){return this._tick++,this._activePath.rect(t,e,i,r,this._transform.clone()),this}roundRect(t,e,i,r,n){return this._tick++,this._activePath.roundRect(t,e,i,r,n,this._transform.clone()),this}poly(t,e){return this._tick++,this._activePath.poly(t,e,this._transform.clone()),this}regularPoly(t,e,i,r,n=0,o){return this._tick++,this._activePath.regularPoly(t,e,i,r,n,o),this}roundPoly(t,e,i,r,n,o){return this._tick++,this._activePath.roundPoly(t,e,i,r,n,o),this}roundShape(t,e,i,r){return this._tick++,this._activePath.roundShape(t,e,i,r),this}filletRect(t,e,i,r,n){return this._tick++,this._activePath.filletRect(t,e,i,r,n),this}chamferRect(t,e,i,r,n,o){return this._tick++,this._activePath.chamferRect(t,e,i,r,n,o),this}star(t,e,i,r,n=0,o=0){return this._tick++,this._activePath.star(t,e,i,r,n,o,this._transform.clone()),this}svg(t){return this._tick++,Jp(t,this),this}restore(){const t=this._stateStack.pop();return t&&(this._transform=t.transform,this._fillStyle=t.fillStyle,this._strokeStyle=t.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(t){return this._transform.rotate(t),this}scale(t,e=t){return this._transform.scale(t,e),this}setTransform(t,e,i,r,n,o){return t instanceof W?(this._transform.set(t.a,t.b,t.c,t.d,t.tx,t.ty),this):(this._transform.set(t,e,i,r,n,o),this)}transform(t,e,i,r,n,o){return t instanceof W?(this._transform.append(t),this):(Ul.set(t,e,i,r,n,o),this._transform.append(Ul),this)}translate(t,e=t){return this._transform.translate(t,e),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const t=this._bounds;t.clear();for(let e=0;e<this.instructions.length;e++){const i=this.instructions[e],r=i.action;if(r==="fill"){const n=i.data;t.addBounds(n.path.bounds)}else if(r==="texture"){const n=i.data;t.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=i.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=rm(n.path,n.style.miterLimit));const l=n.path.bounds;t.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return t.isValid||t.set(0,0,0,0),t}containsPoint(t){var r;if(!this.bounds.containsPoint(t.x,t.y))return!1;const e=this.instructions;let i=!1;for(let n=0;n<e.length;n++){const o=e[n],a=o.data,l=a.path;if(!o.action||!l)continue;const h=a.style,c=l.shapePath.shapePrimitives;for(let u=0;u<c.length;u++){const m=c[u].shape;if(!h||!m)continue;const f=c[u].transform,g=f?f.applyInverse(t,nm):t;if(o.action==="fill")i=m.contains(g.x,g.y);else{const x=h;i=m.strokeContains(g.x,g.y,x.width,x.alignment)}const y=a.hole;if(y){const x=(r=y.shapePath)==null?void 0:r.shapePrimitives;if(x)for(let v=0;v<x.length;v++)x[v].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(t=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof t=="boolean"?t:t==null?void 0:t.texture){const i=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};ln.defaultFillStyle={color:16777215,alpha:1,texture:$.WHITE,matrix:null,fill:null,textureSpace:"local"},ln.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:$.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let ie=ln;class Ll{constructor(t){this._attachedDomElements=[],this._renderer=t,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Qo({domElement:this._domElement,renderer:this._renderer})}addRenderable(t,e){this._attachedDomElements.includes(t)||this._attachedDomElements.push(t)}updateRenderable(t){}validateRenderable(t){return!0}postrender(){const t=this._attachedDomElements;if(t.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let e=0;e<t.length;e++){const i=t[e],r=i.element;if(!i.parent||i.globalDisplayStatus<7)r==null||r.remove(),t.splice(e,1),e--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=i.worldTransform,o=i._anchor,a=i.width*o.x,l=i.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=i.groupAlpha.toString()}}}destroy(){var t;this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)(t=this._attachedDomElements[e].element)==null||t.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Ll.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"dom"};class om{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this._tickerAdded||!this.domElement||(Qt.system.add(this._tickerUpdate,this,ui.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Qt.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const t=this.events._rootPointerEvent;this.events.supportsTouchEvents&&t.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,pointerId:t.pointerId}):new MouseEvent("mousemove",{clientX:t.clientX,clientY:t.clientY}))}_tickerUpdate(t){this._deltaTime+=t.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Te=new om;class ks extends Di{constructor(){super(...arguments),this.client=new mt,this.movement=new mt,this.offset=new mt,this.global=new mt,this.screen=new mt}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,r,n,o,a,l,h,c,u,m,f,g,y){throw new Error("Method not implemented.")}}class se extends ks{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class xi extends ks{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}xi.DOM_DELTA_PIXEL=0,xi.DOM_DELTA_LINE=1,xi.DOM_DELTA_PAGE=2;const am=2048,lm=new mt,es=new mt;class hm{constructor(t){this.dispatch=new Zt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((i,r)=>i.priority-r.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,r=e.length;i<r;i++)e[i].fn(t);else tt(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){Te.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,lm.set(t,e),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let r=0,n=i.length-1;r<n;r++)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!(t.propagationStopped||t.propagationImmediatelyStopped)){t.eventPhase=t.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(i.length===0)return;t.eventPhase=t.BUBBLING_PHASE;const r=Array.isArray(e)?e:[e];for(let n=i.length-1;n>=0;n--)r.forEach(o=>{t.currentTarget=i[n],this.notifyTarget(t,o)})}propagationPath(t){const e=[t];for(let i=0;i<am&&t!==this.rootTarget&&t.parent;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,r,n,o=!1){let a=!1;if(this._interactivePrune(t))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(Te.pauseUpdate=!1),t.interactiveChildren&&t.children){const c=t.children;for(let u=c.length-1;u>=0;u--){const m=c[u],f=this.hitTestMoveRecursive(m,this._isInteractive(e)?e:m.eventMode,i,r,n,o||n(t,i));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const g=t.isInteractive();(f.length>0||g)&&(g&&this._allInteractiveElements.push(t),f.push(t)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(e),h=t.isInteractive();return h&&h&&this._allInteractiveElements.push(t),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(t,i)&&r(t,i)?h?[t]:[]:null}hitTestRecursive(t,e,i,r,n){if(this._interactivePrune(t)||n(t,i))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(Te.pauseUpdate=!1),t.interactiveChildren&&t.children){const l=t.children,h=i;for(let c=l.length-1;c>=0;c--){const u=l[c],m=this.hitTestRecursive(u,this._isInteractive(e)?e:u.eventMode,h,r,n);if(m){if(m.length>0&&!m[m.length-1].parent)continue;const f=t.isInteractive();return(m.length>0||f)&&m.push(t),m}}}const o=this._isInteractive(e),a=t.isInteractive();return o&&r(t,i)?a?[t]:[]:null}_isInteractive(t){return t==="static"||t==="dynamic"}_interactivePrune(t){return!t||!t.visible||!t.renderable||!t.measurable||t.eventMode==="none"||t.eventMode==="passive"&&!t.interactiveChildren}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,es),!t.hitArea.contains(es.x,es.y)))return!0;if(t.effects&&t.effects.length)for(let i=0;i<t.effects.length;i++){const r=t.effects[i];if(r.containsPoint&&!r.containsPoint(e,this.hitTestFn))return!0}return!1}hitTestFn(t,e){return t.hitArea?!0:t!=null&&t.containsPoint?(t.worldTransform.applyInverse(e,es),t.containsPoint(es)):!1}notifyTarget(t,e){var n,o;if(!t.currentTarget.isInteractive())return;e??(e=t.type);const i=`on${e}`;(o=(n=t.currentTarget)[i])==null||o.call(n,t);const r=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this._notifyListeners(t,r),t.eventPhase===t.AT_TARGET&&this._notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),e.pointerType==="touch")this.dispatchEvent(e,"touchstart");else if(e.pointerType==="mouse"||e.pointerType==="pen"){const r=e.button===2;this.dispatchEvent(e,r?"rightdown":"mousedown")}const i=this.trackingData(t.pointerId);i.pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){var l,h;if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i=e.pointerType==="mouse"||e.pointerType==="pen",r=this.trackingData(t.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==e.target){const c=t.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(t,c,n);if(this.dispatchEvent(u,"pointerout"),i&&this.dispatchEvent(u,"mouseout"),!e.composedPath().includes(n)){const m=this.createPointerEvent(t,"pointerleave",n);for(m.eventPhase=m.AT_TARGET;m.target&&!e.composedPath().includes(m.target);)m.currentTarget=m.target,this.notifyTarget(m),i&&this.notifyTarget(m,"mouseleave"),m.target=m.target.parent;this.freeEvent(m)}this.freeEvent(u)}if(n!==e.target){const c=t.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(e,c);this.dispatchEvent(u,"pointerover"),i&&this.dispatchEvent(u,"mouseover");let m=n==null?void 0:n.parent;for(;m&&m!==this.rootTarget.parent&&m!==e.target;)m=m.parent;if(!m||m===this.rootTarget.parent){const g=this.clonePointerEvent(e,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),i&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(e,"pointermove"),a&&o.push("globalpointermove"),e.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),a&&o.push("globaltouchmove")),i&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(h=e.target)==null?void 0:h.cursor),o.length>0&&this.all(e,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){var o;if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),r=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=(o=i.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(i,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(n)}mapPointerOut(t){if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId);if(e.overTargets){const i=t.pointerType==="mouse"||t.pointerType==="pen",r=this.findMountedTarget(e.overTargets),n=this.createPointerEvent(t,"pointerout",r);this.dispatchEvent(n),i&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(t,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),i&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;e.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(t){if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const r=this.trackingData(t.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[t.button]);let o=n;if(n&&!i.composedPath().includes(n)){let a=n;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const l=i.button===2;this.notifyTarget(i,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[t.button],o=a}if(o){const a=this.clonePointerEvent(i,"click");a.target=o,a.path=null,r.clicksByButton[t.button]||(r.clicksByButton[t.button]={clickCount:0,target:a.target,timeStamp:e});const l=r.clicksByButton[t.button];if(l.target===a.target&&e-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=e,a.detail=l.clickCount,a.pointerType==="mouse"){const h=a.button===2;this.dispatchEvent(a,h?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof se)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),r=this.createPointerEvent(t);if(i){let n=i;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(r)}mapWheel(t){if(!(t instanceof xi)){tt("EventBoundary cannot map a non-wheel event as a wheel event");return}const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const r=this.allocateEvent(se);return this.copyPointerData(t,r),this.copyMouseData(t,r),this.copyData(t,r),r.nativeEvent=t.nativeEvent,r.originalEvent=t,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof e=="string"&&(r.type=e),r}createWheelEvent(t){const e=this.allocateEvent(xi);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(se);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof se&&e instanceof se&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof ks&&e instanceof ks&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.defaultPrevented=!1,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}_notifyListeners(t,e){const i=t.currentTarget._events[e];if(i)if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let r=0,n=i.length;r<n&&!t.propagationImmediatelyStopped;r++)i[r].once&&t.currentTarget.removeListener(e,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,t)}}const cm=1,um={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},hn=class io{constructor(t){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=t,this.rootBoundary=new hm(null),Te.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new se(null),this._rootWheelEvent=new xi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...io.defaultEventFeatures},{set:(e,i,r)=>(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),e[i]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(t){const{canvas:e,resolution:i}=this.renderer;this.setTargetElement(e),this.resolution=i,io._defaultEventMode=t.eventMode??"passive",Object.assign(this.features,t.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){Te.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(t){t||(t="default");let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this._currentCursor===t)return;this._currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i);break}else e&&typeof t=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this._rootPointerEvent}_onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,r=e.length;i<r;i++){const n=e[i],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Te.pointerMoved();const e=this._normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,e[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",r=this._normalizeToPointerData(t);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=i,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,e[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this._removeEvents(),this.domElement=t,Te.domElement=t,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Te.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Te.removeTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(t,e,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;t.x=(e-r.left)*(this.domElement.width/r.width)*n,t.y=(i-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,r=t.changedTouches.length;i<r;i++){const n=t.changedTouches[i];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=t.touches.length===1&&t.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=t.type,n.altKey??(n.altKey=t.altKey),n.ctrlKey??(n.ctrlKey=t.ctrlKey),n.metaKey??(n.metaKey=t.metaKey),n.shiftKey??(n.shiftKey=t.shiftKey),e.push(n)}else if(!globalThis.MouseEvent||t instanceof MouseEvent&&(!this.supportsPointerEvents||!(t instanceof globalThis.PointerEvent))){const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=cm),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}else e.push(t);return e}normalizeWheelEvent(t){const e=this._rootWheelEvent;return this._transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}_bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this._transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,t.type==="pointerleave"&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=um[t.type]||t.type),t}_transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};hn.extension={name:"events",type:[w.WebGLSystem,w.CanvasSystem,w.WebGPUSystem],priority:-1},hn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Nl=hn;const dm={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Nl.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,t,e){const i=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,r=typeof e=="object"?e.signal:void 0,n=typeof e=="object"?e.once===!0:!1,o=typeof t=="function"?void 0:t;s=i?`${s}capture`:s;const a=typeof t=="function"?t:t.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(s,a,o)}),n?l.once(s,a,o):l.on(s,a,o)},removeEventListener(s,t,e){const i=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,r=typeof t=="function"?void 0:t;s=i?`${s}capture`:s,t=typeof t=="function"?t:t.handleEvent,this.off(s,t,r)},dispatchEvent(s){if(!(s instanceof Di))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var fm=`in vec2 aPosition;
|
|
251
|
+
`}},Yl={};function Kl(s){let e=Yl[s];if(e)return e;const t=new Int32Array(s);for(let i=0;i<s;i++)t[i]=i;return e=Yl[s]=new _t({uTextures:{value:t,type:"i32",size:s}},{isStatic:!0}),e}class ql extends It{constructor(e){const t=In({name:"batch",bits:[$l,Xl(e),Pn]}),i=wn({name:"batch",bits:[zl,jl(e),Mn]});super({glProgram:t,gpuProgram:i,resources:{batchSamplers:Kl(e)}}),this.maxTextures=e}}let ps=null;const Zl=class Bd extends lm{constructor(e){super(e),this.geometry=new fm,this.name=Bd.extension.name,this.vertexSize=6,ps??(ps=new ql(e.maxTextures)),this.shader=ps}packAttributes(e,t,i,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,{positions:g,uvs:_}=e,y=e.color,x=e.attributeOffset,v=x+e.attributeSize;for(let C=x;C<v;C++){const T=C*2,A=g[T],w=g[T+1];t[r++]=l*A+h*w+p,t[r++]=u*w+c*A+d,t[r++]=_[T],t[r++]=_[T+1],i[r++]=y,i[r++]=o}}packQuadAttributes(e,t,i,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,g=e.bounds,_=g.maxX,y=g.minX,x=g.maxY,v=g.minY,C=o.uvs,T=e.color,A=n<<16|e.roundPixels&65535;t[r+0]=l*y+h*v+p,t[r+1]=u*v+c*y+d,t[r+2]=C.x0,t[r+3]=C.y0,i[r+4]=T,i[r+5]=A,t[r+6]=l*_+h*v+p,t[r+7]=u*v+c*_+d,t[r+8]=C.x1,t[r+9]=C.y1,i[r+10]=T,i[r+11]=A,t[r+12]=l*_+h*x+p,t[r+13]=u*x+c*_+d,t[r+14]=C.x2,t[r+15]=C.y2,i[r+16]=T,i[r+17]=A,t[r+18]=l*y+h*x+p,t[r+19]=u*x+c*y+d,t[r+20]=C.x3,t[r+21]=C.y3,i[r+22]=T,i[r+23]=A}_updateMaxTextures(e){this.shader.maxTextures!==e&&(ps=new ql(e),this.shader=ps)}destroy(){this.shader=null,super.destroy()}};Zl.extension={type:[I.Batcher],name:"default"};let kn=Zl;class bt{constructor(e){this.items=Object.create(null);const{renderer:t,type:i,onUnload:r,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",i,n??0),this._onUnload=r,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var r;if(!this.items[e.uid])return;const i=e._gpuData[this._renderer.uid];i&&((r=this._onUnload)==null||r.call(this,e,...t),i.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function Pm(s,e,t,i,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,p=a.d,d=a.tx,g=a.ty;for(;l<o;){const _=s[t],y=s[t+1];i[r]=c*_+u*y+d,i[r+1]=h*_+p*y+g,r+=n,t+=e,l++}}function km(s,e,t,i){let r=0;for(e*=t;r<i;)s[e]=0,s[e+1]=0,e+=t,r++}function Jl(s,e,t,i,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),i||(i=2),r||(r=s.length/i-t);let u=t*i;for(let p=0;p<r;p++){const d=s[u],g=s[u+1];s[u]=n*d+a*g+c,s[u+1]=o*d+l*g+h,u+=i}}const Bm=new Y;class Bn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,i=this.renderable;return i?vi(t,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||Bm}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const ms={extension:{type:I.ShapeBuilder,name:"circle"},build(s,e){let t,i,r,n,o,a;if(s.type==="circle"){const T=s;if(o=a=T.radius,o<=0)return!1;t=T.x,i=T.y,r=n=0}else if(s.type==="ellipse"){const T=s;if(o=T.halfWidth,a=T.halfHeight,o<=0||a<=0)return!1;t=T.x,i=T.y,r=n=0}else{const T=s,A=T.width/2,w=T.height/2;t=T.x+A,i=T.y+w,o=a=Math.max(0,Math.min(T.radius,Math.min(A,w))),r=A-o,n=w-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=i+n,e[2]=e[4]=t-r,e[5]=e[7]=i-n,!0;let h=0,u=l*4+(r?2:0)+2,p=u,d=c,g=r+o,_=n,y=t+g,x=t-g,v=i+_;if(e[h++]=y,e[h++]=v,e[--u]=v,e[--u]=x,n){const T=i-_;e[p++]=x,e[p++]=T,e[--d]=T,e[--d]=y}for(let T=1;T<l;T++){const A=Math.PI/2*(T/l),w=r+Math.cos(A)*o,R=n+Math.sin(A)*a,D=t+w,B=t-w,k=i+R,O=i-R;e[h++]=D,e[h++]=k,e[--u]=k,e[--u]=B,e[p++]=B,e[p++]=O,e[--d]=O,e[--d]=D}g=r,_=n+a,y=t+g,x=t-g,v=i+_;const C=i-_;return e[h++]=y,e[h++]=v,e[--d]=C,e[--d]=y,r&&(e[h++]=x,e[h++]=v,e[--d]=C,e[--d]=x),!0},triangulate(s,e,t,i,r,n){if(s.length===0)return;let o=0,a=0;for(let h=0;h<s.length;h+=2)o+=s[h],a+=s[h+1];o/=s.length/2,a/=s.length/2;let l=i;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<s.length;h+=2)e[l*t]=s[h],e[l*t+1]=s[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},Om={...ms,extension:{...ms.extension,name:"ellipse"}},Dm={...ms,extension:{...ms.extension,name:"roundedRectangle"}},Ql=1e-4,ec=1e-4;function Nm(s){const e=s.length;if(e<6)return 1;let t=0;for(let i=0,r=s[e-2],n=s[e-1];i<e;i+=2){const o=s[i],a=s[i+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function tc(s,e,t,i,r,n,o,a){const l=s-t*r,c=e-i*r,h=s+t*n,u=e+i*n;let p,d;o?(p=i,d=-t):(p=-i,d=t);const g=l+p,_=c+d,y=h+p,x=u+d;return a.push(g,_),a.push(y,x),2}function ai(s,e,t,i,r,n,o,a){const l=t-s,c=i-e;let h=Math.atan2(l,c),u=Math.atan2(r-s,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let p=h;const d=u-h,g=Math.abs(d),_=Math.sqrt(l*l+c*c),y=(15*g*Math.sqrt(_)/Math.PI>>0)+1,x=d/y;if(p+=x,a){o.push(s,e),o.push(t,i);for(let v=1,C=p;v<y;v++,C+=x)o.push(s,e),o.push(s+Math.sin(C)*_,e+Math.cos(C)*_);o.push(s,e),o.push(r,n)}else{o.push(t,i),o.push(s,e);for(let v=1,C=p;v<y;v++,C+=x)o.push(s+Math.sin(C)*_,e+Math.cos(C)*_),o.push(s,e);o.push(r,n),o.push(s,e)}return y*2}function ic(s,e,t,i,r,n){const o=Ql;if(s.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let N=Nm(s);l=(l-.5)*N+.5}const c=new Ce(s[0],s[1]),h=new Ce(s[s.length-2],s[s.length-1]),u=i,p=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){s=s.slice(),p&&(s.pop(),s.pop(),h.set(s[s.length-2],s[s.length-1]));const N=(c.x+h.x)*.5,V=(h.y+c.y)*.5;s.unshift(N,V),s.push(N,V)}const d=r,g=s.length/2;let _=s.length;const y=d.length/2,x=a.width/2,v=x*x,C=a.miterLimit*a.miterLimit;let T=s[0],A=s[1],w=s[2],R=s[3],D=0,B=0,k=-(A-R),O=T-w,G=0,U=0,W=Math.sqrt(k*k+O*O);k/=W,O/=W,k*=x,O*=x;const te=l,F=(1-te)*2,L=te*2;u||(a.cap==="round"?_+=ai(T-k*(F-L)*.5,A-O*(F-L)*.5,T-k*F,A-O*F,T+k*L,A+O*L,d,!0)+2:a.cap==="square"&&(_+=tc(T,A,k,O,F,L,!0,d))),d.push(T-k*F,A-O*F),d.push(T+k*L,A+O*L);for(let N=1;N<g-1;++N){T=s[(N-1)*2],A=s[(N-1)*2+1],w=s[N*2],R=s[N*2+1],D=s[(N+1)*2],B=s[(N+1)*2+1],k=-(A-R),O=T-w,W=Math.sqrt(k*k+O*O),k/=W,O/=W,k*=x,O*=x,G=-(R-B),U=w-D,W=Math.sqrt(G*G+U*U),G/=W,U/=W,G*=x,U*=x;const V=w-T,K=A-R,H=w-D,$=B-R,se=V*H+K*$,ue=K*H-$*V,z=ue<0;if(Math.abs(ue)<.001*Math.abs(se)){d.push(w-k*F,R-O*F),d.push(w+k*L,R+O*L),se>=0&&(a.join==="round"?_+=ai(w,R,w-k*F,R-O*F,w-G*F,R-U*F,d,!1)+4:_+=2,d.push(w-G*L,R-U*L),d.push(w+G*F,R+U*F));continue}const Q=(-k+T)*(-O+R)-(-k+w)*(-O+A),ae=(-G+D)*(-U+R)-(-G+w)*(-U+B),j=(V*ae-H*Q)/ue,_e=($*Q-K*ae)/ue,ee=(j-w)*(j-w)+(_e-R)*(_e-R),le=w+(j-w)*F,Re=R+(_e-R)*F,pe=w-(j-w)*L,Ve=R-(_e-R)*L,Jt=Math.min(V*V+K*K,H*H+$*$),St=z?F:L,fi=Jt+St*St*v;ee<=fi?a.join==="bevel"||ee/v>C?(z?(d.push(le,Re),d.push(w+k*L,R+O*L),d.push(le,Re),d.push(w+G*L,R+U*L)):(d.push(w-k*F,R-O*F),d.push(pe,Ve),d.push(w-G*F,R-U*F),d.push(pe,Ve)),_+=2):a.join==="round"?z?(d.push(le,Re),d.push(w+k*L,R+O*L),_+=ai(w,R,w+k*L,R+O*L,w+G*L,R+U*L,d,!0)+4,d.push(le,Re),d.push(w+G*L,R+U*L)):(d.push(w-k*F,R-O*F),d.push(pe,Ve),_+=ai(w,R,w-k*F,R-O*F,w-G*F,R-U*F,d,!1)+4,d.push(w-G*F,R-U*F),d.push(pe,Ve)):(d.push(le,Re),d.push(pe,Ve)):(d.push(w-k*F,R-O*F),d.push(w+k*L,R+O*L),a.join==="round"?z?_+=ai(w,R,w+k*L,R+O*L,w+G*L,R+U*L,d,!0)+2:_+=ai(w,R,w-k*F,R-O*F,w-G*F,R-U*F,d,!1)+2:a.join==="miter"&&ee/v<=C&&(z?(d.push(pe,Ve),d.push(pe,Ve)):(d.push(le,Re),d.push(le,Re)),_+=2),d.push(w-G*F,R-U*F),d.push(w+G*L,R+U*L),_+=2)}T=s[(g-2)*2],A=s[(g-2)*2+1],w=s[(g-1)*2],R=s[(g-1)*2+1],k=-(A-R),O=T-w,W=Math.sqrt(k*k+O*O),k/=W,O/=W,k*=x,O*=x,d.push(w-k*F,R-O*F),d.push(w+k*L,R+O*L),u||(a.cap==="round"?_+=ai(w-k*(F-L)*.5,R-O*(F-L)*.5,w-k*F,R-O*F,w+k*L,R+O*L,d,!1)+2:a.cap==="square"&&(_+=tc(w,R,k,O,F,L,!1,d)));const X=ec*ec;for(let N=y;N<_+y-2;++N)T=d[N*2],A=d[N*2+1],w=d[(N+1)*2],R=d[(N+1)*2+1],D=d[(N+2)*2],B=d[(N+2)*2+1],!(Math.abs(T*(R-B)+w*(B-A)+D*(A-R))<X)&&n.push(N,N+1,N+2)}function Fm(s,e,t,i){const r=Ql;if(s.length===0)return;const n=s[0],o=s[1],a=s[s.length-2],l=s[s.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=s.length/2,p=h.length/2;for(let d=0;d<u;d++)h.push(s[d*2]),h.push(s[d*2+1]);for(let d=0;d<u-1;d++)i.push(p+d,p+d+1);c&&i.push(p+u-1,p)}function sc(s,e,t,i,r,n,o){const a=Vp(s,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*i;for(let c=0;c<s.length;c+=2)t[l]=s[c],t[l+1]=s[c+1],l+=i}const Gm=[],Lm={extension:{type:I.ShapeBuilder,name:"polygon"},build(s,e){for(let t=0;t<s.points.length;t++)e[t]=s.points[t];return!0},triangulate(s,e,t,i,r,n){sc(s,Gm,e,t,i,r,n)}},Um={extension:{type:I.ShapeBuilder,name:"rectangle"},build(s,e){const t=s,i=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=i,e[1]=r,e[2]=i+n,e[3]=r,e[4]=i+n,e[5]=r+o,e[6]=i,e[7]=r+o,!0):!1},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[6],e[i+o+1]=s[7],o+=t,e[i+o]=s[4],e[i+o+1]=s[5],o+=t;const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},Wm={extension:{type:I.ShapeBuilder,name:"triangle"},build(s,e){return e[0]=s.x,e[1]=s.y,e[2]=s.x2,e[3]=s.y2,e[4]=s.x3,e[5]=s.y3,!0},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[4],e[i+o+1]=s[5];const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},rc=[{offset:0,color:"white"},{offset:1,color:"black"}],On=class Wo{constructor(...e){this.uid=xe("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=Hm(e);t={...t.type==="radial"?Wo.defaultRadialOptions:Wo.defaultLinearOptions,...Jo(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:be.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:i,y:r}=this.end,n=i-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const y=e;e=i,i=y,n*=-1}if(o<0){const y=t;t=r,r=y,o*=-1}}const l=this.colorStops.length?this.colorStops:rc,c=this._textureSize,{canvas:h,context:u}=oc(c,1),p=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);nc(p,l),u.fillStyle=p,u.fillRect(0,0,c,1),this.texture=new q({source:new Vs({resource:h,addressMode:this._wrapMode})});const d=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),_=new Y;_.scale(d/c,1),_.rotate(g),_.translate(e,t),this.textureSpace==="local"&&_.scale(c,c),this.transform=_}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:rc,t=this._textureSize,{canvas:i,context:r}=oc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,p=l-h,d=t/(h*2),g=(n-u)*d,_=(o-p)*d,y=r.createRadialGradient(g,_,c*d,(a-u)*d,(l-p)*d,h*d);nc(y,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=y,r.translate(g,_),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-_),r.fillRect(0,0,t,t),this.texture=new q({source:new Vs({resource:i,addressMode:this._wrapMode})});const x=new Y;x.scale(1/d,1/d),x.translate(u,p),this.textureSpace==="local"&&x.scale(t,t),this.transform=x}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};On.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},On.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let xt=On;function nc(s,e){for(let t=0;t<e.length;t++){const i=e[t];s.addColorStop(i.offset,i.color)}}function oc(s,e){const t=de.get().createCanvas(s,e),i=t.getContext("2d");return{canvas:t,context:i}}function Hm(s){let e=s[0]??{};return(typeof e=="number"||s[1])&&(J("8.5.2","use options object instead"),e={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??xt.defaultLinearOptions.textureSize}),e}const Vm=new Y,zm=new ye;function ac(s,e,t,i){const r=e.matrix?s.copyFrom(e.matrix).invert():s.identity();if(e.textureSpace==="local"){const o=t.getBounds(zm);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,p=-l*h,d=r.a,g=r.b,_=r.c,y=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*d+p*_+r.tx,r.ty=u*g+p*y+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof xt)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),i&&r.append(Vm.copyFrom(i).invert()),r}const gs={};ie.handleByMap(I.ShapeBuilder,gs),ie.add(Um,Lm,Wm,ms,Om,Dm);const $m=new ye,jm=new Y;function Xm(s,e){const{geometryData:t,batches:i}=e;i.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<s.instructions.length;r++){const n=s.instructions[r];if(n.action==="texture")Ym(n.data,i,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&lc(c.shapePath,l,!0,i,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),lc(a,l,o,i,t)}}}function Ym(s,e,t){const i=[],r=gs.rectangle,n=$m;n.x=s.dx,n.y=s.dy,n.width=s.dw,n.height=s.dh;const o=s.transform;if(!r.build(n,i))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&Jl(i,o),r.triangulate(i,a,2,u,c,h);const p=s.image,d=p.uvs;l.push(d.x0,d.y0,d.x1,d.y1,d.x3,d.y3,d.x2,d.y2);const g=Ue.get(Bn);g.indexOffset=h,g.indexSize=c.length-h,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=s.style,g.alpha=s.alpha,g.texture=p,g.geometryData=t,e.push(g)}function lc(s,e,t,i,r){const{vertices:n,uvs:o,indices:a}=r;s.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],p=gs[l.type];if(!p.build(l,u))return;const d=a.length,g=n.length/2;let _="triangle-list";if(c&&Jl(u,c),t){const C=l.closePath??!0,T=e;T.pixelLine?(Fm(u,C,n,a),_="line-list"):ic(u,T,!1,C,n,a)}else if(h){const C=[],T=u.slice();Km(h).forEach(w=>{C.push(T.length/2),T.push(...w)}),sc(T,C,n,2,g,a,d)}else p.triangulate(u,n,2,g,a,d);const y=o.length/2,x=e.texture;if(x!==q.WHITE){const C=ac(jm,e,l,c);Pm(n,2,g,o,y,2,n.length/2-g,C)}else km(o,y,2,n.length/2-g);const v=Ue.get(Bn);v.indexOffset=d,v.indexSize=a.length-d,v.attributeOffset=g,v.attributeSize=n.length/2-g,v.baseColor=e.color,v.alpha=e.alpha,v.texture=x,v.geometryData=r,v.topology=_,i.push(v)})}function Km(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t].shape,r=[];gs[i.type].build(i,r)&&e.push(r)}return e}class qm{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Ue.return(e)}),this.graphicsData&&Ue.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class Zm{constructor(){this.instructions=new jr}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new kn({maxTextures:t}),this.instructions.reset()}get geometry(){return J(lf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Dn=class Ho{constructor(e){this._renderer=e,this._managedContexts=new bt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){Ho.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??Ho.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],i=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&i.reset(),Xm(e,i);const r=e.batchMode;e.customShader||r==="no-batch"?i.isBatchable=!1:r==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,e.dirty=!1}return i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Ue.get(Zm,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=e._gpuData[this._renderer.uid],{batches:r,geometryData:n}=i;i.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const p=r[u];l.add(p)}l.finish(t.instructions);const c=l.geometry;c.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),c.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const h=l.batches;for(let u=0;u<h.length;u++){const p=h[u];p.bindGroup=Sn(p.textures.textures,p.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new qm;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Dn.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"graphicsContext"},Dn.defaultOptions={bezierSmoothness:.5};let Nn=Dn;const Jm=8,er=11920929e-14,Qm=1;function cc(s,e,t,i,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??Nn.defaultOptions.bezierSmoothness));let p=(Qm-u)/1;return p*=p,eg(e,t,i,r,n,o,a,l,s,p),s}function eg(s,e,t,i,r,n,o,a,l,c){Fn(s,e,t,i,r,n,o,a,l,c,0),l.push(o,a)}function Fn(s,e,t,i,r,n,o,a,l,c,h){if(h>Jm)return;const u=(s+t)/2,p=(e+i)/2,d=(t+r)/2,g=(i+n)/2,_=(r+o)/2,y=(n+a)/2,x=(u+d)/2,v=(p+g)/2,C=(d+_)/2,T=(g+y)/2,A=(x+C)/2,w=(v+T)/2;if(h>0){let R=o-s,D=a-e;const B=Math.abs((t-o)*D-(i-a)*R),k=Math.abs((r-o)*D-(n-a)*R);if(B>er&&k>er){if((B+k)*(B+k)<=c*(R*R+D*D)){l.push(A,w);return}}else if(B>er){if(B*B<=c*(R*R+D*D)){l.push(A,w);return}}else if(k>er){if(k*k<=c*(R*R+D*D)){l.push(A,w);return}}else if(R=A-(s+o)/2,D=w-(e+a)/2,R*R+D*D<=c){l.push(A,w);return}}Fn(s,e,u,p,x,v,A,w,l,c,h+1),Fn(A,w,C,T,_,y,o,a,l,c,h+1)}const tg=8,ig=11920929e-14,sg=1;function rg(s,e,t,i,r,n,o,a){const c=Math.min(.99,Math.max(0,a??Nn.defaultOptions.bezierSmoothness));let h=(sg-c)/1;return h*=h,ng(e,t,i,r,n,o,s,h),s}function ng(s,e,t,i,r,n,o,a){Gn(o,s,e,t,i,r,n,a,0),o.push(r,n)}function Gn(s,e,t,i,r,n,o,a,l){if(l>tg)return;const c=(e+i)/2,h=(t+r)/2,u=(i+n)/2,p=(r+o)/2,d=(c+u)/2,g=(h+p)/2;let _=n-e,y=o-t;const x=Math.abs((i-n)*y-(r-o)*_);if(x>ig){if(x*x<=a*(_*_+y*y)){s.push(d,g);return}}else if(_=d-(e+n)/2,y=g-(t+o)/2,_*_+y*y<=a){s.push(d,g);return}Gn(s,e,t,c,h,d,g,a,l+1),Gn(s,d,g,u,p,n,o,a,l+1)}function hc(s,e,t,i,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const p=Math.cos(h),d=Math.sin(h),g=e+p*i,_=t+d*i;s.push(g,_),h+=c}}function og(s,e,t,i,r,n){const o=s[s.length-2],l=s[s.length-1]-t,c=o-e,h=r-t,u=i-e,p=Math.abs(l*u-c*h);if(p<1e-8||n===0){(s[s.length-2]!==e||s[s.length-1]!==t)&&s.push(e,t);return}const d=l*l+c*c,g=h*h+u*u,_=l*h+c*u,y=n*Math.sqrt(d)/p,x=n*Math.sqrt(g)/p,v=y*_/d,C=x*_/g,T=y*u+x*c,A=y*h+x*l,w=c*(x+v),R=l*(x+v),D=u*(y+C),B=h*(y+C),k=Math.atan2(R-A,w-T),O=Math.atan2(B-A,D-T);hc(s,T+e,A+t,n,k,O,c*h>u*l)}const _s=Math.PI*2,Ln={centerX:0,centerY:0,ang1:0,ang2:0},Un=({x:s,y:e},t,i,r,n,o,a,l)=>{s*=t,e*=i;const c=r*s-n*e,h=n*s+r*e;return l.x=c+o,l.y=h+a,l};function ag(s,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),i=e===1.5707963267948966?.551915024494:t,r=Math.cos(s),n=Math.sin(s),o=Math.cos(s+e),a=Math.sin(s+e);return[{x:r-n*i,y:n+r*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const uc=(s,e,t,i)=>{const r=s*i-e*t<0?-1:1;let n=s*t+e*i;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},lg=(s,e,t,i,r,n,o,a,l,c,h,u,p)=>{const d=Math.pow(r,2),g=Math.pow(n,2),_=Math.pow(h,2),y=Math.pow(u,2);let x=d*g-d*y-g*_;x<0&&(x=0),x/=d*y+g*_,x=Math.sqrt(x)*(o===a?-1:1);const v=x*r/n*u,C=x*-n/r*h,T=c*v-l*C+(s+t)/2,A=l*v+c*C+(e+i)/2,w=(h-v)/r,R=(u-C)/n,D=(-h-v)/r,B=(-u-C)/n,k=uc(1,0,w,R);let O=uc(w,R,D,B);a===0&&O>0&&(O-=_s),a===1&&O<0&&(O+=_s),p.centerX=T,p.centerY=A,p.ang1=k,p.ang2=O};function cg(s,e,t,i,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*_s/360),u=Math.cos(a*_s/360),p=u*(e-i)/2+h*(t-r)/2,d=-h*(e-i)/2+u*(t-r)/2;if(p===0&&d===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(p,2)/Math.pow(n,2)+Math.pow(d,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),lg(e,t,i,r,n,o,l,c,h,u,p,d,Ln);let{ang1:_,ang2:y}=Ln;const{centerX:x,centerY:v}=Ln;let C=Math.abs(y)/(_s/4);Math.abs(1-C)<1e-7&&(C=1);const T=Math.max(Math.ceil(C),1);y/=T;let A=s[s.length-2],w=s[s.length-1];const R={x:0,y:0};for(let D=0;D<T;D++){const B=ag(_,y),{x:k,y:O}=Un(B[0],n,o,u,h,x,v,R),{x:G,y:U}=Un(B[1],n,o,u,h,x,v,R),{x:W,y:te}=Un(B[2],n,o,u,h,x,v,R);cc(s,A,w,k,O,G,U,W,te),A=W,w=te,_+=y}}function hg(s,e,t){const i=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,p=c/h;return{len:h,nx:u,ny:p}},r=(o,a)=>{o===0?s.moveTo(a.x,a.y):s.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=i(a,n),u=i(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let p=Math.asin(h.nx*u.ny-h.ny*u.nx),d=1,g=!1;h.nx*u.nx-h.ny*-u.ny<0?p<0?p=Math.PI+p:(p=Math.PI-p,d=-1,g=!0):p>0&&(d=-1,g=!0);const _=p/2;let y,x=Math.abs(Math.cos(_)*l/Math.sin(_));x>Math.min(h.len/2,u.len/2)?(x=Math.min(h.len/2,u.len/2),y=Math.abs(x*Math.sin(_)/Math.cos(_))):y=l;const v=a.x+u.nx*x+-u.ny*y*d,C=a.y+u.ny*x+u.nx*y*d,T=Math.atan2(h.ny,h.nx)+Math.PI/2*d,A=Math.atan2(u.ny,u.nx)-Math.PI/2*d;o===0&&s.moveTo(v+Math.cos(T)*y,C+Math.sin(T)*y),s.arc(v,C,y,T,A,g),n=a}}function ug(s,e,t,i){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?s.moveTo(l.x,l.y):s.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],p=r(h,l);let d;if(p<1e-4)d=l;else{const y=Math.min(p/2,c);d=n(l,h,y/p)}const g=r(u,l);let _;if(g<1e-4)_=l;else{const y=Math.min(g/2,c);_=n(l,u,y/g)}a===0?s.moveTo(d.x,d.y):s.lineTo(d.x,d.y),s.quadraticCurveTo(l.x,l.y,_.x,_.y,i)}}const dg=new ye;class fg{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new je,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const i=this._currentPoly.points,r=i[i.length-2],n=i[i.length-1];return(r!==e||n!==t)&&i.push(e,t),this}arc(e,t,i,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return hc(a,e,t,i,r,n,o),this}arcTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly.points;return og(o,e,t,i,r,n),this}arcToSvg(e,t,i,r,n,o,a){const l=this._currentPoly.points;return cg(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,i,r,n),this}bezierCurveTo(e,t,i,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return cc(this._currentPoly.points,l.lastX,l.lastY,e,t,i,r,n,o,a),this}quadraticCurveTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly;return rg(this._currentPoly.points,o.lastX,o.lastY,e,t,i,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const i=this.shapePrimitives,r=i.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&i.length-r>1){let n=null;for(let o=r;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const l=a.shape,c=n==null?void 0:n.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,i,r,n){return this.drawShape(new ye(e,t,i,r),n),this}circle(e,t,i,r){return this.drawShape(new bn(e,t,i),r),this}poly(e,t,i){const r=new us(e);return r.closePath=t,this.drawShape(r,i),this}regularPoly(e,t,i,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+i*Math.cos(u),t+i*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,i,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,i,r,o);const l=i*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let p=0;p<r;p++){const d=p*h+c,g=e+i*Math.cos(d),_=t+i*Math.sin(d),y=d+Math.PI+u,x=d-Math.PI-u,v=g+n*Math.cos(y),C=_+n*Math.sin(y),T=g+n*Math.cos(x),A=_+n*Math.sin(x);p===0?this.moveTo(v,C):this.lineTo(v,C),this.quadraticCurveTo(g,_,T,A,a)}return this.closePath()}roundShape(e,t,i=!1,r){return e.length<3?this:(i?ug(this,e,t,r):hg(this,e,t),this.closePath())}filletRect(e,t,i,r,n){if(n===0)return this.rect(e,t,i,r);const o=Math.min(i,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+i,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+i-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,i,r,n,o){if(n<=0)return this.rect(e,t,i,r);const a=Math.min(n,Math.min(i,r)/2),l=e+i,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,i,r,n){return this.drawShape(new xn(e,t,i,r),n),this}roundRect(e,t,i,r,n,o){return this.drawShape(new vn(e,t,i,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let i=this._currentPoly;return i&&this.endPoly(),i=new us,i.points.push(e,t),this._currentPoly=i,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new us,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let i=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=i;i=n.a*i+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(i,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const i=e.instructions[t];this[i.action](...i.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let i=0;i<t.length;i++){const r=t[i],n=r.shape.getBounds(dg);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Rt{constructor(e,t=!1){this.instructions=[],this.uid=xe("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Zp(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new fg(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,i,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(Ce.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,i,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,i){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(Ce.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,i]}),this._dirty=!0,this}rect(e,t,i,r,n){return this.instructions.push({action:"rect",data:[e,t,i,r,n]}),this._dirty=!0,this}circle(e,t,i,r){return this.instructions.push({action:"circle",data:[e,t,i,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,i,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=i*2,h=Math.PI*2/c,u=[];for(let p=0;p<c;p++){const d=p%2?n:r,g=p*h+l;u.push(e+d*Math.cos(g),t+d*Math.sin(g))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Rt;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const r=this.instructions[i];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,i=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,p=0,d=0,g=0,_=0;for(let y=0;y<this.instructions.length;y++){const x=this.instructions[y],v=x.data;switch(x.action){case"moveTo":case"lineTo":l=v[0],c=v[1],v[0]=t*l+r*c+o,v[1]=i*l+n*c+a;break;case"bezierCurveTo":h=v[0],u=v[1],p=v[2],d=v[3],l=v[4],c=v[5],v[0]=t*h+r*u+o,v[1]=i*h+n*u+a,v[2]=t*p+r*d+o,v[3]=i*p+n*d+a,v[4]=t*l+r*c+o,v[5]=i*l+n*c+a;break;case"quadraticCurveTo":h=v[0],u=v[1],l=v[2],c=v[3],v[0]=t*h+r*u+o,v[1]=i*h+n*u+a,v[2]=t*l+r*c+o,v[3]=i*l+n*c+a;break;case"arcToSvg":l=v[5],c=v[6],g=v[0],_=v[1],v[0]=t*g+r*_,v[1]=i*g+n*_,v[5]=t*l+r*c+o,v[6]=i*l+n*c+a;break;case"circle":v[4]=ys(v[3],e);break;case"rect":v[4]=ys(v[4],e);break;case"ellipse":v[8]=ys(v[8],e);break;case"roundRect":v[5]=ys(v[5],e);break;case"addPath":v[0].transform(e);break;case"poly":v[2]=ys(v[2],e);break;default:ne("unknown transform action",x.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,i=this.instructions[t];if(!i)return e.x=0,e.y=0,e;for(;i.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;i=this.instructions[t]}switch(i.action){case"moveTo":case"lineTo":e.x=i.data[0],e.y=i.data[1];break;case"quadraticCurveTo":e.x=i.data[2],e.y=i.data[3];break;case"bezierCurveTo":e.x=i.data[4],e.y=i.data[5];break;case"arc":case"arcToSvg":e.x=i.data[5],e.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(e);break}return e}}function ys(s,e){return s?s.prepend(e):e.clone()}function Me(s,e,t){const i=s.getAttribute(e);return i?Number(i):t}function pg(s,e){const t=s.querySelectorAll("defs");for(let i=0;i<t.length;i++){const r=t[i];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=mg(o);break;case"radialgradient":e.defs[o.id]=gg();break}}}}function mg(s){const e=Me(s,"x1",0),t=Me(s,"y1",0),i=Me(s,"x2",1),r=Me(s,"y2",0),n=s.getAttribute("gradientUnits")||"objectBoundingBox",o=new xt(e,t,i,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<s.children.length;a++){const l=s.children[a],c=Me(l,"offset",0),h=be.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function gg(s){return ne("[SVG Parser] Radial gradients are not yet supported"),new xt(0,0,1,0)}function dc(s){const e=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const fc={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function pc(s,e){const t=s.getAttribute("style"),i={},r={},n={strokeStyle:i,fillStyle:r,useFill:!1,useStroke:!1};for(const o in fc){const a=s.getAttribute(o);a&&mc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");fc[c]&&mc(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?i:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function mc(s,e,t,i){switch(t){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const r=dc(i);e.strokeStyle.fill=s.defs[r]}else e.strokeStyle.color=be.shared.setValue(i).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const r=dc(i);e.fillStyle.fill=s.defs[r]}else e.fillStyle.color=be.shared.setValue(i).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(i);break;case"stroke-opacity":e.strokeStyle.alpha=Number(i);break;case"opacity":e.fillStyle.alpha=Number(i),e.strokeStyle.alpha=Number(i);break}}function _g(s){if(s.length<=2)return!0;const e=s.map(a=>a.area).sort((a,l)=>l-a),[t,i]=e,r=e[e.length-1],n=t/i,o=i/r;return!(n>3&&o<2)}function yg(s){return s.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function bg(s){const e=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),i=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(i.push(t[h]),r.push(t[h+1]));if(i.length===0||r.length===0)return 0;const n=Math.min(...i),o=Math.max(...i),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function gc(s,e){const t=new Rt(s,!1);for(const i of t.instructions)e.instructions.push(i)}function xg(s,e){if(typeof s=="string"){const o=document.createElement("div");o.innerHTML=s.trim(),s=o.querySelector("svg")}const t={context:e,defs:{},path:new Rt};pg(s,t);const i=s.children,{fillStyle:r,strokeStyle:n}=pc(s,t);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&_c(a,t,r,n)}return e}function _c(s,e,t,i){const r=s.children,{fillStyle:n,strokeStyle:o}=pc(s,e);n&&t?t={...t,...n}:n&&(t=n),o&&i?i={...i,...o}:o&&(i=o);const a=!t&&!i;a&&(t={color:0});let l,c,h,u,p,d,g,_,y,x,v,C,T,A,w,R,D;switch(s.nodeName.toLowerCase()){case"path":{A=s.getAttribute("d");const B=s.getAttribute("fill-rule"),k=yg(A),O=B==="evenodd",G=k.length>1;if(O&&G){const W=k.map(F=>({path:F,area:bg(F)}));if(W.sort((F,L)=>L.area-F.area),k.length>3||!_g(W))for(let F=0;F<W.length;F++){const L=W[F],X=F===0;e.context.beginPath();const N=new Rt(void 0,!0);gc(L.path,N),e.context.path(N),X?(t&&e.context.fill(t),i&&e.context.stroke(i)):e.context.cut()}else for(let F=0;F<W.length;F++){const L=W[F],X=F%2===1;e.context.beginPath();const N=new Rt(void 0,!0);gc(L.path,N),e.context.path(N),X?e.context.cut():(t&&e.context.fill(t),i&&e.context.stroke(i))}}else{const W=B?B==="evenodd":!0;w=new Rt(A,W),e.context.path(w),t&&e.context.fill(t),i&&e.context.stroke(i)}break}case"circle":g=Me(s,"cx",0),_=Me(s,"cy",0),y=Me(s,"r",0),e.context.ellipse(g,_,y,y),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"rect":l=Me(s,"x",0),c=Me(s,"y",0),R=Me(s,"width",0),D=Me(s,"height",0),x=Me(s,"rx",0),v=Me(s,"ry",0),x||v?e.context.roundRect(l,c,R,D,x||v):e.context.rect(l,c,R,D),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"ellipse":g=Me(s,"cx",0),_=Me(s,"cy",0),x=Me(s,"rx",0),v=Me(s,"ry",0),e.context.beginPath(),e.context.ellipse(g,_,x,v),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"line":h=Me(s,"x1",0),u=Me(s,"y1",0),p=Me(s,"x2",0),d=Me(s,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(p,d),i&&e.context.stroke(i);break;case"polygon":T=s.getAttribute("points"),C=T.match(/-?\d+/g).map(B=>parseInt(B,10)),e.context.poly(C,!0),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"polyline":T=s.getAttribute("points"),C=T.match(/-?\d+/g).map(B=>parseInt(B,10)),e.context.poly(C,!1),i&&e.context.stroke(i);break;case"g":case"svg":break;default:{ne(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}a&&(t=null);for(let B=0;B<r.length;B++)_c(r[B],e,t,i)}const yc={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class bs{constructor(e,t){this.uid=xe("fillPattern"),this._tick=0,this.transform=new Y,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=yc[t].addressModeU,e.source.style.addressModeV=yc[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function vg(s){return be.isColorLike(s)}function bc(s){return s instanceof bs}function xc(s){return s instanceof xt}function Sg(s){return s instanceof q}function Cg(s,e,t){const i=be.shared.setValue(e??0);return s.color=i.toNumber(),s.alpha=i.alpha===1?t.alpha:i.alpha,s.texture=q.WHITE,{...t,...s}}function Tg(s,e,t){return s.texture=e,{...t,...s}}function vc(s,e,t){return s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,{...t,...s}}function Sc(s,e,t){return e.buildGradient(),s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,s.textureSpace=e.textureSpace,{...t,...s}}function Eg(s,e){const t={...e,...s},i=be.shared.setValue(t.color);return t.alpha*=i.alpha,t.color=i.toNumber(),t}function li(s,e){if(s==null)return null;const t={},i=s;return vg(s)?Cg(t,s,e):Sg(s)?Tg(t,s,e):bc(s)?vc(t,s,e):xc(s)?Sc(t,s,e):i.fill&&bc(i.fill)?vc(i,i.fill,e):i.fill&&xc(i.fill)?Sc(i,i.fill,e):Eg(i,e)}function tr(s,e){const{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=li(s,l);return c?{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}function wg(s,e){let t=1;const i=s.shapePath.shapePrimitives;for(let r=0;r<i.length;r++){const n=i[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let c=0;c<a;c+=2){if(!l&&(c===0||c===a-2))continue;const h=(c-2+a)%a,u=(c+2)%a,p=o[h],d=o[h+1],g=o[c],_=o[c+1],y=o[u],x=o[u+1],v=p-g,C=d-_,T=y-g,A=x-_,w=v*v+C*C,R=T*T+A*A;if(w<1e-12||R<1e-12)continue;let k=(v*T+C*A)/Math.sqrt(w*R);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const G=Math.min(1/O,e);G>t&&(t=G)}}return t}const Ig=new Ce,Cc=new Y,Wn=class Ct extends nt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=xe("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Rt,this._transform=new Y,this._fillStyle={...Ct.defaultFillStyle},this._strokeStyle={...Ct.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new je,this._boundsDirty=!0}clone(){const e=new Ct;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=li(e,Ct.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=tr(e,Ct.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=li(e,Ct.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=li(e,Ct.defaultStrokeStyle),this}texture(e,t,i,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:i||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?be.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Rt,this}fill(e,t){let i;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?i=r.data.path:i=this._activePath.clone(),i?(e!=null&&(t!==void 0&&typeof e=="number"&&(J(Ie,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=li(e,Ct.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(Ce.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?t=i.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=tr(e,Ct.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],i=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(i);else{t.data.hole=i;break}}return this._initNextPathLocation(),this}arc(e,t,i,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,i,r,n,o),this}arcTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}arcToSvg(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,i,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*i+l.c*r+l.tx,l.b*i+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,i,r){return this._tick++,this._activePath.ellipse(e,t,i,r,this._transform.clone()),this}circle(e,t,i){return this._tick++,this._activePath.circle(e,t,i,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*e+i.c*t+i.tx,i.b*e+i.d*t+i.ty),this}moveTo(e,t){this._tick++;const i=this._transform,r=this._activePath.instructions,n=i.a*e+i.c*t+i.tx,o=i.b*e+i.d*t+i.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}rect(e,t,i,r){return this._tick++,this._activePath.rect(e,t,i,r,this._transform.clone()),this}roundRect(e,t,i,r,n){return this._tick++,this._activePath.roundRect(e,t,i,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,i,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,i,r,n,o),this}roundPoly(e,t,i,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,i,r,n,o),this}roundShape(e,t,i,r){return this._tick++,this._activePath.roundShape(e,t,i,r),this}filletRect(e,t,i,r,n){return this._tick++,this._activePath.filletRect(e,t,i,r,n),this}chamferRect(e,t,i,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,i,r,n,o),this}star(e,t,i,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,i,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,xg(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,i,r,n,o){return e instanceof Y?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,i,r,n,o),this)}transform(e,t,i,r,n,o){return e instanceof Y?(this._transform.append(e),this):(Cc.set(e,t,i,r,n,o),this._transform.append(Cc),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const i=this.instructions[t],r=i.action;if(r==="fill"){const n=i.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=i.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=i.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=wg(n.path,n.style.miterLimit));const l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){var r;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let i=!1;for(let n=0;n<t.length;n++){const o=t[n],a=o.data,l=a.path;if(!o.action||!l)continue;const c=a.style,h=l.shapePath.shapePrimitives;for(let u=0;u<h.length;u++){const p=h[u].shape;if(!c||!p)continue;const d=h[u].transform,g=d?d.applyInverse(e,Ig):e;if(o.action==="fill")i=p.contains(g.x,g.y);else{const y=c;i=p.strokeContains(g.x,g.y,y.width,y.alignment)}const _=a.hole;if(_){const y=(r=_.shapePath)==null?void 0:r.shapePrimitives;if(y)for(let x=0;x<y.length;x++)y[x].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};Wn.defaultFillStyle={color:16777215,alpha:1,texture:q.WHITE,matrix:null,fill:null,textureSpace:"local"},Wn.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:q.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let ht=Wn;class Tc{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new La({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const i=e[t],r=i.element;if(!i.parent||i.globalDisplayStatus<7)r==null||r.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=i.worldTransform,o=i._anchor,a=i.width*o.x,l=i.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=i.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Tc.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"dom"};class Ag{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(at.system.add(this._tickerUpdate,this,Ci.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(at.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Mt=new Ag;class ir extends es{constructor(){super(...arguments),this.client=new Ce,this.movement=new Ce,this.offset=new Ce,this.global=new Ce,this.screen=new Ce}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,i){return e.worldTransform.applyInverse(i||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,i,r,n,o,a,l,c,h,u,p,d,g,_){throw new Error("Method not implemented.")}}class ut extends ir{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Pi extends ir{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Pi.DOM_DELTA_PIXEL=0,Pi.DOM_DELTA_LINE=1,Pi.DOM_DELTA_PAGE=2;const Rg=2048,Mg=new Ce,xs=new Ce;class Pg{constructor(e){this.dispatch=new nt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((i,r)=>i.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let i=0,r=t.length;i<r;i++)t[i].fn(e);else ne(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Mt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,Mg.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const i=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=i.length-1;r<n;r++)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,i=this._allInteractiveElements){if(i.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=i.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=i[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let i=0;i<Rg&&e!==this.rootTarget&&e.parent;i++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,i,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Mt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const p=h[u],d=this.hitTestMoveRecursive(p,this._isInteractive(t)?t:p.eventMode,i,r,n,o||n(e,i));if(d){if(d.length>0&&!d[d.length-1].parent)continue;const g=e.isInteractive();(d.length>0||g)&&(g&&this._allInteractiveElements.push(e),d.push(e)),this._hitElements.length===0&&(this._hitElements=d),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,i)&&r(e,i)?c?[e]:[]:null}hitTestRecursive(e,t,i,r,n){if(this._interactivePrune(e)||n(e,i))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Mt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=i;for(let h=l.length-1;h>=0;h--){const u=l[h],p=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(p){if(p.length>0&&!p[p.length-1].parent)continue;const d=e.isInteractive();return(p.length>0||d)&&p.push(e),p}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,i)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,xs),!e.hitArea.contains(xs.x,xs.y)))return!0;if(e.effects&&e.effects.length)for(let i=0;i<e.effects.length;i++){const r=e.effects[i];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e!=null&&e.containsPoint?(e.worldTransform.applyInverse(t,xs),e.containsPoint(xs)):!1}notifyTarget(e,t){var n,o;if(!e.currentTarget.isInteractive())return;t??(t=e.type);const i=`on${t}`;(o=(n=e.currentTarget)[i])==null||o.call(n,e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const i=this.trackingData(e.pointerId);i.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){var l,c;if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const i=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==t.target){const h=e.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(e,h,n);if(this.dispatchEvent(u,"pointerout"),i&&this.dispatchEvent(u,"mouseout"),!t.composedPath().includes(n)){const p=this.createPointerEvent(e,"pointerleave",n);for(p.eventPhase=p.AT_TARGET;p.target&&!t.composedPath().includes(p.target);)p.currentTarget=p.target,this.notifyTarget(p),i&&this.notifyTarget(p,"mouseleave"),p.target=p.target.parent;this.freeEvent(p)}this.freeEvent(u)}if(n!==t.target){const h=e.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(t,h);this.dispatchEvent(u,"pointerover"),i&&this.dispatchEvent(u,"mouseover");let p=n==null?void 0:n.parent;for(;p&&p!==this.rootTarget.parent&&p!==t.target;)p=p.parent;if(!p||p===this.rootTarget.parent){const g=this.clonePointerEvent(t,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),i&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),i&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(c=t.target)==null?void 0:c.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){var o;if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.createPointerEvent(e),r=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=(o=i.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(i,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const i=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),i&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),i&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),i=this.createPointerEvent(e);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!i.composedPath().includes(n)){let a=n;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const l=i.button===2;this.notifyTarget(i,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(i,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(e){if(!(e instanceof ut)){ne("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(i){let n=i;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Pi)){ne("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let i=1;i<e.length&&e[i].parent===t;i++)t=e[i];return t}createPointerEvent(e,t,i){const r=this.allocateEvent(ut);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(Pi);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const i=this.allocateEvent(ut);return i.nativeEvent=e.nativeEvent,i.originalEvent=e.originalEvent,this.copyPointerData(e,i),this.copyMouseData(e,i),this.copyData(e,i),i.target=e.target,i.path=e.composedPath().slice(),i.type=t??i.type,i}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof ut&&t instanceof ut&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof ir&&t instanceof ir&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const i=e.currentTarget._events[t];if(i)if("fn"in i)i.once&&e.currentTarget.removeListener(t,i.fn,void 0,!0),i.fn.call(i.context,e);else for(let r=0,n=i.length;r<n&&!e.propagationImmediatelyStopped;r++)i[r].once&&e.currentTarget.removeListener(t,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,e)}}const kg=1,Bg={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Hn=class Vo{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new Pg(null),Mt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new ut(null),this._rootWheelEvent=new Pi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...Vo.defaultEventFeatures},{set:(t,i,r)=>(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[i]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:i}=this.renderer;this.setTargetElement(t),this.resolution=i,Vo._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Mt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const i=this.cursorStyles[e];if(i)switch(typeof i){case"string":t&&(this.domElement.style.cursor=i);break;case"function":i(e);break;case"object":t&&Object.assign(this.domElement.style,i);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let i=0,r=t.length;i<r;i++){const n=t[i],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Mt.pointerMoved();const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const i=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=i,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Mt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Mt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Mt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(i-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let i=0,r=e.changedTouches.length;i<r;i++){const n=e.changedTouches[i];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,n.altKey??(n.altKey=e.altKey),n.ctrlKey??(n.ctrlKey=e.ctrlKey),n.metaKey??(n.metaKey=e.metaKey),n.shiftKey??(n.shiftKey=e.shiftKey),t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const i=e;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=kg),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,t.push(i)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=Bg[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};Hn.extension={name:"events",type:[I.WebGLSystem,I.CanvasSystem,I.WebGPUSystem],priority:-1},Hn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Ec=Hn;const Og={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Ec.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;s=i?`${s}capture`:s;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(s,a,o)}),n?l.once(s,a,o):l.on(s,a,o)},removeEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;s=i?`${s}capture`:s,e=typeof e=="function"?e:e.handleEvent,this.off(s,e,r)},dispatchEvent(s){if(!(s instanceof es))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var Dg=`in vec2 aPosition;
|
|
252
252
|
out vec2 vTextureCoord;
|
|
253
253
|
|
|
254
254
|
uniform vec4 uInputSize;
|
|
@@ -275,13 +275,13 @@ void main(void)
|
|
|
275
275
|
gl_Position = filterVertexPosition();
|
|
276
276
|
vTextureCoord = filterTextureCoord();
|
|
277
277
|
}
|
|
278
|
-
`,
|
|
278
|
+
`,Ng=`in vec2 vTextureCoord;
|
|
279
279
|
out vec4 finalColor;
|
|
280
280
|
uniform sampler2D uTexture;
|
|
281
281
|
void main() {
|
|
282
282
|
finalColor = texture(uTexture, vTextureCoord);
|
|
283
283
|
}
|
|
284
|
-
`,
|
|
284
|
+
`,wc=`struct GlobalFilterUniforms {
|
|
285
285
|
uInputSize: vec4<f32>,
|
|
286
286
|
uInputPixel: vec4<f32>,
|
|
287
287
|
uInputClamp: vec4<f32>,
|
|
@@ -330,7 +330,7 @@ fn mainFragment(
|
|
|
330
330
|
) -> @location(0) vec4<f32> {
|
|
331
331
|
return textureSample(uTexture, uSampler, uv);
|
|
332
332
|
}
|
|
333
|
-
`;class
|
|
333
|
+
`;class Fg extends hl{constructor(){const e=ni.from({vertex:{source:wc,entryPoint:"mainVertex"},fragment:{source:wc,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=Ai.from({vertex:Dg,fragment:Ng,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class Ic{constructor(e){this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}Ic.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"filter"};const Ac=new Y;function Gg(s,e){e.clear();const t=e.matrix;for(let i=0;i<s.length;i++){const r=s[i];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n!=null&&n.isCachedAsTexture?e.matrix=Ac.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n!=null&&n._parentCacheAsTextureRenderGroup?e.matrix=Ac.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const Lg=new Tn({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class Ug{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new je,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class Rc{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new _t({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Lt({}),this.renderer=e}get activeBackTexture(){var e;return(e=this._activeFilterData)==null?void 0:e.backTexture}push(e){const t=this.renderer,i=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=i,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(i.every(d=>!d.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,p=0;c&&(u=c.bounds.minX,p=c.bounds.minY),this._calculateGlobalFrame(r,u,p,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const i=this._pushFilterData();this._activeFilterData=i,i.skip=!1,i.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(d=>!d.enabled))return i.skip=!0,e;const a=i.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(i,a.rectangle,o,n,0),i.skip)return e;const l=n;this._calculateGlobalFrame(i,0,0,l,r.width,r.height),i.outputRenderSurface=Xe.getOptimalTexture(a.width,a.height,i.resolution,i.antialias),i.backTexture=q.EMPTY,i.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(i,!0);const p=i.outputRenderSurface;return p.source.alphaMode="premultiplied-alpha",p}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&Xe.returnTexture(t.backTexture),Xe.returnTexture(t.inputTexture))}getBackTexture(e,t,i){const r=e.colorTexture.source._resolution,n=Xe.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;i&&(o-=i.minX,a-=i.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,i,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===i,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,p=0;if(l){const g=this._findPreviousFilterOffset();u=g.x,p=g.y}this._updateFilterUniforms(t,i,o,u,p,h,l,r);const d=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(d,t,n)}calculateSpriteMatrix(e,t){const i=this._activeFilterData,r=e.set(i.inputTexture._source.width,0,0,i.inputTexture._source.height,i.bounds.minX,i.bounds.minY),n=t.worldTransform.copyTo(Y.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){var e;(e=this._passthroughFilter)==null||e.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new Fg),this._passthroughFilter}_setupBindGroupsAndRender(e,t,i){if(i.renderPipes.uniformBatch){const r=i.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,i.encoder.draw({geometry:Lg,shader:e,state:e._state,topology:"triangle-list"}),i.type===yt.WEBGL&&i.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,i,r){if(e.backTexture=q.EMPTY,e.inputTexture=Xe.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){i.renderTarget.finishRenderPass();const n=i.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r==null?void 0:r.bounds)}i.renderTarget.bind(e.inputTexture,!0),i.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,i,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=i*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,i,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,p=c.uInputPixel,d=c.uInputClamp,g=c.uGlobalFrame,_=c.uOutputTexture;a?(h[0]=i.bounds.minX-r,h[1]=i.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],p[0]=e.source.pixelWidth,p[1]=e.source.pixelHeight,p[2]=1/p[0],p[3]=1/p[1],d[0]=.5*p[2],d[1]=.5*p[3],d[2]=e.frame.width*u[2]-.5*p[2],d[3]=e.frame.height*u[3]-.5*p[3];const y=this.renderer.renderTarget.rootRenderTarget.colorTexture;g[0]=r*o,g[1]=n*o,g[2]=y.source.width*o,g[3]=y.source.height*o,t instanceof q&&(t.source.resource=null);const x=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind(t,!!l),t instanceof q?(_[0]=t.frame.width,_[1]=t.frame.height):(_[0]=x.width,_[1]=x.height),_[2]=x.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(e){let t=this._filterStackIndex-1;for(;t>0&&this._filterStack[t].skip;)--t;return t>0&&this._filterStack[t].inputTexture?this._filterStack[t].inputTexture.source._resolution:e}_findPreviousFilterOffset(){let e=0,t=0,i=this._filterStackIndex;for(;i>0;){i--;const r=this._filterStack[i];if(!r.skip){e=r.bounds.minX,t=r.bounds.minY;break}}return{x:e,y:t}}_calculateFilterArea(e,t){if(e.renderables?Gg(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){const r=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;r&&t.applyMatrix(r)}}_applyFiltersToTexture(e,t){const i=e.inputTexture,r=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(i.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,i,e.outputRenderSurface,t);else{let l=e.inputTexture;const c=Xe.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let h=c;for(let u=o;u<a;u++){const p=n[u];if(!p.enabled)continue;p.apply(this,l,h,!0);const d=l;l=h,h=d}n[a].apply(this,l,e.outputRenderSurface,t),Xe.returnTexture(c)}}_calculateFilterBounds(e,t,i,r,n){var x;const o=this.renderer,a=e.bounds,l=e.filters;let c=1/0,h=0,u=!0,p=!1,d=!1,g=!0,_=-1,y=-1;for(let v=0;v<l.length;v++){const C=l[v];if(!C.enabled)continue;if(_===-1&&(_=v),y=v,c=Math.min(c,C.resolution==="inherit"?r:C.resolution),h+=C.padding,C.antialias==="off"?u=!1:C.antialias==="inherit"&&u&&(u=i),C.clipToViewport||(g=!1),!!!(C.compatibleRenderers&o.type)){d=!1;break}if(C.blendRequired&&!(((x=o.backBuffer)==null?void 0:x.useBackBuffer)??!0)){ne("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),d=!1;break}d=!0,p||(p=C.blendRequired)}if(!d){e.skip=!0;return}if(g&&a.fitBounds(0,t.width/r,0,t.height/r),a.scale(c).ceil().scale(1/c).pad((h|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=c,e.blendRequired=p,e.firstEnabledIndex=_,e.lastEnabledIndex=y}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let e,t=this._filterStackIndex-1;for(;t>0&&(t--,e=this._filterStack[t],!!e.skip););return e}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new Ug),this._filterStackIndex++,e}}Rc.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"filter"};var Wg=`in vec2 vMaskCoord;
|
|
334
334
|
in vec2 vTextureCoord;
|
|
335
335
|
|
|
336
336
|
uniform sampler2D uTexture;
|
|
@@ -364,7 +364,7 @@ void main(void)
|
|
|
364
364
|
|
|
365
365
|
finalColor = original * a;
|
|
366
366
|
}
|
|
367
|
-
`,
|
|
367
|
+
`,Hg=`in vec2 aPosition;
|
|
368
368
|
|
|
369
369
|
out vec2 vTextureCoord;
|
|
370
370
|
out vec2 vMaskCoord;
|
|
@@ -401,7 +401,7 @@ void main(void)
|
|
|
401
401
|
vTextureCoord = filterTextureCoord(aPosition);
|
|
402
402
|
vMaskCoord = getFilterCoord(aPosition);
|
|
403
403
|
}
|
|
404
|
-
`,
|
|
404
|
+
`,Mc=`struct GlobalFilterUniforms {
|
|
405
405
|
uInputSize:vec4<f32>,
|
|
406
406
|
uInputPixel:vec4<f32>,
|
|
407
407
|
uInputClamp:vec4<f32>,
|
|
@@ -499,7 +499,7 @@ fn mainFragment(
|
|
|
499
499
|
|
|
500
500
|
return source * a;
|
|
501
501
|
}
|
|
502
|
-
`;class vm extends Sa{constructor(t){const{sprite:e,...i}=t,r=new _o(e.texture),n=new le({uFilterMatrix:{value:new W,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:t.inverse?1:0,type:"f32"}}),o=Xe.from({vertex:{source:zl,entryPoint:"mainVertex"},fragment:{source:zl,entryPoint:"mainFragment"}}),a=gi.from({vertex:bm,fragment:xm,name:"mask-filter"});super({...i,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:e.texture.source}}),this.sprite=e,this._textureMatrix=r}set inverse(t){this.resources.filterUniforms.uniforms.uInverse=t?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(t,e,i,r){this._textureMatrix.texture=this.sprite.texture,t.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,t.applyFilter(this,e,i,r)}}class Em{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class Tm{constructor(){this.instructions=new fr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const cn=class so{constructor(t){this._renderer=t,this._managedContexts=new ce({renderer:t,type:"resource",name:"graphicsContext"})}init(t){so.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??so.defaultOptions.bezierSmoothness}getContextRenderData(t){return this.getGpuContext(t).graphicsData||this._initContextRenderData(t)}updateGpuContext(t){const e=t._gpuData,i=!!e[this._renderer.uid],r=e[this._renderer.uid]||this._initContext(t);return(t.dirty||!i)&&(i&&r.reset(),r.isBatchable=!1,t.dirty=!1),r}getGpuContext(t){return t._gpuData[this._renderer.uid]||this._initContext(t)}_initContextRenderData(t){const e=new Tm,i=this.getGpuContext(t);return i.graphicsData=e,e.init(),e}_initContext(t){const e=new Em;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};cn.extension={type:[w.CanvasSystem],name:"graphicsContext"},cn.defaultOptions={bezierSmoothness:.5};let Sm=cn;class $l{constructor(t,e){this.state=ve.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ce({renderer:t,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){return!1}addRenderable(t,e){this._managedGraphics.add(t),this.renderer.renderPipes.batch.break(e),e.add(t)}updateRenderable(t){}execute(t){t.isRenderable&&this._adaptor.execute(this,t)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}$l.extension={type:[w.CanvasPipes],name:"graphics"};function jl(s,t,e){const i=(s>>24&255)/255;t[e++]=(s&255)/255*i,t[e++]=(s>>8&255)/255*i,t[e++]=(s>>16&255)/255*i,t[e++]=i}class Cm{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(t=>{Mt.return(t)}),this.batches.length=0}}class Xl{constructor(t,e){this.state=ve.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ce({renderer:t,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){const e=t.context,i=!!t._gpuData,n=this.renderer.graphicsContext.updateGpuContext(e);return!!(n.isBatchable||i!==n.isBatchable)}addRenderable(t,e){const r=this.renderer.graphicsContext.updateGpuContext(t.context);t.didViewUpdate&&this._rebuild(t),r.isBatchable?this._addToBatcher(t,e):(this.renderer.renderPipes.batch.break(e),e.add(t))}updateRenderable(t){const i=this._getGpuDataForRenderable(t).batches;for(let r=0;r<i.length;r++){const n=i[r];n._batcher.updateElement(n)}}execute(t){if(!t.isRenderable)return;const e=this.renderer,i=t.context;if(!e.graphicsContext.getGpuContext(i).batches.length)return;const n=i.customShader||this._adaptor.shader;this.state.blendMode=t.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=t.groupTransform,o.uRound=e._roundPixels|t._roundPixels,jl(t.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,t)}_rebuild(t){const e=this._getGpuDataForRenderable(t),r=this.renderer.graphicsContext.updateGpuContext(t.context);e.destroy(),r.isBatchable&&this._updateBatchesForRenderable(t,e)}_addToBatcher(t,e){const i=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(t).batches;for(let n=0;n<r.length;n++){const o=r[n];i.addToBatch(o,e)}}_getGpuDataForRenderable(t){return t._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(t)}_initGpuDataForRenderable(t){const e=new Cm;return t._gpuData[this.renderer.uid]=e,this._managedGraphics.add(t),e}_updateBatchesForRenderable(t,e){const i=t.context,n=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|t._roundPixels;e.batches=n.batches.map(a=>{const l=Mt.get(Qr);return a.copyTo(l),l.renderable=t,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}Xl.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"graphics"},J.add($l),J.add(Xl),J.add(Sm),J.add(sn);class is extends yr{constructor(t){t instanceof ie&&(t={context:t});const{context:e,roundPixels:i,...r}=t||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",e?this.context=e:(this.context=this._ownedContext=new ie,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(t){t!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=t,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(t){return this._context.containsPoint(t)}destroy(t){this._ownedContext&&!t?this._ownedContext.destroy(t):(t===!0||(t==null?void 0:t.context)===!0)&&this._context.destroy(t),this._ownedContext=null,this._context=null,super.destroy(t)}_onTouch(t){this._gcLastUsed=t,this._context._gcLastUsed=t}_callContextMethod(t,e){return this.context[t](...e),this}setFillStyle(...t){return this._callContextMethod("setFillStyle",t)}setStrokeStyle(...t){return this._callContextMethod("setStrokeStyle",t)}fill(...t){return this._callContextMethod("fill",t)}stroke(...t){return this._callContextMethod("stroke",t)}texture(...t){return this._callContextMethod("texture",t)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...t){return this._callContextMethod("arc",t)}arcTo(...t){return this._callContextMethod("arcTo",t)}arcToSvg(...t){return this._callContextMethod("arcToSvg",t)}bezierCurveTo(...t){return this._callContextMethod("bezierCurveTo",t)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...t){return this._callContextMethod("ellipse",t)}circle(...t){return this._callContextMethod("circle",t)}path(...t){return this._callContextMethod("path",t)}lineTo(...t){return this._callContextMethod("lineTo",t)}moveTo(...t){return this._callContextMethod("moveTo",t)}quadraticCurveTo(...t){return this._callContextMethod("quadraticCurveTo",t)}rect(...t){return this._callContextMethod("rect",t)}roundRect(...t){return this._callContextMethod("roundRect",t)}poly(...t){return this._callContextMethod("poly",t)}regularPoly(...t){return this._callContextMethod("regularPoly",t)}roundPoly(...t){return this._callContextMethod("roundPoly",t)}roundShape(...t){return this._callContextMethod("roundShape",t)}filletRect(...t){return this._callContextMethod("filletRect",t)}chamferRect(...t){return this._callContextMethod("chamferRect",t)}star(...t){return this._callContextMethod("star",t)}svg(...t){return this._callContextMethod("svg",t)}restore(...t){return this._callContextMethod("restore",t)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...t){return this._callContextMethod("rotate",t)}scaleTransform(...t){return this._callContextMethod("scale",t)}setTransform(...t){return this._callContextMethod("setTransform",t)}transform(...t){return this._callContextMethod("transform",t)}translateTransform(...t){return this._callContextMethod("translate",t)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(t){this._context.fillStyle=t}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(t){this._context.strokeStyle=t}clone(t=!1){return t?new is(this._context.clone()):(this._ownedContext=null,new is(this._context))}lineStyle(t,e,i){K(vt,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return t&&(r.width=t),e&&(r.color=e),i&&(r.alpha=i),this.context.strokeStyle=r,this}beginFill(t,e){K(vt,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return t!==void 0&&(i.color=t),e!==void 0&&(i.alpha=e),this.context.fillStyle=i,this}endFill(){K(vt,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const t=this.context.strokeStyle;return(t.width!==ie.defaultStrokeStyle.width||t.color!==ie.defaultStrokeStyle.color||t.alpha!==ie.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...t){return K(vt,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",t)}drawEllipse(...t){return K(vt,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",t)}drawPolygon(...t){return K(vt,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",t)}drawRect(...t){return K(vt,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",t)}drawRoundedRect(...t){return K(vt,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",t)}drawStar(...t){return K(vt,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",t)}}let bi;function Yl(s){const t=rt.get().createCanvas(6,1),e=t.getContext("2d");return e.fillStyle=s,e.fillRect(0,0,6,1),t}function ql(){if(bi!==void 0)return bi;try{const s=Yl("#ff00ff"),t=Yl("#ffff00"),i=rt.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(s,0,0),i.drawImage(t,2,0);const r=i.getImageData(2,0,1,1);if(!r)bi=!1;else{const n=r.data;bi=n[0]===255&&n[1]===0&&n[2]===0}}catch{bi=!1}return bi}const st={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:ql(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:s=>{const t=s.source,e=t==null?void 0:t.resource;if(!e)return null;const i=t.alphaMode==="premultiplied-alpha",r=t.resourceWidth??t.pixelWidth,n=t.resourceHeight??t.pixelHeight,o=r!==t.pixelWidth||n!==t.pixelHeight;if(i){if((e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)&&!o)return e;const a=st._unpremultipliedCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas}if(e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof ArrayBuffer){const a=st._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const l=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),h=l.getContext("2d"),c=h.createImageData(t.pixelWidth,t.pixelHeight),u=c.data,m=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(t.format==="bgra8unorm")for(let f=0;f<u.length&&f+3<m.length;f+=4)u[f]=m[f+2],u[f+1]=m[f+1],u[f+2]=m[f],u[f+3]=m[f+3];else u.set(m.subarray(0,u.length));return h.putImageData(c,0,0),st._canvasSourceCache.set(t,{canvas:l,resourceId:t._resourceId}),l}if(i){const a=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=t.pixelWidth,a.height=t.pixelHeight,l.drawImage(e,0,0);const h=l.getImageData(0,0,a.width,a.height),c=h.data;for(let u=0;u<c.length;u+=4){const m=c[u+3];if(m>0){const f=255/m;c[u]=Math.min(255,c[u]*f+.5),c[u+1]=Math.min(255,c[u+1]*f+.5),c[u+2]=Math.min(255,c[u+2]*f+.5)}}return l.putImageData(h,0,0),st._unpremultipliedCache.set(t,{canvas:a,resourceId:t._resourceId}),a}if(o){const a=st._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const l=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),h=l.getContext("2d");return l.width=t.pixelWidth,l.height=t.pixelHeight,h.drawImage(e,0,0),st._canvasSourceCache.set(t,{canvas:l,resourceId:t._resourceId}),l}return e},getTintedCanvas:(s,t)=>{const e=s.texture,i=ut.shared.setValue(t).toHex(),r=e.tintCache||(e.tintCache={}),n=r[i],o=e.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:rt.get().createCanvas();return st.tintMethod(e,t,a),a.tintId=o,r[i]=a,r[i]},getTintedPattern:(s,t)=>{const e=ut.shared.setValue(t).toHex(),i=s.patternCache||(s.patternCache={}),r=s.source._resourceId;let n=i[e];return(n==null?void 0:n.tintId)===r||(st.canvas||(st.canvas=rt.get().createCanvas()),st.tintMethod(s,t,st.canvas),n=st.canvas.getContext("2d").createPattern(st.canvas,"repeat"),n.tintId=r,i[e]=n),n},applyPatternTransform:(s,t,e=!0)=>{if(!t)return;const i=s;if(!i.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([t.a,t.b,t.c,t.d,t.tx,t.ty]);i.setTransform(e?n.inverse():n)},tintWithMultiply:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.fillStyle=ut.shared.setValue(t).toHex(),i.fillRect(0,0,l,h),i.globalCompositeOperation="multiply";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.globalCompositeOperation="destination-atop",i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithOverlay:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.globalCompositeOperation="copy",i.fillStyle=ut.shared.setValue(t).toHex(),i.fillRect(0,0,l,h),i.globalCompositeOperation="destination-atop";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithPerPixel:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.globalCompositeOperation="copy";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore();const u=t>>16&255,m=t>>8&255,f=t&255,g=i.getImageData(0,0,l,h),y=g.data;for(let x=0;x<y.length;x+=4)y[x]=y[x]*u/255,y[x+1]=y[x+1]*m/255,y[x+2]=y[x+2]*f/255;i.putImageData(g,0,0)},_applyInverseRotation:(s,t,e,i)=>{const r=it.inv(t),n=it.uX(r),o=it.uY(r),a=it.vX(r),l=it.vY(r),h=-Math.min(0,n*e,a*i,n*e+a*i),c=-Math.min(0,o*e,l*i,o*e+l*i);s.transform(n,o,a,l,h,c)}};st.tintMethod=st.canUseMultiply?st.tintWithMultiply:st.tintWithPerPixel;const Bs={name:"local-uniform-bit",vertex:{header:`
|
|
502
|
+
`;class Vg extends hl{constructor(e){const{sprite:t,...i}=e,r=new sa(t.texture),n=new _t({uFilterMatrix:{value:new Y,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=ni.from({vertex:{source:Mc,entryPoint:"mainVertex"},fragment:{source:Mc,entryPoint:"mainFragment"}}),a=Ai.from({vertex:Hg,fragment:Wg,name:"mask-filter"});super({...i,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,i,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,i,r)}}class zg{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class $g{constructor(){this.instructions=new jr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Vn=class zo{constructor(e){this._renderer=e,this._managedContexts=new bt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){zo.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??zo.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,i=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!i)&&(i&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new $g,i=this.getGpuContext(e);return i.graphicsData=t,t.init(),t}_initContext(e){const t=new zg;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Vn.extension={type:[I.CanvasSystem],name:"graphicsContext"},Vn.defaultOptions={bezierSmoothness:.5};let jg=Vn;class Pc{constructor(e,t){this.state=At.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new bt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}Pc.extension={type:[I.CanvasPipes],name:"graphics"};function kc(s,e,t){const i=(s>>24&255)/255;e[t++]=(s&255)/255*i,e[t++]=(s>>8&255)/255*i,e[t++]=(s>>16&255)/255*i,e[t++]=i}class Xg{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Ue.return(e)}),this.batches.length=0}}class Bc{constructor(e,t){this.state=At.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new bt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,i=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||i!==n.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const i=this._getGpuDataForRenderable(e).batches;for(let r=0;r<i.length;r++){const n=i[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,i=e.context;if(!t.graphicsContext.getGpuContext(i).batches.length)return;const n=i.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,kc(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),r=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),r.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const i=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];i.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new Xg;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const i=e.context,n=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Ue.get(Bn);return a.copyTo(l),l.renderable=e,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}Bc.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"graphics"},ie.add(Pc),ie.add(Bc),ie.add(jg),ie.add(Nn);class vs extends Zr{constructor(e){e instanceof ht&&(e={context:e});const{context:t,roundPixels:i,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new ht,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new vs(this._context.clone()):(this._ownedContext=null,new vs(this._context))}lineStyle(e,t,i){J(Ie,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),i&&(r.alpha=i),this.context.strokeStyle=r,this}beginFill(e,t){J(Ie,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return e!==void 0&&(i.color=e),t!==void 0&&(i.alpha=t),this.context.fillStyle=i,this}endFill(){J(Ie,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==ht.defaultStrokeStyle.width||e.color!==ht.defaultStrokeStyle.color||e.alpha!==ht.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return J(Ie,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return J(Ie,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return J(Ie,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return J(Ie,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return J(Ie,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return J(Ie,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}let ki;function Oc(s){const e=de.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=s,t.fillRect(0,0,6,1),e}function Dc(){if(ki!==void 0)return ki;try{const s=Oc("#ff00ff"),e=Oc("#ffff00"),i=de.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(s,0,0),i.drawImage(e,2,0);const r=i.getImageData(2,0,1,1);if(!r)ki=!1;else{const n=r.data;ki=n[0]===255&&n[1]===0&&n[2]===0}}catch{ki=!1}return ki}const he={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:Dc(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:s=>{const e=s.source,t=e==null?void 0:e.resource;if(!t)return null;const i=e.alphaMode==="premultiplied-alpha",r=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=r!==e.pixelWidth||n!==e.pixelHeight;if(i){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=he._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=he._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=de.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d"),h=c.createImageData(e.pixelWidth,e.pixelHeight),u=h.data,p=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let d=0;d<u.length&&d+3<p.length;d+=4)u[d]=p[d+2],u[d+1]=p[d+1],u[d+2]=p[d],u[d+3]=p[d+3];else u.set(p.subarray(0,u.length));return c.putImageData(h,0,0),he._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(i){const a=de.get().createCanvas(e.pixelWidth,e.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,l.drawImage(t,0,0);const c=l.getImageData(0,0,a.width,a.height),h=c.data;for(let u=0;u<h.length;u+=4){const p=h[u+3];if(p>0){const d=255/p;h[u]=Math.min(255,h[u]*d+.5),h[u+1]=Math.min(255,h[u+1]*d+.5),h[u+2]=Math.min(255,h[u+2]*d+.5)}}return l.putImageData(c,0,0),he._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=he._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=de.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,c.drawImage(t,0,0),he._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(s,e)=>{const t=s.texture,i=be.shared.setValue(e).toHex(),r=t.tintCache||(t.tintCache={}),n=r[i],o=t.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:de.get().createCanvas();return he.tintMethod(t,e,a),a.tintId=o,r[i]=a,r[i]},getTintedPattern:(s,e)=>{const t=be.shared.setValue(e).toHex(),i=s.patternCache||(s.patternCache={}),r=s.source._resourceId;let n=i[t];return(n==null?void 0:n.tintId)===r||(he.canvas||(he.canvas=de.get().createCanvas()),he.tintMethod(s,e,he.canvas),n=he.canvas.getContext("2d").createPattern(he.canvas,"repeat"),n.tintId=r,i[t]=n),n},applyPatternTransform:(s,e,t=!0)=>{if(!e)return;const i=s;if(!i.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([e.a,e.b,e.c,e.d,e.tx,e.ty]);i.setTransform(t?n.inverse():n)},tintWithMultiply:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=ce.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.fillStyle=be.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="multiply";const h=he.getCanvasSource(s);if(!h){i.restore();return}o&&he._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.globalCompositeOperation="destination-atop",i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithOverlay:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=ce.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy",i.fillStyle=be.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="destination-atop";const h=he.getCanvasSource(s);if(!h){i.restore();return}o&&he._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithPerPixel:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=ce.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy";const h=he.getCanvasSource(s);if(!h){i.restore();return}o&&he._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore();const u=e>>16&255,p=e>>8&255,d=e&255,g=i.getImageData(0,0,l,c),_=g.data;for(let y=0;y<_.length;y+=4)_[y]=_[y]*u/255,_[y+1]=_[y+1]*p/255,_[y+2]=_[y+2]*d/255;i.putImageData(g,0,0)},_applyInverseRotation:(s,e,t,i)=>{const r=ce.inv(e),n=ce.uX(r),o=ce.uY(r),a=ce.vX(r),l=ce.vY(r),c=-Math.min(0,n*t,a*i,n*t+a*i),h=-Math.min(0,o*t,l*i,o*t+l*i);s.transform(n,o,a,l,c,h)}};he.tintMethod=he.canUseMultiply?he.tintWithMultiply:he.tintWithPerPixel;const sr={name:"local-uniform-bit",vertex:{header:`
|
|
503
503
|
|
|
504
504
|
struct LocalUniforms {
|
|
505
505
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -516,7 +516,7 @@ fn mainFragment(
|
|
|
516
516
|
{
|
|
517
517
|
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
518
518
|
}
|
|
519
|
-
`}},
|
|
519
|
+
`}},Yg={...sr,vertex:{...sr.vertex,header:sr.vertex.header.replace("group(1)","group(2)")}},Nc={name:"local-uniform-bit",vertex:{header:`
|
|
520
520
|
|
|
521
521
|
uniform mat3 uTransformMatrix;
|
|
522
522
|
uniform vec4 uColor;
|
|
@@ -529,18 +529,18 @@ fn mainFragment(
|
|
|
529
529
|
{
|
|
530
530
|
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
531
531
|
}
|
|
532
|
-
`}};class
|
|
532
|
+
`}};class Kg extends Zr{constructor(e,t){const{text:i,resolution:r,style:n,anchor:o,width:a,height:l,roundPixels:c,...h}=e;super({...h}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=i??"",this.style=n,this.resolution=r??null,this.allowChildren=!1,this._anchor=new ze({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=c??!1,a!==void 0&&(this.width=a),l!==void 0&&(this.height=l)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){var t;e||(e={}),(t=this._style)==null||t.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){const t=this.bounds.width,i=this.bounds.height,r=-t*this.anchor.x;let n=0;return e.x>=r&&e.x<=r+t&&(n=-i*this.anchor.y,e.y>=n&&e.y<=n+i)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e!=null&&e.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function qg(s,e){let t=s[0]??{};return(typeof t=="string"||s[1])&&(J(Ie,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:s[1]}),t}class Zg{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const i=de.get().createCanvas();i.width=e,i.height=t;const r=i.getContext("2d");return{canvas:i,context:r}}getOptimalCanvasAndContext(e,t,i=1){e=Math.ceil(e*i-1e-6),t=Math.ceil(t*i-1e-6),e=yi(e),t=yi(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:i,height:r}=t,n=(i<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,i,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const Ss=new Zg;xi.register(Ss);let ci=null,Pt=null;function Jg(s,e){ci||(ci=de.get().createCanvas(256,128),Pt=ci.getContext("2d",{willReadFrequently:!0}),Pt.globalCompositeOperation="copy",Pt.globalAlpha=1),(ci.width<s||ci.height<e)&&(ci.width=yi(s),ci.height=yi(e))}function Fc(s,e,t){for(let i=0,r=4*t*e;i<e;++i,r+=4)if(s[r+3]!==0)return!1;return!0}function Gc(s,e,t,i,r){const n=4*e;for(let o=i,a=i*n+4*t;o<=r;++o,a+=n)if(s[a+3]!==0)return!1;return!0}function Qg(...s){let e=s[0];e.canvas||(e={canvas:s[0],resolution:s[1]});const{canvas:t}=e,i=Math.min(e.resolution??1,1),r=e.width??t.width,n=e.height??t.height;let o=e.output;if(Jg(r,n),!Pt)throw new TypeError("Failed to get canvas 2D context");Pt.drawImage(t,0,0,r,n,0,0,r*i,n*i);const l=Pt.getImageData(0,0,r,n).data;let c=0,h=0,u=r-1,p=n-1;for(;h<n&&Fc(l,r,h);)++h;if(h===n)return ye.EMPTY;for(;Fc(l,r,p);)--p;for(;Gc(l,r,c,h,p);)++c;for(;Gc(l,r,u,h,p);)--u;return++u,++p,Pt.globalCompositeOperation="source-over",Pt.strokeRect(c,h,u-c,p-h),Pt.globalCompositeOperation="copy",o??(o=new ye),o.set(c/i,h/i,(u-c)/i,(p-h)/i),o}/**
|
|
533
533
|
* tiny-lru
|
|
534
534
|
*
|
|
535
535
|
* @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
|
|
536
536
|
* @license BSD-3-Clause
|
|
537
537
|
* @version 11.4.7
|
|
538
|
-
*/class
|
|
539
|
-
`?(
|
|
540
|
-
`),i++):
|
|
541
|
-
`||
|
|
542
|
-
`?(
|
|
543
|
-
`)}const oh={willReadFrequently:!0},we=class q{static get experimentalLetterSpacingSupported(){let t=q._experimentalLetterSpacingSupported;if(t===void 0){const e=rt.get().getCanvasRenderingContext2D().prototype;t=q._experimentalLetterSpacingSupported="letterSpacing"in e||"textLetterSpacing"in e}return t}constructor(t,e,i,r,n,o,a,l,h,c){this.text=t,this.style=e,this.width=i,this.height=r,this.lines=n,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=l,this.fontProperties=h,c&&(this.runsByLine=c.runsByLine,this.lineAscents=c.lineAscents,this.lineDescents=c.lineDescents,this.lineHeights=c.lineHeights,this.hasDropShadow=c.hasDropShadow)}static measureText(t=" ",e,i=q._canvas,r=e.wordWrap){var R;const n=`${t}-${e.styleKey}-wordWrap-${r}`;if(q._measurementCache.has(n))return q._measurementCache.get(n);if(Ql(e)&&th(t)){const A=Xm(t,e,r,q._context,q._measureText,q.measureFont,q.canBreakChars,q.wordWrapSplit),P=new q(t,e,A.width,A.height,A.lines,A.lineWidths,A.lineHeight,A.maxLineWidth,A.fontProperties,{runsByLine:A.runsByLine,lineAscents:A.lineAscents,lineDescents:A.lineDescents,lineHeights:A.lineHeights,hasDropShadow:A.hasDropShadow});return q._measurementCache.set(n,P),P}const a=e._fontString,l=q.measureFont(a);l.fontSize===0&&(l.fontSize=e.fontSize,l.ascent=e.fontSize,l.descent=0);const h=q._context;h.font=a;const u=(r?q._wordWrap(t,e,i):t).split(zm),m=new Array(u.length);let f=0;for(let A=0;A<u.length;A++){const P=q._measureText(u[A],e.letterSpacing,h);m[A]=P,f=Math.max(f,P)}const g=((R=e._stroke)==null?void 0:R.width)??0,y=e.lineHeight||l.fontSize,x=q._getAlignWidth(f,e,r),v=q._adjustWidthForStyle(x,e),E=Math.max(y,l.fontSize+g)+(u.length-1)*(y+e.leading),T=q._adjustHeightForStyle(E,e),C=new q(t,e,v,T,u,m,y+e.leading,f,l);return q._measurementCache.set(n,C),C}static _adjustWidthForStyle(t,e){var n;const i=((n=e._stroke)==null?void 0:n.width)||0;let r=t+i;return e.dropShadow&&(r+=e.dropShadow.distance),r}static _adjustHeightForStyle(t,e){let i=t;return e.dropShadow&&(i+=e.dropShadow.distance),i}static _getAlignWidth(t,e,i){return i&&e.align!=="left"?Math.max(t,e.wordWrapWidth):t}static _measureText(t,e,i){let r=!1;q.experimentalLetterSpacingSupported&&(q.experimentalLetterSpacing?(i.letterSpacing=`${e}px`,i.textLetterSpacing=`${e}px`,r=!0):(i.letterSpacing="0px",i.textLetterSpacing="0px"));const n=i.measureText(t);let o=n.width;const a=-(n.actualBoundingBoxLeft??0);let h=(n.actualBoundingBoxRight??0)-a;if(o>0)if(r)o-=e,h-=e;else{const c=(q.graphemeSegmenter(t).length-1)*e;o+=c,h+=c}return Math.max(o,h)}static _wordWrap(t,e,i=q._canvas){return Zm(t,e,i,q._measureText,q.canBreakWords,q.canBreakChars,q.wordWrapSplit)}static isBreakingSpace(t,e){return te(t)}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,r,n){return!0}static wordWrapSplit(t){return q.graphemeSegmenter(t)}static measureFont(t){if(q._fonts[t])return q._fonts[t];const e=q._context;e.font=t;const i=e.measureText(q.METRICS_STRING+q.BASELINE_SYMBOL),r=i.actualBoundingBoxAscent??0,n=i.actualBoundingBoxDescent??0,o={ascent:r,descent:n,fontSize:r+n};return q._fonts[t]=o,o}static clearMetrics(t=""){t?delete q._fonts[t]:q._fonts={}}static get _canvas(){if(!q.__canvas){let t;try{const e=new OffscreenCanvas(0,0),i=e.getContext("2d",oh);if(i!=null&&i.measureText)return q.__canvas=e,e;t=rt.get().createCanvas()}catch{t=rt.get().createCanvas()}t.width=t.height=10,q.__canvas=t}return q.__canvas}static get _context(){return q.__context||(q.__context=q._canvas.getContext("2d",oh)),q.__context}};we.METRICS_STRING="|ÉqÅ",we.BASELINE_SYMBOL="M",we.BASELINE_MULTIPLIER=1.4,we.HEIGHT_MULTIPLIER=2,we.graphemeSegmenter=(()=>{if(typeof(Intl==null?void 0:Intl.Segmenter)=="function"){const s=new Intl.Segmenter;return t=>{const e=s.segment(t),i=[];let r=0;for(const n of e)i[r++]=n.segment;return i}}return s=>[...s]})(),we.experimentalLetterSpacing=!1,we._fonts={},we._measurementCache=Bm(1e3);let ke=we;const Jm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function un(s){const t=typeof s.fontSize=="number"?`${s.fontSize}px`:s.fontSize;let e=s.fontFamily;Array.isArray(s.fontFamily)||(e=s.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let r=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(r)&&!Jm.includes(r)&&(r=`"${r}"`),e[i]=r}return`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${t} ${e.join(",")}`}const ah=1e5;function Ds(s,t,e,i=0,r=0,n=0){if(s.texture===$.WHITE&&!s.fill)return ut.shared.setValue(s.color).setAlpha(s.alpha??1).toHexa();if(s.fill){if(s.fill instanceof ts){const o=s.fill,a=t.createPattern(o.texture.source.resource,"repeat"),l=o.transform.copyTo(W.shared);return l.scale(o.texture.source.pixelWidth,o.texture.source.pixelHeight),a.setTransform(l),a}else if(s.fill instanceof ue){const o=s.fill,a=o.type==="linear",l=o.textureSpace==="local";let h=1,c=1;l&&e&&(h=e.width+i,c=e.height+i);let u,m=!1;if(a){const{start:f,end:g}=o;u=t.createLinearGradient(f.x*h+r,f.y*c+n,g.x*h+r,g.y*c+n),m=Math.abs(g.x-f.x)<Math.abs((g.y-f.y)*.1)}else{const{center:f,innerRadius:g,outerCenter:y,outerRadius:x}=o;u=t.createRadialGradient(f.x*h+r,f.y*c+n,g*h,y.x*h+r,y.y*c+n,x*h)}if(m&&l&&e){const f=e.lineHeight/c;for(let g=0;g<e.lines.length;g++){const y=(g*e.lineHeight+i/2)/c;o.colorStops.forEach(x=>{let v=y+x.offset*f;v=Math.max(0,Math.min(1,v)),u.addColorStop(Math.floor(v*ah)/ah,ut.shared.setValue(x.color).toHex())})}}else o.colorStops.forEach(f=>{u.addColorStop(f.offset,ut.shared.setValue(f.color).toHex())});return u}}else{const o=t.createPattern(s.texture.source.resource,"repeat"),a=s.matrix.copyTo(W.shared);return a.scale(s.texture.source.pixelWidth,s.texture.source.pixelHeight),o.setTransform(a),o}return tt("FillStyle not recognised",s),"red"}const lh=new ct;function vi(s){let t=0;for(let e=0;e<s.length;e++)s.charCodeAt(e)===32&&t++;return t}class Qm{getCanvasAndContext(t){const{text:e,style:i,resolution:r=1}=t,n=i._getFinalPadding(),o=ke.measureText(e||" ",i),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*r),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*r),h=ss.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(i,n,r,h,o);const c=i.trim?Mm({canvas:h.canvas,width:a,height:l,resolution:1,output:lh}):lh.set(0,0,a,l);return{canvasAndContext:h,frame:c}}returnCanvasAndContext(t){ss.returnCanvasAndContext(t)}_renderTextToCanvas(t,e,i,r,n){var A,P,F;if(n.runsByLine&&n.runsByLine.length>0){this._renderTaggedTextToCanvas(n,t,e,i,r);return}const{canvas:o,context:a}=r,l=un(t),h=n.lines,c=n.lineHeight,u=n.lineWidths,m=n.maxLineWidth,f=n.fontProperties,g=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=t.textBaseline,(A=t._stroke)!=null&&A.width){const B=t._stroke;a.lineWidth=B.width,a.miterLimit=B.miterLimit,a.lineJoin=B.join,a.lineCap=B.cap}a.font=l;let y,x;const v=t.dropShadow?2:1,E=t.wordWrap?Math.max(t.wordWrapWidth,m):m,C=(((P=t._stroke)==null?void 0:P.width)??0)/2;let R=(c-f.fontSize)/2;c-f.fontSize<0&&(R=0);for(let B=0;B<v;++B){const k=t.dropShadow&&B===0,O=k?Math.ceil(Math.max(1,g)+e*2):0,L=O*i;if(k)this._setupDropShadow(a,t,i,L);else{const N=t._gradientBounds,H=t._gradientOffset;if(N){const at={width:N.width,height:N.height,lineHeight:N.height,lines:n.lines};this._setFillAndStrokeStyles(a,t,at,e,C,(H==null?void 0:H.x)??0,(H==null?void 0:H.y)??0)}else H?this._setFillAndStrokeStyles(a,t,n,e,C,H.x,H.y):this._setFillAndStrokeStyles(a,t,n,e,C);a.shadowColor="rgba(0,0,0,0)"}for(let N=0;N<h.length;N++){y=C,x=C+N*c+f.ascent+R,y+=this._getAlignmentOffset(u[N],E,t.align);let H=0;if(t.align==="justify"&&t.wordWrap&&N<h.length-1){const at=vi(h[N]);at>0&&(H=(E-u[N])/at)}(F=t._stroke)!=null&&F.width&&this._drawLetterSpacing(h[N],t,r,y+e,x+e-O,!0,H),t._fill!==void 0&&this._drawLetterSpacing(h[N],t,r,y+e,x+e-O,!1,H)}}}_renderTaggedTextToCanvas(t,e,i,r,n){var C,R,A;const{canvas:o,context:a}=n,{runsByLine:l,lineWidths:h,maxLineWidth:c,lineAscents:u,lineHeights:m,hasDropShadow:f}=t,g=o.height;a.resetTransform(),a.scale(r,r),a.textBaseline=e.textBaseline;const y=f?2:1,x=e.wordWrap?Math.max(e.wordWrapWidth,c):c;let v=((C=e._stroke)==null?void 0:C.width)??0;for(const P of l)for(const F of P){const B=((R=F.style._stroke)==null?void 0:R.width)??0;B>v&&(v=B)}const E=v/2,T=[];for(let P=0;P<l.length;P++){const F=l[P],B=[];for(const k of F){const O=un(k.style);a.font=O,B.push({width:ke._measureText(k.text,k.style.letterSpacing,a),font:O})}T.push(B)}for(let P=0;P<y;++P){const F=f&&P===0,B=F?Math.ceil(Math.max(1,g)+i*2):0,k=B*r;F||(a.shadowColor="rgba(0,0,0,0)");let O=E;for(let L=0;L<l.length;L++){const N=l[L],H=h[L],at=u[L],G=m[L],U=T[L];let X=E;X+=this._getAlignmentOffset(H,x,e.align);let D=0;if(e.align==="justify"&&e.wordWrap&&L<l.length-1){let j=0;for(const V of N)j+=vi(V.text);j>0&&(D=(x-H)/j)}const z=O+at;let Y=X+i;for(let j=0;j<N.length;j++){const V=N[j],{width:ot,font:lt}=U[j];if(a.font=lt,a.textBaseline=V.style.textBaseline,(A=V.style._stroke)!=null&&A.width){const ht=V.style._stroke;if(a.lineWidth=ht.width,a.miterLimit=ht.miterLimit,a.lineJoin=ht.join,a.lineCap=ht.cap,F)if(V.style.dropShadow)this._setupDropShadow(a,V.style,r,k);else{const _t=vi(V.text);Y+=ot+_t*D;continue}else{const _t=ke.measureFont(lt),Z=V.style.lineHeight||_t.fontSize,Bt={width:ot,height:Z,lineHeight:Z,lines:[V.text]};a.strokeStyle=Ds(ht,a,Bt,i*2,Y-i,O)}this._drawLetterSpacing(V.text,V.style,n,Y,z+i-B,!0,D)}const gt=vi(V.text);Y+=ot+gt*D}Y=X+i;for(let j=0;j<N.length;j++){const V=N[j],{width:ot,font:lt}=U[j];if(a.font=lt,a.textBaseline=V.style.textBaseline,V.style._fill!==void 0){if(F)if(V.style.dropShadow)this._setupDropShadow(a,V.style,r,k);else{const ht=vi(V.text);Y+=ot+ht*D;continue}else{const ht=ke.measureFont(lt),_t=V.style.lineHeight||ht.fontSize,Z={width:ot,height:_t,lineHeight:_t,lines:[V.text]};a.fillStyle=Ds(V.style._fill,a,Z,i*2,Y-i,O)}this._drawLetterSpacing(V.text,V.style,n,Y,z+i-B,!1,D)}const gt=vi(V.text);Y+=ot+gt*D}O+=G}}}_setFillAndStrokeStyles(t,e,i,r,n,o=0,a=0){var l;if(t.fillStyle=e._fill?Ds(e._fill,t,i,r*2,o,a):null,(l=e._stroke)!=null&&l.width){const h=n+r*2;t.strokeStyle=Ds(e._stroke,t,i,h,o,a)}}_setupDropShadow(t,e,i,r){t.fillStyle="black",t.strokeStyle="black";const n=e.dropShadow,o=n.color,a=n.alpha;t.shadowColor=ut.shared.setValue(o).setAlpha(a).toRgbaString();const l=n.blur*i,h=n.distance*i;t.shadowBlur=l,t.shadowOffsetX=Math.cos(n.angle)*h,t.shadowOffsetY=Math.sin(n.angle)*h+r}_getAlignmentOffset(t,e,i){return i==="right"?e-t:i==="center"?(e-t)/2:0}_drawLetterSpacing(t,e,i,r,n,o=!1,a=0){const{context:l}=i,h=e.letterSpacing;let c=!1;if(ke.experimentalLetterSpacingSupported&&(ke.experimentalLetterSpacing?(l.letterSpacing=`${h}px`,l.textLetterSpacing=`${h}px`,c=!0):(l.letterSpacing="0px",l.textLetterSpacing="0px")),(h===0||c)&&a===0){o?l.strokeText(t,r,n):l.fillText(t,r,n);return}if(a!==0&&(h===0||c)){const y=t.split(" ");let x=r;const v=l.measureText(" ").width;for(let E=0;E<y.length;E++)o?l.strokeText(y[E],x,n):l.fillText(y[E],x,n),x+=l.measureText(y[E]).width+v+a;return}let u=r;const m=ke.graphemeSegmenter(t);let f=l.measureText(t).width,g=0;for(let y=0;y<m.length;++y){const x=m[y];o?l.strokeText(x,u,n):l.fillText(x,u,n);let v="";for(let E=y+1;E<m.length;++E)v+=m[E];g=l.measureText(v).width,u+=f-g+h,x===" "&&(u+=a),f=g}}}const Ei=new Qm,dn=class ii extends Zt{constructor(t={}){super(),this.uid=dt("textStyle"),this._tick=0,this._cachedFontString=null,tg(t),t instanceof ii&&(t=t._toObject());const r={...ii.defaultTextStyle,...t};for(const n in r){const o=n;this[o]=r[n]}this._tagStyles=t.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.update())}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(t!==null&&typeof t=="object"?this._dropShadow=this._createProxy({...ii.defaultDropShadow,...t}):this._dropShadow=t?this._createProxy({...ii.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.update())}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(typeof t=="string"?this._fontSize=parseInt(t,10):this._fontSize=t,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.update())}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.update())}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.update())}get filters(){return this._filters}set filters(t){this._filters!==t&&(this._filters=Object.freeze(t),this.update())}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.update())}get fill(){return this._originalFill}set fill(t){t!==this._originalFill&&(this._originalFill=t,this._isFillStyle(t)&&(this._originalFill=this._createProxy({...ie.defaultFillStyle,...t},()=>{this._fill=Ke({...this._originalFill},ie.defaultFillStyle)})),this._fill=Ke(t===0?"black":t,ie.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(t){t!==this._originalStroke&&(this._originalStroke=t,this._isFillStyle(t)&&(this._originalStroke=this._createProxy({...ie.defaultStrokeStyle,...t},()=>{this._stroke=Ms({...this._originalStroke},ie.defaultStrokeStyle)})),this._stroke=Ms(t,ie.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(t){this._tagStyles!==t&&(this._tagStyles=t??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit("update",this)}reset(){const t=ii.defaultTextStyle;for(const e in t)this[e]=t[e]}assign(t){for(const e in t){const i=e;this[i]=t[e]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=un(this)),this._cachedFontString}_toObject(){return{align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill?{...this._fill}:void 0,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke?{...this._stroke}:void 0,textBaseline:this.textBaseline,trim:this.trim,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0,tagStyles:this._tagStyles?{...this._tagStyles}:void 0}}clone(){return new ii(this._toObject())}_getFinalPadding(){let t=0;if(this._filters)for(let e=0;e<this._filters.length;e++)t+=this._filters[e].padding;return Math.max(this._padding,t)}destroy(t=!1){var i,r,n,o;if(this.removeAllListeners(),typeof t=="boolean"?t:t==null?void 0:t.texture){const a=typeof t=="boolean"?t:t==null?void 0:t.textureSource;(i=this._fill)!=null&&i.texture&&this._fill.texture.destroy(a),(r=this._originalFill)!=null&&r.texture&&this._originalFill.texture.destroy(a),(n=this._stroke)!=null&&n.texture&&this._stroke.texture.destroy(a),(o=this._originalStroke)!=null&&o.texture&&this._originalStroke.texture.destroy(a)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(t,e){return new Proxy(t,{set:(i,r,n)=>(i[r]===n||(i[r]=n,e==null||e(r,n),this.update()),!0)})}_isFillStyle(t){return(t??null)!==null&&!(ut.isColorLike(t)||t instanceof ue||t instanceof ts)}};dn.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},dn.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Gs=dn;function tg(s){const t=s;if(typeof t.dropShadow=="boolean"&&t.dropShadow){const e=Gs.defaultDropShadow;s.dropShadow={alpha:t.dropShadowAlpha??e.alpha,angle:t.dropShadowAngle??e.angle,blur:t.dropShadowBlur??e.blur,color:t.dropShadowColor??e.color,distance:t.dropShadowDistance??e.distance}}if(t.strokeThickness!==void 0){K(vt,"strokeThickness is now a part of stroke");const e=t.stroke;let i={};if(ut.isColorLike(e))i.color=e;else if(e instanceof ue||e instanceof ts)i.fill=e;else if(Object.hasOwnProperty.call(e,"color")||Object.hasOwnProperty.call(e,"fill"))i=e;else throw new Error("Invalid stroke value.");s.stroke={...i,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(K(vt,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");t.fill.length!==t.fillGradientStops.length&&tt("The number of fill colors must match the number of fill gradient stops.");const e=new ue({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=t.fillGradientStops.slice(),r=t.fill.map(n=>ut.shared.setValue(n).toNumber());i.forEach((n,o)=>{e.addColorStop(n,r[o])}),s.fill={fill:e}}}function eg(s,t){const{texture:e,bounds:i}=s,r=t._style._getFinalPadding();yo(i,t._anchor,e);const n=t._anchor._x*r*2,o=t._anchor._y*r*2;i.minX-=r-n,i.minY-=r-o,i.maxX-=r-n,i.maxY-=r-o}class fn{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}class ig extends fn{}class hh{constructor(t){this._renderer=t,t.runners.resolutionChange.add(this),this._managedTexts=new ce({renderer:t,type:"renderable",onUnload:this.onTextUnload.bind(this),name:"canvasText"})}resolutionChange(){for(const t in this._managedTexts.items){const e=this._managedTexts.items[t];e!=null&&e._autoResolution&&e.onViewUpdate()}}validateRenderable(t){const e=this._getGpuText(t),i=t.styleKey;return e.currentKey!==i?!0:t._didTextUpdate}addRenderable(t,e){const i=this._getGpuText(t);if(t._didTextUpdate){const r=t._autoResolution?this._renderer.resolution:t.resolution;(i.currentKey!==t.styleKey||t._resolution!==r)&&this._updateGpuText(t),t._didTextUpdate=!1,eg(i,t)}this._renderer.renderPipes.batch.addToBatch(i,e)}updateRenderable(t){const e=this._getGpuText(t);e._batcher.updateElement(e)}_updateGpuText(t){const e=this._getGpuText(t);e.texture&&this._renderer.canvasText.decreaseReferenceCount(e.currentKey),t._resolution=t._autoResolution?this._renderer.resolution:t.resolution,e.texture=this._renderer.canvasText.getManagedTexture(t),e.currentKey=t.styleKey}_getGpuText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new ig;return e.currentKey="--",e.renderable=t,e.transform=t.groupTransform,e.bounds={minX:0,maxX:1,minY:0,maxY:0},e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,this._managedTexts.add(t),e}onTextUnload(t){const e=t._gpuData[this._renderer.uid];if(!e)return;const{canvasText:i}=this._renderer;i.getReferenceCount(e.currentKey)>0?i.decreaseReferenceCount(e.currentKey):e.texture&&i.returnTexture(e.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}hh.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"text"};const sg=new Lt;function rg(s,t,e,i,r=!1){const n=sg;n.minX=0,n.minY=0,n.maxX=s.width/i|0,n.maxY=s.height/i|0;const o=Nt.getOptimalTexture(n.width,n.height,i,!1,r);return o.source.uploadMethodId="image",o.source.resource=s,o.source.alphaMode="premultiply-alpha-on-upload",o.frame.width=t/i,o.frame.height=e/i,o.source.emit("update",o.source),o.updateUvs(),o}class ch{constructor(t,e){this._activeTextures={},this._renderer=t,this._retainCanvasContext=e}getTexture(t,e,i,r){typeof t=="string"&&(K("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),t={text:t,style:i,resolution:e}),t.style instanceof Gs||(t.style=new Gs(t.style)),t.textureStyle instanceof $e||(t.textureStyle=new $e(t.textureStyle)),typeof t.text!="string"&&(t.text=t.text.toString());const{text:n,style:o,textureStyle:a,autoGenerateMipmaps:l}=t,h=t.resolution??this._renderer.resolution,{frame:c,canvasAndContext:u}=Ei.getCanvasAndContext({text:n,style:o,resolution:h}),m=rg(u.canvas,c.width,c.height,h,l);if(a&&(m.source.style=a),o.trim&&(c.pad(o.padding),m.frame.copyFrom(c),m.frame.scale(1/h),m.updateUvs()),o.filters){const f=this._applyFilters(m,o.filters);return this.returnTexture(m),Ei.returnCanvasAndContext(u),f}return this._renderer.texture.initSource(m._source),this._retainCanvasContext||Ei.returnCanvasAndContext(u),m}returnTexture(t){const e=t.source,i=e.resource;if(this._retainCanvasContext&&(i!=null&&i.getContext)){const r=i.getContext("2d");r&&Ei.returnCanvasAndContext({canvas:i,context:r})}e.resource=null,e.uploadMethodId="unknown",e.alphaMode="no-premultiply-alpha",Nt.returnTexture(t,!0)}renderTextToCanvas(){K("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(t){t._resolution=t._autoResolution?this._renderer.resolution:t.resolution;const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].texture;const i=this.getTexture({text:t.text,style:t.style,resolution:t._resolution,textureStyle:t.textureStyle,autoGenerateMipmaps:t.autoGenerateMipmaps});return this._activeTextures[e]={texture:i,usageCount:1},i}decreaseReferenceCount(t){const e=this._activeTextures[t];e&&(e.usageCount--,e.usageCount===0&&(this.returnTexture(e.texture),this._activeTextures[t]=null))}getReferenceCount(t){var e;return((e=this._activeTextures[t])==null?void 0:e.usageCount)??0}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}_applyFilters(t,e){const i=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:t,filters:e});return this._renderer.renderTarget.bind(i,!1),r}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexture(this._activeTextures[t].texture);this._activeTextures=null}}class uh extends ch{constructor(t){super(t,!0)}}uh.extension={type:[w.CanvasSystem],name:"canvasText"};class dh extends ch{constructor(t){super(t,!1)}}dh.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"canvasText"},J.add(uh),J.add(dh),J.add(hh);class ng extends Am{constructor(...t){const e=Rm(t,"Text");super(e,Gs),this.renderPipeId="text",e.textureStyle&&(this.textureStyle=e.textureStyle instanceof $e?e.textureStyle:new $e(e.textureStyle)),this.autoGenerateMipmaps=e.autoGenerateMipmaps??At.defaultOptions.autoGenerateMipmaps}updateBounds(){const t=this._bounds,e=this._anchor;let i=0,r=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Ei.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ei.returnCanvasAndContext(o),i=n.width,r=n.height}else{const n=ke.measureText(this._text,this._style);i=n.width,r=n.height}t.minX=-e._x*i,t.maxX=t.minX+i,t.minY=-e._y*r,t.maxY=t.minY+r}}function og(){const{userAgent:s}=rt.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const pn=class si{static _getPatternRepeat(t,e){const i=t&&t!=="clamp-to-edge",r=e&&e!=="clamp-to-edge";return i&&r?"repeat":i?"repeat-x":r?"repeat-y":"no-repeat"}start(t,e,i){}execute(t,e){var a,l,h,c;const i=e.elements;if(!i||!i.length)return;const r=t.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<i.length;u++){const m=i[u];if(!m.packAsQuad)continue;const f=m,g=f.texture,y=g?st.getCanvasSource(g):null;if(!y)continue;const x=g.source.style,v=n.smoothProperty,E=x.scaleMode!=="nearest";o[v]!==E&&(o[v]=E),n.setBlendMode(e.blendMode);const T=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,C=f.color,R=(T>>>24&255)/255,A=(C>>>24&255)/255,P=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,F=R*A*P;if(F<=0)continue;o.globalAlpha=F;const B=T&16777215,k=C&16777215,O=ci(hi(k,B)),L=g.frame,N=x.addressModeU??x.addressMode,H=x.addressModeV??x.addressMode,at=si._getPatternRepeat(N,H),G=g.source._resolution??g.source.resolution??1,U=(c=(h=f.renderable)==null?void 0:h.renderGroup)==null?void 0:c.isCachedAsTexture,X=L.x*G,D=L.y*G,z=L.width*G,Y=L.height*G,j=f.bounds,V=r.renderTarget.renderTarget.isRoot,ot=j.minX,lt=j.minY,gt=j.maxX-j.minX,ht=j.maxY-j.minY,_t=g.rotate,Z=g.uvs,Bt=Math.min(Z.x0,Z.x1,Z.x2,Z.x3,Z.y0,Z.y1,Z.y2,Z.y3),zt=Math.max(Z.x0,Z.x1,Z.x2,Z.x3,Z.y0,Z.y1,Z.y2,Z.y3),xt=at!=="no-repeat"&&(Bt<0||zt>1),Ut=_t&&!(!xt&&(O!==16777215||_t));Ut?(si._tempPatternMatrix.copyFrom(f.transform),it.matrixAppendRotationInv(si._tempPatternMatrix,_t,ot,lt,gt,ht),n.setContextTransform(si._tempPatternMatrix,f.roundPixels===1,void 0,U&&V)):n.setContextTransform(f.transform,f.roundPixels===1,void 0,U&&V);const $t=Ut?0:ot,Fe=Ut?0:lt,pe=gt,ei=ht;if(xt){let Ii=y;const Re=O!==16777215&&!_t,re=L.width<=g.source.width&&L.height<=g.source.height;Re&&re&&(Ii=st.getTintedCanvas({texture:g},O));const jt=o.createPattern(Ii,at);if(!jt)continue;const Pi=pe,Xs=ei;if(Pi===0||Xs===0)continue;const ne=1/Pi,Ys=1/Xs,_=(Z.x1-Z.x0)*ne,d=(Z.y1-Z.y0)*ne,p=(Z.x3-Z.x0)*Ys,b=(Z.y3-Z.y0)*Ys,S=Z.x0-_*$t-p*Fe,I=Z.y0-d*$t-b*Fe,M=g.source.pixelWidth,Q=g.source.pixelHeight;si._tempPatternMatrix.set(_*M,d*Q,p*M,b*Q,S*M,I*Q),st.applyPatternTransform(jt,si._tempPatternMatrix),o.fillStyle=jt,o.fillRect($t,Fe,pe,ei)}else{const Re=O!==16777215||_t?st.getTintedCanvas({texture:g},O):y,re=Re!==y;o.drawImage(Re,re?0:X,re?0:D,re?Re.width:z,re?Re.height:Y,$t,Fe,pe,ei)}}}};pn._tempPatternMatrix=new W,pn.extension={type:[w.CanvasPipesAdaptor],name:"batch"};let ag=pn;class fh{constructor(){this._tempState=ve.for2d(),this._didUploadHash={}}init(t){t.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(t,e,i){const r=t.renderer,n=this._didUploadHash[i.uid];r.shader.bind(i,n),n||(this._didUploadHash[i.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(e,i.glProgram)}execute(t,e){const i=t.renderer;this._tempState.blendMode=e.blendMode,i.state.set(this._tempState);const r=e.textures.textures;for(let n=0;n<e.textures.count;n++)i.texture.bind(r[n],n);i.geometry.draw(e.topology,e.size,e.start)}}fh.extension={type:[w.WebGLPipesAdaptor],name:"batch"};const Us=ve.for2d();class ph{start(t,e,i){const r=t.renderer,n=r.encoder,o=i.gpuProgram;this._shader=i,this._geometry=e,n.setGeometry(e,o),Us.blendMode="normal",r.pipeline.getPipeline(e,o,Us);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(t,e){const i=this._shader.gpuProgram,r=t.renderer,n=r.encoder;if(!e.bindGroup){const l=e.textures;e.bindGroup=Wr(l.textures,l.count,r.limits.maxBatchableTextures)}Us.blendMode=e.blendMode;const o=r.bindGroup.getBindGroup(e.bindGroup,i,1),a=r.pipeline.getPipeline(this._geometry,i,Us,e.topology);e.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(e.size,1,e.start)}}ph.extension={type:[w.WebGPUPipesAdaptor],name:"batch"};const mn=class du{constructor(t,e){var i,r;this.state=ve.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=t,this._adaptor=e,(r=(i=this._adaptor).init)==null||r.call(i,this)}static getBatcher(t){return new this._availableBatchers[t]}buildStart(t){let e=this._batchersByInstructionSet[t.uid];e||(e=this._batchersByInstructionSet[t.uid]=Object.create(null),e.default||(e.default=new Jr({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=e,this._activeBatch=this._activeBatches.default;for(const i in this._activeBatches)this._activeBatches[i].begin()}addToBatch(t,e){if(this._activeBatch.name!==t.batcherName){this._activeBatch.break(e);let i=this._activeBatches[t.batcherName];i||(i=this._activeBatches[t.batcherName]=du.getBatcher(t.batcherName),i.begin()),this._activeBatch=i}this._activeBatch.add(t)}break(t){this._activeBatch.break(t)}buildEnd(t){this._activeBatch.break(t);const e=this._activeBatches;for(const i in e){const r=e[i],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(t){const e=this._batchersByInstructionSet[t.uid];for(const i in e){const r=e[i],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(t){if(t.action==="startBatch"){const e=t.batcher,i=e.geometry,r=e.shader;this._adaptor.start(this,i,r)}this._adaptor.execute(this,t)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const t in this._activeBatches)this._activeBatches[t].destroy();this._activeBatches=null}};mn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"batch"},mn._availableBatchers=Object.create(null);let gn=mn;J.handleByMap(w.Batcher,gn._availableBatchers),J.add(Jr);const lg={name:"texture-bit",vertex:{header:`
|
|
538
|
+
*/class e_{constructor(e=0,t=0,i=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=i,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){const t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){const t=new Array(e.length);for(let i=0;i<e.length;i++){const r=e[i];t[i]=[r,this.get(r)]}return t}evict(e=!1){if(e||this.size>0){const t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){const t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){const e=new Array(this.size);let t=this.first,i=0;for(;t!==null;)e[i++]=t.key,t=t.next;return e}setWithEvicted(e,t,i=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,i);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,i=!1,r=this.resetTtl){let n=this.items[e];return i||n!==void 0?(n.value=t,i===!1&&r&&(n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(n)):(this.max>0&&this.size===this.max&&this.evict(!0),n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=n:this.last.next=n,this.last=n),this}values(e=this.keys()){const t=new Array(e.length);for(let i=0;i<e.length;i++)t[i]=this.get(e[i]);return t}}function t_(s=1e3,e=0,t=!1){if(isNaN(s)||s<0)throw new TypeError("Invalid max value");if(isNaN(e)||e<0)throw new TypeError("Invalid ttl value");if(typeof t!="boolean")throw new TypeError("Invalid resetTtl value");return new e_(s,e,t)}function Lc(s){return!!s.tagStyles&&Object.keys(s.tagStyles).length>0}function Uc(s){return s.includes("<")}function i_(s,e){return s.clone().assign(e)}function s_(s,e){const t=[],i=e.tagStyles;if(!Lc(e)||!Uc(s))return t.push({text:s,style:e}),t;const r=[e],n=[];let o="",a=0;for(;a<s.length;){const l=s[a];if(l==="<"){const c=s.indexOf(">",a);if(c===-1){o+=l,a++;continue}const h=s.slice(a+1,c);if(h.startsWith("/")){const u=h.slice(1).trim();if(n.length>0&&n[n.length-1]===u){o.length>0&&(t.push({text:o,style:r[r.length-1]}),o=""),r.pop(),n.pop(),a=c+1;continue}else{o+=s.slice(a,c+1),a=c+1;continue}}else{const u=h.trim();if(i[u]){o.length>0&&(t.push({text:o,style:r[r.length-1]}),o="");const p=r[r.length-1],d=i_(p,i[u]);r.push(d),n.push(u),a=c+1;continue}else{o+=s.slice(a,c+1),a=c+1;continue}}}else o+=l,a++}return o.length>0&&t.push({text:o,style:r[r.length-1]}),t}const r_=[10,13],n_=new Set(r_),o_=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],a_=new Set(o_),l_=[9,32];new Set(l_);const c_=[45,8208,8211,8212,173],h_=new Set(c_),u_=/(\r\n|\r|\n)/,d_=/(?:\r\n|\r|\n)/;function rr(s){return typeof s!="string"?!1:n_.has(s.charCodeAt(0))}function lt(s,e){return typeof s!="string"?!1:a_.has(s.charCodeAt(0))}function f_(s){return typeof s!="string"?!1:h_.has(s.charCodeAt(0))}function Wc(s){return s==="normal"||s==="pre-line"}function Hc(s){return s==="normal"}function kt(s){if(typeof s!="string")return"";let e=s.length-1;for(;e>=0&<(s[e]);)e--;return e<s.length-1?s.slice(0,e+1):s}function Vc(s){const e=[],t=[];if(typeof s!="string")return e;for(let i=0;i<s.length;i++){const r=s[i],n=s[i+1];if(lt(r)||rr(r)){t.length>0&&(e.push(t.join("")),t.length=0),r==="\r"&&n===`
|
|
539
|
+
`?(e.push(`\r
|
|
540
|
+
`),i++):e.push(r);continue}t.push(r),f_(r)&&n&&!lt(n)&&!rr(n)&&(e.push(t.join("")),t.length=0)}return t.length>0&&e.push(t.join("")),e}function zc(s,e,t,i){const r=t(s),n=[];for(let o=0;o<r.length;o++){let a=r[o],l=a,c=1;for(;r[o+c];){const h=r[o+c];if(!i(l,h,s,o,e))a+=h,l=h,c++;else break}o+=c-1,n.push(a)}return n}const p_=/\r\n|\r|\n/g;function m_(s,e,t,i,r,n,o,a){var te,F;const l=s_(s,e);if(Hc(e.whiteSpace))for(let L=0;L<l.length;L++){const X=l[L];l[L]={text:X.text.replace(p_," "),style:X.style}}const h=[];let u=[];for(const L of l){const X=L.text.split(u_);for(let N=0;N<X.length;N++){const V=X[N];V===`\r
|
|
541
|
+
`||V==="\r"||V===`
|
|
542
|
+
`?(h.push(u),u=[]):V.length>0&&u.push({text:V,style:L.style})}}(u.length>0||h.length===0)&&h.push(u);const p=t?g_(h,e,i,r,o,a):h,d=[],g=[],_=[],y=[],x=[];let v=0;const C=e._fontString,T=n(C);T.fontSize===0&&(T.fontSize=e.fontSize,T.ascent=e.fontSize);let A="",w=!!e.dropShadow,R=((te=e._stroke)==null?void 0:te.width)||0;for(const L of p){let X=0,N=T.ascent,V=T.descent,K="";for(const $ of L){const se=$.style._fontString,ue=n(se);se!==A&&(i.font=se,A=se);const z=r($.text,$.style.letterSpacing,i);X+=z,N=Math.max(N,ue.ascent),V=Math.max(V,ue.descent),K+=$.text;const Q=((F=$.style._stroke)==null?void 0:F.width)||0;Q>R&&(R=Q),!w&&$.style.dropShadow&&(w=!0)}L.length===0&&(N=T.ascent,V=T.descent),d.push(X),g.push(N),_.push(V),x.push(K);const H=e.lineHeight||N+V;y.push(H+e.leading),v=Math.max(v,X)}const D=R,O=(t&&e.align!=="left"?Math.max(v,e.wordWrapWidth):v)+D+(e.dropShadow?e.dropShadow.distance:0);let G=0;for(let L=0;L<y.length;L++)G+=y[L];G=Math.max(G,y[0]+D);const U=G+(e.dropShadow?e.dropShadow.distance:0),W=e.lineHeight||T.fontSize;return{width:O,height:U,lines:x,lineWidths:d,lineHeight:W+e.leading,maxLineWidth:v,fontProperties:T,runsByLine:p,lineAscents:g,lineDescents:_,lineHeights:y,hasDropShadow:w}}function g_(s,e,t,i,r,n){var y;const{letterSpacing:o,whiteSpace:a,wordWrapWidth:l,breakWords:c}=e,h=Wc(a),u=l+o,p={};let d="";const g=(x,v)=>{const C=`${x}|${v.styleKey}`;let T=p[C];if(T===void 0){const A=v._fontString;A!==d&&(t.font=A,d=A),T=i(x,v.letterSpacing,t)+v.letterSpacing,p[C]=T}return T},_=[];for(const x of s){const v=__(x),C=_.length,T=G=>{let U=0,W=G;do{const{token:te,style:F}=v[W];U+=g(te,F),W++}while(W<v.length&&v[W].continuesFromPrevious);return U},A=G=>{const U=[];let W=G;do U.push({token:v[W].token,style:v[W].style}),W++;while(W<v.length&&v[W].continuesFromPrevious);return U};let w=[],R=0,D=!h,B=null;const k=()=>{B&&B.text.length>0&&w.push(B),B=null},O=()=>{if(k(),w.length>0){const G=w[w.length-1];G.text=kt(G.text),G.text.length===0&&w.pop()}_.push(w),w=[],R=0,D=!1};for(let G=0;G<v.length;G++){const{token:U,style:W,continuesFromPrevious:te}=v[G],F=g(U,W);if(h){const N=lt(U),V=(B==null?void 0:B.text[B.text.length-1])??((y=w[w.length-1])==null?void 0:y.text.slice(-1))??"",K=V?lt(V):!1;if(N&&K)continue}const L=!te,X=L?T(G):F;if(X>u&&L)if(R>0&&O(),c){const N=A(G);for(let V=0;V<N.length;V++){const K=N[V].token,H=N[V].style,$=zc(K,c,n,r);for(const se of $){const ue=g(se,H);ue+R>u&&O(),!B||B.style!==H?(k(),B={text:se,style:H}):B.text+=se,R+=ue}}G+=N.length-1}else{const N=A(G);k(),_.push(N.map(V=>({text:V.token,style:V.style}))),D=!1,G+=N.length-1}else if(X+R>u&&L){if(lt(U)){D=!1;continue}O(),B={text:U,style:W},R=F}else if(te&&!c)!B||B.style!==W?(k(),B={text:U,style:W}):B.text+=U,R+=F;else{const N=lt(U);if(R===0&&N&&!D)continue;!B||B.style!==W?(k(),B={text:U,style:W}):B.text+=U,R+=F}}if(k(),w.length>0){const G=w[w.length-1];G.text=kt(G.text),G.text.length===0&&w.pop()}(w.length>0||_.length===C)&&_.push(w)}return _}function __(s){const e=[];let t=!1;for(const i of s){const r=Vc(i.text);let n=!0;for(const o of r){const a=lt(o)||rr(o),l=n&&t&&!a;e.push({token:o,style:i.style,continuesFromPrevious:l}),t=!a,n=!1}}return e}const y_={willReadFrequently:!0};function $c(s,e,t,i,r){let n=t[s];return typeof n!="number"&&(n=r(s,e,i)+e,t[s]=n),n}function b_(s,e,t,i,r,n,o){const a=t.getContext("2d",y_);a.font=e._fontString;let l=0,c="";const h=[],u=Object.create(null),{letterSpacing:p,whiteSpace:d}=e,g=Wc(d),_=Hc(d);let y=!g;const x=e.wordWrapWidth+p,v=Vc(s);for(let T=0;T<v.length;T++){let A=v[T];if(rr(A)){if(!_){h.push(kt(c)),y=!g,c="",l=0;continue}A=" "}if(g){const R=lt(A),D=lt(c[c.length-1]);if(R&&D)continue}const w=$c(A,p,u,a,i);if(w>x)if(c!==""&&(h.push(kt(c)),c="",l=0),r(A,e.breakWords)){const R=zc(A,e.breakWords,o,n);for(const D of R){const B=$c(D,p,u,a,i);B+l>x&&(h.push(kt(c)),y=!1,c="",l=0),c+=D,l+=B}}else c.length>0&&(h.push(kt(c)),c="",l=0),h.push(kt(A)),y=!1,c="",l=0;else w+l>x&&(y=!1,h.push(kt(c)),c="",l=0),(c.length>0||!lt(A)||y)&&(c+=A,l+=w)}const C=kt(c);return C.length>0&&h.push(C),h.join(`
|
|
543
|
+
`)}const jc={willReadFrequently:!0},Bt=class Z{static get experimentalLetterSpacingSupported(){let e=Z._experimentalLetterSpacingSupported;if(e===void 0){const t=de.get().getCanvasRenderingContext2D().prototype;e=Z._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,i,r,n,o,a,l,c,h){this.text=e,this.style=t,this.width=i,this.height=r,this.lines=n,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=l,this.fontProperties=c,h&&(this.runsByLine=h.runsByLine,this.lineAscents=h.lineAscents,this.lineDescents=h.lineDescents,this.lineHeights=h.lineHeights,this.hasDropShadow=h.hasDropShadow)}static measureText(e=" ",t,i=Z._canvas,r=t.wordWrap){var A;const n=`${e}-${t.styleKey}-wordWrap-${r}`;if(Z._measurementCache.has(n))return Z._measurementCache.get(n);if(Lc(t)&&Uc(e)){const w=m_(e,t,r,Z._context,Z._measureText,Z.measureFont,Z.canBreakChars,Z.wordWrapSplit),R=new Z(e,t,w.width,w.height,w.lines,w.lineWidths,w.lineHeight,w.maxLineWidth,w.fontProperties,{runsByLine:w.runsByLine,lineAscents:w.lineAscents,lineDescents:w.lineDescents,lineHeights:w.lineHeights,hasDropShadow:w.hasDropShadow});return Z._measurementCache.set(n,R),R}const a=t._fontString,l=Z.measureFont(a);l.fontSize===0&&(l.fontSize=t.fontSize,l.ascent=t.fontSize,l.descent=0);const c=Z._context;c.font=a;const u=(r?Z._wordWrap(e,t,i):e).split(d_),p=new Array(u.length);let d=0;for(let w=0;w<u.length;w++){const R=Z._measureText(u[w],t.letterSpacing,c);p[w]=R,d=Math.max(d,R)}const g=((A=t._stroke)==null?void 0:A.width)??0,_=t.lineHeight||l.fontSize,y=Z._getAlignWidth(d,t,r),x=Z._adjustWidthForStyle(y,t),v=Math.max(_,l.fontSize+g)+(u.length-1)*(_+t.leading),C=Z._adjustHeightForStyle(v,t),T=new Z(e,t,x,C,u,p,_+t.leading,d,l);return Z._measurementCache.set(n,T),T}static _adjustWidthForStyle(e,t){var n;const i=((n=t._stroke)==null?void 0:n.width)||0;let r=e+i;return t.dropShadow&&(r+=t.dropShadow.distance),r}static _adjustHeightForStyle(e,t){let i=e;return t.dropShadow&&(i+=t.dropShadow.distance),i}static _getAlignWidth(e,t,i){return i&&t.align!=="left"?Math.max(e,t.wordWrapWidth):e}static _measureText(e,t,i){let r=!1;Z.experimentalLetterSpacingSupported&&(Z.experimentalLetterSpacing?(i.letterSpacing=`${t}px`,i.textLetterSpacing=`${t}px`,r=!0):(i.letterSpacing="0px",i.textLetterSpacing="0px"));const n=i.measureText(e);let o=n.width;const a=-(n.actualBoundingBoxLeft??0);let c=(n.actualBoundingBoxRight??0)-a;if(o>0)if(r)o-=t,c-=t;else{const h=(Z.graphemeSegmenter(e).length-1)*t;o+=h,c+=h}return Math.max(o,c)}static _wordWrap(e,t,i=Z._canvas){return b_(e,t,i,Z._measureText,Z.canBreakWords,Z.canBreakChars,Z.wordWrapSplit)}static isBreakingSpace(e,t){return lt(e)}static canBreakWords(e,t){return t}static canBreakChars(e,t,i,r,n){return!0}static wordWrapSplit(e){return Z.graphemeSegmenter(e)}static measureFont(e){if(Z._fonts[e])return Z._fonts[e];const t=Z._context;t.font=e;const i=t.measureText(Z.METRICS_STRING+Z.BASELINE_SYMBOL),r=i.actualBoundingBoxAscent??0,n=i.actualBoundingBoxDescent??0,o={ascent:r,descent:n,fontSize:r+n};return Z._fonts[e]=o,o}static clearMetrics(e=""){e?delete Z._fonts[e]:Z._fonts={}}static get _canvas(){if(!Z.__canvas){let e;try{const t=new OffscreenCanvas(0,0),i=t.getContext("2d",jc);if(i!=null&&i.measureText)return Z.__canvas=t,t;e=de.get().createCanvas()}catch{e=de.get().createCanvas()}e.width=e.height=10,Z.__canvas=e}return Z.__canvas}static get _context(){return Z.__context||(Z.__context=Z._canvas.getContext("2d",jc)),Z.__context}};Bt.METRICS_STRING="|ÉqÅ",Bt.BASELINE_SYMBOL="M",Bt.BASELINE_MULTIPLIER=1.4,Bt.HEIGHT_MULTIPLIER=2,Bt.graphemeSegmenter=(()=>{if(typeof(Intl==null?void 0:Intl.Segmenter)=="function"){const s=new Intl.Segmenter;return e=>{const t=s.segment(e),i=[];let r=0;for(const n of t)i[r++]=n.segment;return i}}return s=>[...s]})(),Bt.experimentalLetterSpacing=!1,Bt._fonts={},Bt._measurementCache=t_(1e3);let Ht=Bt;const x_=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function zn(s){const e=typeof s.fontSize=="number"?`${s.fontSize}px`:s.fontSize;let t=s.fontFamily;Array.isArray(s.fontFamily)||(t=s.fontFamily.split(","));for(let i=t.length-1;i>=0;i--){let r=t[i].trim();!/([\"\'])[^\'\"]+\1/.test(r)&&!x_.includes(r)&&(r=`"${r}"`),t[i]=r}return`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${e} ${t.join(",")}`}const Xc=1e5;function nr(s,e,t,i=0,r=0,n=0){if(s.texture===q.WHITE&&!s.fill)return be.shared.setValue(s.color).setAlpha(s.alpha??1).toHexa();if(s.fill){if(s.fill instanceof bs){const o=s.fill,a=e.createPattern(o.texture.source.resource,"repeat"),l=o.transform.copyTo(Y.shared);return l.scale(o.texture.source.pixelWidth,o.texture.source.pixelHeight),a.setTransform(l),a}else if(s.fill instanceof xt){const o=s.fill,a=o.type==="linear",l=o.textureSpace==="local";let c=1,h=1;l&&t&&(c=t.width+i,h=t.height+i);let u,p=!1;if(a){const{start:d,end:g}=o;u=e.createLinearGradient(d.x*c+r,d.y*h+n,g.x*c+r,g.y*h+n),p=Math.abs(g.x-d.x)<Math.abs((g.y-d.y)*.1)}else{const{center:d,innerRadius:g,outerCenter:_,outerRadius:y}=o;u=e.createRadialGradient(d.x*c+r,d.y*h+n,g*c,_.x*c+r,_.y*h+n,y*c)}if(p&&l&&t){const d=t.lineHeight/h;for(let g=0;g<t.lines.length;g++){const _=(g*t.lineHeight+i/2)/h;o.colorStops.forEach(y=>{let x=_+y.offset*d;x=Math.max(0,Math.min(1,x)),u.addColorStop(Math.floor(x*Xc)/Xc,be.shared.setValue(y.color).toHex())})}}else o.colorStops.forEach(d=>{u.addColorStop(d.offset,be.shared.setValue(d.color).toHex())});return u}}else{const o=e.createPattern(s.texture.source.resource,"repeat"),a=s.matrix.copyTo(Y.shared);return a.scale(s.texture.source.pixelWidth,s.texture.source.pixelHeight),o.setTransform(a),o}return ne("FillStyle not recognised",s),"red"}const Yc=new ye;function Bi(s){let e=0;for(let t=0;t<s.length;t++)s.charCodeAt(t)===32&&e++;return e}class v_{getCanvasAndContext(e){const{text:t,style:i,resolution:r=1}=e,n=i._getFinalPadding(),o=Ht.measureText(t||" ",i),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*r),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*r),c=Ss.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(i,n,r,c,o);const h=i.trim?Qg({canvas:c.canvas,width:a,height:l,resolution:1,output:Yc}):Yc.set(0,0,a,l);return{canvasAndContext:c,frame:h}}returnCanvasAndContext(e){Ss.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,i,r,n){var w,R,D;if(n.runsByLine&&n.runsByLine.length>0){this._renderTaggedTextToCanvas(n,e,t,i,r);return}const{canvas:o,context:a}=r,l=zn(e),c=n.lines,h=n.lineHeight,u=n.lineWidths,p=n.maxLineWidth,d=n.fontProperties,g=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=e.textBaseline,(w=e._stroke)!=null&&w.width){const B=e._stroke;a.lineWidth=B.width,a.miterLimit=B.miterLimit,a.lineJoin=B.join,a.lineCap=B.cap}a.font=l;let _,y;const x=e.dropShadow?2:1,v=e.wordWrap?Math.max(e.wordWrapWidth,p):p,T=(((R=e._stroke)==null?void 0:R.width)??0)/2;let A=(h-d.fontSize)/2;h-d.fontSize<0&&(A=0);for(let B=0;B<x;++B){const k=e.dropShadow&&B===0,O=k?Math.ceil(Math.max(1,g)+t*2):0,G=O*i;if(k)this._setupDropShadow(a,e,i,G);else{const U=e._gradientBounds,W=e._gradientOffset;if(U){const te={width:U.width,height:U.height,lineHeight:U.height,lines:n.lines};this._setFillAndStrokeStyles(a,e,te,t,T,(W==null?void 0:W.x)??0,(W==null?void 0:W.y)??0)}else W?this._setFillAndStrokeStyles(a,e,n,t,T,W.x,W.y):this._setFillAndStrokeStyles(a,e,n,t,T);a.shadowColor="rgba(0,0,0,0)"}for(let U=0;U<c.length;U++){_=T,y=T+U*h+d.ascent+A,_+=this._getAlignmentOffset(u[U],v,e.align);let W=0;if(e.align==="justify"&&e.wordWrap&&U<c.length-1){const te=Bi(c[U]);te>0&&(W=(v-u[U])/te)}(D=e._stroke)!=null&&D.width&&this._drawLetterSpacing(c[U],e,r,_+t,y+t-O,!0,W),e._fill!==void 0&&this._drawLetterSpacing(c[U],e,r,_+t,y+t-O,!1,W)}}}_renderTaggedTextToCanvas(e,t,i,r,n){var T,A,w;const{canvas:o,context:a}=n,{runsByLine:l,lineWidths:c,maxLineWidth:h,lineAscents:u,lineHeights:p,hasDropShadow:d}=e,g=o.height;a.resetTransform(),a.scale(r,r),a.textBaseline=t.textBaseline;const _=d?2:1,y=t.wordWrap?Math.max(t.wordWrapWidth,h):h;let x=((T=t._stroke)==null?void 0:T.width)??0;for(const R of l)for(const D of R){const B=((A=D.style._stroke)==null?void 0:A.width)??0;B>x&&(x=B)}const v=x/2,C=[];for(let R=0;R<l.length;R++){const D=l[R],B=[];for(const k of D){const O=zn(k.style);a.font=O,B.push({width:Ht._measureText(k.text,k.style.letterSpacing,a),font:O})}C.push(B)}for(let R=0;R<_;++R){const D=d&&R===0,B=D?Math.ceil(Math.max(1,g)+i*2):0,k=B*r;D||(a.shadowColor="rgba(0,0,0,0)");let O=v;for(let G=0;G<l.length;G++){const U=l[G],W=c[G],te=u[G],F=p[G],L=C[G];let X=v;X+=this._getAlignmentOffset(W,y,t.align);let N=0;if(t.align==="justify"&&t.wordWrap&&G<l.length-1){let H=0;for(const $ of U)H+=Bi($.text);H>0&&(N=(y-W)/H)}const V=O+te;let K=X+i;for(let H=0;H<U.length;H++){const $=U[H],{width:se,font:ue}=L[H];if(a.font=ue,a.textBaseline=$.style.textBaseline,(w=$.style._stroke)!=null&&w.width){const Q=$.style._stroke;if(a.lineWidth=Q.width,a.miterLimit=Q.miterLimit,a.lineJoin=Q.join,a.lineCap=Q.cap,D)if($.style.dropShadow)this._setupDropShadow(a,$.style,r,k);else{const ae=Bi($.text);K+=se+ae*N;continue}else{const ae=Ht.measureFont(ue),j=$.style.lineHeight||ae.fontSize,_e={width:se,height:j,lineHeight:j,lines:[$.text]};a.strokeStyle=nr(Q,a,_e,i*2,K-i,O)}this._drawLetterSpacing($.text,$.style,n,K,V+i-B,!0,N)}const z=Bi($.text);K+=se+z*N}K=X+i;for(let H=0;H<U.length;H++){const $=U[H],{width:se,font:ue}=L[H];if(a.font=ue,a.textBaseline=$.style.textBaseline,$.style._fill!==void 0){if(D)if($.style.dropShadow)this._setupDropShadow(a,$.style,r,k);else{const Q=Bi($.text);K+=se+Q*N;continue}else{const Q=Ht.measureFont(ue),ae=$.style.lineHeight||Q.fontSize,j={width:se,height:ae,lineHeight:ae,lines:[$.text]};a.fillStyle=nr($.style._fill,a,j,i*2,K-i,O)}this._drawLetterSpacing($.text,$.style,n,K,V+i-B,!1,N)}const z=Bi($.text);K+=se+z*N}O+=F}}}_setFillAndStrokeStyles(e,t,i,r,n,o=0,a=0){var l;if(e.fillStyle=t._fill?nr(t._fill,e,i,r*2,o,a):null,(l=t._stroke)!=null&&l.width){const c=n+r*2;e.strokeStyle=nr(t._stroke,e,i,c,o,a)}}_setupDropShadow(e,t,i,r){e.fillStyle="black",e.strokeStyle="black";const n=t.dropShadow,o=n.color,a=n.alpha;e.shadowColor=be.shared.setValue(o).setAlpha(a).toRgbaString();const l=n.blur*i,c=n.distance*i;e.shadowBlur=l,e.shadowOffsetX=Math.cos(n.angle)*c,e.shadowOffsetY=Math.sin(n.angle)*c+r}_getAlignmentOffset(e,t,i){return i==="right"?t-e:i==="center"?(t-e)/2:0}_drawLetterSpacing(e,t,i,r,n,o=!1,a=0){const{context:l}=i,c=t.letterSpacing;let h=!1;if(Ht.experimentalLetterSpacingSupported&&(Ht.experimentalLetterSpacing?(l.letterSpacing=`${c}px`,l.textLetterSpacing=`${c}px`,h=!0):(l.letterSpacing="0px",l.textLetterSpacing="0px")),(c===0||h)&&a===0){o?l.strokeText(e,r,n):l.fillText(e,r,n);return}if(a!==0&&(c===0||h)){const _=e.split(" ");let y=r;const x=l.measureText(" ").width;for(let v=0;v<_.length;v++)o?l.strokeText(_[v],y,n):l.fillText(_[v],y,n),y+=l.measureText(_[v]).width+x+a;return}let u=r;const p=Ht.graphemeSegmenter(e);let d=l.measureText(e).width,g=0;for(let _=0;_<p.length;++_){const y=p[_];o?l.strokeText(y,u,n):l.fillText(y,u,n);let x="";for(let v=_+1;v<p.length;++v)x+=p[v];g=l.measureText(x).width,u+=d-g+c,y===" "&&(u+=a),d=g}}}const Oi=new v_,$n=class pi extends nt{constructor(e={}){super(),this.uid=xe("textStyle"),this._tick=0,this._cachedFontString=null,S_(e),e instanceof pi&&(e=e._toObject());const r={...pi.defaultTextStyle,...e};for(const n in r){const o=n;this[o]=r[n]}this._tagStyles=e.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(e){this._dropShadow!==e&&(e!==null&&typeof e=="object"?this._dropShadow=this._createProxy({...pi.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...pi.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(typeof e=="string"?this._fontSize=parseInt(e,10):this._fontSize=e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...ht.defaultFillStyle,...e},()=>{this._fill=li({...this._originalFill},ht.defaultFillStyle)})),this._fill=li(e===0?"black":e,ht.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...ht.defaultStrokeStyle,...e},()=>{this._stroke=tr({...this._originalStroke},ht.defaultStrokeStyle)})),this._stroke=tr(e,ht.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(e){this._tagStyles!==e&&(this._tagStyles=e??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit("update",this)}reset(){const e=pi.defaultTextStyle;for(const t in e)this[t]=e[t]}assign(e){for(const t in e){const i=t;this[i]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=zn(this)),this._cachedFontString}_toObject(){return{align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill?{...this._fill}:void 0,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke?{...this._stroke}:void 0,textBaseline:this.textBaseline,trim:this.trim,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0,tagStyles:this._tagStyles?{...this._tagStyles}:void 0}}clone(){return new pi(this._toObject())}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){var i,r,n,o;if(this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const a=typeof e=="boolean"?e:e==null?void 0:e.textureSource;(i=this._fill)!=null&&i.texture&&this._fill.texture.destroy(a),(r=this._originalFill)!=null&&r.texture&&this._originalFill.texture.destroy(a),(n=this._stroke)!=null&&n.texture&&this._stroke.texture.destroy(a),(o=this._originalStroke)!=null&&o.texture&&this._originalStroke.texture.destroy(a)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(i,r,n)=>(i[r]===n||(i[r]=n,t==null||t(r,n),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(be.isColorLike(e)||e instanceof xt||e instanceof bs)}};$n.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},$n.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let or=$n;function S_(s){const e=s;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=or.defaultDropShadow;s.dropShadow={alpha:e.dropShadowAlpha??t.alpha,angle:e.dropShadowAngle??t.angle,blur:e.dropShadowBlur??t.blur,color:e.dropShadowColor??t.color,distance:e.dropShadowDistance??t.distance}}if(e.strokeThickness!==void 0){J(Ie,"strokeThickness is now a part of stroke");const t=e.stroke;let i={};if(be.isColorLike(t))i.color=t;else if(t instanceof xt||t instanceof bs)i.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))i=t;else throw new Error("Invalid stroke value.");s.stroke={...i,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(J(Ie,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(e.fill)||e.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");e.fill.length!==e.fillGradientStops.length&&ne("The number of fill colors must match the number of fill gradient stops.");const t=new xt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=e.fillGradientStops.slice(),r=e.fill.map(n=>be.shared.setValue(n).toNumber());i.forEach((n,o)=>{t.addColorStop(n,r[o])}),s.fill={fill:t}}}function C_(s,e){const{texture:t,bounds:i}=s,r=e._style._getFinalPadding();ra(i,e._anchor,t);const n=e._anchor._x*r*2,o=e._anchor._y*r*2;i.minX-=r-n,i.minY-=r-o,i.maxX-=r-n,i.maxY-=r-o}class jn{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}class T_ extends jn{}class Kc{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),this._managedTexts=new bt({renderer:e,type:"renderable",onUnload:this.onTextUnload.bind(this),name:"canvasText"})}resolutionChange(){for(const e in this._managedTexts.items){const t=this._managedTexts.items[e];t!=null&&t._autoResolution&&t.onViewUpdate()}}validateRenderable(e){const t=this._getGpuText(e),i=e.styleKey;return t.currentKey!==i?!0:e._didTextUpdate}addRenderable(e,t){const i=this._getGpuText(e);if(e._didTextUpdate){const r=e._autoResolution?this._renderer.resolution:e.resolution;(i.currentKey!==e.styleKey||e._resolution!==r)&&this._updateGpuText(e),e._didTextUpdate=!1,C_(i,e)}this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new T_;return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){const t=e._gpuData[this._renderer.uid];if(!t)return;const{canvasText:i}=this._renderer;i.getReferenceCount(t.currentKey)>0?i.decreaseReferenceCount(t.currentKey):t.texture&&i.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}Kc.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"text"};const E_=new je;function w_(s,e,t,i,r=!1){const n=E_;n.minX=0,n.minY=0,n.maxX=s.width/i|0,n.maxY=s.height/i|0;const o=Xe.getOptimalTexture(n.width,n.height,i,!1,r);return o.source.uploadMethodId="image",o.source.resource=s,o.source.alphaMode="premultiply-alpha-on-upload",o.frame.width=e/i,o.frame.height=t/i,o.source.emit("update",o.source),o.updateUvs(),o}class qc{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,i,r){typeof e=="string"&&(J("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:i,resolution:t}),e.style instanceof or||(e.style=new or(e.style)),e.textureStyle instanceof si||(e.textureStyle=new si(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:n,style:o,textureStyle:a,autoGenerateMipmaps:l}=e,c=e.resolution??this._renderer.resolution,{frame:h,canvasAndContext:u}=Oi.getCanvasAndContext({text:n,style:o,resolution:c}),p=w_(u.canvas,h.width,h.height,c,l);if(a&&(p.source.style=a),o.trim&&(h.pad(o.padding),p.frame.copyFrom(h),p.frame.scale(1/c),p.updateUvs()),o.filters){const d=this._applyFilters(p,o.filters);return this.returnTexture(p),Oi.returnCanvasAndContext(u),d}return this._renderer.texture.initSource(p._source),this._retainCanvasContext||Oi.returnCanvasAndContext(u),p}returnTexture(e){const t=e.source,i=t.resource;if(this._retainCanvasContext&&(i!=null&&i.getContext)){const r=i.getContext("2d");r&&Oi.returnCanvasAndContext({canvas:i,context:r})}t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",Xe.returnTexture(e,!0)}renderTextToCanvas(){J("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const i=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:i,usageCount:1},i}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){var t;return((t=this._activeTextures[e])==null?void 0:t.usageCount)??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const i=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(i,!1),r}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}class Zc extends qc{constructor(e){super(e,!0)}}Zc.extension={type:[I.CanvasSystem],name:"canvasText"};class Jc extends qc{constructor(e){super(e,!1)}}Jc.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"canvasText"},ie.add(Zc),ie.add(Jc),ie.add(Kc);class I_ extends Kg{constructor(...e){const t=qg(e,"Text");super(t,or),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof si?t.textureStyle:new si(t.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??De.defaultOptions.autoGenerateMipmaps}updateBounds(){const e=this._bounds,t=this._anchor;let i=0,r=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Oi.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Oi.returnCanvasAndContext(o),i=n.width,r=n.height}else{const n=Ht.measureText(this._text,this._style);i=n.width,r=n.height}e.minX=-t._x*i,e.maxX=e.minX+i,e.minY=-t._y*r,e.maxY=e.minY+r}}function A_(){const{userAgent:s}=de.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const Xn=class mi{static _getPatternRepeat(e,t){const i=e&&e!=="clamp-to-edge",r=t&&t!=="clamp-to-edge";return i&&r?"repeat":i?"repeat-x":r?"repeat-y":"no-repeat"}start(e,t,i){}execute(e,t){var a,l,c,h;const i=t.elements;if(!i||!i.length)return;const r=e.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<i.length;u++){const p=i[u];if(!p.packAsQuad)continue;const d=p,g=d.texture,_=g?he.getCanvasSource(g):null;if(!_)continue;const y=g.source.style,x=n.smoothProperty,v=y.scaleMode!=="nearest";o[x]!==v&&(o[x]=v),n.setBlendMode(t.blendMode);const C=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,T=d.color,A=(C>>>24&255)/255,w=(T>>>24&255)/255,R=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,D=A*w*R;if(D<=0)continue;o.globalAlpha=D;const B=C&16777215,k=T&16777215,O=Si(vi(k,B)),G=g.frame,U=y.addressModeU??y.addressMode,W=y.addressModeV??y.addressMode,te=mi._getPatternRepeat(U,W),F=g.source._resolution??g.source.resolution??1,L=(h=(c=d.renderable)==null?void 0:c.renderGroup)==null?void 0:h.isCachedAsTexture,X=G.x*F,N=G.y*F,V=G.width*F,K=G.height*F,H=d.bounds,$=r.renderTarget.renderTarget.isRoot,se=H.minX,ue=H.minY,z=H.maxX-H.minX,Q=H.maxY-H.minY,ae=g.rotate,j=g.uvs,_e=Math.min(j.x0,j.x1,j.x2,j.x3,j.y0,j.y1,j.y2,j.y3),ee=Math.max(j.x0,j.x1,j.x2,j.x3,j.y0,j.y1,j.y2,j.y3),le=te!=="no-repeat"&&(_e<0||ee>1),pe=ae&&!(!le&&(O!==16777215||ae));pe?(mi._tempPatternMatrix.copyFrom(d.transform),ce.matrixAppendRotationInv(mi._tempPatternMatrix,ae,se,ue,z,Q),n.setContextTransform(mi._tempPatternMatrix,d.roundPixels===1,void 0,L&&$)):n.setContextTransform(d.transform,d.roundPixels===1,void 0,L&&$);const Ve=pe?0:se,Jt=pe?0:ue,St=z,fi=Q;if(le){let Yi=_;const Ft=O!==16777215&&!ae,ft=G.width<=g.source.width&&G.height<=g.source.height;Ft&&ft&&(Yi=he.getTintedCanvas({texture:g},O));const et=o.createPattern(Yi,te);if(!et)continue;const Ki=St,wr=fi;if(Ki===0||wr===0)continue;const pt=1/Ki,Ir=1/wr,b=(j.x1-j.x0)*pt,f=(j.y1-j.y0)*pt,m=(j.x3-j.x0)*Ir,S=(j.y3-j.y0)*Ir,E=j.x0-b*Ve-m*Jt,M=j.y0-f*Ve-S*Jt,P=g.source.pixelWidth,re=g.source.pixelHeight;mi._tempPatternMatrix.set(b*P,f*re,m*P,S*re,E*P,M*re),he.applyPatternTransform(et,mi._tempPatternMatrix),o.fillStyle=et,o.fillRect(Ve,Jt,St,fi)}else{const Ft=O!==16777215||ae?he.getTintedCanvas({texture:g},O):_,ft=Ft!==_;o.drawImage(Ft,ft?0:X,ft?0:N,ft?Ft.width:V,ft?Ft.height:K,Ve,Jt,St,fi)}}}};Xn._tempPatternMatrix=new Y,Xn.extension={type:[I.CanvasPipesAdaptor],name:"batch"};let R_=Xn;class Qc{constructor(){this._tempState=At.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,i){const r=e.renderer,n=this._didUploadHash[i.uid];r.shader.bind(i,n),n||(this._didUploadHash[i.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,i.glProgram)}execute(e,t){const i=e.renderer;this._tempState.blendMode=t.blendMode,i.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)i.texture.bind(r[n],n);i.geometry.draw(t.topology,t.size,t.start)}}Qc.extension={type:[I.WebGLPipesAdaptor],name:"batch"};const ar=At.for2d();class eh{start(e,t,i){const r=e.renderer,n=r.encoder,o=i.gpuProgram;this._shader=i,this._geometry=t,n.setGeometry(t,o),ar.blendMode="normal",r.pipeline.getPipeline(t,o,ar);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const i=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Sn(l.textures,l.count,r.limits.maxBatchableTextures)}ar.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,i,1),a=r.pipeline.getPipeline(this._geometry,i,ar,t.topology);t.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}eh.extension={type:[I.WebGPUPipesAdaptor],name:"batch"};const Yn=class Od{constructor(e,t){var i,r;this.state=At.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,(r=(i=this._adaptor).init)==null||r.call(i,this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new kn({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const i in this._activeBatches)this._activeBatches[i].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let i=this._activeBatches[e.batcherName];i||(i=this._activeBatches[e.batcherName]=Od.getBatcher(e.batcherName),i.begin()),this._activeBatch=i}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const i in t){const r=t[i],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const i in t){const r=t[i],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,i=t.geometry,r=t.shader;this._adaptor.start(this,i,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};Yn.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"batch"},Yn._availableBatchers=Object.create(null);let Kn=Yn;ie.handleByMap(I.Batcher,Kn._availableBatchers),ie.add(kn);const M_={name:"texture-bit",vertex:{header:`
|
|
544
544
|
|
|
545
545
|
struct TextureUniforms {
|
|
546
546
|
uTextureMatrix:mat3x3<f32>,
|
|
@@ -556,7 +556,7 @@ fn mainFragment(
|
|
|
556
556
|
|
|
557
557
|
`,main:`
|
|
558
558
|
outColor = textureSample(uTexture, uSampler, vUV);
|
|
559
|
-
`}},
|
|
559
|
+
`}},P_={name:"texture-bit",vertex:{header:`
|
|
560
560
|
uniform mat3 uTextureMatrix;
|
|
561
561
|
`,main:`
|
|
562
562
|
uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
@@ -566,9 +566,9 @@ fn mainFragment(
|
|
|
566
566
|
|
|
567
567
|
`,main:`
|
|
568
568
|
outColor = texture(uTexture, vUV);
|
|
569
|
-
`}},cg=new Lt;class ug extends ps{constructor(){super(),this.filters=[new vm({sprite:new ye($.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(t){this.filters[0].sprite=t}get inverse(){return this.filters[0].inverse}set inverse(t){this.filters[0].inverse=t}}class _n{constructor(t){this._activeMaskStage=[],this._renderer=t}push(t,e,i){const r=this._renderer;if(r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1,maskedContainer:e}),t.inverse=e._maskOptions.inverse,t.renderMaskToTexture){const n=t.mask;n.includeInBuild=!0,n.collectRenderables(i,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:t,maskedContainer:e,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){const e=this._renderer,i=t.mask.renderMaskToTexture;if(t.action==="pushMaskBegin"){const r=Mt.get(ug);if(r.inverse=t.inverse,i){t.mask.mask.measurable=!0;const n=cr(t.mask.mask,!0,cg);t.mask.mask.measurable=!1,n.ceil();const o=e.renderTarget.renderTarget.colorTexture.source,a=Nt.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);e.renderTarget.push(a,!0),e.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:t.maskedContainer,filterTexture:a})}else r.sprite=t.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:t.maskedContainer})}else if(t.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];i&&(e.type===he.WEBGL&&e.renderTarget.finishRenderPass(),e.renderTarget.pop(),e.globalUniforms.pop()),e.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(t.action==="popMaskEnd"){e.filter.pop();const r=this._activeMaskStage.pop();i&&Nt.returnTexture(r.filterTexture),Mt.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}_n.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"alphaMask"};class mh{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&t.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(t,e,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(t){}destroy(){this._renderer=null,this._colorStack=null}}mh.extension={type:[w.CanvasPipes],name:"colorMask"};class gh{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&t.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(t,e,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(t){this._renderer.colorMask.setMask(t.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}gh.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"colorMask"};function dg(s,t,e,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(t+n,e),s.lineTo(t+i-n,e),s.quadraticCurveTo(t+i,e,t+i,e+n),s.lineTo(t+i,e+r-n),s.quadraticCurveTo(t+i,e+r,t+i-n,e+r),s.lineTo(t+n,e+r),s.quadraticCurveTo(t,e+r,t,e+r-n),s.lineTo(t,e+n),s.quadraticCurveTo(t,e,t+n,e)}function _h(s,t){switch(t.type){case"rectangle":{const e=t;s.rect(e.x,e.y,e.width,e.height);break}case"roundedRectangle":{const e=t;dg(s,e.x,e.y,e.width,e.height,e.radius);break}case"circle":{const e=t;s.moveTo(e.x+e.radius,e.y),s.arc(e.x,e.y,e.radius,0,Math.PI*2);break}case"ellipse":{const e=t;s.ellipse?(s.moveTo(e.x+e.halfWidth,e.y),s.ellipse(e.x,e.y,e.halfWidth,e.halfHeight,0,0,Math.PI*2)):(s.save(),s.translate(e.x,e.y),s.scale(e.halfWidth,e.halfHeight),s.moveTo(1,0),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const e=t;s.moveTo(e.x,e.y),s.lineTo(e.x2,e.y2),s.lineTo(e.x3,e.y3),s.closePath();break}case"polygon":default:{const e=t,i=e.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);e.closePath&&s.closePath();break}}}function fg(s,t){if(!(t!=null&&t.length))return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),_h(s,i.shape),n&&s.restore()}return!0}class yh{constructor(t){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=t}push(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){var c,u,m;if(t.action!=="pushMaskBegin"&&t.action!=="popMaskEnd")return;const e=this._renderer,i=e.canvasContext,r=i==null?void 0:i.activeContext;if(!r)return;if(t.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}t.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=t.mask.mask;if(!(n instanceof is)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(c=o.context)==null?void 0:c.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),i.setContextTransform(o.groupTransform,(e._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,h=!1;for(let f=0;f<a.length;f++){const g=a[f],y=g.action;if(y!=="fill"&&y!=="stroke")continue;const x=g.data,v=(u=x==null?void 0:x.path)==null?void 0:u.shapePath;if(!((m=v==null?void 0:v.shapePrimitives)!=null&&m.length))continue;const E=v.shapePrimitives;for(let T=0;T<E.length;T++){const C=E[T];if(!(C!=null&&C.shape))continue;const R=C.transform,A=R&&!R.isIdentity();A&&(r.save(),r.transform(R.a,R.b,R.c,R.d,R.tx,R.ty)),_h(r,C.shape),h=fg(r,C.holes)||h,l=!0,A&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}h?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(t,e){this._warnedMaskTypes.has(t)||(this._warnedMaskTypes.add(t),tt(e))}}yh.extension={type:[w.CanvasPipes],name:"stencilMask"};class xh{constructor(t){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=t}push(t,e,i){var r;const n=t,o=this._renderer;o.renderPipes.batch.break(i),o.renderPipes.blendMode.setBlendMode(n.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=i.instructionSize,a.collectRenderables(i,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const h=i.instructionSize-l.instructionsStart-1;l.instructionsLength=h;const c=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[c]??(r[c]=0)}pop(t,e,i){const r=t,n=this._renderer;n.renderPipes.batch.break(i),n.renderPipes.blendMode.setBlendMode(r.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:e._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(t);for(let a=0;a<o.instructionsLength;a++)i.instructions[i.instructionSize++]=i.instructions[o.instructionsStart++];i.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(t){var e;const i=this._renderer,r=i,n=i.renderTarget.renderTarget.uid;let o=(e=this._maskStackHash)[n]??(e[n]=0);t.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(wt.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):t.action==="pushMaskEnd"?(t.inverse?r.stencil.setStencilMode(wt.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(wt.MASK_ACTIVE,o),r.colorMask.setMask(15)):t.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(wt.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,Xt.STENCIL),r.stencil.setStencilMode(wt.DISABLED,o)),o--):t.action==="popMaskEnd"&&(t.inverse?r.stencil.setStencilMode(wt.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(wt.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}xh.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"stencilMask"};const ft="source-over";function pg(){const s=ql(),t=Object.create(null);return t.inherit=ft,t.none=ft,t.normal="source-over",t.add="lighter",t.multiply=s?"multiply":ft,t.screen=s?"screen":ft,t.overlay=s?"overlay":ft,t.darken=s?"darken":ft,t.lighten=s?"lighten":ft,t["color-dodge"]=s?"color-dodge":ft,t["color-burn"]=s?"color-burn":ft,t["hard-light"]=s?"hard-light":ft,t["soft-light"]=s?"soft-light":ft,t.difference=s?"difference":ft,t.exclusion=s?"exclusion":ft,t.saturation=s?"saturation":ft,t.color=s?"color":ft,t.luminosity=s?"luminosity":ft,t["linear-burn"]=s?"color-burn":ft,t["linear-dodge"]=s?"color-dodge":ft,t["linear-light"]=s?"hard-light":ft,t["pin-light"]=s?"hard-light":ft,t["vivid-light"]=s?"hard-light":ft,t["hard-mix"]=ft,t.negation=s?"difference":ft,t["normal-npm"]=t.normal,t["add-npm"]=t.add,t["screen-npm"]=t.screen,t.erase="destination-out",t.subtract=ft,t.divide=ft,t.min=ft,t.max=ft,t}const mg=new W;class bh{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=pg(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=t}resolutionChange(t){this.activeResolution=t}init(){const t=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":e.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":e.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":e.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i,r){var h;const n=r?W.IDENTITY:((h=this._renderer.globalUniforms.globalUniformData)==null?void 0:h.worldTransformMatrix)||W.IDENTITY;let o=mg;o.copyFrom(n),o.append(t);const a=this._projTransform,l=this.activeResolution;if(i=i||l,a){const c=W.shared;c.copyFrom(o),c.prepend(a),o=c}e?this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l,o.ty*l)}clear(t,e){const i=this.activeContext,r=this._renderer;if(i.clearRect(0,0,r.width,r.height),t){const n=ut.shared.setValue(t);i.globalAlpha=e??n.alpha,i.fillStyle=n.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1}}setBlendMode(t){if(this._activeBlendMode===t)return;this._activeBlendMode=t,this._outerBlend=!1;const e=this.blendModes[t];if(!e){this._warnedBlendModes.has(t)||(console.warn(`CanvasRenderer: blend mode "${t}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(t)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=e}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}bh.extension={type:[w.CanvasSystem],name:"canvasContext"};class vh{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}vh.extension={type:[w.CanvasSystem],name:"limits"};class yn{constructor(t){this._renderer=t}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(t,e){this._renderer.renderPipes.batch.break(e),e.add(t)}execute(t){t.isRenderable&&t.render(this._renderer)}destroy(){this._renderer=null}}yn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"customRender"};function xn(s,t){const e=s.instructionSet,i=e.instructions;for(let r=0;r<e.instructionSize;r++){const n=i[r];t[n.renderPipeId].execute(n)}}class bn{constructor(t){this._renderer=t}addRenderGroup(t,e){t.isCachedAsTexture?this._addRenderableCacheAsTexture(t,e):this._addRenderableDirect(t,e)}execute(t){t.isRenderable&&(t.isCachedAsTexture?this._executeCacheAsTexture(t):this._executeDirect(t))}destroy(){this._renderer=null}_addRenderableDirect(t,e){this._renderer.renderPipes.batch.break(e),t._batchableRenderGroup&&(Mt.return(t._batchableRenderGroup),t._batchableRenderGroup=null),e.add(t)}_addRenderableCacheAsTexture(t,e){const i=t._batchableRenderGroup??(t._batchableRenderGroup=Mt.get(fn));i.renderable=t.root,i.transform=t.root.relativeGroupTransform,i.texture=t.texture,i.bounds=t._textureBounds,e.add(t),this._renderer.renderPipes.blendMode.pushBlendMode(t,t.root.groupBlendMode,e),this._renderer.renderPipes.batch.addToBatch(i,e),this._renderer.renderPipes.blendMode.popBlendMode(e)}_executeCacheAsTexture(t){if(t.textureNeedsUpdate){t.textureNeedsUpdate=!1;const e=new W().translate(-t._textureBounds.x,-t._textureBounds.y);this._renderer.renderTarget.push(t.texture,!0,null,t.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:e,worldColor:4294967295,offset:{x:0,y:0}}),xn(t,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}t._batchableRenderGroup._batcher.updateElement(t._batchableRenderGroup),t._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(t){this._renderer.globalUniforms.push({worldTransformMatrix:t.inverseParentTextureTransform,worldColor:t.worldColorAlpha}),xn(t,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}bn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"renderGroup"};const gg="#808080",Ls=new W,_g=new W,yg=new W,vn=new W;function xg(s,t,e){s.beginPath();for(let i=0;i<e.length;i+=3){const r=e[i]*2,n=e[i+1]*2,o=e[i+2]*2;s.moveTo(t[r],t[r+1]),s.lineTo(t[n],t[n+1]),s.lineTo(t[o],t[o+1]),s.closePath()}s.fill()}function bg(s){return`#${(s&16777215).toString(16).padStart(6,"0")}`}function vg(s,t,e,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(t+n,e),s.lineTo(t+i-n,e),s.quadraticCurveTo(t+i,e,t+i,e+n),s.lineTo(t+i,e+r-n),s.quadraticCurveTo(t+i,e+r,t+i-n,e+r),s.lineTo(t+n,e+r),s.quadraticCurveTo(t,e+r,t,e+r-n),s.lineTo(t,e+n),s.quadraticCurveTo(t,e,t+n,e)}function Ns(s,t){switch(t.type){case"rectangle":{const e=t;s.rect(e.x,e.y,e.width,e.height);break}case"roundedRectangle":{const e=t;vg(s,e.x,e.y,e.width,e.height,e.radius);break}case"circle":{const e=t;s.arc(e.x,e.y,e.radius,0,Math.PI*2);break}case"ellipse":{const e=t;s.ellipse?s.ellipse(e.x,e.y,e.halfWidth,e.halfHeight,0,0,Math.PI*2):(s.save(),s.translate(e.x,e.y),s.scale(e.halfWidth,e.halfHeight),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const e=t;s.moveTo(e.x,e.y),s.lineTo(e.x2,e.y2),s.lineTo(e.x3,e.y3),s.closePath();break}case"polygon":default:{const e=t,i=e.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);e.closePath&&s.closePath();break}}}function Eg(s,t){if(!(t!=null&&t.length))return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),Ns(s,i.shape),n&&s.restore()}return!0}function Tg(s,t,e,i){const r=s.fill;if(r instanceof ue){r.buildGradient();const o=r.texture;if(o){const a=st.getTintedPattern(o,t),l=e?vn.copyFrom(e).scale(o.source.pixelWidth,o.source.pixelHeight):vn.copyFrom(r.transform);return i&&!s.textureSpace&&l.append(i),st.applyPatternTransform(a,l),a}}if(r instanceof ts){const o=st.getTintedPattern(r.texture,t);return st.applyPatternTransform(o,r.transform),o}const n=s.texture;if(n&&n!==$.WHITE){if(!n.source.resource)return gg;const o=st.getTintedPattern(n,t),a=e?vn.copyFrom(e).scale(n.source.pixelWidth,n.source.pixelHeight):s.matrix;return st.applyPatternTransform(o,a),o}return bg(t)}class Eh{constructor(){this.shader=null}contextChange(t){}execute(t,e){var E,T,C,R,A,P,F;const i=t.renderer,r=i.canvasContext,n=r.activeContext,o=e.groupTransform,a=((E=i.globalUniforms.globalUniformData)==null?void 0:E.worldColor)??4294967295,l=e.groupColorAlpha,h=(a>>>24&255)/255,c=(l>>>24&255)/255,u=((T=i.filter)==null?void 0:T.alphaMultiplier)??1,m=h*c*u;if(m<=0)return;const f=a&16777215,g=l&16777215,y=ci(hi(g,f)),x=i._roundPixels|e._roundPixels;n.save(),r.setContextTransform(o,x===1),r.setBlendMode(e.groupBlendMode);const v=e.context.instructions;for(let B=0;B<v.length;B++){const k=v[B];if(k.action==="texture"){const X=k.data,D=X.image,z=D?st.getCanvasSource(D):null;if(!z)continue;const Y=X.alpha*m;if(Y<=0)continue;const j=hi(X.style,y);n.globalAlpha=Y;let V=z;j!==16777215&&(V=st.getTintedCanvas({texture:D},j));const ot=D.frame,lt=D.source._resolution??D.source.resolution??1;let gt=ot.x*lt,ht=ot.y*lt;const _t=ot.width*lt,Z=ot.height*lt;V!==z&&(gt=0,ht=0);const Bt=X.transform,zt=Bt&&!Bt.isIdentity(),xt=D.rotate;zt||xt?(Ls.copyFrom(o),zt&&Ls.append(Bt),xt&&it.matrixAppendRotationInv(Ls,xt,X.dx,X.dy,X.dw,X.dh),r.setContextTransform(Ls,x===1)):r.setContextTransform(o,x===1),n.drawImage(V,gt,ht,V===z?_t:V.width,V===z?Z:V.height,xt?0:X.dx,xt?0:X.dy,X.dw,X.dh),(zt||xt)&&r.setContextTransform(o,x===1);continue}const O=k.data,L=(C=O==null?void 0:O.path)==null?void 0:C.shapePath;if(!((R=L==null?void 0:L.shapePrimitives)!=null&&R.length))continue;const N=O.style,H=hi(N.color,y),at=N.alpha*m;if(at<=0)continue;const G=k.action==="stroke";if(n.globalAlpha=at,G){const X=N;n.lineWidth=X.width,n.lineCap=X.cap,n.lineJoin=X.join,n.miterLimit=X.miterLimit}const U=L.shapePrimitives;if(!G&&((F=(P=(A=O.hole)==null?void 0:A.shapePath)==null?void 0:P.shapePrimitives)!=null&&F.length)){const X=U[U.length-1];X.holes=O.hole.shapePath.shapePrimitives}for(let X=0;X<U.length;X++){const D=U[X];if(!(D!=null&&D.shape))continue;const z=D.transform,Y=z&&!z.isIdentity(),j=N.texture&&N.texture!==$.WHITE,V=N.textureSpace==="global"?z:null,ot=j?vl(_g,N,D.shape,V):null,lt=Y?yg.copyFrom(o).append(z):o,gt=Tg(N,H,ot,lt);if(Y&&(n.save(),n.transform(z.a,z.b,z.c,z.d,z.tx,z.ty)),G){const ht=N;if(ht.alignment!==.5&&!ht.pixelLine){const Z=[],Bt=[],zt=[],xt=Zi[D.shape.type];if(xt!=null&&xt.build(D.shape,Z)){const Gt=D.shape.closePath??!0;gl(Z,ht,!1,Gt,Bt,zt),n.fillStyle=gt,xg(n,Bt,zt)}else n.strokeStyle=gt,n.beginPath(),Ns(n,D.shape),n.stroke()}else n.strokeStyle=gt,n.beginPath(),Ns(n,D.shape),n.stroke()}else n.fillStyle=gt,n.beginPath(),Ns(n,D.shape),Eg(n,D.holes)?n.fill("evenodd"):n.fill();Y&&n.restore()}}n.restore()}destroy(){this.shader=null}}Eh.extension={type:[w.CanvasPipesAdaptor],name:"graphics"};class En{constructor(t){this._renderer=t}addRenderable(t,e){const i=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,i),this._renderer.renderPipes.batch.addToBatch(i,e)}updateRenderable(t){const e=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,e),e._batcher.updateElement(e)}validateRenderable(t){const e=this._getGpuSprite(t);return!e._batcher.checkAndUpdateTexture(e,t._texture)}_updateBatchableSprite(t,e){e.bounds=t.visualBounds,e.texture=t._texture}_getGpuSprite(t){return t._gpuData[this._renderer.uid]||this._initGPUSprite(t)}_initGPUSprite(t){const e=new fn;return e.renderable=t,e.transform=t.groupTransform,e.texture=t._texture,e.bounds=t.visualBounds,e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}En.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"sprite"};const rs={};J.handle(w.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");rs[s.name]=s.ref},s=>{delete rs[s.name]});class Tn{constructor(t){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=t,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(t,e,i){this._blendModeStack.push(e),this.setBlendMode(t,e,i)}popBlendMode(t){this._blendModeStack.pop();const e=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,e,t)}setBlendMode(t,e,i){var n;const r=t instanceof pr;if(this._activeBlendMode===e){this._isAdvanced&&t&&!r&&((n=this._renderableList)==null||n.push(t));return}this._isAdvanced&&this._endAdvancedBlendMode(i),this._activeBlendMode=e,t&&(this._isAdvanced=!!rs[e],this._isAdvanced&&this._beginAdvancedBlendMode(t,i))}_beginAdvancedBlendMode(t,e){this._renderer.renderPipes.batch.break(e);const i=this._activeBlendMode;if(!rs[i]){tt(`Unable to assign BlendMode: '${i}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(i),n=t instanceof pr,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[t],container:n?t.root:null,canBundle:!1};this._renderableList=o.renderables,e.add(o)}_ensureFilterEffect(t){let e=this._filterHash[t];return e||(e=this._filterHash[t]=new ps,e.filters=[new rs[t]]),e}_endAdvancedBlendMode(t){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(t),t.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(t){this._isAdvanced&&this._endAdvancedBlendMode(t)}destroy(){this._renderer=null,this._renderableList=null;for(const t in this._filterHash)this._filterHash[t].destroy();this._filterHash=null}}Tn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"blendMode"};function Sn(s,t){t||(t=0);for(let e=t;e<s.length&&s[e];e++)s[e]=null}const Sg=new kt,Th=ki|ys|_r;function Sh(s,t=!1){Cg(s);const e=s.childrenToUpdate,i=s.updateTick++;for(const r in e){const n=Number(r),o=e[r],a=o.list,l=o.index;for(let h=0;h<l;h++){const c=a[h];c.parentRenderGroup===s&&c.relativeRenderGroupDepth===n&&Ch(c,i,0)}Sn(a,l),o.index=0}if(t)for(let r=0;r<s.renderGroupChildren.length;r++)Sh(s.renderGroupChildren[r],t)}function Cg(s){const t=s.root;let e;if(s.renderGroupParent){const i=s.renderGroupParent;s.worldTransform.appendFrom(t.relativeGroupTransform,i.worldTransform),s.worldColor=ms(t.groupColor,i.worldColor),e=t.groupAlpha*i.worldAlpha}else s.worldTransform.copyFrom(t.localTransform),s.worldColor=t.localColor,e=t.localAlpha;e=e<0?0:e>1?1:e,s.worldAlpha=e,s.worldColorAlpha=s.worldColor+((e*255|0)<<24)}function Ch(s,t,e){if(t===s.updateTick)return;s.updateTick=t,s.didChange=!1;const i=s.localTransform;s.updateLocalTransform();const r=s.parent;if(r&&!r.renderGroup?(e|=s._updateFlags,s.relativeGroupTransform.appendFrom(i,r.relativeGroupTransform),e&Th&&wh(s,r,e)):(e=s._updateFlags,s.relativeGroupTransform.copyFrom(i),e&Th&&wh(s,Sg,e)),!s.renderGroup){const n=s.children,o=n.length;for(let h=0;h<o;h++)Ch(n[h],t,e);const a=s.parentRenderGroup,l=s;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function wh(s,t,e){if(e&ys){s.groupColor=ms(s.localColor,t.groupColor);let i=s.localAlpha*t.groupAlpha;i=i<0?0:i>1?1:i,s.groupAlpha=i,s.groupColorAlpha=s.groupColor+((i*255|0)<<24)}e&_r&&(s.groupBlendMode=s.localBlendMode==="inherit"?t.groupBlendMode:s.localBlendMode),e&ki&&(s.globalDisplayStatus=s.localDisplayStatus&t.globalDisplayStatus),s._updateFlags=0}function wg(s,t){const{list:e}=s.childrenRenderablesToUpdate;let i=!1;for(let r=0;r<s.childrenRenderablesToUpdate.index;r++){const n=e[r];if(i=t[n.renderPipeId].validateRenderable(n),i)break}return s.structureDidChange=i,i}const Ag=new W;class Ah{constructor(t){this._renderer=t}render({container:t,transform:e}){const i=t.parent,r=t.renderGroup.renderGroupParent;t.parent=null,t.renderGroup.renderGroupParent=null;const n=this._renderer,o=Ag;e&&(o.copyFrom(t.renderGroup.localTransform),t.renderGroup.localTransform.copyFrom(e));const a=n.renderPipes;this._updateCachedRenderGroups(t.renderGroup,null),this._updateRenderGroups(t.renderGroup),n.globalUniforms.start({worldTransformMatrix:e?t.renderGroup.localTransform:t.renderGroup.worldTransform,worldColor:t.renderGroup.worldColorAlpha}),xn(t.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),e&&t.renderGroup.localTransform.copyFrom(o),t.parent=i,t.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(t,e){if(t._parentCacheAsTextureRenderGroup=e,t.isCachedAsTexture){if(!t.textureNeedsUpdate)return;e=t}for(let i=t.renderGroupChildren.length-1;i>=0;i--)this._updateCachedRenderGroups(t.renderGroupChildren[i],e);if(t.invalidateMatrices(),t.isCachedAsTexture){if(t.textureNeedsUpdate){const i=t.root.getLocalBounds(),r=this._renderer,n=t.textureOptions.resolution||r.view.resolution,o=t.textureOptions.antialias??r.view.antialias,a=t.textureOptions.scaleMode??"linear",l=t.texture;i.ceil(),t.texture&&Nt.returnTexture(t.texture,!0);const h=Nt.getOptimalTexture(i.width,i.height,n,o);h._source.style=new $e({scaleMode:a}),t.texture=h,t._textureBounds||(t._textureBounds=new Lt),t._textureBounds.copyFrom(i),l!==t.texture&&t.renderGroupParent&&(t.renderGroupParent.structureDidChange=!0)}}else t.texture&&(Nt.returnTexture(t.texture,!0),t.texture=null)}_updateRenderGroups(t){const e=this._renderer,i=e.renderPipes;if(t.runOnRender(e),t.instructionSet.renderPipes=i,t.structureDidChange?Sn(t.childrenRenderablesToUpdate.list,0):wg(t,i),Sh(t),t.structureDidChange?(t.structureDidChange=!1,this._buildInstructions(t,e)):this._updateRenderables(t),t.childrenRenderablesToUpdate.index=0,e.renderPipes.batch.upload(t.instructionSet),!(t.isCachedAsTexture&&!t.textureNeedsUpdate))for(let r=0;r<t.renderGroupChildren.length;r++)this._updateRenderGroups(t.renderGroupChildren[r])}_updateRenderables(t){const{list:e,index:i}=t.childrenRenderablesToUpdate;for(let r=0;r<i;r++){const n=e[r];n.didViewUpdate&&t.updateRenderable(n)}Sn(e,i)}_buildInstructions(t,e){const i=t.root,r=t.instructionSet;r.reset();const n=e.renderPipes?e:e.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),i.sortableChildren&&i.sortChildren(),i.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}Ah.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"renderGroup"};const Cn=class fu{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new ut(0),this.color=this._backgroundColor,this.alpha=1}init(t){t={...fu.defaultOptions,...t},this.clearBeforeRender=t.clearBeforeRender,this.color=t.background||t.backgroundColor||this._backgroundColor,this.alpha=t.backgroundAlpha,this._backgroundColor.setAlpha(t.backgroundAlpha)}get color(){return this._backgroundColor}set color(t){ut.shared.setValue(t).alpha<1&&this._backgroundColor.alpha===1&&tt("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};Cn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"background",priority:0},Cn.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Rg=Cn;const wn={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},An=class pu{constructor(t){this._renderer=t}_normalizeOptions(t,e={}){return t instanceof kt||t instanceof $?{target:t,...e}:{...e,...t}}async image(t){const e=rt.get().createImage();return e.src=await this.base64(t),e}async base64(t){t=this._normalizeOptions(t,pu.defaultImageOptions);const{format:e,quality:i}=t,r=this.canvas(t);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},wn[e],i)});if(r.toDataURL!==void 0)return r.toDataURL(wn[e],i);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:wn[e],quality:i});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t){t=this._normalizeOptions(t);const e=t.target,i=this._renderer;if(e instanceof $)return i.texture.generateCanvas(e);const r=i.textureGenerator.generateTexture(t),n=i.texture.generateCanvas(r);return r.destroy(!0),n}pixels(t){t=this._normalizeOptions(t);const e=t.target,i=this._renderer,r=e instanceof $?e:i.textureGenerator.generateTexture(t),n=i.texture.getPixels(r);return e instanceof kt&&r.destroy(!0),n}texture(t){return t=this._normalizeOptions(t),t.target instanceof $?t.target:this._renderer.textureGenerator.generateTexture(t)}download(t){t=this._normalizeOptions(t);const e=this.canvas(t),i=document.createElement("a");i.download=t.filename??"image.png",i.href=e.toDataURL("image/png"),document.body.appendChild(i),i.click(),document.body.removeChild(i)}log(t){const e=t.width??200;t=this._normalizeOptions(t);const i=this.canvas(t),r=i.toDataURL();console.log(`[Pixi Texture] ${i.width}px ${i.height}px`);const n=["font-size: 1px;",`padding: ${e}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};An.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"extract"},An.defaultImageOptions={format:"png",quality:1};let Ig=An;class Rn extends ${static create(t){const{dynamic:e,...i}=t;return new Rn({source:new At(i),dynamic:e??!1})}resize(t,e,i){return this.source.resize(t,e,i),this}}const Pg=new ct,Mg=new Lt,kg=[0,0,0,0];class Rh{constructor(t){this._renderer=t}generateTexture(t){var h;t instanceof kt&&(t={target:t,frame:void 0,textureSourceOptions:{},resolution:void 0});const e=t.resolution||this._renderer.resolution,i=t.antialias||this._renderer.view.antialias,r=t.target;let n=t.clearColor;n?n=Array.isArray(n)&&n.length===4?n:ut.shared.setValue(n).toArray():n=kg;const o=((h=t.frame)==null?void 0:h.copyTo(Pg))||dr(r,Mg).rectangle;o.width=Math.max(o.width,1/e)|0,o.height=Math.max(o.height,1/e)|0;const a=Rn.create({...t.textureSourceOptions,width:o.width,height:o.height,resolution:e,antialias:i}),l=W.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}Rh.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"textureGenerator"};function Bg(s){let t=!1;for(const i in s)if(s[i]==null){t=!0;break}if(!t)return s;const e=Object.create(null);for(const i in s){const r=s[i];r&&(e[i]=r)}return e}function Og(s){let t=0;for(let e=0;e<s.length;e++)s[e]==null?t++:s[e-t]=s[e];return s.length-=t,s}const In=class mu{constructor(t){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=t}init(t){t={...mu.defaultOptions,...t},this.maxUnusedTime=t.gcMaxUnusedTime,this._frequency=t.gcFrequency,this.enabled=t.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(t){this.enabled!==t&&(t?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedCollections){const{context:i,collection:r,type:n}=e;n==="hash"?i[r]=Bg(i[r]):i[r]=Og(i[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:t}){this.now=performance.now(),t.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(t.renderGroup,t.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(t,e){t.instructionSet.gcTick=e,t.gcTick=e;for(const i of t.renderGroupChildren)this._updateInstructionGCTick(i,e)}addCollection(t,e,i){this._managedCollections.push({context:t,collection:e,type:i})}addResource(t,e){var r,n;if(t._gcLastUsed!==-1){t._gcLastUsed=this.now,(r=t._onTouch)==null||r.call(t,this.now);return}const i=this._managedResources.length;t._gcData={index:i,type:e},t._gcLastUsed=this.now,(n=t._onTouch)==null||n.call(t,this.now),t.once("unload",this.removeResource,this),this._managedResources.push(t)}removeResource(t){const e=t._gcData;if(!e)return;const i=e.index,r=this._managedResources.length-1;if(i!==r){const n=this._managedResources[r];this._managedResources[i]=n,n._gcData.index=i}this._managedResources.length--,t._gcData=null,t._gcLastUsed=-1}addResourceHash(t,e,i,r=0){this._managedResourceHashes.push({context:t,hash:e,type:i,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const t=performance.now(),e=this._managedResourceHashes;for(const r of e)this.runOnHash(r,t);let i=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];i=this.runOnResource(n,t,i)}this._managedResources.length=i}updateRenderableGCTick(t,e){var n,o;const i=t.renderGroup??t.parentRenderGroup,r=((n=i==null?void 0:i.instructionSet)==null?void 0:n.gcTick)??-1;((i==null?void 0:i.gcTick)??0)===r&&(t._gcLastUsed=e,(o=t._onTouch)==null||o.call(t,e))}runOnResource(t,e,i){const r=t._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(t,e),e-t._gcLastUsed<this.maxUnusedTime||!t.autoGarbageCollect?(this._managedResources[i]=t,r.index=i,i++):(t.unload(),t._gcData=null,t._gcLastUsed=-1,t.off("unload",this.removeResource,this)),i}_createHashClone(t,e){const i=Object.create(null);for(const r in t){if(r===e)break;t[r]!==null&&(i[r]=t[r])}return i}runOnHash(t,e){var h;const{context:i,hash:r,type:n}=t,o=i[r];let a=null,l=0;for(const c in o){const u=o[c];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,c));continue}if(u._gcLastUsed===-1){u._gcLastUsed=e,(h=u._onTouch)==null||h.call(u,e),a&&(a[c]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,e),!(e-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[c]=null,l++):a=this._createHashClone(o,c)),n==="renderable"){const f=u,g=f.renderGroup??f.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[c]=u)}a&&(i[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(t=>{t.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};In.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"gc",priority:0},In.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Dg=In;class Ih{constructor(t){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=t}reset(){this._stackIndex=0;for(let t=0;t<this._activeUniforms.length;t++)this._uniformsPool.push(this._activeUniforms[t]);for(let t=0;t<this._activeBindGroups.length;t++)this._bindGroupPool.push(this._activeBindGroups[t]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(t){this.reset(),this.push(t)}bind({size:t,projectionMatrix:e,worldTransformMatrix:i,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new W,worldColor:4294967295,offset:new mt},l={projectionMatrix:e||this._renderer.renderTarget.projectionMatrix,resolution:t||o.size,worldTransformMatrix:i||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},h=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(h);const c=h.uniforms;c.uProjectionMatrix=l.projectionMatrix,c.uResolution=l.resolution,c.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),c.uWorldTransformMatrix.tx-=l.offset.x,c.uWorldTransformMatrix.ty-=l.offset.y,jl(l.worldColor,c.uWorldColorAlpha,0),h.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(h,!1):(u=this._bindGroupPool.pop()||new Ie,this._activeBindGroups.push(u),u.setResource(h,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(t){this.bind(t),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===he.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new le({uProjectionMatrix:{value:new W,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new W,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Ih.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"globalUniforms"};let Gg=1;class Ph{constructor(){this._tasks=[],this._offset=0}init(){Qt.system.add(this._update,this)}repeat(t,e,i=!0){const r=Gg++;let n=0;return i&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:t,duration:e,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(t){for(let e=0;e<this._tasks.length;e++)if(this._tasks[e].id===t){this._tasks.splice(e,1);return}}_update(){const t=performance.now();for(let e=0;e<this._tasks.length;e++){const i=this._tasks[e];if(t-i.offset-i.last>=i.duration){const r=t-i.start;i.func(r),i.last=t}}}destroy(){Qt.system.remove(this._update,this),this._tasks.length=0}}Ph.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"scheduler",priority:0};let Mh=!1;function Ug(s){if(!Mh){if(rt.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const t=[`%c %c %c %c %c PixiJS %c v${As} (${s}) http://www.pixijs.com/
|
|
569
|
+
`}},k_=new je;class B_ extends Gs{constructor(){super(),this.filters=[new Vg({sprite:new Gt(q.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}}class qn{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,i){const r=this._renderer;if(r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(i,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,i=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const r=Ue.get(B_);if(r.inverse=e.inverse,i){e.mask.mask.measurable=!0;const n=Vr(e.mask.mask,!0,k_);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Xe.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);t.renderTarget.push(a,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];i&&(t.type===yt.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const r=this._activeMaskStage.pop();i&&Xe.returnTexture(r.filterTexture),Ue.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}qn.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"alphaMask"};class th{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}th.extension={type:[I.CanvasPipes],name:"colorMask"};class ih{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}ih.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"colorMask"};function O_(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function sh(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;O_(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.moveTo(t.x+t.radius,t.y),s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?(s.moveTo(t.x+t.halfWidth,t.y),s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.moveTo(1,0),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function D_(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),sh(s,i.shape),n&&s.restore()}return!0}class rh{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var h,u,p;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,i=t.canvasContext,r=i==null?void 0:i.activeContext;if(!r)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=e.mask.mask;if(!(n instanceof vs)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(h=o.context)==null?void 0:h.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),i.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,c=!1;for(let d=0;d<a.length;d++){const g=a[d],_=g.action;if(_!=="fill"&&_!=="stroke")continue;const y=g.data,x=(u=y==null?void 0:y.path)==null?void 0:u.shapePath;if(!((p=x==null?void 0:x.shapePrimitives)!=null&&p.length))continue;const v=x.shapePrimitives;for(let C=0;C<v.length;C++){const T=v[C];if(!(T!=null&&T.shape))continue;const A=T.transform,w=A&&!A.isIdentity();w&&(r.save(),r.transform(A.a,A.b,A.c,A.d,A.tx,A.ty)),sh(r,T.shape),c=D_(r,T.holes)||c,l=!0,w&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),ne(t))}}rh.extension={type:[I.CanvasPipes],name:"stencilMask"};class nh{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,i){var r;const n=e,o=this._renderer;o.renderPipes.batch.break(i),o.renderPipes.blendMode.setBlendMode(n.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=i.instructionSize,a.collectRenderables(i,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const c=i.instructionSize-l.instructionsStart-1;l.instructionsLength=c;const h=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[h]??(r[h]=0)}pop(e,t,i){const r=e,n=this._renderer;n.renderPipes.batch.break(i),n.renderPipes.blendMode.setBlendMode(r.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(e);for(let a=0;a<o.instructionsLength;a++)i.instructions[i.instructionSize++]=i.instructions[o.instructionsStart++];i.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const i=this._renderer,r=i,n=i.renderTarget.renderTarget.uid;let o=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(Be.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(Be.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(Be.MASK_ACTIVE,o),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(Be.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,it.STENCIL),r.stencil.setStencilMode(Be.DISABLED,o)),o--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(Be.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(Be.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}nh.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"stencilMask"};const ve="source-over";function N_(){const s=Dc(),e=Object.create(null);return e.inherit=ve,e.none=ve,e.normal="source-over",e.add="lighter",e.multiply=s?"multiply":ve,e.screen=s?"screen":ve,e.overlay=s?"overlay":ve,e.darken=s?"darken":ve,e.lighten=s?"lighten":ve,e["color-dodge"]=s?"color-dodge":ve,e["color-burn"]=s?"color-burn":ve,e["hard-light"]=s?"hard-light":ve,e["soft-light"]=s?"soft-light":ve,e.difference=s?"difference":ve,e.exclusion=s?"exclusion":ve,e.saturation=s?"saturation":ve,e.color=s?"color":ve,e.luminosity=s?"luminosity":ve,e["linear-burn"]=s?"color-burn":ve,e["linear-dodge"]=s?"color-dodge":ve,e["linear-light"]=s?"hard-light":ve,e["pin-light"]=s?"hard-light":ve,e["vivid-light"]=s?"hard-light":ve,e["hard-mix"]=ve,e.negation=s?"difference":ve,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=ve,e.divide=ve,e.min=ve,e.max=ve,e}const F_=new Y;class oh{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=N_(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,i,r){var c;const n=r?Y.IDENTITY:((c=this._renderer.globalUniforms.globalUniformData)==null?void 0:c.worldTransformMatrix)||Y.IDENTITY;let o=F_;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(i=i||l,a){const h=Y.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l,o.ty*l)}clear(e,t){const i=this.activeContext,r=this._renderer;if(i.clearRect(0,0,r.width,r.height),e){const n=be.shared.setValue(e);i.globalAlpha=t??n.alpha,i.fillStyle=n.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}oh.extension={type:[I.CanvasSystem],name:"canvasContext"};class ah{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}ah.extension={type:[I.CanvasSystem],name:"limits"};class Zn{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}Zn.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"customRender"};function Jn(s,e){const t=s.instructionSet,i=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=i[r];e[n.renderPipeId].execute(n)}}class Qn{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Ue.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const i=e._batchableRenderGroup??(e._batchableRenderGroup=Ue.get(jn));i.renderable=e.root,i.transform=e.root.relativeGroupTransform,i.texture=e.texture,i.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(i,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new Y().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),Jn(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),Jn(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Qn.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"renderGroup"};const G_="#808080",lr=new Y,L_=new Y,U_=new Y,eo=new Y;function W_(s,e,t){s.beginPath();for(let i=0;i<t.length;i+=3){const r=t[i]*2,n=t[i+1]*2,o=t[i+2]*2;s.moveTo(e[r],e[r+1]),s.lineTo(e[n],e[n+1]),s.lineTo(e[o],e[o+1]),s.closePath()}s.fill()}function H_(s){return`#${(s&16777215).toString(16).padStart(6,"0")}`}function V_(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function cr(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;V_(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function z_(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),cr(s,i.shape),n&&s.restore()}return!0}function $_(s,e,t,i){const r=s.fill;if(r instanceof xt){r.buildGradient();const o=r.texture;if(o){const a=he.getTintedPattern(o,e),l=t?eo.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):eo.copyFrom(r.transform);return i&&!s.textureSpace&&l.append(i),he.applyPatternTransform(a,l),a}}if(r instanceof bs){const o=he.getTintedPattern(r.texture,e);return he.applyPatternTransform(o,r.transform),o}const n=s.texture;if(n&&n!==q.WHITE){if(!n.source.resource)return G_;const o=he.getTintedPattern(n,e),a=t?eo.copyFrom(t).scale(n.source.pixelWidth,n.source.pixelHeight):s.matrix;return he.applyPatternTransform(o,a),o}return H_(e)}class lh{constructor(){this.shader=null}contextChange(e){}execute(e,t){var v,C,T,A,w,R,D;const i=e.renderer,r=i.canvasContext,n=r.activeContext,o=t.groupTransform,a=((v=i.globalUniforms.globalUniformData)==null?void 0:v.worldColor)??4294967295,l=t.groupColorAlpha,c=(a>>>24&255)/255,h=(l>>>24&255)/255,u=((C=i.filter)==null?void 0:C.alphaMultiplier)??1,p=c*h*u;if(p<=0)return;const d=a&16777215,g=l&16777215,_=Si(vi(g,d)),y=i._roundPixels|t._roundPixels;n.save(),r.setContextTransform(o,y===1),r.setBlendMode(t.groupBlendMode);const x=t.context.instructions;for(let B=0;B<x.length;B++){const k=x[B];if(k.action==="texture"){const X=k.data,N=X.image,V=N?he.getCanvasSource(N):null;if(!V)continue;const K=X.alpha*p;if(K<=0)continue;const H=vi(X.style,_);n.globalAlpha=K;let $=V;H!==16777215&&($=he.getTintedCanvas({texture:N},H));const se=N.frame,ue=N.source._resolution??N.source.resolution??1;let z=se.x*ue,Q=se.y*ue;const ae=se.width*ue,j=se.height*ue;$!==V&&(z=0,Q=0);const _e=X.transform,ee=_e&&!_e.isIdentity(),le=N.rotate;ee||le?(lr.copyFrom(o),ee&&lr.append(_e),le&&ce.matrixAppendRotationInv(lr,le,X.dx,X.dy,X.dw,X.dh),r.setContextTransform(lr,y===1)):r.setContextTransform(o,y===1),n.drawImage($,z,Q,$===V?ae:$.width,$===V?j:$.height,le?0:X.dx,le?0:X.dy,X.dw,X.dh),(ee||le)&&r.setContextTransform(o,y===1);continue}const O=k.data,G=(T=O==null?void 0:O.path)==null?void 0:T.shapePath;if(!((A=G==null?void 0:G.shapePrimitives)!=null&&A.length))continue;const U=O.style,W=vi(U.color,_),te=U.alpha*p;if(te<=0)continue;const F=k.action==="stroke";if(n.globalAlpha=te,F){const X=U;n.lineWidth=X.width,n.lineCap=X.cap,n.lineJoin=X.join,n.miterLimit=X.miterLimit}const L=G.shapePrimitives;if(!F&&((D=(R=(w=O.hole)==null?void 0:w.shapePath)==null?void 0:R.shapePrimitives)!=null&&D.length)){const X=L[L.length-1];X.holes=O.hole.shapePath.shapePrimitives}for(let X=0;X<L.length;X++){const N=L[X];if(!(N!=null&&N.shape))continue;const V=N.transform,K=V&&!V.isIdentity(),H=U.texture&&U.texture!==q.WHITE,$=U.textureSpace==="global"?V:null,se=H?ac(L_,U,N.shape,$):null,ue=K?U_.copyFrom(o).append(V):o,z=$_(U,W,se,ue);if(K&&(n.save(),n.transform(V.a,V.b,V.c,V.d,V.tx,V.ty)),F){const Q=U;if(Q.alignment!==.5&&!Q.pixelLine){const j=[],_e=[],ee=[],le=gs[N.shape.type];if(le!=null&&le.build(N.shape,j)){const Re=N.shape.closePath??!0;ic(j,Q,!1,Re,_e,ee),n.fillStyle=z,W_(n,_e,ee)}else n.strokeStyle=z,n.beginPath(),cr(n,N.shape),n.stroke()}else n.strokeStyle=z,n.beginPath(),cr(n,N.shape),n.stroke()}else n.fillStyle=z,n.beginPath(),cr(n,N.shape),z_(n,N.holes)?n.fill("evenodd"):n.fill();K&&n.restore()}}n.restore()}destroy(){this.shader=null}}lh.extension={type:[I.CanvasPipesAdaptor],name:"graphics"};class to{constructor(e){this._renderer=e}addRenderable(e,t){const i=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,i),this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new jn;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}to.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"sprite"};const Cs={};ie.handle(I.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");Cs[s.name]=s.ref},s=>{delete Cs[s.name]});class io{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,i){this._blendModeStack.push(t),this.setBlendMode(e,t,i)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,i){var n;const r=e instanceof Xr;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(i),this._activeBlendMode=t,e&&(this._isAdvanced=!!Cs[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,i))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const i=this._activeBlendMode;if(!Cs[i]){ne(`Unable to assign BlendMode: '${i}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(i),n=e instanceof Xr,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new Gs,t.filters=[new Cs[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}io.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"blendMode"};function so(s,e){e||(e=0);for(let t=e;t<s.length&&s[t];t++)s[t]=null}const j_=new We,ch=Zi|Hs|qr;function hh(s,e=!1){X_(s);const t=s.childrenToUpdate,i=s.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===s&&h.relativeRenderGroupDepth===n&&uh(h,i,0)}so(a,l),o.index=0}if(e)for(let r=0;r<s.renderGroupChildren.length;r++)hh(s.renderGroupChildren[r],e)}function X_(s){const e=s.root;let t;if(s.renderGroupParent){const i=s.renderGroupParent;s.worldTransform.appendFrom(e.relativeGroupTransform,i.worldTransform),s.worldColor=Ls(e.groupColor,i.worldColor),t=e.groupAlpha*i.worldAlpha}else s.worldTransform.copyFrom(e.localTransform),s.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,s.worldAlpha=t,s.worldColorAlpha=s.worldColor+((t*255|0)<<24)}function uh(s,e,t){if(e===s.updateTick)return;s.updateTick=e,s.didChange=!1;const i=s.localTransform;s.updateLocalTransform();const r=s.parent;if(r&&!r.renderGroup?(t|=s._updateFlags,s.relativeGroupTransform.appendFrom(i,r.relativeGroupTransform),t&ch&&dh(s,r,t)):(t=s._updateFlags,s.relativeGroupTransform.copyFrom(i),t&ch&&dh(s,j_,t)),!s.renderGroup){const n=s.children,o=n.length;for(let c=0;c<o;c++)uh(n[c],e,t);const a=s.parentRenderGroup,l=s;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function dh(s,e,t){if(t&Hs){s.groupColor=Ls(s.localColor,e.groupColor);let i=s.localAlpha*e.groupAlpha;i=i<0?0:i>1?1:i,s.groupAlpha=i,s.groupColorAlpha=s.groupColor+((i*255|0)<<24)}t&qr&&(s.groupBlendMode=s.localBlendMode==="inherit"?e.groupBlendMode:s.localBlendMode),t&Zi&&(s.globalDisplayStatus=s.localDisplayStatus&e.globalDisplayStatus),s._updateFlags=0}function Y_(s,e){const{list:t}=s.childrenRenderablesToUpdate;let i=!1;for(let r=0;r<s.childrenRenderablesToUpdate.index;r++){const n=t[r];if(i=e[n.renderPipeId].validateRenderable(n),i)break}return s.structureDidChange=i,i}const K_=new Y;class fh{constructor(e){this._renderer=e}render({container:e,transform:t}){const i=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=K_;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),Jn(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=i,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let i=e.renderGroupChildren.length-1;i>=0;i--)this._updateCachedRenderGroups(e.renderGroupChildren[i],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const i=e.root.getLocalBounds(),r=this._renderer,n=e.textureOptions.resolution||r.view.resolution,o=e.textureOptions.antialias??r.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;i.ceil(),e.texture&&Xe.returnTexture(e.texture,!0);const c=Xe.getOptimalTexture(i.width,i.height,n,o);c._source.style=new si({scaleMode:a}),e.texture=c,e._textureBounds||(e._textureBounds=new je),e._textureBounds.copyFrom(i),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Xe.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,i=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=i,e.structureDidChange?so(e.childrenRenderablesToUpdate.list,0):Y_(e,i),hh(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:i}=e.childrenRenderablesToUpdate;for(let r=0;r<i;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}so(t,i)}_buildInstructions(e,t){const i=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),i.sortableChildren&&i.sortChildren(),i.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}fh.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"renderGroup"};const ro=class Dd{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new be(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...Dd.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){be.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&ne("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};ro.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"background",priority:0},ro.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let q_=ro;const no={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},oo=class Nd{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof We||e instanceof q?{target:e,...t}:{...t,...e}}async image(e){const t=de.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Nd.defaultImageOptions);const{format:t,quality:i}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},no[t],i)});if(r.toDataURL!==void 0)return r.toDataURL(no[t],i);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:no[t],quality:i});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer;if(t instanceof q)return i.texture.generateCanvas(t);const r=i.textureGenerator.generateTexture(e),n=i.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer,r=t instanceof q?t:i.textureGenerator.generateTexture(e),n=i.texture.getPixels(r);return t instanceof We&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof q?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),i=document.createElement("a");i.download=e.filename??"image.png",i.href=t.toDataURL("image/png"),document.body.appendChild(i),i.click(),document.body.removeChild(i)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const i=this.canvas(e),r=i.toDataURL();console.log(`[Pixi Texture] ${i.width}px ${i.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};oo.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"extract"},oo.defaultImageOptions={format:"png",quality:1};let Z_=oo;class ao extends q{static create(e){const{dynamic:t,...i}=e;return new ao({source:new De(i),dynamic:t??!1})}resize(e,t,i){return this.source.resize(e,t,i),this}}const J_=new ye,Q_=new je,ey=[0,0,0,0];class ph{constructor(e){this._renderer=e}generateTexture(e){var c;e instanceof We&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,i=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:be.shared.setValue(n).toArray():n=ey;const o=((c=e.frame)==null?void 0:c.copyTo(J_))||$r(r,Q_).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=ao.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:i}),l=Y.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}ph.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"textureGenerator"};function ty(s){let e=!1;for(const i in s)if(s[i]==null){e=!0;break}if(!e)return s;const t=Object.create(null);for(const i in s){const r=s[i];r&&(t[i]=r)}return t}function iy(s){let e=0;for(let t=0;t<s.length;t++)s[t]==null?e++:s[t-e]=s[t];return s.length-=e,s}const lo=class Fd{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...Fd.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:i,collection:r,type:n}=t;n==="hash"?i[r]=ty(i[r]):i[r]=iy(i[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const i of e.renderGroupChildren)this._updateInstructionGCTick(i,t)}addCollection(e,t,i){this._managedCollections.push({context:e,collection:t,type:i})}addResource(e,t){var r,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(r=e._onTouch)==null||r.call(e,this.now);return}const i=this._managedResources.length;e._gcData={index:i,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const i=t.index,r=this._managedResources.length-1;if(i!==r){const n=this._managedResources[r];this._managedResources[i]=n,n._gcData.index=i}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,i,r=0){this._managedResourceHashes.push({context:e,hash:t,type:i,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const r of t)this.runOnHash(r,e);let i=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];i=this.runOnResource(n,e,i)}this._managedResources.length=i}updateRenderableGCTick(e,t){var n,o;const i=e.renderGroup??e.parentRenderGroup,r=((n=i==null?void 0:i.instructionSet)==null?void 0:n.gcTick)??-1;((i==null?void 0:i.gcTick)??0)===r&&(e._gcLastUsed=t,(o=e._onTouch)==null||o.call(e,t))}runOnResource(e,t,i){const r=e._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[i]=e,r.index=i,i++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),i}_createHashClone(e,t){const i=Object.create(null);for(const r in e){if(r===t)break;e[r]!==null&&(i[r]=e[r])}return i}runOnHash(e,t){var c;const{context:i,hash:r,type:n}=e,o=i[r];let a=null,l=0;for(const h in o){const u=o[h];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),a&&(a[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h)),n==="renderable"){const d=u,g=d.renderGroup??d.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[h]=u)}a&&(i[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};lo.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"gc",priority:0},lo.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let sy=lo;class mh{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:i,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new Y,worldColor:4294967295,offset:new Ce},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:i||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,kc(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Lt,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===yt.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new _t({uProjectionMatrix:{value:new Y,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new Y,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}mh.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"globalUniforms"};let ry=1;class gh{constructor(){this._tasks=[],this._offset=0}init(){at.system.add(this._update,this)}repeat(e,t,i=!0){const r=ry++;let n=0;return i&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const i=this._tasks[t];if(e-i.offset-i.last>=i.duration){const r=e-i.start;i.func(r),i.last=e}}}destroy(){at.system.remove(this._update,this),this._tasks.length=0}}gh.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"scheduler",priority:0};let _h=!1;function ny(s){if(!_h){if(de.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${Zs} (${s}) http://www.pixijs.com/
|
|
570
570
|
|
|
571
|
-
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...t)}else globalThis.console&&globalThis.console.log(`PixiJS ${As} - ${s} - http://www.pixijs.com/`);Mh=!0}}class Pn{constructor(t){this._renderer=t}init(t){if(t.hello){let e=this._renderer.name;this._renderer.type===he.WEBGL&&(e+=` ${this._renderer.context.webGLVersion}`),Ug(e)}}}Pn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"hello",priority:-2},Pn.defaultOptions={hello:!1};const Mn=class gu{constructor(t){this._renderer=t}init(t){t={...gu.defaultOptions,...t},this.maxUnusedTime=t.renderableGCMaxUnusedTime}get enabled(){return K("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(t){K("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=t}addManagedHash(t,e){K("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(t,e,"hash")}addManagedArray(t,e){K("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(t,e,"array")}addRenderable(t){K("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(t,"renderable")}run(){K("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};Mn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"renderableGC",priority:0},Mn.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Lg=Mn;const kn=class qs{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=t}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=t/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=t}constructor(t){this._renderer=t,this._checkCount=0}init(t){t.textureGCActive!==qs.defaultOptions.textureGCActive&&(this.active=t.textureGCActive),t.textureGCMaxIdle!==qs.defaultOptions.textureGCMaxIdle&&(this.maxIdle=t.textureGCMaxIdle),t.textureGCCheckCountMax!==qs.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=t.textureGCCheckCountMax)}run(){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};kn.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"textureGC"},kn.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Ng=kn;const kh=class _u{constructor(t={}){if(this.uid=dt("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,t={..._u.defaultOptions,...t},this.stencil=t.stencil,this.depth=t.depth,this.isRoot=t.isRoot,typeof t.colorTextures=="number"){this._managedColorTextures=!0;for(let e=0;e<t.colorTextures;e++)this.colorTextures.push(new At({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}))}else{this.colorTextures=[...t.colorTextures.map(i=>i.source)];const e=this.colorTexture.source;this.resize(e.width,e.height,e._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(t.depthStencilTexture||this.stencil)&&(t.depthStencilTexture instanceof $||t.depthStencilTexture instanceof At?this.depthStencilTexture=t.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const t=this._size;return t[0]=this.pixelWidth,t[1]=this.pixelHeight,t}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(t){this.resize(t.width,t.height,t._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new At({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(t,e,i=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(t,e,i)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(t,e,i)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(t=>{t.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};kh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Bn=kh;const Ti=new Map;li.register(Ti);function Bh(s,t){if(!Ti.has(s)){const e=new $({source:new ae({resource:s,...t})}),i=()=>{Ti.get(s)===e&&Ti.delete(s)};e.once("destroy",i),e.source.once("destroy",i),Ti.set(s,e)}return Ti.get(s)}const On=class yu{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(t){this.texture.source.autoDensity=t}get resolution(){return this.texture.source._resolution}set resolution(t){this.texture.source.resize(this.texture.source.width,this.texture.source.height,t)}init(t){t={...yu.defaultOptions,...t},t.view&&(K(vt,"ViewSystem.view has been renamed to ViewSystem.canvas"),t.canvas=t.view),this.screen=new ct(0,0,t.width,t.height),this.canvas=t.canvas||rt.get().createCanvas(),this.antialias=!!t.antialias,this.texture=Bh(this.canvas,t),this.renderTarget=new Bn({colorTextures:[this.texture],depth:!!t.depth,isRoot:!0}),this.texture.source.transparent=t.backgroundAlpha<1,this.resolution=t.resolution}resize(t,e,i){this.texture.source.resize(t,e,i),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(t=!1){(typeof t=="boolean"?t:!!(t!=null&&t.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};On.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"view",priority:0},On.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Dn=[Rg,Ih,Pn,On,Ah,Dg,Ng,Rh,Ig,Ga,Lg,Ph],Oh=[Tn,gn,En,bn,_n,xh,gh,yn];function Fg(s,t,e,i,r,n){const o=n?1:-1;return s.identity(),s.a=1/i*2,s.d=o*(1/r*2),s.tx=-1-t*s.a,s.ty=-o-e*s.d,s}function Hg(s){const t=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement&&document.body.contains(t)}class Gn{constructor(t){this.rootViewPort=new ct,this.viewport=new ct,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new ka("onRenderTargetChange"),this.projectionMatrix=new W,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=t,t.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:t,clear:e,clearColor:i,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(t,e,i,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=Hg(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var t,e;(e=(t=this.adaptor).postrender)==null||e.call(t,this.rootRenderTarget)}bind(t,e=!0,i,r,n=0,o=0){const a=this.getRenderTarget(t),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=t;const h=this.getGpuRenderTarget(a);(a.pixelWidth!==h.width||a.pixelHeight!==h.height)&&(this.adaptor.resizeGpuRenderTarget(a),h.width=a.pixelWidth,h.height=a.pixelHeight);const c=a.colorTexture,u=this.viewport,m=c.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=m)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${m}).`);this.mipLevel=n|0,this.layer=o|0;const f=Math.max(c.pixelWidth>>n,1),g=Math.max(c.pixelHeight>>n,1);if(!r&&t instanceof $&&(r=t.frame),r){const y=c._resolution,x=1<<Math.max(n|0,0),v=r.x*y+.5|0,E=r.y*y+.5|0,T=r.width*y+.5|0,C=r.height*y+.5|0;let R=Math.floor(v/x),A=Math.floor(E/x),P=Math.ceil(T/x),F=Math.ceil(C/x);R=Math.min(Math.max(R,0),f-1),A=Math.min(Math.max(A,0),g-1),P=Math.min(Math.max(P,1),f-R),F=Math.min(Math.max(F,1),g-A),u.x=R,u.y=A,u.width=P,u.height=F}else u.x=0,u.y=0,u.width=f,u.height=g;return Fg(this.projectionMatrix,0,0,u.width/c.resolution,u.height/c.resolution,!a.isRoot),this.adaptor.startRenderPass(a,e,i,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(t,e=Xt.ALL,i,r=this.mipLevel,n=this.layer){e&&(t&&(t=this.getRenderTarget(t)),this.adaptor.clear(t||this.renderTarget,e,i,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(t,e=Xt.ALL,i,r,n=0,o=0){const a=this.bind(t,e,i,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const t=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(t.renderTarget,!1,null,t.frame,t.mipLevel,t.layer)}getRenderTarget(t){return t.isTexture&&(t=t.source),this._renderSurfaceToRenderTargetHash.get(t)??this._initRenderTarget(t)}copyToTexture(t,e,i,r,n){i.x<0&&(r.width+=i.x,n.x-=i.x,i.x=0),i.y<0&&(r.height+=i.y,n.y-=i.y,i.y=0);const{pixelWidth:o,pixelHeight:a}=t;return r.width=Math.min(r.width,o-i.x),r.height=Math.min(r.height,a-i.y),this.adaptor.copyToTexture(t,e,i,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((t,e)=>{t!==e&&t.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(t){let e=null;return ae.test(t)&&(t=Bh(t).source),t instanceof Bn?e=t:t instanceof At&&(e=new Bn({colorTextures:[t]}),t.source instanceof ae&&(e.isRoot=!0),t.once("destroy",()=>{e.destroy(),this._renderSurfaceToRenderTargetHash.delete(t);const i=this._gpuRenderTargetHash[e.uid];i&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(i))})),this._renderSurfaceToRenderTargetHash.set(t,e),e}getGpuRenderTarget(t){return this._gpuRenderTargetHash[t.uid]||(this._gpuRenderTargetHash[t.uid]=this.adaptor.initGpuRenderTarget(t))}resetState(){this.renderTarget=null,this.renderSurface=null}}class Wg{init(t,e){this._renderer=t,this._renderTargetSystem=e}initGpuRenderTarget(t){const e=t.colorTexture,{canvas:i,context:r}=this._ensureCanvas(e);return{canvas:i,context:r,width:i.width,height:i.height}}resizeGpuRenderTarget(t){const e=t.colorTexture,{canvas:i}=this._ensureCanvas(e);i.width=t.pixelWidth,i.height=t.pixelHeight}startRenderPass(t,e,i,r){const n=this._renderTargetSystem.getGpuRenderTarget(t);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=t.resolution,e&&this.clear(t,e,i,r)}clear(t,e,i,r){const o=this._renderTargetSystem.getGpuRenderTarget(t).context,a=r||{x:0,y:0,width:t.pixelWidth,height:t.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),i){const l=ut.shared.setValue(i);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(t,e,i,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(t).canvas,l=e.source,{context:h}=this._ensureCanvas(l),c=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return h.drawImage(a,i.x,i.y,r.width,r.height,c,u,r.width,r.height),l.update(),e}destroyGpuRenderTarget(t){}_ensureCanvas(t){let e=t.resource;(!e||!ae.test(e))&&(e=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),t.resource=e),(e.width!==t.pixelWidth||e.height!==t.pixelHeight)&&(e.width=t.pixelWidth,e.height=t.pixelHeight);const i=e.getContext("2d");return{canvas:e,context:i}}}class Dh extends Gn{constructor(t){super(t),this.adaptor=new Wg,this.adaptor.init(t,this)}}Dh.extension={type:[w.CanvasSystem],name:"renderTarget"};class Gh{constructor(t){}init(){}initSource(t){}generateCanvas(t){const e=rt.get().createCanvas(),i=e.getContext("2d"),r=st.getCanvasSource(t);if(!r)return e;const n=t.frame,o=t.source._resolution??t.source.resolution??1,a=n.x*o,l=n.y*o,h=n.width*o,c=n.height*o;return e.width=Math.ceil(h),e.height=Math.ceil(c),i.drawImage(r,a,l,h,c,0,0,h,c),e}getPixels(t){const e=this.generateCanvas(t);return{pixels:e.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}destroy(){}}Gh.extension={type:[w.CanvasSystem],name:"texture"};const Vg=[...Dn,bh,vh,Gh,Dh],zg=[Tn,gn,En,bn,_n,yh,mh,yn],$g=[ag,Eh],Uh=[],Lh=[],Nh=[];J.handleByNamedList(w.CanvasSystem,Uh),J.handleByNamedList(w.CanvasPipes,Lh),J.handleByNamedList(w.CanvasPipesAdaptor,Nh),J.add(...Vg,...zg,...$g);class jg extends $i{constructor(){const t={name:"canvas",type:he.CANVAS,systems:Uh,renderPipes:Lh,renderPipeAdaptors:Nh};super(t)}}const Xg=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:jg},Symbol.toStringTag,{value:"Module"}));var Fs=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(Fs||{});class Yg{constructor(t,e){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.type=e}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class Fh{constructor(t){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=t,this._managedBuffers=new ce({renderer:t,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(t){return t._gcLastUsed=this._renderer.gc.now,t._gpuData[this._renderer.uid]||this.createGLBuffer(t)}bind(t){const{_gl:e}=this,i=this.getGlBuffer(t);e.bindBuffer(i.type,i.buffer)}bindBufferBase(t,e){const{_gl:i}=this;this._boundBufferBases[e]!==t&&(this._boundBufferBases[e]=t,t._lastBindBaseLocation=e,i.bindBufferBase(i.UNIFORM_BUFFER,e,t.buffer))}nextBindBase(t){this._bindCallId++,this._minBaseLocation=0,t&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(t){let e=this.getLastBindBaseLocation(t);if(e>=this._minBaseLocation)return t._lastBindCallId=this._bindCallId,e;let i=0,r=this._nextBindBaseIndex;for(;i<2;){r>=this._maxBindings&&(r=this._minBaseLocation,i++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return e=r,this._nextBindBaseIndex=r+1,i>=2?-1:(t._lastBindCallId=this._bindCallId,this._boundBufferBases[e]=null,e)}getLastBindBaseLocation(t){const e=t._lastBindBaseLocation;return this._boundBufferBases[e]===t?e:-1}bindBufferRange(t,e,i,r){const{_gl:n}=this;i||(i=0),e||(e=0),this._boundBufferBases[e]=null,n.bindBufferRange(n.UNIFORM_BUFFER,e||0,t.buffer,i*256,r||256)}updateBuffer(t){const{_gl:e}=this,i=this.getGlBuffer(t);if(t._updateID===i.updateID)return i;i.updateID=t._updateID,e.bindBuffer(i.type,i.buffer);const r=t.data,n=t.descriptor.usage&yt.STATIC?e.STATIC_DRAW:e.DYNAMIC_DRAW;return r?i.byteLength>=r.byteLength?e.bufferSubData(i.type,0,r,0,t._updateSize/r.BYTES_PER_ELEMENT):(i.byteLength=r.byteLength,e.bufferData(i.type,r,n)):(i.byteLength=t.descriptor.size,e.bufferData(i.type,i.byteLength,n)),i}destroyAll(t=!1){this._managedBuffers.removeAll(t)}onBufferUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];i&&(e||this._gl.deleteBuffer(i.buffer))}createGLBuffer(t){const{_gl:e}=this;let i=Fs.ARRAY_BUFFER;t.descriptor.usage&yt.INDEX?i=Fs.ELEMENT_ARRAY_BUFFER:t.descriptor.usage&yt.UNIFORM&&(i=Fs.UNIFORM_BUFFER);const r=new Yg(e.createBuffer(),i);return t._gpuData[this._renderer.uid]=r,this._managedBuffers.add(t),r}resetState(){this._boundBufferBases=Object.create(null)}}Fh.extension={type:[w.WebGLSystem],name:"buffer"};const Un=class xu{constructor(t){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=t,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this._renderer.gl=t}init(t){t={...xu.defaultOptions,...t};let e=this.multiView=t.multiView;if(t.context&&e&&(tt("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),e=!1),e?this.canvas=rt.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,t.context)this.initFromContext(t.context);else{const i=this._renderer.background.alpha<1,r=t.premultipliedAlpha??!0,n=t.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(t.preferWebGLVersion,{alpha:i,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference??"default"})}}ensureCanvasSize(t){if(!this.multiView){t!==this.canvas&&tt("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:e}=this;(e.width<t.width||e.height<t.height)&&(e.width=Math.max(t.width,t.width),e.height=Math.max(t.height,t.height))}initFromContext(t){this.gl=t,this.webGLVersion=t instanceof rt.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(t),this._renderer.runners.contextChange.emit(t);const e=this._renderer.view.canvas;e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(t,e){let i;const r=this.canvas;if(t===2&&(i=r.getContext("webgl2",e)),!i&&(i=r.getContext("webgl",e),!i))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=i,this.initFromContext(this.gl)}getExtensions(){const{gl:t}=this,e={anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc"),rgtc:t.getExtension("EXT_texture_compression_rgtc"),loseContext:t.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...e,drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:t.getExtension("ANGLE_instanced_arrays"),srgb:t.getExtension("EXT_sRGB")};else{this.extensions={...e,colorBufferFloat:t.getExtension("EXT_color_buffer_float")};const i=t.getExtension("WEBGL_provoking_vertex");i&&i.provokingVertexWEBGL(i.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(t){t.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var e;this.gl.isContextLost()&&((e=this.extensions.loseContext)==null||e.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var e;const t=this._renderer.view.canvas;this._renderer=null,t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(e=this.extensions.loseContext)==null||e.loseContext()}forceContextLoss(){var t;(t=this.extensions.loseContext)==null||t.loseContext(),this._contextLossForced=!0}validateContext(t){const e=t.getContextAttributes();e&&!e.stencil&&tt("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const i=this.supports,r=this.webGLVersion===2,n=this.extensions;i.uint32Indices=r||!!n.uint32ElementIndex,i.uniformBufferObject=r,i.vertexArrayObject=r||!!n.vertexArrayObject,i.srgbTextures=r||!!n.srgb,i.nonPowOf2wrapping=r,i.nonPowOf2mipmaps=r,i.msaa=r,i.uint32Indices||tt("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};Un.extension={type:[w.WebGLSystem],name:"context"},Un.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let qg=Un;function Hh(s,t){for(const e in s.attributes){const i=s.attributes[e],r=t[e];r?(i.format??(i.format=r.format),i.offset??(i.offset=r.offset),i.instance??(i.instance=r.instance)):tt(`Attribute ${e} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Kg(s)}function Kg(s){const{buffers:t,attributes:e}=s,i={},r={};for(const n in t){const o=t[n];i[o.uid]=0,r[o.uid]=0}for(const n in e){const o=e[n];i[o.buffer.uid]+=Li(o.format).stride}for(const n in e){const o=e[n];o.stride??(o.stride=i[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=Li(o.format).stride}}var Ln=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(Ln||{}),Nn=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(Nn||{}),nt=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(nt||{});const Wh={uint8x2:nt.UNSIGNED_BYTE,uint8x4:nt.UNSIGNED_BYTE,sint8x2:nt.BYTE,sint8x4:nt.BYTE,unorm8x2:nt.UNSIGNED_BYTE,unorm8x4:nt.UNSIGNED_BYTE,snorm8x2:nt.BYTE,snorm8x4:nt.BYTE,uint16x2:nt.UNSIGNED_SHORT,uint16x4:nt.UNSIGNED_SHORT,sint16x2:nt.SHORT,sint16x4:nt.SHORT,unorm16x2:nt.UNSIGNED_SHORT,unorm16x4:nt.UNSIGNED_SHORT,snorm16x2:nt.SHORT,snorm16x4:nt.SHORT,float16x2:nt.HALF_FLOAT,float16x4:nt.HALF_FLOAT,float32:nt.FLOAT,float32x2:nt.FLOAT,float32x3:nt.FLOAT,float32x4:nt.FLOAT,uint32:nt.UNSIGNED_INT,uint32x2:nt.UNSIGNED_INT,uint32x3:nt.UNSIGNED_INT,uint32x4:nt.UNSIGNED_INT,sint32:nt.INT,sint32x2:nt.INT,sint32x3:nt.INT,sint32x4:nt.INT};function Zg(s){return Wh[s]??Wh.float32}const Jg={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class Qg{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Vh{constructor(t){this._renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new ce({renderer:t,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const t=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const e=this._renderer.context.extensions.vertexArrayObject;e&&(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=r=>e.bindVertexArrayOES(r),t.deleteVertexArray=r=>e.deleteVertexArrayOES(r));const i=this._renderer.context.extensions.vertexAttribDivisorANGLE;i&&(t.drawArraysInstanced=(r,n,o,a)=>{i.drawArraysInstancedANGLE(r,n,o,a)},t.drawElementsInstanced=(r,n,o,a,l)=>{i.drawElementsInstancedANGLE(r,n,o,a,l)},t.vertexAttribDivisor=(r,n)=>i.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(t,e){const i=this.gl;this._activeGeometry=t;const r=this.getVao(t,e);this._activeVao!==r&&(this._activeVao=r,i.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this._renderer.buffer;for(let i=0;i<t.buffers.length;i++){const r=t.buffers[i];e.updateBuffer(r)}t._gcLastUsed=this._renderer.gc.now}checkCompatibility(t,e){const i=t.attributes,r=e._attributeData;for(const n in r)if(!i[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(t,e){const i=t.attributes,r=e._attributeData,n=["g",t.uid];for(const o in i)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(t,e){var i;return((i=t._gpuData[this._renderer.uid])==null?void 0:i.vaoCache[e._key])||this.initGeometryVao(t,e)}initGeometryVao(t,e,i=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(e),this.checkCompatibility(t,e);const o=this.getSignature(t,e);let a=t._gpuData[this._renderer.uid];a||(a=new Qg,t._gpuData[this._renderer.uid]=a,this._managedGeometries.add(t));const l=a.vaoCache;let h=l[o];if(h)return l[e._key]=h,h;Hh(t,e._attributeData);const c=t.buffers;h=r.createVertexArray(),r.bindVertexArray(h);for(let u=0;u<c.length;u++){const m=c[u];n.bind(m)}return this.activateVao(t,e),l[e._key]=h,l[o]=h,r.bindVertexArray(null),h}onGeometryUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];if(!i)return;const r=i.vaoCache;if(!e)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(t=!1){this._managedGeometries.removeAll(t)}activateVao(t,e){var a;const i=this._renderer.gl,r=this._renderer.buffer,n=t.attributes;t.indexBuffer&&r.bind(t.indexBuffer);let o=null;for(const l in n){const h=n[l],c=h.buffer,u=r.getGlBuffer(c),m=e._attributeData[l];if(m){o!==u&&(r.bind(c),o=u);const f=m.location;i.enableVertexAttribArray(f);const g=Li(h.format),y=Zg(h.format);if(((a=m.format)==null?void 0:a.substring(1,4))==="int"?i.vertexAttribIPointer(f,g.size,y,h.stride,h.offset):i.vertexAttribPointer(f,g.size,y,g.normalised,h.stride,h.offset),h.instance)if(this.hasInstance){const x=h.divisor??1;i.vertexAttribDivisor(f,x)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(t,e,i,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=Jg[t||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,h=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,e||o.indexBuffer.data.length,h,(i||0)*l,r):n.drawElements(a,e||o.indexBuffer.data.length,h,(i||0)*l)}else r!==1?n.drawArraysInstanced(a,i||0,e||o.getSize(),r):n.drawArrays(a,i||0,e||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Vh.extension={type:[w.WebGLSystem],name:"geometry"};const t_=new zr({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Fn=class bu{constructor(t){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=t}init(t={}){const{useBackBuffer:e,antialias:i}={...bu.defaultOptions,...t};this.useBackBuffer=e,this._antialias=i,this._renderer.context.supports.msaa||(tt("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=ve.for2d();const r=new gi({vertex:`
|
|
571
|
+
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${Zs} - ${s} - http://www.pixijs.com/`);_h=!0}}class co{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===yt.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),ny(t)}}}co.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"hello",priority:-2},co.defaultOptions={hello:!1};const ho=class Gd{constructor(e){this._renderer=e}init(e){e={...Gd.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return J("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){J("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){J("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){J("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){J("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){J("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};ho.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"renderableGC",priority:0},ho.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let oy=ho;const uo=class Ar{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){J("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){J("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){J("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){J("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==Ar.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==Ar.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==Ar.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){J("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};uo.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"textureGC"},uo.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let ay=uo;const yh=class Ld{constructor(e={}){if(this.uid=xe("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...Ld.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new De({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(i=>i.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof q||e.depthStencilTexture instanceof De?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new De({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,i=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,i)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,i)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};yh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let fo=yh;const Di=new Map;xi.register(Di);function bh(s,e){if(!Di.has(s)){const t=new q({source:new gt({resource:s,...e})}),i=()=>{Di.get(s)===t&&Di.delete(s)};t.once("destroy",i),t.source.once("destroy",i),Di.set(s,t)}return Di.get(s)}const po=class Ud{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Ud.defaultOptions,...e},e.view&&(J(Ie,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new ye(0,0,e.width,e.height),this.canvas=e.canvas||de.get().createCanvas(),this.antialias=!!e.antialias,this.texture=bh(this.canvas,e),this.renderTarget=new fo({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,i){this.texture.source.resize(e,t,i),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};po.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:"view",priority:0},po.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const mo=[q_,mh,co,po,fh,sy,ay,ph,Z_,Sl,oy,gh],xh=[io,Kn,to,Qn,qn,nh,ih,Zn];function ly(s,e,t,i,r,n){const o=n?1:-1;return s.identity(),s.a=1/i*2,s.d=o*(1/r*2),s.tx=-1-e*s.a,s.ty=-o-t*s.d,s}function cy(s){const e=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class go{constructor(e){this.rootViewPort=new ye,this.viewport=new ye,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new yl("onRenderTargetChange"),this.projectionMatrix=new Y,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:i,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(e,t,i,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=cy(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,i,r,n=0,o=0){const a=this.getRenderTarget(e),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=e;const c=this.getGpuRenderTarget(a);(a.pixelWidth!==c.width||a.pixelHeight!==c.height)&&(this.adaptor.resizeGpuRenderTarget(a),c.width=a.pixelWidth,c.height=a.pixelHeight);const h=a.colorTexture,u=this.viewport,p=h.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=p)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${p}).`);this.mipLevel=n|0,this.layer=o|0;const d=Math.max(h.pixelWidth>>n,1),g=Math.max(h.pixelHeight>>n,1);if(!r&&e instanceof q&&(r=e.frame),r){const _=h._resolution,y=1<<Math.max(n|0,0),x=r.x*_+.5|0,v=r.y*_+.5|0,C=r.width*_+.5|0,T=r.height*_+.5|0;let A=Math.floor(x/y),w=Math.floor(v/y),R=Math.ceil(C/y),D=Math.ceil(T/y);A=Math.min(Math.max(A,0),d-1),w=Math.min(Math.max(w,0),g-1),R=Math.min(Math.max(R,1),d-A),D=Math.min(Math.max(D,1),g-w),u.x=A,u.y=w,u.width=R,u.height=D}else u.x=0,u.y=0,u.width=d,u.height=g;return ly(this.projectionMatrix,0,0,u.width/h.resolution,u.height/h.resolution,!a.isRoot),this.adaptor.startRenderPass(a,t,i,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(e,t=it.ALL,i,r=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,i,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=it.ALL,i,r,n=0,o=0){const a=this.bind(e,t,i,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame,e.mipLevel,e.layer)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,i,r,n){i.x<0&&(r.width+=i.x,n.x-=i.x,i.x=0),i.y<0&&(r.height+=i.y,n.y-=i.y,i.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-i.x),r.height=Math.min(r.height,a-i.y),this.adaptor.copyToTexture(e,t,i,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return gt.test(e)&&(e=bh(e).source),e instanceof fo?t=e:e instanceof De&&(t=new fo({colorTextures:[e]}),e.source instanceof gt&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const i=this._gpuRenderTargetHash[t.uid];i&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(i))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class hy{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:i,context:r}=this._ensureCanvas(t);return{canvas:i,context:r,width:i.width,height:i.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:i}=this._ensureCanvas(t);i.width=e.pixelWidth,i.height=e.pixelHeight}startRenderPass(e,t,i,r){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,i,r)}clear(e,t,i,r){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),i){const l=be.shared.setValue(i);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,i,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:c}=this._ensureCanvas(l),h=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return c.drawImage(a,i.x,i.y,r.width,r.height,h,u,r.width,r.height),l.update(),t}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!gt.test(t))&&(t=de.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const i=t.getContext("2d");return{canvas:t,context:i}}}class vh extends go{constructor(e){super(e),this.adaptor=new hy,this.adaptor.init(e,this)}}vh.extension={type:[I.CanvasSystem],name:"renderTarget"};class Sh{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=de.get().createCanvas(),i=t.getContext("2d"),r=he.getCanvasSource(e);if(!r)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,c=n.width*o,h=n.height*o;return t.width=Math.ceil(c),t.height=Math.ceil(h),i.drawImage(r,a,l,c,h,0,0,c,h),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Sh.extension={type:[I.CanvasSystem],name:"texture"};const uy=[...mo,oh,ah,Sh,vh],dy=[io,Kn,to,Qn,qn,rh,th,Zn],fy=[R_,lh],Ch=[],Th=[],Eh=[];ie.handleByNamedList(I.CanvasSystem,Ch),ie.handleByNamedList(I.CanvasPipes,Th),ie.handleByNamedList(I.CanvasPipesAdaptor,Eh),ie.add(...uy,...dy,...fy);class py extends hs{constructor(){const e={name:"canvas",type:yt.CANVAS,systems:Ch,renderPipes:Th,renderPipeAdaptors:Eh};super(e)}}const my=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:py},Symbol.toStringTag,{value:"Module"}));var hr=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(hr||{});class gy{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class wh{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new bt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,i=this.getGlBuffer(e);t.bindBuffer(i.type,i.buffer)}bindBufferBase(e,t){const{_gl:i}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,i.bindBufferBase(i.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let i=0,r=this._nextBindBaseIndex;for(;i<2;){r>=this._maxBindings&&(r=this._minBaseLocation,i++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return t=r,this._nextBindBaseIndex=r+1,i>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,i,r){const{_gl:n}=this;i||(i=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,i*256,r||256)}updateBuffer(e){const{_gl:t}=this,i=this.getGlBuffer(e);if(e._updateID===i.updateID)return i;i.updateID=e._updateID,t.bindBuffer(i.type,i.buffer);const r=e.data,n=e.descriptor.usage&Ee.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?i.byteLength>=r.byteLength?t.bufferSubData(i.type,0,r,0,e._updateSize/r.BYTES_PER_ELEMENT):(i.byteLength=r.byteLength,t.bufferData(i.type,r,n)):(i.byteLength=e.descriptor.size,t.bufferData(i.type,i.byteLength,n)),i}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||this._gl.deleteBuffer(i.buffer))}createGLBuffer(e){const{_gl:t}=this;let i=hr.ARRAY_BUFFER;e.descriptor.usage&Ee.INDEX?i=hr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&Ee.UNIFORM&&(i=hr.UNIFORM_BUFFER);const r=new gy(t.createBuffer(),i);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}}wh.extension={type:[I.WebGLSystem],name:"buffer"};const _o=class Wd{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...Wd.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(ne("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=de.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const i=this._renderer.background.alpha<1,r=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:i,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&ne("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof de.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let i;const r=this.canvas;if(e===2&&(i=r.getContext("webgl2",t)),!i&&(i=r.getContext("webgl",t),!i))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=i,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const i=e.getExtension("WEBGL_provoking_vertex");i&&i.provokingVertexWEBGL(i.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&ne("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const i=this.supports,r=this.webGLVersion===2,n=this.extensions;i.uint32Indices=r||!!n.uint32ElementIndex,i.uniformBufferObject=r,i.vertexArrayObject=r||!!n.vertexArrayObject,i.srgbTextures=r||!!n.srgb,i.nonPowOf2wrapping=r,i.nonPowOf2mipmaps=r,i.msaa=r,i.uint32Indices||ne("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};_o.extension={type:[I.WebGLSystem],name:"context"},_o.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let _y=_o;function Ih(s,e){for(const t in s.attributes){const i=s.attributes[t],r=e[t];r?(i.format??(i.format=r.format),i.offset??(i.offset=r.offset),i.instance??(i.instance=r.instance)):ne(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}yy(s)}function yy(s){const{buffers:e,attributes:t}=s,i={},r={};for(const n in e){const o=e[n];i[o.uid]=0,r[o.uid]=0}for(const n in t){const o=t[n];i[o.buffer.uid]+=ss(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=i[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=ss(o.format).stride}}var yo=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(yo||{}),bo=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(bo||{}),me=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(me||{});const Ah={uint8x2:me.UNSIGNED_BYTE,uint8x4:me.UNSIGNED_BYTE,sint8x2:me.BYTE,sint8x4:me.BYTE,unorm8x2:me.UNSIGNED_BYTE,unorm8x4:me.UNSIGNED_BYTE,snorm8x2:me.BYTE,snorm8x4:me.BYTE,uint16x2:me.UNSIGNED_SHORT,uint16x4:me.UNSIGNED_SHORT,sint16x2:me.SHORT,sint16x4:me.SHORT,unorm16x2:me.UNSIGNED_SHORT,unorm16x4:me.UNSIGNED_SHORT,snorm16x2:me.SHORT,snorm16x4:me.SHORT,float16x2:me.HALF_FLOAT,float16x4:me.HALF_FLOAT,float32:me.FLOAT,float32x2:me.FLOAT,float32x3:me.FLOAT,float32x4:me.FLOAT,uint32:me.UNSIGNED_INT,uint32x2:me.UNSIGNED_INT,uint32x3:me.UNSIGNED_INT,uint32x4:me.UNSIGNED_INT,sint32:me.INT,sint32x2:me.INT,sint32x3:me.INT,sint32x4:me.INT};function by(s){return Ah[s]??Ah.float32}const xy={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class vy{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Rh{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new bt({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=r=>t.bindVertexArrayOES(r),e.deleteVertexArray=r=>t.deleteVertexArrayOES(r));const i=this._renderer.context.extensions.vertexAttribDivisorANGLE;i&&(e.drawArraysInstanced=(r,n,o,a)=>{i.drawArraysInstancedANGLE(r,n,o,a)},e.drawElementsInstanced=(r,n,o,a,l)=>{i.drawElementsInstancedANGLE(r,n,o,a,l)},e.vertexAttribDivisor=(r,n)=>i.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const i=this.gl;this._activeGeometry=e;const r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,i.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let i=0;i<e.buffers.length;i++){const r=e.buffers[i];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const i=e.attributes,r=t._attributeData;for(const n in r)if(!i[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const i=e.attributes,r=t._attributeData,n=["g",e.uid];for(const o in i)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(e,t){var i;return((i=e._gpuData[this._renderer.uid])==null?void 0:i.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,i=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const o=this.getSignature(e,t);let a=e._gpuData[this._renderer.uid];a||(a=new vy,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let c=l[o];if(c)return l[t._key]=c,c;Ih(e,t._attributeData);const h=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let u=0;u<h.length;u++){const p=h[u];n.bind(p)}return this.activateVao(e,t),l[t._key]=c,l[o]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];if(!i)return;const r=i.vaoCache;if(!t)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var a;const i=this._renderer.gl,r=this._renderer.buffer,n=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let o=null;for(const l in n){const c=n[l],h=c.buffer,u=r.getGlBuffer(h),p=t._attributeData[l];if(p){o!==u&&(r.bind(h),o=u);const d=p.location;i.enableVertexAttribArray(d);const g=ss(c.format),_=by(c.format);if(((a=p.format)==null?void 0:a.substring(1,4))==="int"?i.vertexAttribIPointer(d,g.size,_,c.stride,c.offset):i.vertexAttribPointer(d,g.size,_,g.normalised,c.stride,c.offset),c.instance)if(this.hasInstance){const y=c.divisor??1;i.vertexAttribDivisor(d,y)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,i,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=xy[e||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,c=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,t||o.indexBuffer.data.length,c,(i||0)*l,r):n.drawElements(a,t||o.indexBuffer.data.length,c,(i||0)*l)}else r!==1?n.drawArraysInstanced(a,i||0,t||o.getSize(),r):n.drawArrays(a,i||0,t||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Rh.extension={type:[I.WebGLSystem],name:"geometry"};const Sy=new Tn({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),xo=class Hd{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:i}={...Hd.defaultOptions,...e};this.useBackBuffer=t,this._antialias=i,this._renderer.context.supports.msaa||(ne("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=At.for2d();const r=new Ai({vertex:`
|
|
572
572
|
attribute vec2 aPosition;
|
|
573
573
|
out vec2 vUv;
|
|
574
574
|
|
|
@@ -587,7 +587,7 @@ fn mainFragment(
|
|
|
587
587
|
|
|
588
588
|
void main() {
|
|
589
589
|
finalColor = texture(uTexture, vUv);
|
|
590
|
-
}`,name:"big-triangle"});this._bigTriangleShader=new
|
|
590
|
+
}`,name:"big-triangle"});this._bigTriangleShader=new It({glProgram:r,resources:{uTexture:q.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const i=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=i.colorTexture,e.target=this._getBackBufferTexture(i.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:Sy,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new q({source:new De({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};xo.extension={type:[I.WebGLSystem],name:"backBuffer",priority:1},xo.defaultOptions={useBackBuffer:!1};let Cy=xo;class Mh{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}Mh.extension={type:[I.WebGLSystem],name:"colorMask"};class Ph{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:i,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(i,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??i.instanceCount)}destroy(){this._renderer=null}}Ph.extension={type:[I.WebGLSystem],name:"encoder"};class kh{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=Pl(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}kh.extension={type:[I.WebGLSystem],name:"limits"};class Ty{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[]}}const Vt=[];Vt[Be.NONE]=void 0,Vt[Be.DISABLED]={stencilWriteMask:0,stencilReadMask:0},Vt[Be.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},Vt[Be.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},Vt[Be.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},Vt[Be.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Bh{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:Be.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:Be.DISABLED,stencilReference:0}),this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=Be.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=Vt[e],o=this._stencilCache;if(i.stencilMode=e,i.stencilReference=t,e===Be.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}Bh.extension={type:[I.WebGLSystem],name:"stencil"};class Oh{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!ul())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(e){const t=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ut({data:new Float32Array(t.layout.size/4),usage:Ee.UNIFORM|Ee.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let i=this._syncFunctionHash[t];if(!i){const r=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);i=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,i){const r=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ut({data:new Float32Array(r.layout.size/4),usage:Ee.UNIFORM|Ee.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),i||(i=0),r.syncFunction(e.uniforms,t,n,i),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const Dh={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function Ey(s){const e=s.map(n=>({data:n,offset:0,size:0})),t=16;let i=0,r=0;for(let n=0;n<e.length;n++){const o=e[n];if(i=Dh[o.data.type],!i)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(i=Math.max(i,t)*o.data.size);const a=i===12?16:i;o.size=i;const l=r%t;l>0&&t-l<a?r+=(t-l)%16:r+=(i-l%i)%i,o.offset=r,r+=i}return r=Math.ceil(r/16)*16,{uboElements:e,size:r}}const hi=[{type:"mat3x3<f32>",test:s=>s.value.a!==void 0,ubo:`
|
|
591
591
|
var matrix = uv[name].toArray(true);
|
|
592
592
|
data[offset] = matrix[0];
|
|
593
593
|
data[offset + 1] = matrix[1];
|
|
@@ -658,23 +658,23 @@ fn mainFragment(
|
|
|
658
658
|
cv[2] = v.blue;
|
|
659
659
|
gl.uniform3f(ud[name].location, v.red, v.green, v.blue);
|
|
660
660
|
}
|
|
661
|
-
`}];function
|
|
661
|
+
`}];function Nh(s,e,t,i){const r=[`
|
|
662
662
|
var v = null;
|
|
663
663
|
var v2 = null;
|
|
664
664
|
var t = 0;
|
|
665
665
|
var index = 0;
|
|
666
666
|
var name = null;
|
|
667
667
|
var arrayOffset = null;
|
|
668
|
-
`];let n=0;for(let a=0;a<s.length;a++){const l=s[a],
|
|
669
|
-
v = uv.${
|
|
668
|
+
`];let n=0;for(let a=0;a<s.length;a++){const l=s[a],c=l.data.name;let h=!1,u=0;for(let p=0;p<hi.length;p++)if(hi[p].test(l.data)){u=l.offset/4,r.push(`name = "${c}";`,`offset += ${u-n};`,hi[p][e]||hi[p].ubo),h=!0;break}if(!h)if(l.data.size>1)u=l.offset/4,r.push(t(l,u-n));else{const p=i[l.data.type];u=l.offset/4,r.push(`
|
|
669
|
+
v = uv.${c};
|
|
670
670
|
offset += ${u-n};
|
|
671
|
-
${
|
|
671
|
+
${p};
|
|
672
672
|
`)}n=u}const o=r.join(`
|
|
673
|
-
`);return new Function("uv","data","dataInt32","offset",o)}function
|
|
674
|
-
for (let i = 0; i < ${s*
|
|
673
|
+
`);return new Function("uv","data","dataInt32","offset",o)}function Ni(s,e){return`
|
|
674
|
+
for (let i = 0; i < ${s*e}; i++) {
|
|
675
675
|
data[offset + (((i / ${s})|0) * 4) + (i % ${s})] = v[i];
|
|
676
676
|
}
|
|
677
|
-
`}const
|
|
677
|
+
`}const Fh={f32:`
|
|
678
678
|
data[offset] = v;`,i32:`
|
|
679
679
|
dataInt32[offset] = v;`,"vec2<f32>":`
|
|
680
680
|
data[offset] = v[0];
|
|
@@ -710,20 +710,20 @@ fn mainFragment(
|
|
|
710
710
|
data[offset + 10] = v[8];`,"mat4x4<f32>":`
|
|
711
711
|
for (let i = 0; i < 16; i++) {
|
|
712
712
|
data[offset + i] = v[i];
|
|
713
|
-
}`,"mat3x2<f32>":
|
|
713
|
+
}`,"mat3x2<f32>":Ni(3,2),"mat4x2<f32>":Ni(4,2),"mat2x3<f32>":Ni(2,3),"mat4x3<f32>":Ni(4,3),"mat2x4<f32>":Ni(2,4),"mat3x4<f32>":Ni(3,4)},wy={...Fh,"mat2x2<f32>":`
|
|
714
714
|
data[offset] = v[0];
|
|
715
715
|
data[offset + 1] = v[1];
|
|
716
716
|
data[offset + 2] = v[2];
|
|
717
717
|
data[offset + 3] = v[3];
|
|
718
|
-
`};function
|
|
718
|
+
`};function Iy(s,e){const t=Math.max(Dh[s.data.type]/16,1),i=s.data.value.length/s.data.size,r=(4-i%4)%4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
719
719
|
v = uv.${s.data.name};
|
|
720
|
-
offset += ${
|
|
720
|
+
offset += ${e};
|
|
721
721
|
|
|
722
722
|
arrayOffset = offset;
|
|
723
723
|
|
|
724
724
|
t = 0;
|
|
725
725
|
|
|
726
|
-
for(var i=0; i < ${s.data.size*
|
|
726
|
+
for(var i=0; i < ${s.data.size*t}; i++)
|
|
727
727
|
{
|
|
728
728
|
for(var j = 0; j < ${i}; j++)
|
|
729
729
|
{
|
|
@@ -731,37 +731,37 @@ fn mainFragment(
|
|
|
731
731
|
}
|
|
732
732
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
733
733
|
}
|
|
734
|
-
`}function
|
|
734
|
+
`}function Ay(s){return Nh(s,"uboStd40",Iy,Fh)}class Gh extends Oh{constructor(){super({createUboElements:Ey,generateUboSync:Ay})}}Gh.extension={type:[I.WebGLSystem],name:"ubo"};class Ry{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ye}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ye;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(i,r)=>e.COLOR_ATTACHMENT0+r)}copyToTexture(e,t,i,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,i.x,i.y,r.width,r.height),t}startRenderPass(e,t=!0,i,r,n=0,o=0){const a=this._renderTargetSystem,l=e.colorTexture,c=a.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(c.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}let h=r.y;e.isRoot&&(h=l.pixelHeight-r.height-r.y),e.colorTextures.forEach(d=>{this._renderer.texture.unbind(d)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.framebuffer),!e.isRoot&&(c._attachedMipLevel!==n||c._attachedLayer!==o)&&(e.colorTextures.forEach((d,g)=>{const _=this._renderer.texture.getGlSource(d);if(_.target===u.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_2D,_.texture,n)}else if(_.target===u.TEXTURE_2D_ARRAY){if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to 2D array textures requires WebGL2.");u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,_.texture,n,o)}else if(_.target===u.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_CUBE_MAP_POSITIVE_X+o,_.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),c._attachedMipLevel=n,c._attachedLayer=o),e.colorTextures.length>1&&this._setDrawBuffers(e,u);const p=this._viewPortCache;(p.x!==r.x||p.y!==h||p.width!==r.width||p.height!==r.height)&&(p.x=r.x,p.y=h,p.width=r.width,p.height=r.height,u.viewport(r.x,h,r.width,r.height)),!c.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(c),this.clear(e,t,i)}finishRenderPass(e){const i=this._renderTargetSystem.getGpuRenderTarget(e);if(!i.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,i.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,i.framebuffer),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer)}initGpuRenderTarget(e){const i=this._renderer.gl,r=new Ty;return r._attachedMipLevel=0,r._attachedLayer=0,e.colorTexture instanceof gt?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),i.bindFramebuffer(i.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(i=>{t.deleteRenderbuffer(i)}),e.msaaRenderBuffer=null}clear(e,t,i,r,n=0,o=0){if(!t)return;if(o!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const a=this._renderTargetSystem;typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const l=this._renderer.gl;if(t&it.COLOR){i??(i=a.defaultClearColor);const c=this._clearColorCache,h=i;(c[0]!==h[0]||c[1]!==h[1]||c[2]!==h[2]||c[3]!==h[3])&&(c[0]=h[0],c[1]=h[1],c[2]=h[2],c[3]=h[3],l.clearColor(h[0],h[1],h[2],h[3]))}l.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const i=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,i),(e.stencil||e.depth)&&this._resizeStencil(i)}_initColor(e,t){const i=this._renderer,r=i.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((a,l)=>{const c=a.source;c.antialias&&(i.context.supports.msaa?t.msaa=!0:ne("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),i.texture.bindSource(c,0);const h=i.texture.getGlSource(c),u=h.texture;if(h.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_2D,u,0);else if(h.target===r.TEXTURE_2D_ARRAY){if(i.context.webGLVersion<2)throw new Error("[RenderTargetSystem] TEXTURE_2D_ARRAY requires WebGL2.");r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,u,0,0)}else if(h.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=r.createFramebuffer();t.framebuffer=a,r.bindFramebuffer(r.FRAMEBUFFER,a),e.colorTextures.forEach((l,c)=>{const h=r.createRenderbuffer();t.msaaRenderBuffer[c]=h})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const i=e.colorTexture.source;if(t.width=i.pixelWidth,t.height=i.pixelHeight,t._attachedMipLevel=0,t._attachedLayer=0,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(i.width,i.height,i._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,p=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,p),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,p)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,i=t.createRenderbuffer();e.depthStencilRenderBuffer=i,t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,i),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&>.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&>.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,i=e.colorTexture;i.context2D.drawImage(t,0,i.pixelHeight-t.height)}}_setDrawBuffers(e,t){const i=e.colorTextures.length,r=this._drawBuffersCache[i];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(r):ne("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(r)}}class Lh extends go{constructor(e){super(e),this.adaptor=new Ry,this.adaptor.init(e,this)}}Lh.extension={type:[I.WebGLSystem],name:"renderTarget"};class vo extends nt{constructor({buffer:e,offset:t,size:i}){super(),this.uid=xe("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=xe("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=i,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=xe("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function My(s,e){const t=[],i=[`
|
|
735
735
|
var g = s.groups;
|
|
736
736
|
var sS = r.shader;
|
|
737
737
|
var p = s.glProgram;
|
|
738
738
|
var ugS = r.uniformGroup;
|
|
739
739
|
var resources;
|
|
740
|
-
`];let r=!1,n=0;const o=
|
|
740
|
+
`];let r=!1,n=0;const o=e._getProgramData(s.glProgram);for(const l in s.groups){const c=s.groups[l];t.push(`
|
|
741
741
|
resources = g[${l}].resources;
|
|
742
|
-
`);for(const
|
|
742
|
+
`);for(const h in c.resources){const u=c.resources[h];if(u instanceof _t)if(u.ubo){const p=s._uniformBindMap[l][Number(h)];t.push(`
|
|
743
743
|
sS.bindUniformBlock(
|
|
744
|
-
resources[${
|
|
745
|
-
'${
|
|
746
|
-
${s.glProgram._uniformBlockData[
|
|
744
|
+
resources[${h}],
|
|
745
|
+
'${p}',
|
|
746
|
+
${s.glProgram._uniformBlockData[p].index}
|
|
747
747
|
);
|
|
748
|
-
`)}else
|
|
749
|
-
ugS.updateUniformGroup(resources[${
|
|
750
|
-
`);else if(u instanceof
|
|
748
|
+
`)}else t.push(`
|
|
749
|
+
ugS.updateUniformGroup(resources[${h}], p, sD);
|
|
750
|
+
`);else if(u instanceof vo){const p=s._uniformBindMap[l][Number(h)];t.push(`
|
|
751
751
|
sS.bindUniformBlock(
|
|
752
|
-
resources[${
|
|
753
|
-
'${
|
|
754
|
-
${s.glProgram._uniformBlockData[
|
|
752
|
+
resources[${h}],
|
|
753
|
+
'${p}',
|
|
754
|
+
${s.glProgram._uniformBlockData[p].index}
|
|
755
755
|
);
|
|
756
|
-
`)}else if(u instanceof
|
|
756
|
+
`)}else if(u instanceof De){const p=s._uniformBindMap[l][h],d=o.uniformData[p];d&&(r||(r=!0,i.push(`
|
|
757
757
|
var tS = r.texture;
|
|
758
|
-
`)),
|
|
759
|
-
tS.bind(resources[${
|
|
760
|
-
`),n++)}}}const a=[...i,...
|
|
761
|
-
`);return new Function("r","s","sD",a)}class
|
|
762
|
-
`).map((h
|
|
763
|
-
`),n={},o=r.map(
|
|
764
|
-
`);a[0]=l,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function
|
|
758
|
+
`)),e._gl.uniform1i(d.location,n),t.push(`
|
|
759
|
+
tS.bind(resources[${h}], ${n});
|
|
760
|
+
`),n++)}}}const a=[...i,...t].join(`
|
|
761
|
+
`);return new Function("r","s","sD",a)}class Py{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function Uh(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}function So(s){const e=new Array(s);for(let t=0;t<e.length;t++)e[t]=!1;return e}function Wh(s,e){switch(s){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return So(2*e);case"bvec3":return So(3*e);case"bvec4":return So(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}let ur=null;const Hh={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},ky={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function Vh(s,e){if(!ur){const t=Object.keys(Hh);ur={};for(let i=0;i<t.length;++i){const r=t[i];ur[s[r]]=Hh[r]}}return ur[e]}function By(s,e){const t=Vh(s,e);return ky[t]||"float32"}function Oy(s,e,t=!1){const i={},r=e.getProgramParameter(s,e.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=e.getActiveAttrib(s,o);if(a.name.startsWith("gl_"))continue;const l=By(e,a.type);i[a.name]={location:0,format:l,stride:ss(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(i);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)i[n[o]].location=o,e.bindAttribLocation(s,o,n[o]);e.linkProgram(s)}else for(let o=0;o<n.length;o++)i[n[o]].location=e.getAttribLocation(s,n[o]);return i}function Dy(s,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<i;r++){const n=e.getActiveUniformBlockName(s,r),o=e.getUniformBlockIndex(s,n),a=e.getActiveUniformBlockParameter(s,r,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function Ny(s,e){const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORMS);for(let r=0;r<i;r++){const n=e.getActiveUniform(s,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=Vh(e,n.type);t[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:Wh(l,n.size)}}return t}function zh(s,e){const t=s.getShaderSource(e).split(`
|
|
762
|
+
`).map((c,h)=>`${h}: ${c}`),i=s.getShaderInfoLog(e),r=i.split(`
|
|
763
|
+
`),n={},o=r.map(c=>parseFloat(c.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(c=>c&&!n[c]?(n[c]=!0,!0):!1),a=[""];o.forEach(c=>{t[c-1]=`%c${t[c-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=t.join(`
|
|
764
|
+
`);a[0]=l,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function Fy(s,e,t,i){s.getProgramParameter(e,s.LINK_STATUS)||(s.getShaderParameter(t,s.COMPILE_STATUS)||zh(s,t),s.getShaderParameter(i,s.COMPILE_STATUS)||zh(s,i),console.error("PixiJS Error: Could not initialize shader."),s.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",s.getProgramInfoLog(e)))}function Gy(s,e){const t=Uh(s,s.VERTEX_SHADER,e.vertex),i=Uh(s,s.FRAGMENT_SHADER,e.fragment),r=s.createProgram();s.attachShader(r,t),s.attachShader(r,i);const n=e.transformFeedbackVaryings;n&&(typeof s.transformFeedbackVaryings!="function"?ne("TransformFeedback is not supported but TransformFeedbackVaryings are given."):s.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?s.SEPARATE_ATTRIBS:s.INTERLEAVED_ATTRIBS)),s.linkProgram(r),s.getProgramParameter(r,s.LINK_STATUS)||Fy(s,r,t,i),e._attributeData=Oy(r,s,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=Ny(r,s),e._uniformBlockData=Dy(r,s),s.deleteShader(t),s.deleteShader(i);const o={};for(const l in e._uniformData){const c=e._uniformData[l];o[l]={location:s.getUniformLocation(r,l),value:Wh(c.type,c.size)}}return new Py(r,o)}const dr={textureCount:0,blockIndex:0};class $h{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;dr.textureCount=0,dr.blockIndex=0;let i=this._shaderSyncFunctions[e.glProgram._key];i||(i=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),i(this._renderer,e,dr)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,dr)}bindUniformBlock(e,t,i=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=r.updateBuffer(a),c=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:p}=e;u===0&&p===a.data.byteLength?r.bindBufferBase(l,c):r.bindBufferRange(l,c,u)}else r.getLastBindBaseLocation(l)!==c&&r.bindBufferBase(l,c);const h=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[i]!==c&&(n.uniformBlockBindings[i]=c,this._renderer.gl.uniformBlockBinding(n.program,h,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=Gy(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return My(e,t)}resetState(){this._activeProgram=null}}$h.extension={type:[I.WebGLSystem],name:"shader"};const Ly={f32:`if (cv !== v) {
|
|
765
765
|
cu.value = v;
|
|
766
766
|
gl.uniform1f(location, v);
|
|
767
767
|
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
@@ -833,41 +833,41 @@ fn mainFragment(
|
|
|
833
833
|
cv[2] = v[2];
|
|
834
834
|
cv[3] = v[3];
|
|
835
835
|
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
836
|
-
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},
|
|
836
|
+
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},Uy={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function Wy(s,e){const t=[`
|
|
837
837
|
var v = null;
|
|
838
838
|
var cv = null;
|
|
839
839
|
var cu = null;
|
|
840
840
|
var t = 0;
|
|
841
841
|
var gl = renderer.gl;
|
|
842
842
|
var name = null;
|
|
843
|
-
`];for(const i in s.uniforms){if(!
|
|
843
|
+
`];for(const i in s.uniforms){if(!e[i]){s.uniforms[i]instanceof _t?s.uniforms[i].ubo?t.push(`
|
|
844
844
|
renderer.shader.bindUniformBlock(uv.${i}, "${i}");
|
|
845
|
-
`):
|
|
845
|
+
`):t.push(`
|
|
846
846
|
renderer.shader.updateUniformGroup(uv.${i});
|
|
847
|
-
`):s.uniforms[i]instanceof
|
|
847
|
+
`):s.uniforms[i]instanceof vo&&t.push(`
|
|
848
848
|
renderer.shader.bindBufferResource(uv.${i}, "${i}");
|
|
849
|
-
`);continue}const r=s.uniformStructures[i];let n=!1;for(let o=0;o<
|
|
849
|
+
`);continue}const r=s.uniformStructures[i];let n=!1;for(let o=0;o<hi.length;o++){const a=hi[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${i}";`,hi[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?Ly:Uy)[r.type].replace("location",`ud["${i}"].location`);t.push(`
|
|
850
850
|
cu = ud["${i}"];
|
|
851
851
|
cv = cu.value;
|
|
852
852
|
v = uv["${i}"];
|
|
853
|
-
${a};`)}}return new Function("ud","uv","renderer","syncData",
|
|
854
|
-
`))}class oc{constructor(t){this._cache={},this._uniformGroupSyncHash={},this._renderer=t,this.gl=null,this._cache={}}contextChange(t){this.gl=t}updateUniformGroup(t,e,i){const r=this._renderer.shader._getProgramData(e);(!t.isStatic||t._dirtyId!==r.uniformDirtyGroups[t.uid])&&(r.uniformDirtyGroups[t.uid]=t._dirtyId,this._getUniformSyncFunction(t,e)(r.uniformData,t.uniforms,this._renderer,i))}_getUniformSyncFunction(t,e){var i;return((i=this._uniformGroupSyncHash[t._signature])==null?void 0:i[e._key])||this._createUniformSyncFunction(t,e)}_createUniformSyncFunction(t,e){const i=this._uniformGroupSyncHash[t._signature]||(this._uniformGroupSyncHash[t._signature]={}),r=this._getSignature(t,e._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(t,e._uniformData)),i[e._key]=this._cache[r],i[e._key]}_generateUniformsSync(t,e){return x_(t,e)}_getSignature(t,e,i){const r=t.uniforms,n=[`${i}-`];for(const o in r)n.push(o),e[o]&&n.push(e[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}oc.extension={type:[w.WebGLSystem],name:"uniformGroup"};function b_(s){const t={};if(t.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],t.add=[s.ONE,s.ONE],t.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],t["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof rt.get().getWebGLRenderingContext()))t.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const i=s.getExtension("EXT_blend_minmax");i&&(t.min=[s.ONE,s.ONE,s.ONE,s.ONE,i.MIN_EXT,i.MIN_EXT],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,i.MAX_EXT,i.MAX_EXT])}return t}const v_=0,E_=1,T_=2,S_=3,C_=4,w_=5,ac=class ro{constructor(t){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[v_]=this.setBlend,this.map[E_]=this.setOffset,this.map[T_]=this.setCullFace,this.map[S_]=this.setDepthTest,this.map[C_]=this.setFrontFace,this.map[w_]=this.setDepthMask,this.checks=[],this.defaultState=ve.for2d(),t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){this._invertFrontFace=!t.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(t){this.gl=t,this.blendModesMap=b_(t),this.resetState()}set(t){if(t||(t=this.defaultState),this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)e&1&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t||(t=this.defaultState);for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(t){this._updateCheck(ro._checkBlendMode,t),this.gl[t?"enable":"disable"](this.gl.BLEND)}setOffset(t){this._updateCheck(ro._checkPolygonOffset,t),this.gl[t?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this._cullFace=t,this.gl[t?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(t){this._frontFace=t,this._frontFaceDirty=!1;const e=this._invertFrontFace?!t:t;this._glFrontFace!==e&&(this._glFrontFace=e,this.gl.frontFace(this.gl[e?"CW":"CCW"]))}setBlendMode(t){if(this.blendModesMap[t]||(t="normal"),t===this.blendMode)return;this.blendMode=t;const e=this.blendModesMap[t],i=this.gl;e.length===2?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),e.length===6?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(t,e){const i=this.checks.indexOf(t);e&&i===-1?this.checks.push(t):!e&&i!==-1&&this.checks.splice(i,1)}static _checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static _checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};ac.extension={type:[w.WebGLSystem],name:"state"};let A_=ac;class R_{constructor(t){this.target=Nn.TEXTURE_2D,this._layerInitMask=0,this.texture=t,this.width=-1,this.height=-1,this.type=nt.UNSIGNED_BYTE,this.internalFormat=Ln.RGBA,this.format=Ln.RGBA,this.samplerType=0}destroy(){}}const I_={id:"buffer",upload(s,t,e,i,r,n=!1){const o=r||t.target;!n&&t.width===s.width&&t.height===s.height?e.texSubImage2D(o,0,0,0,s.width,s.height,t.format,t.type,s.resource):e.texImage2D(o,0,t.internalFormat,s.width,s.height,0,t.format,t.type,s.resource),t.width=s.width,t.height=s.height}},P_={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},M_={id:"compressed",upload(s,t,e,i,r,n){const o=r??t.target;e.pixelStorei(e.UNPACK_ALIGNMENT,4);let a=s.pixelWidth,l=s.pixelHeight;const h=!!P_[s.format];for(let c=0;c<s.resource.length;c++){const u=s.resource[c];h?e.compressedTexImage2D(o,c,t.internalFormat,a,l,0,u):e.texImage2D(o,c,t.internalFormat,a,l,0,t.format,t.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},lc=["right","left","top","bottom","front","back"];function k_(s){return{id:"cube",upload(t,e,i,r){const n=t.faces;for(let o=0;o<lc.length;o++){const a=lc[o],l=n[a];(s[l.uploadMethodId]||s.image).upload(l,e,i,r,Nn.TEXTURE_CUBE_MAP_POSITIVE_X+o,(e._layerInitMask&1<<o)===0),e._layerInitMask|=1<<o}e.width=t.pixelWidth,e.height=t.pixelHeight}}}const hc={id:"image",upload(s,t,e,i,r,n=!1){const o=r||t.target,a=s.pixelWidth,l=s.pixelHeight,h=s.resourceWidth,c=s.resourceHeight,u=i===2,m=n||t.width!==a||t.height!==l,f=h>=a&&c>=l,g=s.resource;(u?B_:O_)(e,o,t,a,l,h,c,g,m,f),t.width=a,t.height=l}};function B_(s,t,e,i,r,n,o,a,l,h){if(!h){l&&s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,null),s.texSubImage2D(t,0,0,0,n,o,e.format,e.type,a);return}if(!l){s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,a)}function O_(s,t,e,i,r,n,o,a,l,h){if(!h){l&&s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,null),s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}if(!l){s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}s.texImage2D(t,0,e.internalFormat,e.format,e.type,a)}const D_=og(),G_={id:"video",upload(s,t,e,i,r,n=D_){if(!s.isValid){const o=r??t.target;e.texImage2D(o,0,t.internalFormat,1,1,0,t.format,t.type,null);return}hc.upload(s,t,e,i,r,n)}},cc={linear:9729,nearest:9728},U_={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Vn={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},L_={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function uc(s,t,e,i,r,n,o,a){const l=n;if(!a||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const h=Vn[o?"clamp-to-edge":s.addressModeU],c=Vn[o?"clamp-to-edge":s.addressModeV],u=Vn[o?"clamp-to-edge":s.addressModeW];t[r](l,t.TEXTURE_WRAP_S,h),t[r](l,t.TEXTURE_WRAP_T,c),t.TEXTURE_WRAP_R&&t[r](l,t.TEXTURE_WRAP_R,u)}if((!a||s.magFilter!=="linear")&&t[r](l,t.TEXTURE_MAG_FILTER,cc[s.magFilter]),e){if(!a||s.mipmapFilter!=="linear"){const h=U_[s.minFilter][s.mipmapFilter];t[r](l,t.TEXTURE_MIN_FILTER,h)}}else t[r](l,t.TEXTURE_MIN_FILTER,cc[s.minFilter]);if(i&&s.maxAnisotropy>1){const h=Math.min(s.maxAnisotropy,t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[r](l,i.TEXTURE_MAX_ANISOTROPY_EXT,h)}s.compare&&t[r](l,t.TEXTURE_COMPARE_FUNC,L_[s.compare])}function N_(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function F_(s,t){let e={},i=s.RGBA;return s instanceof rt.get().getWebGLRenderingContext()?t.srgb&&(e={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(e={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},i=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...e,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:i,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function H_(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}function W_(s){return{"2d":s.TEXTURE_2D,cube:s.TEXTURE_CUBE_MAP,"1d":null,"3d":(s==null?void 0:s.TEXTURE_3D)||null,"2d-array":(s==null?void 0:s.TEXTURE_2D_ARRAY)||null,"cube-array":(s==null?void 0:s.TEXTURE_CUBE_MAP_ARRAY)||null}}const V_=4;class dc{constructor(t){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._managedTextures=new ce({renderer:t,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const e={image:hc,buffer:I_,video:G_,compressed:M_};this._uploads={...e,cube:k_(e)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(t){this._gl=t,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=F_(t,this._renderer.context.extensions),this._mapFormatToType=H_(t),this._mapFormatToFormat=N_(t),this._mapViewDimensionToGlTarget=W_(t)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind($.EMPTY,e)}initSource(t){this.bind(t)}bind(t,e=0){const i=t.source;t?(this.bindSource(i,e),this._useSeparateSamplers&&this._bindSampler(i.style,e)):(this.bindSource(null,e),this._useSeparateSamplers&&this._bindSampler(null,e))}bindSource(t,e=0){const i=this._gl;if(t._gcLastUsed=this._renderer.gc.now,this._boundTextures[e]!==t){this._boundTextures[e]=t,this._activateLocation(e),t||(t=$.EMPTY.source);const r=this.getGlSource(t);i.bindTexture(r.target,r.texture)}}_bindSampler(t,e=0){const i=this._gl;if(!t){this._boundSamplers[e]=null,i.bindSampler(e,null);return}const r=this._getGlSampler(t);this._boundSamplers[e]!==r&&(this._boundSamplers[e]=r,i.bindSampler(e,r))}unbind(t){const e=t.source,i=this._boundTextures,r=this._gl;for(let n=0;n<i.length;n++)if(i[n]===e){this._activateLocation(n);const o=this.getGlSource(e);r.bindTexture(o.target,null),i[n]=null}}_activateLocation(t){this._activeTextureLocation!==t&&(this._activeTextureLocation=t,this._gl.activeTexture(this._gl.TEXTURE0+t))}_initSource(t){const e=this._gl,i=new R_(e.createTexture());if(i.type=this._mapFormatToType[t.format],i.internalFormat=this._mapFormatToInternalFormat[t.format],i.format=this._mapFormatToFormat[t.format],i.target=this._mapViewDimensionToGlTarget[t.viewDimension],i.target===null)throw new Error(`Unsupported view dimension: ${t.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(t.uploadMethodId==="cube"&&(i.target=e.TEXTURE_CUBE_MAP),t.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||t.isPowerOfTwo)){const n=Math.max(t.width,t.height);t.mipLevelCount=Math.floor(Math.log2(n))+1}return t._gpuData[this._renderer.uid]=i,this._managedTextures.add(t)&&(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceUpdate,this),t.on("styleChange",this.onStyleChange,this),t.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(t),this.updateStyle(t,!1),i}onStyleChange(t){this.updateStyle(t,!1)}updateStyle(t,e){const i=this._gl,r=this.getGlSource(t);i.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=t,uc(t.style,i,t.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!t.isPowerOfTwo,e)}onSourceUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];i&&(e||(this.unbind(t),this._gl.deleteTexture(i.texture)),t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceUpdate,this),t.off("styleChange",this.onStyleChange,this),t.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(t){const e=this._gl,i=this.getGlSource(t);e.bindTexture(i.target,i.texture),this._boundTextures[this._activeTextureLocation]=t;const r=t.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[t.uploadMethodId])this._uploads[t.uploadMethodId].upload(t,i,e,this._renderer.context.webGLVersion);else if(i.target===e.TEXTURE_2D)this._initEmptyTexture2D(i,t);else if(i.target===e.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(i,t);else if(i.target===e.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(i,t);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(i,t),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t,!1)}onUpdateMipmaps(t,e=!0){e&&this.bindSource(t,0);const i=this.getGlSource(t);this._gl.generateMipmap(i.target)}_initEmptyTexture2D(t,e){const i=this._gl;i.texImage2D(i.TEXTURE_2D,0,t.internalFormat,e.pixelWidth,e.pixelHeight,0,t.format,t.type,null);let r=Math.max(e.pixelWidth>>1,1),n=Math.max(e.pixelHeight>>1,1);for(let o=1;o<e.mipLevelCount;o++)i.texImage2D(i.TEXTURE_2D,o,t.internalFormat,r,n,0,t.format,t.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(t,e){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const i=this._gl,r=Math.max(e.arrayLayerCount|0,1);i.texImage3D(i.TEXTURE_2D_ARRAY,0,t.internalFormat,e.pixelWidth,e.pixelHeight,r,0,t.format,t.type,null);let n=Math.max(e.pixelWidth>>1,1),o=Math.max(e.pixelHeight>>1,1);for(let a=1;a<e.mipLevelCount;a++)i.texImage3D(i.TEXTURE_2D_ARRAY,a,t.internalFormat,n,o,r,0,t.format,t.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(t,e){const i=this._gl,r=6;for(let a=0;a<r;a++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,t.internalFormat,e.pixelWidth,e.pixelHeight,0,t.format,t.type,null);let n=Math.max(e.pixelWidth>>1,1),o=Math.max(e.pixelHeight>>1,1);for(let a=1;a<e.mipLevelCount;a++){for(let l=0;l<r;l++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,t.internalFormat,n,o,0,t.format,t.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(t,e){if(this._renderer.context.webGLVersion!==2)return;const i=this._gl,r=Math.max((e.mipLevelCount|0)-1,0);i.texParameteri(t.target,i.TEXTURE_BASE_LEVEL,0),i.texParameteri(t.target,i.TEXTURE_MAX_LEVEL,r)}_initSampler(t){const e=this._gl,i=this._gl.createSampler();return this._glSamplers[t._resourceId]=i,uc(t,e,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",i,!1,!0),this._glSamplers[t._resourceId]}_getGlSampler(t){return this._glSamplers[t._resourceId]||this._initSampler(t)}getGlSource(t){return t._gcLastUsed=this._renderer.gc.now,t._gpuData[this._renderer.uid]||this._initSource(t)}generateCanvas(t){const{pixels:e,width:i,height:r}=this.getPixels(t),n=rt.get().createCanvas();n.width=i,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(i,r);a.data.set(e),o.putImageData(a,0,0)}return n}getPixels(t){const e=t.source.resolution,i=t.frame,r=Math.max(Math.round(i.width*e),1),n=Math.max(Math.round(i.height*e),1),o=new Uint8Array(V_*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(t),h=a.renderTarget.getGpuRenderTarget(l),c=a.gl;return c.bindFramebuffer(c.FRAMEBUFFER,h.resolveTargetFramebuffer),c.readPixels(Math.round(i.x*e),Math.round(i.y*e),r,n,c.RGBA,c.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill($.EMPTY.source),this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}dc.extension={type:[w.WebGLSystem],name:"texture"};class fc{contextChange(t){const e=new le({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new W,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),i=t.limits.maxBatchableTextures,r=Xr({name:"graphics",bits:[nl,al(i),Kl,Zr]});this.shader=new be({glProgram:r,resources:{localUniforms:e,batchSamplers:hl(i)}})}execute(t,e){const i=e.context,r=i.customShader||this.shader,n=t.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(t.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const h=l.instructions;for(let c=0;c<l.instructionSize;c++){const u=h[c];if(u.size){for(let m=0;m<u.textures.count;m++)n.texture.bind(u.textures.textures[m],m);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}fc.extension={type:[w.WebGLPipesAdaptor],name:"graphics"};class pc{init(){const t=Xr({name:"mesh",bits:[Kl,hg,Zr]});this._shader=new be({glProgram:t,resources:{uTexture:$.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new W}}}})}execute(t,e){const i=t.renderer;let r=e._shader;if(r){if(!r.glProgram){tt("Mesh shader has no glProgram",e.shader);return}}else{r=this._shader;const n=e.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=i.globalUniforms.bindGroup,r.groups[101]=t.localUniformsBindGroup,i.encoder.draw({geometry:e._geometry,shader:r,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}pc.extension={type:[w.WebGLPipesAdaptor],name:"mesh"};const z_=[...Dn,Jh,e_,qg,jh,Fh,dc,Qh,Vh,oc,nc,$h,A_,Xh,zh],$_=[...Oh],j_=[fh,pc,fc],mc=[],gc=[],_c=[];J.handleByNamedList(w.WebGLSystem,mc),J.handleByNamedList(w.WebGLPipes,gc),J.handleByNamedList(w.WebGLPipesAdaptor,_c),J.add(...z_,...$_,...j_);class X_ extends $i{constructor(){const t={name:"webgl",type:he.WEBGL,systems:mc,renderPipes:gc,renderPipeAdaptors:_c};super(t)}}const Y_=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:X_},Symbol.toStringTag,{value:"Module"}));class yc{constructor(t){this._hash=Object.create(null),this._renderer=t}contextChange(t){this._gpu=t}getBindGroup(t,e,i){return t._updateKey(),this._hash[t._key]||this._createBindGroup(t,e,i)}_createBindGroup(t,e,i){const r=this._gpu.device,n=e.layout[i],o=[],a=this._renderer;for(const c in n){const u=t.resources[c]??t.resources[n[c]];let m;if(u._resourceType==="uniformGroup"){const f=u;a.ubo.updateUniformGroup(f);const g=f.buffer;m={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const f=u;m={buffer:a.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(u._resourceType==="bufferResource"){const f=u;m={buffer:a.buffer.getGPUBuffer(f.buffer),offset:f.offset,size:f.size}}else if(u._resourceType==="textureSampler"){const f=u;m=a.texture.getGpuSampler(f)}else if(u._resourceType==="textureSource"){const f=u;m=a.texture.getTextureView(f)}o.push({binding:n[c],resource:m})}const l=a.shader.getProgramData(e).bindGroups[i],h=r.createBindGroup({layout:l,entries:o});return this._hash[t._key]=h,h}destroy(){this._hash=null,this._renderer=null}}yc.extension={type:[w.WebGPUSystem],name:"bindGroup"};class q_{constructor(t){this.gpuBuffer=t}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class xc{constructor(t){this._renderer=t,this._managedBuffers=new ce({renderer:t,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(t){this._gpu=t}getGPUBuffer(t){var e;return t._gcLastUsed=this._renderer.gc.now,((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuBuffer)||this.createGPUBuffer(t)}updateBuffer(t){const e=this.getGPUBuffer(t),i=t.data;return t._updateID&&i&&(t._updateID=0,this._gpu.device.queue.writeBuffer(e,0,i.buffer,0,(t._updateSize||i.byteLength)+3&-4)),e}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(t){t.off("update",this.updateBuffer,this),t.off("change",this.onBufferChange,this)}createGPUBuffer(t){const e=this._gpu.device.createBuffer(t.descriptor);return t._updateID=0,t._resourceId=dt("resource"),t.data&&(Vr(t.data.buffer,e.getMappedRange(),t.data.byteOffset,t.data.byteLength),e.unmap()),t._gpuData[this._renderer.uid]=new q_(e),this._managedBuffers.add(t)&&(t.on("update",this.updateBuffer,this),t.on("change",this.onBufferChange,this)),e}onBufferChange(t){this._managedBuffers.remove(t),t._updateID=0,this.createGPUBuffer(t)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}xc.extension={type:[w.WebGPUSystem],name:"buffer"};class K_{constructor({minUniformOffsetAlignment:t}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=t,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(t){if(t>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${t*4}`);const e=this.byteIndex;let i=e+t*4;if(i=Math.ceil(i/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,i>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=i,e}addGroup(t){const e=this.addEmptyGroup(t.length);for(let i=0;i<t.length;i++)this.data[e/4+i]=t[i];return e}destroy(){this.data=null}}class bc{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.pipeline.setColorMask(t))}destroy(){this._renderer=null,this._colorMaskCache=null}}bc.extension={type:[w.WebGPUSystem],name:"colorMask"};class zn{constructor(t){this._renderer=t}async init(t){return this._initPromise?this._initPromise:(this._initPromise=(t.gpu?Promise.resolve(t.gpu):this._createDeviceAndAdaptor(t)).then(e=>{this.gpu=e,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(t){this._renderer.gpu=t}async _createDeviceAndAdaptor(t){const e=await rt.get().getNavigator().gpu.requestAdapter({powerPreference:t.powerPreference,forceFallbackAdapter:t.forceFallbackAdapter}),i=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>e.features.has(n)),r=await e.requestDevice({requiredFeatures:i});return{adapter:e,device:r}}destroy(){this.gpu=null,this._renderer=null}}zn.extension={type:[w.WebGPUSystem],name:"device"},zn.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class vc{constructor(t){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=t}renderStart(){this.commandFinished=new Promise(t=>{this._resolveCommandFinished=t}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(t){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(t.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(t){this.renderPassEncoder.setViewport(t.x,t.y,t.width,t.height,0,1)}setPipelineFromGeometryProgramAndState(t,e,i,r){const n=this._renderer.pipeline.getPipeline(t,e,i,r);this.setPipeline(n)}setPipeline(t){this._boundPipeline!==t&&(this._boundPipeline=t,this.renderPassEncoder.setPipeline(t))}_setVertexBuffer(t,e){this._boundVertexBuffer[t]!==e&&(this._boundVertexBuffer[t]=e,this.renderPassEncoder.setVertexBuffer(t,this._renderer.buffer.updateBuffer(e)))}_setIndexBuffer(t){if(this._boundIndexBuffer===t)return;this._boundIndexBuffer=t;const e=t.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(t),e)}resetBindGroup(t){this._boundBindGroup[t]=null}setBindGroup(t,e,i){if(this._boundBindGroup[t]===e)return;this._boundBindGroup[t]=e,e._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(e,i,t);this.renderPassEncoder.setBindGroup(t,r)}setGeometry(t,e){const i=this._renderer.pipeline.getBufferNamesToBind(t,e);for(const r in i)this._setVertexBuffer(parseInt(r,10),t.attributes[i[r]].buffer);t.indexBuffer&&this._setIndexBuffer(t.indexBuffer)}_setShaderBindGroups(t,e){for(const i in t.groups){const r=t.groups[i];e||this._syncBindGroup(r),this.setBindGroup(i,r,t.gpuProgram)}}_syncBindGroup(t){for(const e in t.resources){const i=t.resources[e];i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(t){const{geometry:e,shader:i,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:h}=t;this.setPipelineFromGeometryProgramAndState(e,i.gpuProgram,r,n),this.setGeometry(e,i.gpuProgram),this._setShaderBindGroups(i,h),e.indexBuffer?this.renderPassEncoder.drawIndexed(o||e.indexBuffer.data.length,l??e.instanceCount,a||0):this.renderPassEncoder.draw(o||e.getSize(),l??e.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const t=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(t);const e=this._boundPipeline,i={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(e);for(const a in i)this._setVertexBuffer(a,i[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let t=0;t<16;t++)this._boundBindGroup[t]=null,this._boundVertexBuffer[t]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(t){this._gpu=t}}vc.extension={type:[w.WebGPUSystem],name:"encoder",priority:1};class Ec{constructor(t){this._renderer=t}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}Ec.extension={type:[w.WebGPUSystem],name:"limits"};class Tc{constructor(t){this._renderTargetStencilState=Object.create(null),this._renderer=t,t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:wt.DISABLED,stencilReference:0}),this._activeRenderTarget=t,this.setStencilMode(e.stencilMode,e.stencilReference)}setStencilMode(t,e){const i=this._renderTargetStencilState[this._activeRenderTarget.uid];i.stencilMode=t,i.stencilReference=e;const r=this._renderer;r.pipeline.setStencilMode(t),r.encoder.renderPassEncoder.setStencilReference(e)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}Tc.extension={type:[w.WebGPUSystem],name:"stencil"};const Vs={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Z_(s){const t=s.map(i=>({data:i,offset:0,size:0}));let e=0;for(let i=0;i<t.length;i++){const r=t[i];let n=Vs[r.data.type].size;const o=Vs[r.data.type].align;if(!Vs[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),e=Math.ceil(e/o)*o,r.size=n,r.offset=e,e+=n}return e=Math.ceil(e/16)*16,{uboElements:t,size:e}}function J_(s,t){const{size:e,align:i}=Vs[s.data.type],r=(i-e)/4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
853
|
+
${a};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
|
|
854
|
+
`))}class jh{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,i){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,i))}_getUniformSyncFunction(e,t){var i;return((i=this._uniformGroupSyncHash[e._signature])==null?void 0:i[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const i=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),i[t._key]=this._cache[r],i[t._key]}_generateUniformsSync(e,t){return Wy(e,t)}_getSignature(e,t,i){const r=e.uniforms,n=[`${i}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}jh.extension={type:[I.WebGLSystem],name:"uniformGroup"};function Hy(s){const e={};if(e.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],e.add=[s.ONE,s.ONE],e.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],e["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof de.get().getWebGLRenderingContext()))e.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const i=s.getExtension("EXT_blend_minmax");i&&(e.min=[s.ONE,s.ONE,s.ONE,s.ONE,i.MIN_EXT,i.MIN_EXT],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,i.MAX_EXT,i.MAX_EXT])}return e}const Vy=0,zy=1,$y=2,jy=3,Xy=4,Yy=5,Xh=class $o{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[Vy]=this.setBlend,this.map[zy]=this.setOffset,this.map[$y]=this.setCullFace,this.map[jy]=this.setDepthTest,this.map[Xy]=this.setFrontFace,this.map[Yy]=this.setDepthMask,this.checks=[],this.defaultState=At.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=Hy(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,i=0;for(;t;)t&1&&this.map[i].call(this,!!(e.data&1<<i)),t>>=1,i++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck($o._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck($o._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],i=this.gl;t.length===2?i.blendFunc(t[0],t[1]):i.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,i.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const i=this.checks.indexOf(e);t&&i===-1?this.checks.push(e):!t&&i!==-1&&this.checks.splice(i,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Xh.extension={type:[I.WebGLSystem],name:"state"};let Ky=Xh;class qy{constructor(e){this.target=bo.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=me.UNSIGNED_BYTE,this.internalFormat=yo.RGBA,this.format=yo.RGBA,this.samplerType=0}destroy(){}}const Zy={id:"buffer",upload(s,e,t,i,r,n=!1){const o=r||e.target;!n&&e.width===s.width&&e.height===s.height?t.texSubImage2D(o,0,0,0,s.width,s.height,e.format,e.type,s.resource):t.texImage2D(o,0,e.internalFormat,s.width,s.height,0,e.format,e.type,s.resource),e.width=s.width,e.height=s.height}},Jy={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},Qy={id:"compressed",upload(s,e,t,i,r,n){const o=r??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=s.pixelWidth,l=s.pixelHeight;const c=!!Jy[s.format];for(let h=0;h<s.resource.length;h++){const u=s.resource[h];c?t.compressedTexImage2D(o,h,e.internalFormat,a,l,0,u):t.texImage2D(o,h,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},Yh=["right","left","top","bottom","front","back"];function eb(s){return{id:"cube",upload(e,t,i,r){const n=e.faces;for(let o=0;o<Yh.length;o++){const a=Yh[o],l=n[a];(s[l.uploadMethodId]||s.image).upload(l,t,i,r,bo.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const Kh={id:"image",upload(s,e,t,i,r,n=!1){const o=r||e.target,a=s.pixelWidth,l=s.pixelHeight,c=s.resourceWidth,h=s.resourceHeight,u=i===2,p=n||e.width!==a||e.height!==l,d=c>=a&&h>=l,g=s.resource;(u?tb:ib)(t,o,e,a,l,c,h,g,p,d),e.width=a,e.height=l}};function tb(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,a)}function ib(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const sb=A_(),rb={id:"video",upload(s,e,t,i,r,n=sb){if(!s.isValid){const o=r??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}Kh.upload(s,e,t,i,r,n)}},qh={linear:9729,nearest:9728},nb={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Co={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},ob={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Zh(s,e,t,i,r,n,o,a){const l=n;if(!a||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const c=Co[o?"clamp-to-edge":s.addressModeU],h=Co[o?"clamp-to-edge":s.addressModeV],u=Co[o?"clamp-to-edge":s.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||s.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,qh[s.magFilter]),t){if(!a||s.mipmapFilter!=="linear"){const c=nb[s.minFilter][s.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,qh[s.minFilter]);if(i&&s.maxAnisotropy>1){const c=Math.min(s.maxAnisotropy,e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,i.TEXTURE_MAX_ANISOTROPY_EXT,c)}s.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,ob[s.compare])}function ab(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function lb(s,e){let t={},i=s.RGBA;return s instanceof de.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},i=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...t,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:i,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function cb(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}function hb(s){return{"2d":s.TEXTURE_2D,cube:s.TEXTURE_CUBE_MAP,"1d":null,"3d":(s==null?void 0:s.TEXTURE_3D)||null,"2d-array":(s==null?void 0:s.TEXTURE_2D_ARRAY)||null,"cube-array":(s==null?void 0:s.TEXTURE_CUBE_MAP_ARRAY)||null}}const ub=4;class Jh{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new bt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:Kh,buffer:Zy,video:rb,compressed:Qy};this._uploads={...t,cube:eb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=lb(e,this._renderer.context.extensions),this._mapFormatToType=cb(e),this._mapFormatToFormat=ab(e),this._mapViewDimensionToGlTarget=hb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(q.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const i=e.source;e?(this.bindSource(i,t),this._useSeparateSamplers&&this._bindSampler(i.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const i=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=q.EMPTY.source);const r=this.getGlSource(e);i.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const i=this._gl;if(!e){this._boundSamplers[t]=null,i.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,i.bindSampler(t,r))}unbind(e){const t=e.source,i=this._boundTextures,r=this._gl;for(let n=0;n<i.length;n++)if(i[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),i[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,i=new qy(t.createTexture());if(i.type=this._mapFormatToType[e.format],i.internalFormat=this._mapFormatToInternalFormat[e.format],i.format=this._mapFormatToFormat[e.format],i.target=this._mapViewDimensionToGlTarget[e.viewDimension],i.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.uploadMethodId==="cube"&&(i.target=t.TEXTURE_CUBE_MAP),e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=i,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),i}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const i=this._gl,r=this.getGlSource(e);i.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,Zh(e.style,i,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||(this.unbind(e),this._gl.deleteTexture(i.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,i=this.getGlSource(e);t.bindTexture(i.target,i.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,i,t,this._renderer.context.webGLVersion);else if(i.target===t.TEXTURE_2D)this._initEmptyTexture2D(i,e);else if(i.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(i,e);else if(i.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(i,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(i,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const i=this.getGlSource(e);this._gl.generateMipmap(i.target)}_initEmptyTexture2D(e,t){const i=this._gl;i.texImage2D(i.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)i.texImage2D(i.TEXTURE_2D,o,e.internalFormat,r,n,0,e.format,e.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const i=this._gl,r=Math.max(t.arrayLayerCount|0,1);i.texImage3D(i.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)i.texImage3D(i.TEXTURE_2D_ARRAY,a,e.internalFormat,n,o,r,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(e,t){const i=this._gl,r=6;for(let a=0;a<r;a++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let l=0;l<r;l++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,e.internalFormat,n,o,0,e.format,e.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2)return;const i=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);i.texParameteri(e.target,i.TEXTURE_BASE_LEVEL,0),i.texParameteri(e.target,i.TEXTURE_MAX_LEVEL,r)}_initSampler(e){const t=this._gl,i=this._gl.createSampler();return this._glSamplers[e._resourceId]=i,Zh(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",i,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:i,height:r}=this.getPixels(e),n=de.get().createCanvas();n.width=i,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(i,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,i=e.frame,r=Math.max(Math.round(i.width*t),1),n=Math.max(Math.round(i.height*t),1),o=new Uint8Array(ub*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(i.x*t),Math.round(i.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(q.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}Jh.extension={type:[I.WebGLSystem],name:"texture"};class Qh{contextChange(e){const t=new _t({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new Y,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),i=e.limits.maxBatchableTextures,r=In({name:"graphics",bits:[$l,Xl(i),Nc,Pn]});this.shader=new It({glProgram:r,resources:{localUniforms:t,batchSamplers:Kl(i)}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let p=0;p<u.textures.count;p++)n.texture.bind(u.textures.textures[p],p);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Qh.extension={type:[I.WebGLPipesAdaptor],name:"graphics"};class eu{init(){const e=In({name:"mesh",bits:[Nc,P_,Pn]});this._shader=new It({glProgram:e,resources:{uTexture:q.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new Y}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(r){if(!r.glProgram){ne("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=i.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}eu.extension={type:[I.WebGLPipesAdaptor],name:"mesh"};const db=[...mo,Gh,Cy,_y,kh,wh,Jh,Lh,Rh,jh,$h,Ph,Ky,Bh,Mh],fb=[...xh],pb=[Qc,eu,Qh],tu=[],iu=[],su=[];ie.handleByNamedList(I.WebGLSystem,tu),ie.handleByNamedList(I.WebGLPipes,iu),ie.handleByNamedList(I.WebGLPipesAdaptor,su),ie.add(...db,...fb,...pb);class mb extends hs{constructor(){const e={name:"webgl",type:yt.WEBGL,systems:tu,renderPipes:iu,renderPipeAdaptors:su};super(e)}}const gb=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:mb},Symbol.toStringTag,{value:"Module"}));class ru{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,i){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,i)}_createBindGroup(e,t,i){const r=this._gpu.device,n=t.layout[i],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let p;if(u._resourceType==="uniformGroup"){const d=u;a.ubo.updateUniformGroup(d);const g=d.buffer;p={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const d=u;p={buffer:a.buffer.getGPUBuffer(d),offset:0,size:d.descriptor.size}}else if(u._resourceType==="bufferResource"){const d=u;p={buffer:a.buffer.getGPUBuffer(d.buffer),offset:d.offset,size:d.size}}else if(u._resourceType==="textureSampler"){const d=u;p=a.texture.getGpuSampler(d)}else if(u._resourceType==="textureSource"){const d=u;p=a.texture.getTextureView(d)}o.push({binding:n[h],resource:p})}const l=a.shader.getProgramData(t).bindGroups[i],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}}ru.extension={type:[I.WebGPUSystem],name:"bindGroup"};class _b{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class nu{constructor(e){this._renderer=e,this._managedBuffers=new bt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),i=e.data;return e._updateID&&i&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,i.buffer,0,(e._updateSize||i.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=xe("resource"),e.data&&(Cn(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new _b(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}nu.extension={type:[I.WebGPUSystem],name:"buffer"};class yb{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let i=t+e*4;if(i=Math.ceil(i/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,i>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=i,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let i=0;i<e.length;i++)this.data[t/4+i]=e[i];return t}destroy(){this.data=null}}class ou{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}ou.extension={type:[I.WebGPUSystem],name:"colorMask"};class To{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await de.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),i=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}To.extension={type:[I.WebGPUSystem],name:"device"},To.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class au{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,i,r){const n=this._renderer.pipeline.getPipeline(e,t,i,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,i){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(t,i,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const i=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in i)this._setVertexBuffer(parseInt(r,10),e.attributes[i[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const i in e.groups){const r=e.groups[i];t||this._syncBindGroup(r),this.setBindGroup(i,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const i=e.resources[t];i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(e){const{geometry:t,shader:i,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,i.gpuProgram,r,n),this.setGeometry(t,i.gpuProgram),this._setShaderBindGroups(i,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,i={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in i)this._setVertexBuffer(a,i[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}au.extension={type:[I.WebGPUSystem],name:"encoder",priority:1};class lu{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}lu.extension={type:[I.WebGPUSystem],name:"limits"};class cu{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:Be.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid];i.stencilMode=e,i.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}cu.extension={type:[I.WebGPUSystem],name:"stencil"};const fr={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function bb(s){const e=s.map(i=>({data:i,offset:0,size:0}));let t=0;for(let i=0;i<e.length;i++){const r=e[i];let n=fr[r.data.type].size;const o=fr[r.data.type].align;if(!fr[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function xb(s,e){const{size:t,align:i}=fr[s.data.type],r=(i-t)/4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
855
855
|
v = uv.${s.data.name};
|
|
856
|
-
${
|
|
856
|
+
${e!==0?`offset += ${e};`:""}
|
|
857
857
|
|
|
858
858
|
arrayOffset = offset;
|
|
859
859
|
|
|
860
860
|
t = 0;
|
|
861
861
|
|
|
862
|
-
for(var i=0; i < ${s.data.size*(
|
|
862
|
+
for(var i=0; i < ${s.data.size*(t/4)}; i++)
|
|
863
863
|
{
|
|
864
|
-
for(var j = 0; j < ${
|
|
864
|
+
for(var j = 0; j < ${t/4}; j++)
|
|
865
865
|
{
|
|
866
866
|
${n}[arrayOffset++] = v[t++];
|
|
867
867
|
}
|
|
868
868
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
869
869
|
}
|
|
870
|
-
`}function Q_(s){return Kh(s,"uboWgsl",J_,r_)}class Sc extends Yh{constructor(){super({createUboElements:Z_,generateUboSync:Q_})}}Sc.extension={type:[w.WebGPUSystem],name:"ubo"};const Oe=128;class Cc{constructor(t){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=t,this._batchBuffer=new K_({minUniformOffsetAlignment:Oe});const e=256/Oe;for(let i=0;i<e;i++){let r=yt.UNIFORM|yt.COPY_DST;i===0&&(r|=yt.COPY_SRC),this._buffers.push(new Pe({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(t,e){if(!e&&this._bindGroupHash[t.uid])return this._bindGroupHash[t.uid];this._renderer.ubo.ensureUniformGroup(t);const i=t.buffer.data,r=this._batchBuffer.addEmptyGroup(i.length);return this._renderer.ubo.syncUniformGroup(t,this._batchBuffer.data,r/4),this._bindGroupHash[t.uid]=this._getBindGroup(r/Oe),this._bindGroupHash[t.uid]}getUboResource(t){this._renderer.ubo.updateUniformGroup(t);const e=t.buffer.data,i=this._batchBuffer.addGroup(e);return this._getBufferResource(i/Oe)}getArrayBindGroup(t){const e=this._batchBuffer.addGroup(t);return this._getBindGroup(e/Oe)}getArrayBufferResource(t){const i=this._batchBuffer.addGroup(t)/Oe;return this._getBufferResource(i)}_getBufferResource(t){if(!this._bufferResources[t]){const e=this._buffers[t%2];this._bufferResources[t]=new Hn({buffer:e,offset:(t/2|0)*256,size:Oe})}return this._bufferResources[t]}_getBindGroup(t){if(!this._bindGroups[t]){const e=new Ie({0:this._getBufferResource(t)});this._bindGroups[t]=e}return this._bindGroups[t]}_uploadBindGroups(){const t=this._renderer.buffer,e=this._buffers[0];e.update(this._batchBuffer.byteIndex),t.updateBuffer(e);const i=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];i.copyBufferToBuffer(t.getGPUBuffer(e),Oe,t.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([i.finish()])}destroy(){var t;for(let e=0;e<this._bindGroups.length;e++)(t=this._bindGroups[e])==null||t.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}Cc.extension={type:[w.WebGPUPipes],name:"uniformBatch"};const ty={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function ey(s,t,e,i,r){return s<<24|t<<16|e<<10|i<<5|r}function iy(s,t,e,i,r){return e<<8|s<<5|i<<3|r<<1|t}class wc{constructor(t){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=t}contextChange(t){this._gpu=t,this.setStencilMode(wt.DISABLED),this._updatePipeHash()}setMultisampleCount(t){this._multisampleCount!==t&&(this._multisampleCount=t,this._updatePipeHash())}setRenderTarget(t){this._multisampleCount=t.msaaSamples,this._depthStencilAttachment=t.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=t.colorTargetCount,this._updatePipeHash()}setColorMask(t){this._colorMask!==t&&(this._colorMask=t,this._updatePipeHash())}setStencilMode(t){this._stencilMode!==t&&(this._stencilMode=t,this._stencilState=Be[t],this._updatePipeHash())}setPipeline(t,e,i,r){const n=this.getPipeline(t,e,i);r.setPipeline(n)}getPipeline(t,e,i,r){t._layoutKey||(Hh(t,e.attributeData),this._generateBufferKey(t)),r||(r=t.topology);const n=ey(t._layoutKey,e._layoutKey,i.data,i._blendModeId,ty[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(t,e,i,r),this._pipeCache[n])}_createPipeline(t,e,i,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(t,e),a=this._renderer.state.getColorTargets(i,this._colorTargetCount),l=this._stencilMode===wt.RENDERING_MASK_ADD?0:this._colorMask;for(let m=0;m<a.length;m++)a[m].writeMask=l;const h=this._renderer.shader.getProgramData(e).pipeline,c={vertex:{module:this._getModule(e.vertex.source),entryPoint:e.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(e.fragment.source),entryPoint:e.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:i.cullMode},layout:h,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(c.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:i.depthTest,depthCompare:i.depthTest?"less":"always"}),n.createRenderPipeline(c)}_getModule(t){return this._moduleCache[t]||this._createModule(t)}_createModule(t){const e=this._gpu.device;return this._moduleCache[t]=e.createShaderModule({code:t}),this._moduleCache[t]}_generateBufferKey(t){const e=[];let i=0;const r=Object.keys(t.attributes).sort();for(let o=0;o<r.length;o++){const a=t.attributes[r[o]];e[i++]=a.offset,e[i++]=a.format,e[i++]=a.stride,e[i++]=a.instance}const n=e.join("|");return t._layoutKey=Gi(n,"geometry"),t._layoutKey}_generateAttributeLocationsKey(t){const e=[];let i=0;const r=Object.keys(t.attributeData).sort();for(let o=0;o<r.length;o++){const a=t.attributeData[r[o]];e[i++]=a.location}const n=e.join("|");return t._attributeLocationsKey=Gi(n,"programAttributes"),t._attributeLocationsKey}getBufferNamesToBind(t,e){const i=t._layoutKey<<16|e._attributeLocationsKey;if(this._bindingNamesCache[i])return this._bindingNamesCache[i];const r=this._createVertexBufferLayouts(t,e),n=Object.create(null),o=e.attributeData;for(let a=0;a<r.length;a++){const h=Object.values(r[a].attributes)[0].shaderLocation;for(const c in o)if(o[c].location===h){n[a]=c;break}}return this._bindingNamesCache[i]=n,n}_createVertexBufferLayouts(t,e){e._attributeLocationsKey||this._generateAttributeLocationsKey(e);const i=t._layoutKey<<16|e._attributeLocationsKey;if(this._bufferLayoutsCache[i])return this._bufferLayoutsCache[i];const r=[];return t.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in e.attributeData){const h=t.attributes[l];(h.divisor??1)!==1&&tt(`Attribute ${l} has an invalid divisor value of '${h.divisor}'. WebGPU only supports a divisor value of 1`),h.buffer===n&&(o.arrayStride=h.stride,o.stepMode=h.instance?"instance":"vertex",a.push({shaderLocation:e.attributeData[l].location,offset:h.offset,format:h.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[i]=r,r}_updatePipeHash(){const t=iy(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[t]||(this._pipeStateCaches[t]=Object.create(null)),this._pipeCache=this._pipeStateCaches[t]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}wc.extension={type:[w.WebGPUSystem],name:"pipeline"};class sy{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class ry{init(t,e){this._renderer=t,this._renderTargetSystem=e}copyToTexture(t,e,i,r,n){const o=this._renderer,a=this._getGpuColorTexture(t),l=o.texture.getGpuSource(e.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:i},{texture:l,origin:n},r),e}startRenderPass(t,e=!0,i,r,n=0,o=0){var c,u;const l=this._renderTargetSystem.getGpuRenderTarget(t);if(o!==0&&((c=l.msaaTextures)!=null&&c.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const h=this.getDescriptor(t,e,i,n,o);l.descriptor=h,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);return e.contexts[0]?e.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(t.colorTextures[0].source)}getDescriptor(t,e,i,r=0,n=0){typeof e=="boolean"&&(e=e?Xt.ALL:Xt.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(t),l=t.colorTextures.map((u,m)=>{const f=a.contexts[m];let g,y;if(f){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=f.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[m]&&(y=g,g=this._renderer.texture.getTextureView(a.msaaTextures[m]));const x=e&Xt.COLOR?"clear":"load";return i??(i=o.defaultClearColor),{view:g,resolveTarget:y,clearValue:i,storeOp:"store",loadOp:x}});let h;if((t.stencil||t.depth)&&!t.depthStencilTexture&&(t.ensureDepthStencilTexture(),t.depthStencilTexture.source.sampleCount=a.msaa?4:1),t.depthStencilTexture){const u=e&Xt.STENCIL?"clear":"load",m=e&Xt.DEPTH?"clear":"load";h={view:this._renderer.texture.getGpuSource(t.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:m,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:h}}clear(t,e=!0,i,r,n=0,o=0){if(!e)return;const{gpu:a,encoder:l}=this._renderer,h=a.device;if(l.commandEncoder===null){const u=h.createCommandEncoder(),m=this.getDescriptor(t,e,i,n,o),f=u.beginRenderPass(m);f.setViewport(r.x,r.y,r.width,r.height,0,1),f.end();const g=u.finish();h.queue.submit([g])}else this.startRenderPass(t,e,i,r,n,o)}initGpuRenderTarget(t){t.isRoot=!0;const e=new sy;return e.colorTargetCount=t.colorTextures.length,t.colorTextures.forEach((i,r)=>{if(i instanceof ae){const n=i.resource.getContext("webgpu"),o=i.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}e.contexts[r]=n}if(e.msaa=i.source.antialias,i.source.antialias){const n=new At({width:0,height:0,sampleCount:4,arrayLayerCount:i.source.arrayLayerCount});e.msaaTextures[r]=n}}),e.msaa&&(e.msaaSamples=4,t.depthStencilTexture&&(t.depthStencilTexture.source.sampleCount=4)),e}destroyGpuRenderTarget(t){t.contexts.forEach(e=>{e.unconfigure()}),t.msaaTextures.forEach(e=>{e.destroy()}),t.msaaTextures.length=0,t.contexts.length=0}ensureDepthStencilTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);t.depthStencilTexture&&e.msaa&&(t.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);e.width=t.width,e.height=t.height,e.msaa&&t.colorTextures.forEach((i,r)=>{const n=e.msaaTextures[r];n==null||n.resize(i.source.width,i.source.height,i.source._resolution)})}}class Ac extends Gn{constructor(t){super(t),this.adaptor=new ry,this.adaptor.init(t,this)}}Ac.extension={type:[w.WebGPUSystem],name:"renderTarget"};class Rc{constructor(){this._gpuProgramData=Object.create(null)}contextChange(t){this._gpu=t}getProgramData(t){return this._gpuProgramData[t._layoutKey]||this._createGPUProgramData(t)}_createGPUProgramData(t){const e=this._gpu.device,i=t.gpuLayout.map(n=>e.createBindGroupLayout({entries:n})),r={bindGroupLayouts:i};return this._gpuProgramData[t._layoutKey]={bindGroups:i,pipeline:e.createPipelineLayout(r)},this._gpuProgramData[t._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Rc.extension={type:[w.WebGPUSystem],name:"shader"};const Vt={};Vt.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},Vt.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Vt.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Vt.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},Vt["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},Vt["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},Vt.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},Vt.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},Vt.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class Ic{constructor(){this.defaultState=new ve,this.defaultState.blend=!0}contextChange(t){this.gpu=t}getColorTargets(t,e){const i=Vt[t.blendMode]||Vt.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:i};for(let o=0;o<e;o++)r[o]=n;return r}destroy(){this.gpu=null}}Ic.extension={type:[w.WebGPUSystem],name:"state"};const ny={type:"image",upload(s,t,e,i=0){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;e.device.queue.writeTexture({texture:t,origin:{x:0,y:0,z:i}},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},Pc={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},oy={blockBytes:4,blockWidth:1,blockHeight:1},ay={type:"compressed",upload(s,t,e,i=0){let r=s.pixelWidth,n=s.pixelHeight;const o=Pc[s.format]||oy;for(let a=0;a<s.resource.length;a++){const l=s.resource[a],h=Math.ceil(r/o.blockWidth)*o.blockBytes;e.device.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:0,bytesPerRow:h},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},Mc=["right","left","top","bottom","front","back"];function ly(s){return{type:"cube",upload(t,e,i){const r=t.faces;for(let n=0;n<Mc.length;n++){const o=Mc[n],a=r[o];(s[a.uploadMethodId]||s.image).upload(a,e,i,n)}}}}const kc={type:"image",upload(s,t,e,i=0){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=rt.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=l,tt("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(t.width,s.resourceWidth||s.pixelWidth),o=Math.min(t.height,s.resourceHeight||s.pixelHeight),a=s.alphaMode==="premultiply-alpha-on-upload";e.device.queue.copyExternalImageToTexture({source:r},{texture:t,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:n,height:o})}},hy={type:"video",upload(s,t,e,i){kc.upload(s,t,e,i)}};class cy{constructor(t){this.device=t,this.sampler=t.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(t){let e=this.pipelines[t];return e||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
870
|
+
`}function vb(s){return Nh(s,"uboWgsl",xb,wy)}class hu extends Oh{constructor(){super({createUboElements:bb,generateUboSync:vb})}}hu.extension={type:[I.WebGPUSystem],name:"ubo"};const zt=128;class uu{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new yb({minUniformOffsetAlignment:zt});const t=256/zt;for(let i=0;i<t;i++){let r=Ee.UNIFORM|Ee.COPY_DST;i===0&&(r|=Ee.COPY_SRC),this._buffers.push(new Ut({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const i=e.buffer.data,r=this._batchBuffer.addEmptyGroup(i.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/zt),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,i=this._batchBuffer.addGroup(t);return this._getBufferResource(i/zt)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/zt)}getArrayBufferResource(e){const i=this._batchBuffer.addGroup(e)/zt;return this._getBufferResource(i)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new vo({buffer:t,offset:(e/2|0)*256,size:zt})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Lt({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const i=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];i.copyBufferToBuffer(e.getGPUBuffer(t),zt,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([i.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}uu.extension={type:[I.WebGPUPipes],name:"uniformBatch"};const Sb={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function Cb(s,e,t,i,r){return s<<24|e<<16|t<<10|i<<5|r}function Tb(s,e,t,i,r){return t<<8|s<<5|i<<3|r<<1|e}class du{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(Be.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Vt[e],this._updatePipeHash())}setPipeline(e,t,i,r){const n=this.getPipeline(e,t,i);r.setPipeline(n)}getPipeline(e,t,i,r){e._layoutKey||(Ih(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=Cb(e._layoutKey,t._layoutKey,i.data,i._blendModeId,Sb[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,i,r),this._pipeCache[n])}_createPipeline(e,t,i,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(i,this._colorTargetCount),l=this._stencilMode===Be.RENDERING_MASK_ADD?0:this._colorMask;for(let p=0;p<a.length;p++)a[p].writeMask=l;const c=this._renderer.shader.getProgramData(t).pipeline,h={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:i.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(h.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:i.depthTest,depthCompare:i.depthTest?"less":"always"}),n.createRenderPipeline(h)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let i=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[i++]=a.offset,t[i++]=a.format,t[i++]=a.stride,t[i++]=a.instance}const n=t.join("|");return e._layoutKey=ts(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let i=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[i++]=a.location}const n=t.join("|");return e._attributeLocationsKey=ts(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[i])return this._bindingNamesCache[i];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[i]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[i])return this._bufferLayoutsCache[i];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&ne(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[i]=r,r}_updatePipeHash(){const e=Tb(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}du.extension={type:[I.WebGPUSystem],name:"pipeline"};class Eb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class wb{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,i,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:i},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,i,r,n=0,o=0){var h,u;const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&((h=l.msaaTextures)!=null&&h.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const c=this.getDescriptor(e,t,i,n,o);l.descriptor=c,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,i,r=0,n=0){typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(e),l=e.colorTextures.map((u,p)=>{const d=a.contexts[p];let g,_;if(d){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=d.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[p]&&(_=g,g=this._renderer.texture.getTextureView(a.msaaTextures[p]));const y=t&it.COLOR?"clear":"load";return i??(i=o.defaultClearColor),{view:g,resolveTarget:_,clearValue:i,storeOp:"store",loadOp:y}});let c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=a.msaa?4:1),e.depthStencilTexture){const u=t&it.STENCIL?"clear":"load",p=t&it.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:p,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:c}}clear(e,t=!0,i,r,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,c=a.device;if(l.commandEncoder===null){const u=c.createCommandEncoder(),p=this.getDescriptor(e,t,i,n,o),d=u.beginRenderPass(p);d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();const g=u.finish();c.queue.submit([g])}else this.startRenderPass(e,t,i,r,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Eb;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((i,r)=>{if(i instanceof gt){const n=i.resource.getContext("webgpu"),o=i.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=i.source.antialias,i.source.antialias){const n=new De({width:0,height:0,sampleCount:4,arrayLayerCount:i.source.arrayLayerCount});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((i,r)=>{const n=t.msaaTextures[r];n==null||n.resize(i.source.width,i.source.height,i.source._resolution)})}}class fu extends go{constructor(e){super(e),this.adaptor=new wb,this.adaptor.init(e,this)}}fu.extension={type:[I.WebGPUSystem],name:"renderTarget"};class pu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,i=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:i};return this._gpuProgramData[e._layoutKey]={bindGroups:i,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}pu.extension={type:[I.WebGPUSystem],name:"shader"};const Qe={};Qe.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},Qe.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},Qe.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},Qe.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Qe.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Qe.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},Qe["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},Qe["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},Qe["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},Qe.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},Qe.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},Qe.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class mu{constructor(){this.defaultState=new At,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){const i=Qe[e.blendMode]||Qe.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:i};for(let o=0;o<t;o++)r[o]=n;return r}destroy(){this.gpu=null}}mu.extension={type:[I.WebGPUSystem],name:"state"};const Ib={type:"image",upload(s,e,t,i=0){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:i}},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},gu={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},Ab={blockBytes:4,blockWidth:1,blockHeight:1},Rb={type:"compressed",upload(s,e,t,i=0){let r=s.pixelWidth,n=s.pixelHeight;const o=gu[s.format]||Ab;for(let a=0;a<s.resource.length;a++){const l=s.resource[a],c=Math.ceil(r/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:0,bytesPerRow:c},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},_u=["right","left","top","bottom","front","back"];function Mb(s){return{type:"cube",upload(e,t,i){const r=e.faces;for(let n=0;n<_u.length;n++){const o=_u[n],a=r[o];(s[a.uploadMethodId]||s.image).upload(a,t,i,n)}}}}const yu={type:"image",upload(s,e,t,i=0){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=de.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=l,ne("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,s.resourceWidth||s.pixelWidth),o=Math.min(e.height,s.resourceHeight||s.pixelHeight),a=s.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:r},{texture:e,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:n,height:o})}},Pb={type:"video",upload(s,e,t,i){yu.upload(s,e,t,i)}};class kb{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
871
871
|
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
872
872
|
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
873
873
|
|
|
@@ -891,7 +891,7 @@ fn mainFragment(
|
|
|
891
891
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
892
892
|
return textureSample(img, imgSampler, texCoord);
|
|
893
893
|
}
|
|
894
|
-
`})),e=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:t}]}}),this.pipelines[t]=e),e}generateMipmap(t){const e=this._getMipmapPipeline(t.format);if(t.dimension==="3d"||t.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=t;const r=t.depthOrArrayLayers||1,n=t.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:r},format:t.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:t.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=e.getBindGroupLayout(0);for(let l=0;l<r;++l){let h=t.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),c=n?1:0;for(let u=1;u<t.mipLevelCount;++u){const m=i.createView({baseMipLevel:c++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:m,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:h}]});f.setPipeline(e),f.setBindGroup(0,g),f.draw(3,1,0,0),f.end(),h=m}}if(!n){const l={width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:r};for(let h=1;h<t.mipLevelCount;++h)o.copyTextureToTexture({texture:i,mipLevel:h-1},{texture:t,mipLevel:h},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),t}}class uy{constructor(t){this.textureView=null,this.gpuTexture=t}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Bc{constructor(t){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=t,t.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new ce({renderer:t,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const e={image:kc,buffer:ny,video:hy,compressed:ay};this._uploads={...e,cube:ly(e)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(t){this._gpu=t}initSource(t){var e;return((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuTexture)||this._initSource(t)}_initSource(t){if(t.autoGenerateMipmaps){const h=Math.max(t.pixelWidth,t.pixelHeight);t.mipLevelCount=Math.floor(Math.log2(h))+1}let e=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;t.uploadMethodId!=="compressed"&&(e|=GPUTextureUsage.RENDER_ATTACHMENT,e|=GPUTextureUsage.COPY_SRC);const i=Pc[t.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(t.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(t.pixelHeight/i.blockHeight)*i.blockHeight,o={label:t.label,size:{width:r,height:n,depthOrArrayLayers:t.arrayLayerCount},format:t.format,sampleCount:t.sampleCount,mipLevelCount:t.mipLevelCount,dimension:t.dimension,usage:e},a=this._gpu.device.createTexture(o);return t._gpuData[this._renderer.uid]=new uy(a),this._managedTextures.add(t)&&(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceResize,this),t.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(t),a}onSourceUpdate(t){const e=this.getGpuSource(t);e&&(this._uploads[t.uploadMethodId]&&this._uploads[t.uploadMethodId].upload(t,e,this._gpu),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t))}onUpdateMipmaps(t){this._mipmapGenerator||(this._mipmapGenerator=new cy(this._gpu.device));const e=this.getGpuSource(t);this._mipmapGenerator.generateMipmap(e)}onSourceUnload(t){t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceResize,this),t.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(t){t._gcLastUsed=this._renderer.gc.now;const e=t._gpuData[this._renderer.uid],i=e==null?void 0:e.gpuTexture;i?(i.width!==t.pixelWidth||i.height!==t.pixelHeight)&&(e.destroy(),this._bindGroupHash[t.uid]=null,t._gpuData[this._renderer.uid]=null,this.initSource(t)):this.initSource(t)}_initSampler(t){return this._gpuSamplers[t._resourceId]=this._gpu.device.createSampler(t),this._gpuSamplers[t._resourceId]}getGpuSampler(t){return this._gpuSamplers[t._resourceId]||this._initSampler(t)}getGpuSource(t){var e;return t._gcLastUsed=this._renderer.gc.now,((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuTexture)||this.initSource(t)}getTextureBindGroup(t){return this._bindGroupHash[t.uid]||this._createTextureBindGroup(t)}_createTextureBindGroup(t){const e=t.source;return this._bindGroupHash[t.uid]=new Ie({0:e,1:e.style,2:new le({uTextureMatrix:{type:"mat3x3<f32>",value:t.textureMatrix.mapCoord}})}),this._bindGroupHash[t.uid]}getTextureView(t){const e=t.source;e._gcLastUsed=this._renderer.gc.now;let i=e._gpuData[this._renderer.uid];return i||(this.initSource(e),i=e._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:e.viewDimension})),i.textureView}generateCanvas(t){const e=this._renderer,i=e.gpu.device.createCommandEncoder(),r=rt.get().createCanvas();r.width=t.source.pixelWidth,r.height=t.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:e.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:rt.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:e.texture.getGpuSource(t.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),e.gpu.device.queue.submit([i.finish()]),r}getPixels(t){const e=this.generateCanvas(t),i=ss.getOptimalCanvasAndContext(e.width,e.height),r=i.context;r.drawImage(e,0,0);const{width:n,height:o}=e,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return ss.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const t of Object.keys(this._bindGroupHash)){const e=Number(t),i=this._bindGroupHash[e];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Bc.extension={type:[w.WebGPUSystem],name:"texture"};class Oc{constructor(){this._maxTextures=0}contextChange(t){const e=new le({uTransformMatrix:{value:new W,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=t.limits.maxBatchableTextures;const i=jr({name:"graphics",bits:[rl,ol(this._maxTextures),wm,Kr]});this.shader=new be({gpuProgram:i,resources:{localUniforms:e}})}execute(t,e){const i=e.context,r=i.customShader||this.shader,n=t.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),h=n.encoder;h.setGeometry(a.geometry,r.gpuProgram);const c=n.globalUniforms.bindGroup;h.setBindGroup(0,c,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);h.setBindGroup(2,u,r.gpuProgram);const m=l.instructions;let f=null;for(let g=0;g<l.instructionSize;g++){const y=m[g];if(y.topology!==f&&(f=y.topology,h.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,t.state,y.topology)),r.groups[1]=y.bindGroup,!y.gpuBindGroup){const x=y.textures;y.bindGroup=Wr(x.textures,x.count,this._maxTextures),y.gpuBindGroup=n.bindGroup.getBindGroup(y.bindGroup,r.gpuProgram,1)}h.setBindGroup(1,y.bindGroup,r.gpuProgram),h.renderPassEncoder.drawIndexed(y.size,1,y.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Oc.extension={type:[w.WebGPUPipesAdaptor],name:"graphics"};class Dc{init(){const t=jr({name:"mesh",bits:[Bs,lg,Kr]});this._shader=new be({gpuProgram:t,resources:{uTexture:$.EMPTY._source,uSampler:$.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new W}}}})}execute(t,e){const i=t.renderer;let r=e._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(e.texture);else if(!r.gpuProgram){tt("Mesh shader has no gpuProgram",e.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=t.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:e._geometry,shader:r,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Dc.extension={type:[w.WebGPUPipesAdaptor],name:"mesh"};const dy=[...Dn,Sc,vc,zn,Ec,xc,Bc,Ac,Rc,Ic,wc,bc,Tc,yc],fy=[...Oh,Cc],py=[ph,Dc,Oc],Gc=[],Uc=[],Lc=[];J.handleByNamedList(w.WebGPUSystem,Gc),J.handleByNamedList(w.WebGPUPipes,Uc),J.handleByNamedList(w.WebGPUPipesAdaptor,Lc),J.add(...dy,...fy,...py);class my extends $i{constructor(){const t={name:"webgpu",type:he.WEBGPU,systems:Gc,renderPipes:Uc,renderPipeAdaptors:Lc};super(t)}}const gy=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:my},Symbol.toStringTag,{value:"Module"}));J.add(Iu,Pu);const Ci=480,ns=480;class _y{constructor(){this.container=null,this.resizeObserver=null,this.app=new Fa}async init(){await this.app.init({width:Ci,height:ns,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Ci}px`,height:`${ns}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"});const t=this.app.canvas;return Object.assign(t.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(t),document.body.appendChild(this.container),this.setupResize(),t}setupResize(){const t=()=>{const e=window.innerWidth,i=Math.min(Ci,e),r=i/Ci,n=ns*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`),this.app.renderer.resize(Ci,ns)};window.addEventListener("resize",t),t()}get stageWidth(){return Ci}get stageHeight(){return ns}destroy(){var t,e;window.removeEventListener("resize",this.setupResize),(t=this.resizeObserver)==null||t.disconnect(),(e=this.container)==null||e.remove(),this.app.destroy(!0)}}function Nc(){var s,t;return((t=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:t.matches)??!1}const Qe={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function wi(s){const{target:t,props:e,duration:i,easing:r=Qe.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(Nc()){for(const m of Object.keys(e))t[m]=e[m];return o==null||o(),()=>{}}const l={};for(const m of Object.keys(e))l[m]=t[m];let h=-n,c=!1;const u=m=>{if(c||(h+=m.deltaMS,h<0))return;const f=Math.min(h/i,1),g=r(f);for(const y of Object.keys(e))t[y]=l[y]+(e[y]-l[y])*g;f>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{c=!0,a.remove(u)}}function Fc(s,t,e=.3,i=.7,r=2e3){if(Nc())return s.alpha=(e+i)/2,()=>{};let n=0,o=!1;const a=l=>{if(o)return;n+=l.deltaMS;const h=(Math.sin(n/r*Math.PI*2)+1)/2;s.alpha=e+(i-e)*h};return t.add(a),()=>{o=!0,t.remove(a)}}const os=200,de=os*(480/854),Hc=280;class yy{constructor(t,e){this.idleSprite=null,this.idleGroup=null,this.liveSprite=null,this.videoElement=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.stageWidth=t,this.stageHeight=e,this.container=new kt,this.container.visible=!1,this.container.y=e+de}async loadIdleVideo(t){this.videoElement=document.createElement("video"),this.videoElement.src=t,this.videoElement.loop=!0,this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.crossOrigin="anonymous",this.videoElement.style.display="none",document.body.appendChild(this.videoElement),await this.videoElement.play();const e=$.from(this.videoElement);this.idleSprite=new ye(e),this.idleSprite.width=os,this.idleSprite.height=de,this.idleSprite.anchor.set(.5,1),this.idleGroup=new kt,this.idleGroup.addChild(this.idleSprite),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+de}async loadIdleImage(t){const e=$.from(t);this.idleSprite=new ye(e),this.idleSprite.width=os,this.idleSprite.height=de,this.idleSprite.anchor.set(.5,1),this.idleGroup=new kt,this.idleGroup.addChild(this.idleSprite),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+de}slideIn(t){if(this.visible)return;this.visible=!0;const e=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+de,this.cancelEntrance=wi({target:this.container,props:{y:e},duration:700,easing:Qe.easeOutBack,ticker:t}),this.idleGroup&&setTimeout(()=>{this.idleGroup&&(this.cancelGlow=Fc(this.idleGroup,t,.85,1,2500))},700)}slideOut(t){var e;this.visible&&(this.visible=!1,(e=this.cancelGlow)==null||e.call(this),this.cancelGlow=null,wi({target:this.container,props:{y:this.stageHeight+de},duration:450,easing:Qe.easeInCubic,ticker:t,onComplete:()=>{this.container.visible=!1}}))}get isVisible(){return this.visible}setInteractive(t){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new ct(-os/2,-de,os,de),this.container.on("pointertap",t),this.container.on("pointerenter",()=>{this.container&&this.container.scale.set(1.04)}),this.container.on("pointerleave",()=>{this.container&&this.container.scale.set(1)})}setLiveVideo(t,e){const i=()=>{var l;const r=$.from(t);this.liveSprite=new ye(r);const n=t.videoWidth||1,o=t.videoHeight||1,a=Hc/n;this.liveSprite.width=Hc,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,wi({target:this.liveSprite,props:{alpha:1},duration:500,easing:Qe.easeInOutSine,ticker:e})};if(t.videoWidth>0&&t.videoHeight>0)i();else{const r=()=>{t.removeEventListener("loadeddata",r),t.removeEventListener("resize",r),i()};t.addEventListener("loadeddata",r),t.addEventListener("resize",r)}}clearLiveVideo(t){this.liveSprite&&wi({target:this.liveSprite,props:{alpha:0},duration:400,easing:Qe.easeInCubic,ticker:t,onComplete:()=>{var e;(e=this.liveSprite)==null||e.destroy(),this.liveSprite=null}}),this.idleGroup&&(this.idleGroup.visible=!0,this.idleSprite&&(this.idleSprite.alpha=1)),this.idleGroup&&(this.cancelGlow=Fc(this.idleGroup,t,.85,1,2500))}destroy(){var t,e;(t=this.cancelGlow)==null||t.call(this),(e=this.cancelEntrance)==null||e.call(this),this.videoElement&&(this.videoElement.pause(),this.videoElement.remove()),this.container.destroy({children:!0})}}const $n=18,Wc=12,xy=20,by=240,zs=14,vy=35,Ey=2500,Vc=300,Ty=16777215,Sy=13160666,Cy=1.5,wy=3820124,Ay=.1,Ry=["Got questions? Click me!","I can guide you through this page","Need help? Let’s chat!"];class Iy{constructor(t,e){this.promptIndex=0,this.charIndex=0,this.phase="idle",this.phaseElapsed=0,this.cancelFade=null,this.tickCb=null,this.running=!1,this.ticker=t,this.prompts=e!=null&&e.length?e:Ry,this.container=new kt,this.container.alpha=0,this.container.visible=!1,this.bg=new is,this.container.addChild(this.bg),this.label=new ng({text:"",style:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:13,fontWeight:"500",fill:2763326,wordWrap:!0,wordWrapWidth:by-$n*2,lineHeight:19}}),this.label.x=$n,this.label.y=Wc,this.container.addChild(this.label),this.container.eventMode="static",this.container.cursor="pointer"}start(){this.running||(this.running=!0,this.container.visible=!0,this.promptIndex=0,this.beginTyping(),this.tickCb=t=>this.update(t.deltaMS),this.ticker.add(this.tickCb))}stop(){var t;this.running&&(this.running=!1,this.phase="idle",this.tickCb&&this.ticker.remove(this.tickCb),this.tickCb=null,(t=this.cancelFade)==null||t.call(this),this.cancelFade=null,this.container.visible=!1,this.container.alpha=0)}beginTyping(){this.charIndex=0,this.phaseElapsed=0,this.phase="typing",this.label.text="",this.drawBubble(),this.container.alpha=0,this.cancelFade=wi({target:this.container,props:{alpha:1},duration:Vc,easing:Qe.easeOutCubic,ticker:this.ticker})}update(t){var e;if(this.phase==="typing"){this.phaseElapsed+=t;const i=this.prompts[this.promptIndex],r=Math.min(Math.floor(this.phaseElapsed/vy),i.length);r!==this.charIndex&&(this.charIndex=r,this.label.text=i.substring(0,this.charIndex),this.drawBubble()),this.charIndex>=i.length&&(this.phase="holding",this.phaseElapsed=0)}else this.phase==="holding"&&(this.phaseElapsed+=t,this.phaseElapsed>=Ey&&(this.phase="fading",this.phaseElapsed=0,(e=this.cancelFade)==null||e.call(this),this.cancelFade=wi({target:this.container,props:{alpha:0},duration:Vc,easing:Qe.easeInCubic,ticker:this.ticker,onComplete:()=>{this.promptIndex=(this.promptIndex+1)%this.prompts.length,this.beginTyping()}})))}drawBubble(){const t=Math.max(this.label.width,50),e=Math.max(this.label.height,18),i=t+$n*2,r=e+Wc*2,n=xy,o=14,a=i*.5-o/2,l=i*.5+o/2,h=i*.48,c=r+zs;this.bg.clear(),this.bg.roundRect(2,3,i,r+2,n),this.bg.fill({color:wy,alpha:Ay}),this.bg.moveTo(n,0),this.bg.lineTo(i-n,0),this.bg.quadraticCurveTo(i,0,i,n),this.bg.lineTo(i,r-n),this.bg.quadraticCurveTo(i,r,i-n,r),this.bg.lineTo(l,r),this.bg.quadraticCurveTo(l-2,r+zs*.35,h,c),this.bg.quadraticCurveTo(a+2,r+zs*.55,a,r),this.bg.lineTo(n,r),this.bg.quadraticCurveTo(0,r,0,r-n),this.bg.lineTo(0,n),this.bg.quadraticCurveTo(0,0,n,0),this.bg.closePath(),this.bg.fill({color:Ty,alpha:.97}),this.bg.stroke({color:Sy,width:Cy,alpha:.6}),this.container.pivot.x=i/2,this.container.pivot.y=r+zs}onClick(t){this.container.on("pointertap",t)}destroy(){this.stop(),this.container.destroy({children:!0})}}const Py=[{urls:"stun:stun.l.google.com:19302"}],My=3e3,ky="oai-events";class By{constructor(t){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...t}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var t,e;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:Py}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(ky),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(t=this.pc.localDescription)==null?void 0:t.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(e=this.onError)==null||e.call(this,r),this.close(),r}}sendJSON(t){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",t);return}this.dc.send(JSON.stringify(t))}close(){var t;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const e of this.micStream.getTracks())e.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(t=this.onDisconnected)==null||t.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=t=>{var e;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=t.streams[0]??new MediaStream([t.track]),(e=this.onRemoteTrack)==null||e.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var e,i,r,n;const t=(e=this.pc)==null?void 0:e.connectionState;console.log("[RealtimeSession] Connection state:",t),t==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(t==="failed"||t==="closed"||t==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),t==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(t=>{const e=this.pc;let i;const r=()=>{clearTimeout(i);try{e.removeEventListener("icegatheringstatechange",n)}catch{}t()},n=()=>{e.iceGatheringState==="complete"&&r()};e.addEventListener("icegatheringstatechange",n),i=setTimeout(r,My)})}async exchangeSDP(t){const{webrtcUrl:e,ephemeralKey:i,model:r,voice:n}=this.opts,o=`${e}?model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:t});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`SDP exchange failed (${a.status}): ${l}`)}return a.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=t=>{var e;try{const i=JSON.parse(t.data);(e=this.onDataMessage)==null||e.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=t=>{console.error("[RealtimeSession] Data channel error:",t)})}sendSessionUpdate(){const t={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(t.tools=this.opts.tools),this.sendJSON({type:"session.update",session:t})}}const Oy=24e3,Dy=`
|
|
894
|
+
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const p=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:p,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=p}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class Bb{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class bu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new bt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:yu,buffer:Ib,video:Pb,compressed:Rb};this._uploads={...t,cube:Mb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=gu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new Bb(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new kb(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Lt({0:t,1:t.style,2:new _t({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=de.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:de.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=Ss.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return Ss.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}bu.extension={type:[I.WebGPUSystem],name:"texture"};class xu{constructor(){this._maxTextures=0}contextChange(e){const t=new _t({uTransformMatrix:{value:new Y,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=wn({name:"graphics",bits:[zl,jl(this._maxTextures),Yg,Mn]});this.shader=new It({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const p=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=p[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const y=_.textures;_.bindGroup=Sn(y.textures,y.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}xu.extension={type:[I.WebGPUPipesAdaptor],name:"graphics"};class vu{init(){const e=wn({name:"mesh",bits:[sr,M_,Mn]});this._shader=new It({gpuProgram:e,resources:{uTexture:q.EMPTY._source,uSampler:q.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new Y}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){ne("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}vu.extension={type:[I.WebGPUPipesAdaptor],name:"mesh"};const Ob=[...mo,hu,au,To,lu,nu,bu,fu,pu,mu,du,ou,cu,ru],Db=[...xh,uu],Nb=[eh,vu,xu],Su=[],Cu=[],Tu=[];ie.handleByNamedList(I.WebGPUSystem,Su),ie.handleByNamedList(I.WebGPUPipes,Cu),ie.handleByNamedList(I.WebGPUPipesAdaptor,Tu),ie.add(...Ob,...Db,...Nb);class Fb extends hs{constructor(){const e={name:"webgpu",type:yt.WEBGPU,systems:Su,renderPipes:Cu,renderPipeAdaptors:Tu};super(e)}}const Gb=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:Fb},Symbol.toStringTag,{value:"Module"}));ie.add(Zd,Jd);const Fi=480,Ts=480;class Lb{constructor(){this.container=null,this.resizeObserver=null,this.app=new wl}async init(){await this.app.init({width:Fi,height:Ts,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Fi}px`,height:`${Ts}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"});const e=this.app.canvas;return Object.assign(e.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(e),document.body.appendChild(this.container),this.setupResize(),e}setupResize(){const e=()=>{const t=window.innerWidth,i=Math.min(Fi,t),r=i/Fi,n=Ts*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`),this.app.renderer.resize(Fi,Ts)};window.addEventListener("resize",e),e()}get rootElement(){return this.container}get stageWidth(){return Fi}get stageHeight(){return Ts}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function Ub(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const Ot={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function $t(s){const{target:e,props:t,duration:i,easing:r=Ot.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(Ub()){for(const p of Object.keys(t))e[p]=t[p];return o==null||o(),()=>{}}const l={};for(const p of Object.keys(t))l[p]=e[p];let c=-n,h=!1;const u=p=>{if(h||(c+=p.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Es=200,Dt=Es*(480/854),Eu=280;class Wb{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new We,this.container.visible=!1,this.container.y=t+Dt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Es}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new We,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Dt}async loadIdleImage(e){const t=q.from(e),i=new Gt(t);i.width=Es,i.height=Dt,i.anchor.set(.5,1),this.idleGroup=new We,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Dt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Dt,this.cancelEntrance=$t({target:this.container,props:{y:t},duration:700,easing:Ot.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,$t({target:this.container,props:{y:this.stageHeight+Dt},duration:450,easing:Ot.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new ye(-Es/2,-Dt,Es,Dt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=q.from(e);this.liveSprite=new Gt(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Eu/n;this.liveSprite.width=Eu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,$t({target:this.liveSprite,props:{alpha:1},duration:500,easing:Ot.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&$t({target:this.liveSprite,props:{alpha:0},duration:400,easing:Ot.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const Eo=18,wu=12,Hb=20,Vb=240,pr=14,zb=35,$b=2500,mr=300,jb=16777215,Xb=13160666,Yb=1.5,Kb=3820124,qb=.1,Zb=["Got questions? Click me!","I can guide you through this page","Need help? Let’s chat!"];class Jb{constructor(e,t){this.promptIndex=0,this.charIndex=0,this.phase="idle",this.phaseElapsed=0,this.cancelFade=null,this.tickCb=null,this.running=!1,this.ticker=e,this.prompts=t!=null&&t.length?t:Zb,this.container=new We,this.container.alpha=0,this.container.visible=!1,this.bg=new vs,this.container.addChild(this.bg),this.label=new I_({text:"",style:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:13,fontWeight:"500",fill:2763326,wordWrap:!0,wordWrapWidth:Vb-Eo*2,lineHeight:19}}),this.label.x=Eo,this.label.y=wu,this.container.addChild(this.label),this.container.eventMode="static",this.container.cursor="pointer"}start(){this.running||(this.running=!0,this.container.visible=!0,this.promptIndex=0,this.beginTyping(),this.tickCb=e=>this.update(e.deltaMS),this.ticker.add(this.tickCb))}stop(){var e;this.running&&(this.running=!1,this.phase="idle",this.tickCb&&this.ticker.remove(this.tickCb),this.tickCb=null,(e=this.cancelFade)==null||e.call(this),this.cancelFade=null,this.container.visible=!1,this.container.alpha=0)}showStatic(e){this.stop(),this.label.text=e,this.drawBubble(),this.container.visible=!0,this.container.alpha=0,this.cancelFade=$t({target:this.container,props:{alpha:1},duration:mr,easing:Ot.easeOutCubic,ticker:this.ticker})}hideStatic(){var e;this.container.visible&&((e=this.cancelFade)==null||e.call(this),this.cancelFade=$t({target:this.container,props:{alpha:0},duration:mr,easing:Ot.easeInCubic,ticker:this.ticker,onComplete:()=>{this.container.visible=!1}}))}beginTyping(){this.charIndex=0,this.phaseElapsed=0,this.phase="typing",this.label.text="",this.drawBubble(),this.container.alpha=0,this.cancelFade=$t({target:this.container,props:{alpha:1},duration:mr,easing:Ot.easeOutCubic,ticker:this.ticker})}update(e){var t;if(this.phase==="typing"){this.phaseElapsed+=e;const i=this.prompts[this.promptIndex],r=Math.min(Math.floor(this.phaseElapsed/zb),i.length);r!==this.charIndex&&(this.charIndex=r,this.label.text=i.substring(0,this.charIndex),this.drawBubble()),this.charIndex>=i.length&&(this.phase="holding",this.phaseElapsed=0)}else this.phase==="holding"&&(this.phaseElapsed+=e,this.phaseElapsed>=$b&&(this.phase="fading",this.phaseElapsed=0,(t=this.cancelFade)==null||t.call(this),this.cancelFade=$t({target:this.container,props:{alpha:0},duration:mr,easing:Ot.easeInCubic,ticker:this.ticker,onComplete:()=>{this.promptIndex=(this.promptIndex+1)%this.prompts.length,this.beginTyping()}})))}drawBubble(){const e=Math.max(this.label.width,50),t=Math.max(this.label.height,18),i=e+Eo*2,r=t+wu*2,n=Hb,o=14,a=i*.5-o/2,l=i*.5+o/2,c=i*.48,h=r+pr;this.bg.clear(),this.bg.roundRect(2,3,i,r+2,n),this.bg.fill({color:Kb,alpha:qb}),this.bg.moveTo(n,0),this.bg.lineTo(i-n,0),this.bg.quadraticCurveTo(i,0,i,n),this.bg.lineTo(i,r-n),this.bg.quadraticCurveTo(i,r,i-n,r),this.bg.lineTo(l,r),this.bg.quadraticCurveTo(l-2,r+pr*.35,c,h),this.bg.quadraticCurveTo(a+2,r+pr*.55,a,r),this.bg.lineTo(n,r),this.bg.quadraticCurveTo(0,r,0,r-n),this.bg.lineTo(0,n),this.bg.quadraticCurveTo(0,0,n,0),this.bg.closePath(),this.bg.fill({color:jb,alpha:.97}),this.bg.stroke({color:Xb,width:Yb,alpha:.6}),this.container.pivot.x=i/2,this.container.pivot.y=r+pr}onClick(e){this.container.on("pointertap",e)}destroy(){this.stop(),this.container.destroy({children:!0})}}const Qb=[{urls:"stun:stun.l.google.com:19302"}],ex=3e3,tx="oai-events";class ix{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:Qb}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(tx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,ex)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=`${t}?model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`SDP exchange failed (${a.status}): ${l}`)}return a.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const sx=24e3,rx=`
|
|
895
895
|
class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
896
896
|
constructor() {
|
|
897
897
|
super()
|
|
@@ -929,27 +929,47 @@ class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
|
929
929
|
}
|
|
930
930
|
|
|
931
931
|
registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
932
|
-
`;function
|
|
932
|
+
`;function nx(s){const e=new Int16Array(s.length);for(let t=0;t<s.length;t++){const i=Math.max(-1,Math.min(1,s[t]));e[t]=i<0?i*32768:i*32767}return e}class ox{constructor(){this.onAudioChunk=null,this.audioCtx=null,this.sourceNode=null,this.workletNode=null,this._started=!1,this._paused=!1}get isStarted(){return this._started}get isPaused(){return this._paused}async start(e){if(this._started)return;this.audioCtx=new AudioContext({sampleRate:sx});const t=new Blob([rx],{type:"application/javascript"}),i=URL.createObjectURL(t);await this.audioCtx.audioWorklet.addModule(i),URL.revokeObjectURL(i),this.sourceNode=this.audioCtx.createMediaStreamSource(e),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-buffer-processor"),this.workletNode.port.onmessage=n=>{var o;if(n.data.type==="chunk"){const a=n.data.samples,l=nx(a);(o=this.onAudioChunk)==null||o.call(this,new Uint8Array(l.buffer))}},this.sourceNode.connect(this.workletNode);const r=this.audioCtx.createGain();r.gain.value=0,r.connect(this.audioCtx.destination),this.workletNode.connect(r),this._started=!0,this._paused=!1,console.log("[AudioForwarder] Started capturing remote audio at 24kHz")}pause(){var e;!this._started||this._paused||(this._paused=!0,(e=this.workletNode)==null||e.port.postMessage({type:"pause"}),console.log("[AudioForwarder] Paused"))}resume(){var e;!this._started||!this._paused||(this._paused=!1,(e=this.workletNode)==null||e.port.postMessage({type:"resume"}),console.log("[AudioForwarder] Resumed"))}stop(){var e,t,i;if(this._started){try{(e=this.workletNode)==null||e.disconnect()}catch{}try{(t=this.sourceNode)==null||t.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}this.workletNode=null,this.sourceNode=null,this.audioCtx=null,this._started=!1,this._paused=!1,console.log("[AudioForwarder] Stopped")}}}var wo={},ws={},Iu;function ax(){if(Iu)return ws;Iu=1,ws.byteLength=a,ws.toByteArray=c,ws.fromByteArray=p;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,n=i.length;r<n;++r)s[r]=i[r],e[i.charCodeAt(r)]=r;e[45]=62,e[95]=63;function o(d){var g=d.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=d.indexOf("=");_===-1&&(_=g);var y=_===g?0:4-_%4;return[_,y]}function a(d){var g=o(d),_=g[0],y=g[1];return(_+y)*3/4-y}function l(d,g,_){return(g+_)*3/4-_}function c(d){var g,_=o(d),y=_[0],x=_[1],v=new t(l(d,y,x)),C=0,T=x>0?y-4:y,A;for(A=0;A<T;A+=4)g=e[d.charCodeAt(A)]<<18|e[d.charCodeAt(A+1)]<<12|e[d.charCodeAt(A+2)]<<6|e[d.charCodeAt(A+3)],v[C++]=g>>16&255,v[C++]=g>>8&255,v[C++]=g&255;return x===2&&(g=e[d.charCodeAt(A)]<<2|e[d.charCodeAt(A+1)]>>4,v[C++]=g&255),x===1&&(g=e[d.charCodeAt(A)]<<10|e[d.charCodeAt(A+1)]<<4|e[d.charCodeAt(A+2)]>>2,v[C++]=g>>8&255,v[C++]=g&255),v}function h(d){return s[d>>18&63]+s[d>>12&63]+s[d>>6&63]+s[d&63]}function u(d,g,_){for(var y,x=[],v=g;v<_;v+=3)y=(d[v]<<16&16711680)+(d[v+1]<<8&65280)+(d[v+2]&255),x.push(h(y));return x.join("")}function p(d){for(var g,_=d.length,y=_%3,x=[],v=16383,C=0,T=_-y;C<T;C+=v)x.push(u(d,C,C+v>T?T:C+v));return y===1?(g=d[_-1],x.push(s[g>>2]+s[g<<4&63]+"==")):y===2&&(g=(d[_-2]<<8)+d[_-1],x.push(s[g>>10]+s[g>>4&63]+s[g<<2&63]+"=")),x.join("")}return ws}var gr={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var Au;function lx(){return Au||(Au=1,gr.read=function(s,e,t,i,r){var n,o,a=r*8-i-1,l=(1<<a)-1,c=l>>1,h=-7,u=t?r-1:0,p=t?-1:1,d=s[e+u];for(u+=p,n=d&(1<<-h)-1,d>>=-h,h+=a;h>0;n=n*256+s[e+u],u+=p,h-=8);for(o=n&(1<<-h)-1,n>>=-h,h+=i;h>0;o=o*256+s[e+u],u+=p,h-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,i),n=n-c}return(d?-1:1)*o*Math.pow(2,n-i)},gr.write=function(s,e,t,i,r,n){var o,a,l,c=n*8-r-1,h=(1<<c)-1,u=h>>1,p=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,g=i?1:-1,_=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?e+=p/l:e+=p*Math.pow(2,1-u),e*l>=2&&(o++,l/=2),o+u>=h?(a=0,o=h):o+u>=1?(a=(e*l-1)*Math.pow(2,r),o=o+u):(a=e*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;s[t+d]=a&255,d+=g,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;s[t+d]=o&255,d+=g,o/=256,c-=8);s[t+d-g]|=_*128}),gr}/*!
|
|
933
933
|
* The buffer module from node.js, for the browser.
|
|
934
934
|
*
|
|
935
935
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
936
936
|
* @license MIT
|
|
937
|
-
*/var jc;function Fy(){return jc||(jc=1,(function(s){const t=Ly(),e=Ny(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=E,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const _=new Uint8Array(1),d={foo:function(){return 42}};return Object.setPrototypeOf(d,Uint8Array.prototype),Object.setPrototypeOf(_,d),_.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(_){if(_>r)throw new RangeError('The value "'+_+'" is invalid for option "size"');const d=new Uint8Array(_);return Object.setPrototypeOf(d,a.prototype),d}function a(_,d,p){if(typeof _=="number"){if(typeof d=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(_)}return l(_,d,p)}a.poolSize=8192;function l(_,d,p){if(typeof _=="string")return m(_,d);if(ArrayBuffer.isView(_))return g(_);if(_==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(jt(_,ArrayBuffer)||_&&jt(_.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(jt(_,SharedArrayBuffer)||_&&jt(_.buffer,SharedArrayBuffer)))return y(_,d,p);if(typeof _=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const b=_.valueOf&&_.valueOf();if(b!=null&&b!==_)return a.from(b,d,p);const S=x(_);if(S)return S;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]=="function")return a.from(_[Symbol.toPrimitive]("string"),d,p);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}a.from=function(_,d,p){return l(_,d,p)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function h(_){if(typeof _!="number")throw new TypeError('"size" argument must be of type number');if(_<0)throw new RangeError('The value "'+_+'" is invalid for option "size"')}function c(_,d,p){return h(_),_<=0?o(_):d!==void 0?typeof p=="string"?o(_).fill(d,p):o(_).fill(d):o(_)}a.alloc=function(_,d,p){return c(_,d,p)};function u(_){return h(_),o(_<0?0:v(_)|0)}a.allocUnsafe=function(_){return u(_)},a.allocUnsafeSlow=function(_){return u(_)};function m(_,d){if((typeof d!="string"||d==="")&&(d="utf8"),!a.isEncoding(d))throw new TypeError("Unknown encoding: "+d);const p=T(_,d)|0;let b=o(p);const S=b.write(_,d);return S!==p&&(b=b.slice(0,S)),b}function f(_){const d=_.length<0?0:v(_.length)|0,p=o(d);for(let b=0;b<d;b+=1)p[b]=_[b]&255;return p}function g(_){if(jt(_,Uint8Array)){const d=new Uint8Array(_);return y(d.buffer,d.byteOffset,d.byteLength)}return f(_)}function y(_,d,p){if(d<0||_.byteLength<d)throw new RangeError('"offset" is outside of buffer bounds');if(_.byteLength<d+(p||0))throw new RangeError('"length" is outside of buffer bounds');let b;return d===void 0&&p===void 0?b=new Uint8Array(_):p===void 0?b=new Uint8Array(_,d):b=new Uint8Array(_,d,p),Object.setPrototypeOf(b,a.prototype),b}function x(_){if(a.isBuffer(_)){const d=v(_.length)|0,p=o(d);return p.length===0||_.copy(p,0,0,d),p}if(_.length!==void 0)return typeof _.length!="number"||Pi(_.length)?o(0):f(_);if(_.type==="Buffer"&&Array.isArray(_.data))return f(_.data)}function v(_){if(_>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return _|0}function E(_){return+_!=_&&(_=0),a.alloc(+_)}a.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==a.prototype},a.compare=function(d,p){if(jt(d,Uint8Array)&&(d=a.from(d,d.offset,d.byteLength)),jt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(d)||!a.isBuffer(p))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===p)return 0;let b=d.length,S=p.length;for(let I=0,M=Math.min(b,S);I<M;++I)if(d[I]!==p[I]){b=d[I],S=p[I];break}return b<S?-1:S<b?1:0},a.isEncoding=function(d){switch(String(d).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(d,p){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return a.alloc(0);let b;if(p===void 0)for(p=0,b=0;b<d.length;++b)p+=d[b].length;const S=a.allocUnsafe(p);let I=0;for(b=0;b<d.length;++b){let M=d[b];if(jt(M,Uint8Array))I+M.length>S.length?(a.isBuffer(M)||(M=a.from(M)),M.copy(S,I)):Uint8Array.prototype.set.call(S,M,I);else if(a.isBuffer(M))M.copy(S,I);else throw new TypeError('"list" argument must be an Array of Buffers');I+=M.length}return S};function T(_,d){if(a.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||jt(_,ArrayBuffer))return _.byteLength;if(typeof _!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);const p=_.length,b=arguments.length>2&&arguments[2]===!0;if(!b&&p===0)return 0;let S=!1;for(;;)switch(d){case"ascii":case"latin1":case"binary":return p;case"utf8":case"utf-8":return pe(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return p*2;case"hex":return p>>>1;case"base64":return Re(_).length;default:if(S)return b?-1:pe(_).length;d=(""+d).toLowerCase(),S=!0}}a.byteLength=T;function C(_,d,p){let b=!1;if((d===void 0||d<0)&&(d=0),d>this.length||((p===void 0||p>this.length)&&(p=this.length),p<=0)||(p>>>=0,d>>>=0,p<=d))return"";for(_||(_="utf8");;)switch(_){case"hex":return D(this,d,p);case"utf8":case"utf-8":return H(this,d,p);case"ascii":return U(this,d,p);case"latin1":case"binary":return X(this,d,p);case"base64":return N(this,d,p);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,d,p);default:if(b)throw new TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),b=!0}}a.prototype._isBuffer=!0;function R(_,d,p){const b=_[d];_[d]=_[p],_[p]=b}a.prototype.swap16=function(){const d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let p=0;p<d;p+=2)R(this,p,p+1);return this},a.prototype.swap32=function(){const d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let p=0;p<d;p+=4)R(this,p,p+3),R(this,p+1,p+2);return this},a.prototype.swap64=function(){const d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let p=0;p<d;p+=8)R(this,p,p+7),R(this,p+1,p+6),R(this,p+2,p+5),R(this,p+3,p+4);return this},a.prototype.toString=function(){const d=this.length;return d===0?"":arguments.length===0?H(this,0,d):C.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(d){if(!a.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:a.compare(this,d)===0},a.prototype.inspect=function(){let d="";const p=s.INSPECT_MAX_BYTES;return d=this.toString("hex",0,p).replace(/(.{2})/g,"$1 ").trim(),this.length>p&&(d+=" ... "),"<Buffer "+d+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(d,p,b,S,I){if(jt(d,Uint8Array)&&(d=a.from(d,d.offset,d.byteLength)),!a.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(p===void 0&&(p=0),b===void 0&&(b=d?d.length:0),S===void 0&&(S=0),I===void 0&&(I=this.length),p<0||b>d.length||S<0||I>this.length)throw new RangeError("out of range index");if(S>=I&&p>=b)return 0;if(S>=I)return-1;if(p>=b)return 1;if(p>>>=0,b>>>=0,S>>>=0,I>>>=0,this===d)return 0;let M=I-S,Q=b-p;const St=Math.min(M,Q),bt=this.slice(S,I),Ct=d.slice(p,b);for(let pt=0;pt<St;++pt)if(bt[pt]!==Ct[pt]){M=bt[pt],Q=Ct[pt];break}return M<Q?-1:Q<M?1:0};function A(_,d,p,b,S){if(_.length===0)return-1;if(typeof p=="string"?(b=p,p=0):p>2147483647?p=2147483647:p<-2147483648&&(p=-2147483648),p=+p,Pi(p)&&(p=S?0:_.length-1),p<0&&(p=_.length+p),p>=_.length){if(S)return-1;p=_.length-1}else if(p<0)if(S)p=0;else return-1;if(typeof d=="string"&&(d=a.from(d,b)),a.isBuffer(d))return d.length===0?-1:P(_,d,p,b,S);if(typeof d=="number")return d=d&255,typeof Uint8Array.prototype.indexOf=="function"?S?Uint8Array.prototype.indexOf.call(_,d,p):Uint8Array.prototype.lastIndexOf.call(_,d,p):P(_,[d],p,b,S);throw new TypeError("val must be string, number or Buffer")}function P(_,d,p,b,S){let I=1,M=_.length,Q=d.length;if(b!==void 0&&(b=String(b).toLowerCase(),b==="ucs2"||b==="ucs-2"||b==="utf16le"||b==="utf-16le")){if(_.length<2||d.length<2)return-1;I=2,M/=2,Q/=2,p/=2}function St(Ct,pt){return I===1?Ct[pt]:Ct.readUInt16BE(pt*I)}let bt;if(S){let Ct=-1;for(bt=p;bt<M;bt++)if(St(_,bt)===St(d,Ct===-1?0:bt-Ct)){if(Ct===-1&&(Ct=bt),bt-Ct+1===Q)return Ct*I}else Ct!==-1&&(bt-=bt-Ct),Ct=-1}else for(p+Q>M&&(p=M-Q),bt=p;bt>=0;bt--){let Ct=!0;for(let pt=0;pt<Q;pt++)if(St(_,bt+pt)!==St(d,pt)){Ct=!1;break}if(Ct)return bt}return-1}a.prototype.includes=function(d,p,b){return this.indexOf(d,p,b)!==-1},a.prototype.indexOf=function(d,p,b){return A(this,d,p,b,!0)},a.prototype.lastIndexOf=function(d,p,b){return A(this,d,p,b,!1)};function F(_,d,p,b){p=Number(p)||0;const S=_.length-p;b?(b=Number(b),b>S&&(b=S)):b=S;const I=d.length;b>I/2&&(b=I/2);let M;for(M=0;M<b;++M){const Q=parseInt(d.substr(M*2,2),16);if(Pi(Q))return M;_[p+M]=Q}return M}function B(_,d,p,b){return re(pe(d,_.length-p),_,p,b)}function k(_,d,p,b){return re(ei(d),_,p,b)}function O(_,d,p,b){return re(Re(d),_,p,b)}function L(_,d,p,b){return re(Ii(d,_.length-p),_,p,b)}a.prototype.write=function(d,p,b,S){if(p===void 0)S="utf8",b=this.length,p=0;else if(b===void 0&&typeof p=="string")S=p,b=this.length,p=0;else if(isFinite(p))p=p>>>0,isFinite(b)?(b=b>>>0,S===void 0&&(S="utf8")):(S=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const I=this.length-p;if((b===void 0||b>I)&&(b=I),d.length>0&&(b<0||p<0)||p>this.length)throw new RangeError("Attempt to write outside buffer bounds");S||(S="utf8");let M=!1;for(;;)switch(S){case"hex":return F(this,d,p,b);case"utf8":case"utf-8":return B(this,d,p,b);case"ascii":case"latin1":case"binary":return k(this,d,p,b);case"base64":return O(this,d,p,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,d,p,b);default:if(M)throw new TypeError("Unknown encoding: "+S);S=(""+S).toLowerCase(),M=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function N(_,d,p){return d===0&&p===_.length?t.fromByteArray(_):t.fromByteArray(_.slice(d,p))}function H(_,d,p){p=Math.min(_.length,p);const b=[];let S=d;for(;S<p;){const I=_[S];let M=null,Q=I>239?4:I>223?3:I>191?2:1;if(S+Q<=p){let St,bt,Ct,pt;switch(Q){case 1:I<128&&(M=I);break;case 2:St=_[S+1],(St&192)===128&&(pt=(I&31)<<6|St&63,pt>127&&(M=pt));break;case 3:St=_[S+1],bt=_[S+2],(St&192)===128&&(bt&192)===128&&(pt=(I&15)<<12|(St&63)<<6|bt&63,pt>2047&&(pt<55296||pt>57343)&&(M=pt));break;case 4:St=_[S+1],bt=_[S+2],Ct=_[S+3],(St&192)===128&&(bt&192)===128&&(Ct&192)===128&&(pt=(I&15)<<18|(St&63)<<12|(bt&63)<<6|Ct&63,pt>65535&&pt<1114112&&(M=pt))}}M===null?(M=65533,Q=1):M>65535&&(M-=65536,b.push(M>>>10&1023|55296),M=56320|M&1023),b.push(M),S+=Q}return G(b)}const at=4096;function G(_){const d=_.length;if(d<=at)return String.fromCharCode.apply(String,_);let p="",b=0;for(;b<d;)p+=String.fromCharCode.apply(String,_.slice(b,b+=at));return p}function U(_,d,p){let b="";p=Math.min(_.length,p);for(let S=d;S<p;++S)b+=String.fromCharCode(_[S]&127);return b}function X(_,d,p){let b="";p=Math.min(_.length,p);for(let S=d;S<p;++S)b+=String.fromCharCode(_[S]);return b}function D(_,d,p){const b=_.length;(!d||d<0)&&(d=0),(!p||p<0||p>b)&&(p=b);let S="";for(let I=d;I<p;++I)S+=Xs[_[I]];return S}function z(_,d,p){const b=_.slice(d,p);let S="";for(let I=0;I<b.length-1;I+=2)S+=String.fromCharCode(b[I]+b[I+1]*256);return S}a.prototype.slice=function(d,p){const b=this.length;d=~~d,p=p===void 0?b:~~p,d<0?(d+=b,d<0&&(d=0)):d>b&&(d=b),p<0?(p+=b,p<0&&(p=0)):p>b&&(p=b),p<d&&(p=d);const S=this.subarray(d,p);return Object.setPrototypeOf(S,a.prototype),S};function Y(_,d,p){if(_%1!==0||_<0)throw new RangeError("offset is not uint");if(_+d>p)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d],I=1,M=0;for(;++M<p&&(I*=256);)S+=this[d+M]*I;return S},a.prototype.readUintBE=a.prototype.readUIntBE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d+--p],I=1;for(;p>0&&(I*=256);)S+=this[d+--p]*I;return S},a.prototype.readUint8=a.prototype.readUInt8=function(d,p){return d=d>>>0,p||Y(d,1,this.length),this[d]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(d,p){return d=d>>>0,p||Y(d,2,this.length),this[d]|this[d+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(d,p){return d=d>>>0,p||Y(d,2,this.length),this[d]<<8|this[d+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},a.prototype.readBigUInt64LE=ne(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=p+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,I=this[++d]+this[++d]*2**8+this[++d]*2**16+b*2**24;return BigInt(S)+(BigInt(I)<<BigInt(32))}),a.prototype.readBigUInt64BE=ne(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=p*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],I=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+b;return(BigInt(S)<<BigInt(32))+BigInt(I)}),a.prototype.readIntLE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d],I=1,M=0;for(;++M<p&&(I*=256);)S+=this[d+M]*I;return I*=128,S>=I&&(S-=Math.pow(2,8*p)),S},a.prototype.readIntBE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=p,I=1,M=this[d+--S];for(;S>0&&(I*=256);)M+=this[d+--S]*I;return I*=128,M>=I&&(M-=Math.pow(2,8*p)),M},a.prototype.readInt8=function(d,p){return d=d>>>0,p||Y(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},a.prototype.readInt16LE=function(d,p){d=d>>>0,p||Y(d,2,this.length);const b=this[d]|this[d+1]<<8;return b&32768?b|4294901760:b},a.prototype.readInt16BE=function(d,p){d=d>>>0,p||Y(d,2,this.length);const b=this[d+1]|this[d]<<8;return b&32768?b|4294901760:b},a.prototype.readInt32LE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},a.prototype.readInt32BE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},a.prototype.readBigInt64LE=ne(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(b<<24);return(BigInt(S)<<BigInt(32))+BigInt(p+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24)}),a.prototype.readBigInt64BE=ne(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=(p<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(S)<<BigInt(32))+BigInt(this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+b)}),a.prototype.readFloatLE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),e.read(this,d,!0,23,4)},a.prototype.readFloatBE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),e.read(this,d,!1,23,4)},a.prototype.readDoubleLE=function(d,p){return d=d>>>0,p||Y(d,8,this.length),e.read(this,d,!0,52,8)},a.prototype.readDoubleBE=function(d,p){return d=d>>>0,p||Y(d,8,this.length),e.read(this,d,!1,52,8)};function j(_,d,p,b,S,I){if(!a.isBuffer(_))throw new TypeError('"buffer" argument must be a Buffer instance');if(d>S||d<I)throw new RangeError('"value" argument is out of bounds');if(p+b>_.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(d,p,b,S){if(d=+d,p=p>>>0,b=b>>>0,!S){const Q=Math.pow(2,8*b)-1;j(this,d,p,b,Q,0)}let I=1,M=0;for(this[p]=d&255;++M<b&&(I*=256);)this[p+M]=d/I&255;return p+b},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(d,p,b,S){if(d=+d,p=p>>>0,b=b>>>0,!S){const Q=Math.pow(2,8*b)-1;j(this,d,p,b,Q,0)}let I=b-1,M=1;for(this[p+I]=d&255;--I>=0&&(M*=256);)this[p+I]=d/M&255;return p+b},a.prototype.writeUint8=a.prototype.writeUInt8=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,1,255,0),this[p]=d&255,p+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,65535,0),this[p]=d&255,this[p+1]=d>>>8,p+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,65535,0),this[p]=d>>>8,this[p+1]=d&255,p+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,4294967295,0),this[p+3]=d>>>24,this[p+2]=d>>>16,this[p+1]=d>>>8,this[p]=d&255,p+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,4294967295,0),this[p]=d>>>24,this[p+1]=d>>>16,this[p+2]=d>>>8,this[p+3]=d&255,p+4};function V(_,d,p,b,S){xt(d,b,S,_,p,7);let I=Number(d&BigInt(4294967295));_[p++]=I,I=I>>8,_[p++]=I,I=I>>8,_[p++]=I,I=I>>8,_[p++]=I;let M=Number(d>>BigInt(32)&BigInt(4294967295));return _[p++]=M,M=M>>8,_[p++]=M,M=M>>8,_[p++]=M,M=M>>8,_[p++]=M,p}function ot(_,d,p,b,S){xt(d,b,S,_,p,7);let I=Number(d&BigInt(4294967295));_[p+7]=I,I=I>>8,_[p+6]=I,I=I>>8,_[p+5]=I,I=I>>8,_[p+4]=I;let M=Number(d>>BigInt(32)&BigInt(4294967295));return _[p+3]=M,M=M>>8,_[p+2]=M,M=M>>8,_[p+1]=M,M=M>>8,_[p]=M,p+8}a.prototype.writeBigUInt64LE=ne(function(d,p=0){return V(this,d,p,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=ne(function(d,p=0){return ot(this,d,p,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(d,p,b,S){if(d=+d,p=p>>>0,!S){const St=Math.pow(2,8*b-1);j(this,d,p,b,St-1,-St)}let I=0,M=1,Q=0;for(this[p]=d&255;++I<b&&(M*=256);)d<0&&Q===0&&this[p+I-1]!==0&&(Q=1),this[p+I]=(d/M>>0)-Q&255;return p+b},a.prototype.writeIntBE=function(d,p,b,S){if(d=+d,p=p>>>0,!S){const St=Math.pow(2,8*b-1);j(this,d,p,b,St-1,-St)}let I=b-1,M=1,Q=0;for(this[p+I]=d&255;--I>=0&&(M*=256);)d<0&&Q===0&&this[p+I+1]!==0&&(Q=1),this[p+I]=(d/M>>0)-Q&255;return p+b},a.prototype.writeInt8=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,1,127,-128),d<0&&(d=255+d+1),this[p]=d&255,p+1},a.prototype.writeInt16LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,32767,-32768),this[p]=d&255,this[p+1]=d>>>8,p+2},a.prototype.writeInt16BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,32767,-32768),this[p]=d>>>8,this[p+1]=d&255,p+2},a.prototype.writeInt32LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,2147483647,-2147483648),this[p]=d&255,this[p+1]=d>>>8,this[p+2]=d>>>16,this[p+3]=d>>>24,p+4},a.prototype.writeInt32BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[p]=d>>>24,this[p+1]=d>>>16,this[p+2]=d>>>8,this[p+3]=d&255,p+4},a.prototype.writeBigInt64LE=ne(function(d,p=0){return V(this,d,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=ne(function(d,p=0){return ot(this,d,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function lt(_,d,p,b,S,I){if(p+b>_.length)throw new RangeError("Index out of range");if(p<0)throw new RangeError("Index out of range")}function gt(_,d,p,b,S){return d=+d,p=p>>>0,S||lt(_,d,p,4),e.write(_,d,p,b,23,4),p+4}a.prototype.writeFloatLE=function(d,p,b){return gt(this,d,p,!0,b)},a.prototype.writeFloatBE=function(d,p,b){return gt(this,d,p,!1,b)};function ht(_,d,p,b,S){return d=+d,p=p>>>0,S||lt(_,d,p,8),e.write(_,d,p,b,52,8),p+8}a.prototype.writeDoubleLE=function(d,p,b){return ht(this,d,p,!0,b)},a.prototype.writeDoubleBE=function(d,p,b){return ht(this,d,p,!1,b)},a.prototype.copy=function(d,p,b,S){if(!a.isBuffer(d))throw new TypeError("argument should be a Buffer");if(b||(b=0),!S&&S!==0&&(S=this.length),p>=d.length&&(p=d.length),p||(p=0),S>0&&S<b&&(S=b),S===b||d.length===0||this.length===0)return 0;if(p<0)throw new RangeError("targetStart out of bounds");if(b<0||b>=this.length)throw new RangeError("Index out of range");if(S<0)throw new RangeError("sourceEnd out of bounds");S>this.length&&(S=this.length),d.length-p<S-b&&(S=d.length-p+b);const I=S-b;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(p,b,S):Uint8Array.prototype.set.call(d,this.subarray(b,S),p),I},a.prototype.fill=function(d,p,b,S){if(typeof d=="string"){if(typeof p=="string"?(S=p,p=0,b=this.length):typeof b=="string"&&(S=b,b=this.length),S!==void 0&&typeof S!="string")throw new TypeError("encoding must be a string");if(typeof S=="string"&&!a.isEncoding(S))throw new TypeError("Unknown encoding: "+S);if(d.length===1){const M=d.charCodeAt(0);(S==="utf8"&&M<128||S==="latin1")&&(d=M)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));if(p<0||this.length<p||this.length<b)throw new RangeError("Out of range index");if(b<=p)return this;p=p>>>0,b=b===void 0?this.length:b>>>0,d||(d=0);let I;if(typeof d=="number")for(I=p;I<b;++I)this[I]=d;else{const M=a.isBuffer(d)?d:a.from(d,S),Q=M.length;if(Q===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(I=0;I<b-p;++I)this[I+p]=M[I%Q]}return this};const _t={};function Z(_,d,p){_t[_]=class extends p{constructor(){super(),Object.defineProperty(this,"message",{value:d.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${_}]`,this.stack,delete this.name}get code(){return _}set code(S){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:S,writable:!0})}toString(){return`${this.name} [${_}]: ${this.message}`}}}Z("ERR_BUFFER_OUT_OF_BOUNDS",function(_){return _?`${_} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Z("ERR_INVALID_ARG_TYPE",function(_,d){return`The "${_}" argument must be of type number. Received type ${typeof d}`},TypeError),Z("ERR_OUT_OF_RANGE",function(_,d,p){let b=`The value of "${_}" is out of range.`,S=p;return Number.isInteger(p)&&Math.abs(p)>2**32?S=Bt(String(p)):typeof p=="bigint"&&(S=String(p),(p>BigInt(2)**BigInt(32)||p<-(BigInt(2)**BigInt(32)))&&(S=Bt(S)),S+="n"),b+=` It must be ${d}. Received ${S}`,b},RangeError);function Bt(_){let d="",p=_.length;const b=_[0]==="-"?1:0;for(;p>=b+4;p-=3)d=`_${_.slice(p-3,p)}${d}`;return`${_.slice(0,p)}${d}`}function zt(_,d,p){Gt(d,"offset"),(_[d]===void 0||_[d+p]===void 0)&&Ut(d,_.length-(p+1))}function xt(_,d,p,b,S,I){if(_>p||_<d){const M=typeof d=="bigint"?"n":"";let Q;throw d===0||d===BigInt(0)?Q=`>= 0${M} and < 2${M} ** ${(I+1)*8}${M}`:Q=`>= -(2${M} ** ${(I+1)*8-1}${M}) and < 2 ** ${(I+1)*8-1}${M}`,new _t.ERR_OUT_OF_RANGE("value",Q,_)}zt(b,S,I)}function Gt(_,d){if(typeof _!="number")throw new _t.ERR_INVALID_ARG_TYPE(d,"number",_)}function Ut(_,d,p){throw Math.floor(_)!==_?(Gt(_,p),new _t.ERR_OUT_OF_RANGE("offset","an integer",_)):d<0?new _t.ERR_BUFFER_OUT_OF_BOUNDS:new _t.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${d}`,_)}const $t=/[^+/0-9A-Za-z-_]/g;function Fe(_){if(_=_.split("=")[0],_=_.trim().replace($t,""),_.length<2)return"";for(;_.length%4!==0;)_=_+"=";return _}function pe(_,d){d=d||1/0;let p;const b=_.length;let S=null;const I=[];for(let M=0;M<b;++M){if(p=_.charCodeAt(M),p>55295&&p<57344){if(!S){if(p>56319){(d-=3)>-1&&I.push(239,191,189);continue}else if(M+1===b){(d-=3)>-1&&I.push(239,191,189);continue}S=p;continue}if(p<56320){(d-=3)>-1&&I.push(239,191,189),S=p;continue}p=(S-55296<<10|p-56320)+65536}else S&&(d-=3)>-1&&I.push(239,191,189);if(S=null,p<128){if((d-=1)<0)break;I.push(p)}else if(p<2048){if((d-=2)<0)break;I.push(p>>6|192,p&63|128)}else if(p<65536){if((d-=3)<0)break;I.push(p>>12|224,p>>6&63|128,p&63|128)}else if(p<1114112){if((d-=4)<0)break;I.push(p>>18|240,p>>12&63|128,p>>6&63|128,p&63|128)}else throw new Error("Invalid code point")}return I}function ei(_){const d=[];for(let p=0;p<_.length;++p)d.push(_.charCodeAt(p)&255);return d}function Ii(_,d){let p,b,S;const I=[];for(let M=0;M<_.length&&!((d-=2)<0);++M)p=_.charCodeAt(M),b=p>>8,S=p%256,I.push(S),I.push(b);return I}function Re(_){return t.toByteArray(Fe(_))}function re(_,d,p,b){let S;for(S=0;S<b&&!(S+p>=d.length||S>=_.length);++S)d[S+p]=_[S];return S}function jt(_,d){return _ instanceof d||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===d.name}function Pi(_){return _!==_}const Xs=(function(){const _="0123456789abcdef",d=new Array(256);for(let p=0;p<16;++p){const b=p*16;for(let S=0;S<16;++S)d[b+S]=_[p]+_[S]}return d})();function ne(_){return typeof BigInt>"u"?Ys:_}function Ys(){throw new Error("BigInt not supported")}})(jn)),jn}var Hy=Fy();const Wy="https://api.anam.ai",Vy="/v1",Xc={client:"js-sdk",version:"4.12.0"};var zy=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const Yc="https://api.anam.ai",Xn="/v1";var Ae;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Ae||(Ae={}));let Yn=Yc,qc=Xn,De,Kc=!1;const $y=(s,t=Xn)=>{Yn=s,qc=t},jy=s=>{De=s},Xy=s=>{Kc=s};let Ge={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ai=s=>{Ge=Object.assign(Object.assign({},Ge),s)},ti=(s,t,e)=>zy(void 0,void 0,void 0,function*(){if(!Kc)try{const i=Object.assign(Object.assign({},Xc),e);Ge.sessionId&&(i.sessionId=Ge.sessionId),Ge.organizationId&&(i.organizationId=Ge.organizationId),Ge.attemptCorrelationId&&(i.attemptCorrelationId=Ge.attemptCorrelationId);const r=`${qc}/metrics/client`;let n,o={"Content-Type":"application/json"};De!=null&&De.enabled&&(De!=null&&De.baseUrl)?(n=`${De.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Yn}${r}`):n=`${Yn}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:t,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),Yy=(s,t="console")=>{var e,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((e=n["inbound-rtp"])===null||e===void 0?void 0:e.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var m,f,g,y,x;const v={framesReceived:(m=u.framesReceived)!==null&&m!==void 0?m:"unknown",framesDropped:(f=u.framesDropped)!==null&&f!==void 0?f:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(y=u.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(x=u.packetsLost)!==null&&x!==void 0?x:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(v)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var m,f,g;const y={packetsReceived:(m=u.packetsReceived)!==null&&m!==void 0?m:"unknown",packetsLost:(f=u.packetsLost)!==null&&f!==void 0?f:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(y)}));const h=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];h.length>0&&(o.userAudioInput=[],h.forEach(u=>{var m,f;const g={packetsSent:(m=u.packetsSent)!==null&&m!==void 0?m:"unknown",retransmittedPackets:(f=u.retransmittedPacketsSent)!==null&&f!==void 0?f:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const m={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(m)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const m={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(m)}));const c=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&c.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&c.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&c.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&c.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&c.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=c,t==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var Dt;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(Dt||(Dt={}));class Rt extends Error{constructor(t,e,i=500,r){super(t),this.name="ClientError",this.code=e,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Rt.prototype),ti(Ae.CLIENT_METRIC_MEASUREMENT_ERROR,e,{details:r,statusCode:i})}}function Zc(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function qy(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const t=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return`Invalid API Gateway baseUrl protocol: ${t.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Ft;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Ft||(Ft={}));var fe;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(fe||(fe={}));var Ue;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(Ue||(Ue={}));var js;(function(s){s.USER="user",s.PERSONA="persona"})(js||(js={}));var et;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(et||(et={}));var It;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(It||(It={}));var Le;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Le||(Le={}));class Ky{constructor(t,e){this.sequenceNumber=0,this.config=t,this.signallingClient=e}sendAudioChunk(t){const i={audioData:typeof t=="string"?t:this.arrayBufferToBase64(t),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(t){const e=t instanceof Uint8Array?t:new Uint8Array(t),i=Array.from(e,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Ri=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const Zy=5,Jy=5;class Qy{constructor(t,e,i,r,n){var o,a,l,h,c;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!t)throw new Error("Signalling Client: sessionId is required");this.sessionId=t;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:m,url:f}=e;if(this.heartbeatIntervalSeconds=u||Zy,this.maxWsReconnectionAttempts=m||Jy,!f.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),y=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=y,this.url=g;const x=f.protocol||"https",v=x==="http"?"ws":"wss",E=`${x}://${f.baseUrl}`,T=(h=f.signallingPath)!==null&&h!==void 0?h:"/ws",C=new URL(E);C.protocol=v==="ws"?"ws:":"wss:",f.port&&(C.port=f.port),C.pathname=T,C.searchParams.append("session_id",t),this.url.searchParams.append("target_url",C.href)}else{const y=`${f.protocol||"https"}://${f.baseUrl}`;this.url=new URL(y),this.url.protocol=f.protocol==="http"?"ws:":"wss:",f.port&&(this.url.port=f.port),this.url.pathname=(c=f.signallingPath)!==null&&c!==void 0?c:"/ws",this.url.searchParams.append("session_id",t)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(t){return Ri(this,void 0,void 0,function*(){const e={connectionDescription:t,userUid:this.sessionId},i={actionType:Ft.OFFER,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendIceCandidate(t){return Ri(this,void 0,void 0,function*(){const e={actionType:Ft.ICE_CANDIDATE,sessionId:this.sessionId,payload:t.toJSON()};this.sendSignalMessage(e)})}sendSignalMessage(t){var e;if(((e=this.socket)===null||e===void 0?void 0:e.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(t))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(t)}sendTalkMessage(t){return Ri(this,void 0,void 0,function*(){const e={actionType:Ft.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:t};this.sendSignalMessage(e)})}sendAgentAudioInput(t){const e={actionType:Ft.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:t};this.sendSignalMessage(e)}sendAgentAudioInputEnd(){const t={actionType:Ft.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(t)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Ri(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(It.WEB_SOCKET_OPEN)}catch(t){console.error("SignallingClient - onOpen: error in onOpen",t),this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Ri(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(t){this.stopSignal||console.error("SignallingClient - onError: ",t)}flushSendingBuffer(){const t=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(e=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(e)):t.push(e)}),this.sendingBuffer=t}onMessage(t){return Ri(this,void 0,void 0,function*(){const e=JSON.parse(t.data);this.internalEventEmitter.emit(It.SIGNAL_MESSAGE_RECEIVED,e)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const t=this.heartbeatIntervalSeconds*1e3,e={actionType:Ft.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(e);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},t)}}function tx(s){return"brainType"in s||"llmId"in s}var Jc=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class ex{constructor(t,e,i){if(!t&&!e)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=t||null,this.apiKey=e||null,this.baseUrl=(i==null?void 0:i.baseUrl)||Wy,this.apiVersion=(i==null?void 0:i.apiVersion)||Vy,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(t,e){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${t}`,o=new URL(`${this.baseUrl}${t}`),a=Object.assign(Object.assign({},e),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${t}`,headers:e}}startSession(t,e){return Jc(this,void 0,void 0,function*(){if(!this.sessionToken){if(!t)throw new Rt("Persona configuration must be provided when using apiKey",Dt.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(t)}t&&"brainType"in t&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:t,sessionOptions:e,clientMetadata:Xc})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Rt("Invalid request to start session",Dt.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Rt("Authentication failed when starting session",Dt.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Rt("Please sign up for a plan to start a session",Dt.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Rt("Authentication failed when starting session",Dt.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Rt("Concurrency limit reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Rt("Spend cap reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Rt("Usage limit reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Rt("There are no available personas, please try again later",Dt.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Rt("Unknown error when starting session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Rt?i:new Rt("Failed to start session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(t){return Jc(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");t&&"brainType"in t&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let e={clientLabel:"js-sdk-api-key"};tx(t)&&(e=Object.assign(Object.assign({},e),{personaConfig:t}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var ix=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class sx{constructor(t,e,i){this.baseUrl=t,this.sessionId=e,this.apiGatewayConfig=i}sendTalkCommand(t){return ix(this,void 0,void 0,function*(){var e,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((e=this.apiGatewayConfig)===null||e===void 0)&&e.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const h=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=h.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:t})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class rx{constructor(){this.listeners={}}addListener(t,e){this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e)}removeListener(t,e){this.listeners[t]&&this.listeners[t].delete(e)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(i=>{i(...e)})}}class nx{constructor(t,e){this.messages=[],this.publicEventEmitter=t,this.internalEventEmitter=e,this.internalEventEmitter.addListener(It.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(t){return{id:`${t.role}::${t.message_id}`,content:t.content,role:t.role,endOfSpeech:t.end_of_speech,interrupted:t.interrupted}}processUserMessage(t){const e={id:t.id,content:t.content,role:t.role};this.messages.push(e)}processPersonaMessage(t){const e={id:t.id,content:t.content,role:t.role,interrupted:t.interrupted},i=this.messages.findIndex(r=>r.id===e.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+e.content,interrupted:r.interrupted||e.interrupted})}else this.messages.push(e)}processWebRtcTextMessageEvent(t){const e=this.webRtcTextMessageEventToMessageStreamEvent(t);switch(this.publicEventEmitter.emit(et.MESSAGE_STREAM_EVENT_RECEIVED,e),e.role){case js.USER:this.processUserMessage(e);break;case js.PERSONA:this.processPersonaMessage(e);break}e.endOfSpeech&&this.publicEventEmitter.emit(et.MESSAGE_HISTORY_UPDATED,this.messages)}}class ox{constructor(){this.listeners={}}addListener(t,e){this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e)}removeListener(t,e){this.listeners[t]&&this.listeners[t].delete(e)}emit(t,...e){if(t===et.CONNECTION_ESTABLISHED&&ti(Ae.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),t===et.CONNECTION_CLOSED){const[i,r]=e;ti(Ae.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[t]&&this.listeners[t].forEach(i=>{i(...e)})}}var Wt;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(Wt||(Wt={}));var qn=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class ax{constructor(t,e,i){this.state=Wt.UNSTARTED,this.correlationId=t,this.internalEventEmitter=e,this.signallingClient=i,this.internalEventEmitter.addListener(It.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(It.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(t){return qn(this,void 0,void 0,function*(){t.actionType===Ft.TALK_STREAM_INTERRUPTED&&t.payload.correlationId===this.correlationId&&(this.state=Wt.INTERRUPTED,this.onDeactivate())})}endMessage(){return qn(this,void 0,void 0,function*(){if(this.state===Wt.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Wt.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const t={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(t),this.state=Wt.ENDED,this.onDeactivate()})}streamMessageChunk(t,e){return qn(this,void 0,void 0,function*(){if(this.state!==Wt.STREAMING&&this.state!==Wt.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:t,startOfSpeech:this.state===Wt.UNSTARTED,endOfSpeech:e,correlationId:this.correlationId};this.state=e?Wt.ENDED:Wt.STREAMING,this.state===Wt.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Wt.STREAMING||this.state===Wt.UNSTARTED}getState(){return this.state}}var Kn=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const Qc=(s,t)=>{if(isNaN(s)||isNaN(t))return 0;const e=t-s;return e>0?e:0};class tu{constructor(t){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=t}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(t,e){return this.handlers[t]=e,()=>{delete this.handlers[t]}}processToolCallStartedEvent(t){return Kn(this,void 0,void 0,function*(){const{tool_name:e,timestamp:i}=t,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(t),n=new Date(i);if(this.pendingCalls[t.tool_call_id]={payload:r,timestamp:n.getTime()},!(e in this.handlers))return;const o=this.handlers[e];if(o.onStart)try{let a=yield o.onStart(r);if(t.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},t),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},t),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},t),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(t){return Kn(this,void 0,void 0,function*(){const{tool_name:e,tool_call_id:i,timestamp:r}=t,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(t);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(e in this.handlers))return;const o=this.handlers[e];if(o.onComplete){t.tool_type==="client"&&this.publicEventEmitter.emit(et.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${e}:`,a);return}}})}processToolCallFailedEvent(t){return Kn(this,void 0,void 0,function*(){const{tool_name:e,tool_call_id:i,timestamp:r}=t,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(t);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(e in this.handlers))return;const o=this.handlers[e];if(o.onFail){t.tool_type==="client"&&this.publicEventEmitter.emit(et.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${e}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(t){return{eventUid:t.event_uid,sessionId:t.session_id,eventName:t.event_name,eventData:t.event_data,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(t){return{eventUid:t.event_uid,sessionId:t.session_id,eventName:t.tool_name,eventData:t.arguments,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(t){return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,arguments:t.arguments,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(t){const e=new Date(t.timestamp),i=this.pendingCalls[t.tool_call_id],r=i?Qc(i.timestamp,e.getTime()):0;return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,result:t.result,executionTime:r>0?r:0,timestamp:t.timestamp,documentsAccessed:t.documents_accessed,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(t){const e=new Date(t.timestamp),i=this.pendingCalls[t.tool_call_id],r=i?Qc(i.timestamp,e.getTime()):0;return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,errorMessage:t.error_message,executionTime:r>0?r:0,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}}var Yt=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const lx=15e3,hx=5e3,cx=2;class ux{constructor(t,e,i,r,n){var o,a,l,h;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:Ue.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=e.apiGateway;const{inputAudio:c}=e;this.inputAudioState=c.inputAudioState,e.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=e.inputAudio.userProvidedMediaStream),this.disableInputAudio=e.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(It.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(It.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(It.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(It.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(It.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=e.iceServers,this.signallingClient=new Qy(t,e.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new sx(e.engine.baseUrl,t,this.apiGatewayConfig),this.audioDeviceId=e.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=e.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(h=(l=e.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&h!==void 0?h:"console"}onInputAudioStateChange(t,e){t.isMuted!==e.isMuted&&(e.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var t;(t=this.inputAudioStream)===null||t===void 0||t.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var t;(t=this.inputAudioStream)===null||t===void 0||t.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>Yt(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const t=yield this.peerConnection.getStats();this.sendClientSideMetrics(t)}catch(t){console.error("Failed to collect and send stats:",t)}}),hx))}sendClientSideMetrics(t){t.forEach(e=>{if(e.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:e};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const t=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},lx);this.successMetricPoller=setInterval(()=>Yt(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(t);return}try{const e=yield this.peerConnection.getStats();let i=!1,r=null;e.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,ti(Ae.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(t),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const t=this.inputAudioState,e=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=e,this.onInputAudioStateChange(t,e),this.inputAudioState}unmuteInputAudio(){const t=this.inputAudioState,e=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=e,this.onInputAudioStateChange(t,e),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(t){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(t==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const e=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:t}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=t,yield this.setupAudioTrack(),e&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(et.INPUT_AUDIO_DEVICE_CHANGED,t)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(t){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(t)}setMediaStreamTargetById(t){if(t){const e=document.getElementById(t);if(!e)throw new Error(`StreamingClient: video element with id ${t} not found`);this.videoElement=e}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(t){console.error("StreamingClient - startConnection: error",t),this.handleWebrtcFailure(t)}}stopConnection(){return Yt(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(t){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(t)})}startTalkMessageStream(t){return t||(t=Math.random().toString(36).substring(2,15)),new ax(t,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(t){return this.agentAudioInputStream=new Ky(t,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return Yt(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:cx}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(t=>{console.error("Async microphone permission request failed:",t)}))})}onSignalMessage(t){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(t.actionType){case Ft.ANSWER:const e=t.payload;yield this.peerConnection.setRemoteDescription(e),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Ft.ICE_CANDIDATE:const i=t.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Ft.END_SESSION:const n=t.payload;this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Ft.WARNING:const o=t.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(et.SERVER_WARNING,o);break;case Ft.TALK_STREAM_INTERRUPTED:const a=t.payload;this.publicEventEmitter.emit(et.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Ft.SESSION_READY:const l=t.sessionId;this.publicEventEmitter.emit(et.SESSION_READY,l);break;case Ft.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",t)}})}onSignallingClientConnected(){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(t){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",t),this.handleWebrtcFailure(t)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(t=>{var e;(e=this.peerConnection)===null||e===void 0||e.addIceCandidate(t)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(t){t.candidate&&this.signallingClient.sendIceCandidate(t.candidate)}onIceConnectionStateChange(){var t,e;(((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="connected"||((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(et.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var t;((t=this.peerConnection)===null||t===void 0?void 0:t.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(t){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:t}),t.name==="NotAllowedError"&&t.message==="Permission denied"?this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(t){if(t.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=t.streams[0],this.publicEventEmitter.emit(et.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(et.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ti(Ae.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else t.track.kind==="audio"&&(this.audioStream=t.streams[0],this.publicEventEmitter.emit(et.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const t=this.peerConnection.createDataChannel("session",{ordered:!0});t.onopen=()=>{this.dataChannel=t??null},t.onclose=()=>{},t.onmessage=e=>{var i,r,n,o;try{const a=JSON.parse(e.data);switch(a.messageType){case fe.SPEECH_TEXT:this.internalEventEmitter.emit(It.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case fe.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(It.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const h=tu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(et.CLIENT_TOOL_EVENT_RECEIVED,h);break;case fe.TOOL_CALL_STARTED_EVENT:const c=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(c)),this.internalEventEmitter.emit(It.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,c);break;case fe.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(It.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case fe.TOOL_CALL_FAILED_EVENT:const m=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(m)),this.internalEventEmitter.emit(It.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,m);break;case fe.REASONING_TEXT:this.internalEventEmitter.emit(It.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case fe.USER_SPEECH_STARTED:this.publicEventEmitter.emit(et.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case fe.USER_SPEECH_ENDED:this.publicEventEmitter.emit(et.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return Yt(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==Ue.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Ue.PENDING}),this.publicEventEmitter.emit(et.MIC_PERMISSION_PENDING);try{const t={echoCancellation:!0};this.audioDeviceId&&(t.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:t}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Ue.GRANTED}),this.publicEventEmitter.emit(et.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(t){console.error("Failed to get microphone permission:",t),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Ue.DENIED});const e=t instanceof Error?t.message:String(t);this.publicEventEmitter.emit(et.MIC_PERMISSION_DENIED,e)}}})}setupAudioTrack(){return Yt(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const t=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(t)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(t,this.inputAudioStream)}else this.peerConnection.addTrack(t,this.inputAudioStream);this.publicEventEmitter.emit(et.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return Yt(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const t=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(t)}catch(t){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",t)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return Yt(this,void 0,void 0,function*(){var t;if(this.showPeerConnectionStatsReport){const e=yield(t=this.peerConnection)===null||t===void 0?void 0:t.getStats();if(e){const i=Yy(e,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(e=>{e.stop()}),this.inputAudioStream=null}catch(e){console.error("StreamingClient - shutdown: error stopping input audio stream",e)}try{this.signallingClient.stop()}catch(e){console.error("StreamingClient - shutdown: error stopping signallilng",e)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(e){console.error("StreamingClient - shutdown: error closing peer connection",e)}})}}class dx{constructor(t,e){this.reasoning_messages=[],this.publicEventEmitter=t,this.internalEventEmitter=e,this.internalEventEmitter.addListener(It.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(t){return{id:`${t.role}::${t.message_id}`,content:t.content,endOfThought:t.end_of_thought,role:t.role}}processWebRtcReasoningTextMessageEvent(t){const e=this.webRtcTextMessageEventToReasoningStreamEvent(t);this.publicEventEmitter.emit(et.REASONING_STREAM_EVENT_RECEIVED,e);const i={id:e.id,content:e.content,role:e.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);e.endOfThought&&this.publicEventEmitter.emit(et.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var Ne=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class fx{constructor(t,e,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:Ue.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const h=this.validateClientConfig(t,e,i);if(h)throw new Rt(h,Dt.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=e,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&$y(i.api.baseUrl||Yc,i.api.apiVersion||Xn),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&jy(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&Xy(!0),this.publicEventEmitter=new ox,this.internalEventEmitter=new rx,this.toolCallManager=new tu(this.publicEventEmitter),this.apiClient=new ex(t,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new nx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new dx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(t){try{const e=t.split(".")[1],i=Hy.Buffer.from(e,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(t,e,i){var r,n;if(!t&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&t)return"Only one of sessionToken or apiKey should be used";const o=qy((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(t){const a=this.decodeJwt(t);this.organizationId=a.accountId,Ai({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&e)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!e)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var t;const e={};if(!((t=this.clientOptions)===null||t===void 0)&&t.voiceDetection&&(e.voiceDetection=this.clientOptions.voiceDetection),Object.keys(e).length!==0)return e}startSession(t){return Ne(this,void 0,void 0,function*(){var e,i,r,n,o,a,l,h,c,u,m,f;const g=this.personaConfig,y=this.buildStartSessionOptionsForClient(),x=yield this.apiClient.startSession(g,y),{sessionId:v,clientConfig:E,engineHost:T,engineProtocol:C,signallingEndpoint:R}=x,{heartbeatIntervalSeconds:A,maxWsReconnectionAttempts:P,iceServers:F}=E;this.sessionId=v,Ai({sessionId:this.sessionId});const B=!((e=this.clientOptions)===null||e===void 0)&&e.iceServers?this.clientOptions.iceServers:F;try{this.streamingClient=new ux(v,{engine:{baseUrl:`${C}://${T}`},signalling:{heartbeatIntervalSeconds:A,maxWsReconnectionAttempts:P,url:{baseUrl:T,protocol:C,signallingPath:R}},iceServers:B,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:t,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(c=(h=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||h===void 0?void 0:h.showPeerConnectionStatsReport)!==null&&c!==void 0?c:!1,peerConnectionStatsReportOutputFormat:(f=(m=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||m===void 0?void 0:m.peerConnectionStatsReportOutputFormat)!==null&&f!==void 0?f:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Ai({sessionId:null}),new Rt("Failed to initialize streaming client",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:v})}return v})}startSessionIfNeeded(t){return Ne(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(t),!this.sessionId||!this.streamingClient))throw new Rt("Session ID or streaming client is not available after starting session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(t){return Ne(this,void 0,void 0,function*(){var e;if(this._isStreaming)throw new Error("Already streaming");const i=Zc();return Ai({attemptCorrelationId:i,sessionId:null}),ti(Ae.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(t),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(et.VIDEO_STREAM_STARTED,h=>{o.push(h),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(et.AUDIO_STREAM_STARTED,h=>{o.push(h),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(t,e,i){return Ne(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(t,i)})}streamToVideoElement(t,e){return Ne(this,void 0,void 0,function*(){var i;const r=Zc();Ai({attemptCorrelationId:r,sessionId:null}),ti(Ae.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e)}catch(n){throw n instanceof Rt?n:new Rt("Failed to start session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(t),this.streamingClient.startConnection()})}talk(t){return Ne(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(t)})}sendDataMessage(t){if(this.streamingClient)this.streamingClient.sendDataMessage(t);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(t){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:t,timestamp:i,session_id:e,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send interrupt command: no active session");const e=JSON.stringify({message_type:"interrupt",session_id:t,timestamp:new Date().toISOString()});this.sendDataMessage(e)}addContext(t){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:e,content:t});this.sendDataMessage(i)}stopStreaming(){return Ne(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Le.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ai({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(t){this.personaConfig=t}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var t;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var t,e;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var t,e;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(t){return Ne(this,void 0,void 0,function*(){var e;if(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(t)})}createTalkMessageStream(t){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(t&&t.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(t)}createAgentAudioInputStream(t){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(t)}addListener(t,e){this.publicEventEmitter.addListener(t,e)}removeListener(t,e){this.publicEventEmitter.removeListener(t,e)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(t,e){return this.toolCallManager.registerHandler(t,e)}}const px=(s,t)=>new fx(s,void 0,t);let mx=0;class gx{constructor(t){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.client=px(t.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var t;try{const e=`anam-avatar-video-${++mx}`;this.videoElement=document.createElement("video"),this.videoElement.id=e,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.videoElement.style.display="none",document.body.appendChild(this.videoElement),this.client.addListener(et.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(et.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&((i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(et.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(et.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(e),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(e){const i=e instanceof Error?e:new Error(String(e));throw console.error("[AnamSession] Connection failed:",i.message),(t=this.onError)==null||t.call(this,i),this.close(),i}}sendAudioChunk(t){var e;(e=this.audioInputStream)==null||e.sendAudioChunk(t)}endSequence(){var t;(t=this.audioInputStream)==null||t.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),this.audioInputStream=null,this._connected=!1}}}const _x=new Set(["a","button","input","select","textarea","details","summary","label","option"]),yx=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),xx=new Set(["h1","h2","h3","h4","h5","h6"]),bx=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class vx{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let t=0;const e=[];e.push(`Page: ${document.title}`),e.push(`URL: ${location.href}`),e.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const h=(r.textContent??"").trim();h&&h.length>1&&e.push(h);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=xx.has(o);if(a||l){const h=t++;this.elementMap.set(h,n);const c=this.getUsefulAttrs(n),u=c?" "+c:"",m=this.getDirectText(n).slice(0,200);if(l){const f=parseInt(o[1]),g="#".repeat(f);e.push(""),e.push(`${g} [${h}]${m}`)}else e.push(`[${h}]<${o}${u}>${m}</${o}>`);return}for(const h of n.childNodes)i(h)};return i(document.body),{text:e.join(`
|
|
938
|
-
`),elementMap:this.elementMap}}getElementByIndex(
|
|
937
|
+
*/var Ru;function cx(){return Ru||(Ru=1,(function(s){const e=ax(),t=lx(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=v,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const b=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(b,f),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>r)throw new RangeError('The value "'+b+'" is invalid for option "size"');const f=new Uint8Array(b);return Object.setPrototypeOf(f,a.prototype),f}function a(b,f,m){if(typeof b=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(b)}return l(b,f,m)}a.poolSize=8192;function l(b,f,m){if(typeof b=="string")return p(b,f);if(ArrayBuffer.isView(b))return g(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(et(b,ArrayBuffer)||b&&et(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(et(b,SharedArrayBuffer)||b&&et(b.buffer,SharedArrayBuffer)))return _(b,f,m);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const S=b.valueOf&&b.valueOf();if(S!=null&&S!==b)return a.from(S,f,m);const E=y(b);if(E)return E;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),f,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,f,m){return l(b,f,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function h(b,f,m){return c(b),b<=0?o(b):f!==void 0?typeof m=="string"?o(b).fill(f,m):o(b).fill(f):o(b)}a.alloc=function(b,f,m){return h(b,f,m)};function u(b){return c(b),o(b<0?0:x(b)|0)}a.allocUnsafe=function(b){return u(b)},a.allocUnsafeSlow=function(b){return u(b)};function p(b,f){if((typeof f!="string"||f==="")&&(f="utf8"),!a.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const m=C(b,f)|0;let S=o(m);const E=S.write(b,f);return E!==m&&(S=S.slice(0,E)),S}function d(b){const f=b.length<0?0:x(b.length)|0,m=o(f);for(let S=0;S<f;S+=1)m[S]=b[S]&255;return m}function g(b){if(et(b,Uint8Array)){const f=new Uint8Array(b);return _(f.buffer,f.byteOffset,f.byteLength)}return d(b)}function _(b,f,m){if(f<0||b.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<f+(m||0))throw new RangeError('"length" is outside of buffer bounds');let S;return f===void 0&&m===void 0?S=new Uint8Array(b):m===void 0?S=new Uint8Array(b,f):S=new Uint8Array(b,f,m),Object.setPrototypeOf(S,a.prototype),S}function y(b){if(a.isBuffer(b)){const f=x(b.length)|0,m=o(f);return m.length===0||b.copy(m,0,0,f),m}if(b.length!==void 0)return typeof b.length!="number"||Ki(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function x(b){if(b>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return b|0}function v(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==a.prototype},a.compare=function(f,m){if(et(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),et(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(f)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===m)return 0;let S=f.length,E=m.length;for(let M=0,P=Math.min(S,E);M<P;++M)if(f[M]!==m[M]){S=f[M],E=m[M];break}return S<E?-1:E<S?1:0},a.isEncoding=function(f){switch(String(f).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(f,m){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return a.alloc(0);let S;if(m===void 0)for(m=0,S=0;S<f.length;++S)m+=f[S].length;const E=a.allocUnsafe(m);let M=0;for(S=0;S<f.length;++S){let P=f[S];if(et(P,Uint8Array))M+P.length>E.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(E,M)):Uint8Array.prototype.set.call(E,P,M);else if(a.isBuffer(P))P.copy(E,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=P.length}return E};function C(b,f){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||et(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const m=b.length,S=arguments.length>2&&arguments[2]===!0;if(!S&&m===0)return 0;let E=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return St(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Ft(b).length;default:if(E)return S?-1:St(b).length;f=(""+f).toLowerCase(),E=!0}}a.byteLength=C;function T(b,f,m){let S=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,f>>>=0,m<=f))return"";for(b||(b="utf8");;)switch(b){case"hex":return N(this,f,m);case"utf8":case"utf-8":return W(this,f,m);case"ascii":return L(this,f,m);case"latin1":case"binary":return X(this,f,m);case"base64":return U(this,f,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,f,m);default:if(S)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),S=!0}}a.prototype._isBuffer=!0;function A(b,f,m){const S=b[f];b[f]=b[m],b[m]=S}a.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<f;m+=2)A(this,m,m+1);return this},a.prototype.swap32=function(){const f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<f;m+=4)A(this,m,m+3),A(this,m+1,m+2);return this},a.prototype.swap64=function(){const f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<f;m+=8)A(this,m,m+7),A(this,m+1,m+6),A(this,m+2,m+5),A(this,m+3,m+4);return this},a.prototype.toString=function(){const f=this.length;return f===0?"":arguments.length===0?W(this,0,f):T.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(f){if(!a.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:a.compare(this,f)===0},a.prototype.inspect=function(){let f="";const m=s.INSPECT_MAX_BYTES;return f=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(f+=" ... "),"<Buffer "+f+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(f,m,S,E,M){if(et(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(m===void 0&&(m=0),S===void 0&&(S=f?f.length:0),E===void 0&&(E=0),M===void 0&&(M=this.length),m<0||S>f.length||E<0||M>this.length)throw new RangeError("out of range index");if(E>=M&&m>=S)return 0;if(E>=M)return-1;if(m>=S)return 1;if(m>>>=0,S>>>=0,E>>>=0,M>>>=0,this===f)return 0;let P=M-E,re=S-m;const Pe=Math.min(P,re),we=this.slice(E,M),ke=f.slice(m,S);for(let Se=0;Se<Pe;++Se)if(we[Se]!==ke[Se]){P=we[Se],re=ke[Se];break}return P<re?-1:re<P?1:0};function w(b,f,m,S,E){if(b.length===0)return-1;if(typeof m=="string"?(S=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,Ki(m)&&(m=E?0:b.length-1),m<0&&(m=b.length+m),m>=b.length){if(E)return-1;m=b.length-1}else if(m<0)if(E)m=0;else return-1;if(typeof f=="string"&&(f=a.from(f,S)),a.isBuffer(f))return f.length===0?-1:R(b,f,m,S,E);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?E?Uint8Array.prototype.indexOf.call(b,f,m):Uint8Array.prototype.lastIndexOf.call(b,f,m):R(b,[f],m,S,E);throw new TypeError("val must be string, number or Buffer")}function R(b,f,m,S,E){let M=1,P=b.length,re=f.length;if(S!==void 0&&(S=String(S).toLowerCase(),S==="ucs2"||S==="ucs-2"||S==="utf16le"||S==="utf-16le")){if(b.length<2||f.length<2)return-1;M=2,P/=2,re/=2,m/=2}function Pe(ke,Se){return M===1?ke[Se]:ke.readUInt16BE(Se*M)}let we;if(E){let ke=-1;for(we=m;we<P;we++)if(Pe(b,we)===Pe(f,ke===-1?0:we-ke)){if(ke===-1&&(ke=we),we-ke+1===re)return ke*M}else ke!==-1&&(we-=we-ke),ke=-1}else for(m+re>P&&(m=P-re),we=m;we>=0;we--){let ke=!0;for(let Se=0;Se<re;Se++)if(Pe(b,we+Se)!==Pe(f,Se)){ke=!1;break}if(ke)return we}return-1}a.prototype.includes=function(f,m,S){return this.indexOf(f,m,S)!==-1},a.prototype.indexOf=function(f,m,S){return w(this,f,m,S,!0)},a.prototype.lastIndexOf=function(f,m,S){return w(this,f,m,S,!1)};function D(b,f,m,S){m=Number(m)||0;const E=b.length-m;S?(S=Number(S),S>E&&(S=E)):S=E;const M=f.length;S>M/2&&(S=M/2);let P;for(P=0;P<S;++P){const re=parseInt(f.substr(P*2,2),16);if(Ki(re))return P;b[m+P]=re}return P}function B(b,f,m,S){return ft(St(f,b.length-m),b,m,S)}function k(b,f,m,S){return ft(fi(f),b,m,S)}function O(b,f,m,S){return ft(Ft(f),b,m,S)}function G(b,f,m,S){return ft(Yi(f,b.length-m),b,m,S)}a.prototype.write=function(f,m,S,E){if(m===void 0)E="utf8",S=this.length,m=0;else if(S===void 0&&typeof m=="string")E=m,S=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(S)?(S=S>>>0,E===void 0&&(E="utf8")):(E=S,S=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-m;if((S===void 0||S>M)&&(S=M),f.length>0&&(S<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");E||(E="utf8");let P=!1;for(;;)switch(E){case"hex":return D(this,f,m,S);case"utf8":case"utf-8":return B(this,f,m,S);case"ascii":case"latin1":case"binary":return k(this,f,m,S);case"base64":return O(this,f,m,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,f,m,S);default:if(P)throw new TypeError("Unknown encoding: "+E);E=(""+E).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(b,f,m){return f===0&&m===b.length?e.fromByteArray(b):e.fromByteArray(b.slice(f,m))}function W(b,f,m){m=Math.min(b.length,m);const S=[];let E=f;for(;E<m;){const M=b[E];let P=null,re=M>239?4:M>223?3:M>191?2:1;if(E+re<=m){let Pe,we,ke,Se;switch(re){case 1:M<128&&(P=M);break;case 2:Pe=b[E+1],(Pe&192)===128&&(Se=(M&31)<<6|Pe&63,Se>127&&(P=Se));break;case 3:Pe=b[E+1],we=b[E+2],(Pe&192)===128&&(we&192)===128&&(Se=(M&15)<<12|(Pe&63)<<6|we&63,Se>2047&&(Se<55296||Se>57343)&&(P=Se));break;case 4:Pe=b[E+1],we=b[E+2],ke=b[E+3],(Pe&192)===128&&(we&192)===128&&(ke&192)===128&&(Se=(M&15)<<18|(Pe&63)<<12|(we&63)<<6|ke&63,Se>65535&&Se<1114112&&(P=Se))}}P===null?(P=65533,re=1):P>65535&&(P-=65536,S.push(P>>>10&1023|55296),P=56320|P&1023),S.push(P),E+=re}return F(S)}const te=4096;function F(b){const f=b.length;if(f<=te)return String.fromCharCode.apply(String,b);let m="",S=0;for(;S<f;)m+=String.fromCharCode.apply(String,b.slice(S,S+=te));return m}function L(b,f,m){let S="";m=Math.min(b.length,m);for(let E=f;E<m;++E)S+=String.fromCharCode(b[E]&127);return S}function X(b,f,m){let S="";m=Math.min(b.length,m);for(let E=f;E<m;++E)S+=String.fromCharCode(b[E]);return S}function N(b,f,m){const S=b.length;(!f||f<0)&&(f=0),(!m||m<0||m>S)&&(m=S);let E="";for(let M=f;M<m;++M)E+=wr[b[M]];return E}function V(b,f,m){const S=b.slice(f,m);let E="";for(let M=0;M<S.length-1;M+=2)E+=String.fromCharCode(S[M]+S[M+1]*256);return E}a.prototype.slice=function(f,m){const S=this.length;f=~~f,m=m===void 0?S:~~m,f<0?(f+=S,f<0&&(f=0)):f>S&&(f=S),m<0?(m+=S,m<0&&(m=0)):m>S&&(m=S),m<f&&(m=f);const E=this.subarray(f,m);return Object.setPrototypeOf(E,a.prototype),E};function K(b,f,m){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+f>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(f,m,S){f=f>>>0,m=m>>>0,S||K(f,m,this.length);let E=this[f],M=1,P=0;for(;++P<m&&(M*=256);)E+=this[f+P]*M;return E},a.prototype.readUintBE=a.prototype.readUIntBE=function(f,m,S){f=f>>>0,m=m>>>0,S||K(f,m,this.length);let E=this[f+--m],M=1;for(;m>0&&(M*=256);)E+=this[f+--m]*M;return E},a.prototype.readUint8=a.prototype.readUInt8=function(f,m){return f=f>>>0,m||K(f,1,this.length),this[f]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(f,m){return f=f>>>0,m||K(f,2,this.length),this[f]|this[f+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(f,m){return f=f>>>0,m||K(f,2,this.length),this[f]<<8|this[f+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(f,m){return f=f>>>0,m||K(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(f,m){return f=f>>>0,m||K(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},a.prototype.readBigUInt64LE=pt(function(f){f=f>>>0,Re(f,"offset");const m=this[f],S=this[f+7];(m===void 0||S===void 0)&&pe(f,this.length-8);const E=m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,M=this[++f]+this[++f]*2**8+this[++f]*2**16+S*2**24;return BigInt(E)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=pt(function(f){f=f>>>0,Re(f,"offset");const m=this[f],S=this[f+7];(m===void 0||S===void 0)&&pe(f,this.length-8);const E=m*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],M=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+S;return(BigInt(E)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(f,m,S){f=f>>>0,m=m>>>0,S||K(f,m,this.length);let E=this[f],M=1,P=0;for(;++P<m&&(M*=256);)E+=this[f+P]*M;return M*=128,E>=M&&(E-=Math.pow(2,8*m)),E},a.prototype.readIntBE=function(f,m,S){f=f>>>0,m=m>>>0,S||K(f,m,this.length);let E=m,M=1,P=this[f+--E];for(;E>0&&(M*=256);)P+=this[f+--E]*M;return M*=128,P>=M&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(f,m){return f=f>>>0,m||K(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},a.prototype.readInt16LE=function(f,m){f=f>>>0,m||K(f,2,this.length);const S=this[f]|this[f+1]<<8;return S&32768?S|4294901760:S},a.prototype.readInt16BE=function(f,m){f=f>>>0,m||K(f,2,this.length);const S=this[f+1]|this[f]<<8;return S&32768?S|4294901760:S},a.prototype.readInt32LE=function(f,m){return f=f>>>0,m||K(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},a.prototype.readInt32BE=function(f,m){return f=f>>>0,m||K(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},a.prototype.readBigInt64LE=pt(function(f){f=f>>>0,Re(f,"offset");const m=this[f],S=this[f+7];(m===void 0||S===void 0)&&pe(f,this.length-8);const E=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(S<<24);return(BigInt(E)<<BigInt(32))+BigInt(m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),a.prototype.readBigInt64BE=pt(function(f){f=f>>>0,Re(f,"offset");const m=this[f],S=this[f+7];(m===void 0||S===void 0)&&pe(f,this.length-8);const E=(m<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(E)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+S)}),a.prototype.readFloatLE=function(f,m){return f=f>>>0,m||K(f,4,this.length),t.read(this,f,!0,23,4)},a.prototype.readFloatBE=function(f,m){return f=f>>>0,m||K(f,4,this.length),t.read(this,f,!1,23,4)},a.prototype.readDoubleLE=function(f,m){return f=f>>>0,m||K(f,8,this.length),t.read(this,f,!0,52,8)},a.prototype.readDoubleBE=function(f,m){return f=f>>>0,m||K(f,8,this.length),t.read(this,f,!1,52,8)};function H(b,f,m,S,E,M){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>E||f<M)throw new RangeError('"value" argument is out of bounds');if(m+S>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(f,m,S,E){if(f=+f,m=m>>>0,S=S>>>0,!E){const re=Math.pow(2,8*S)-1;H(this,f,m,S,re,0)}let M=1,P=0;for(this[m]=f&255;++P<S&&(M*=256);)this[m+P]=f/M&255;return m+S},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(f,m,S,E){if(f=+f,m=m>>>0,S=S>>>0,!E){const re=Math.pow(2,8*S)-1;H(this,f,m,S,re,0)}let M=S-1,P=1;for(this[m+M]=f&255;--M>=0&&(P*=256);)this[m+M]=f/P&255;return m+S},a.prototype.writeUint8=a.prototype.writeUInt8=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,1,255,0),this[m]=f&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,2,65535,0),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,2,65535,0),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,4,4294967295,0),this[m+3]=f>>>24,this[m+2]=f>>>16,this[m+1]=f>>>8,this[m]=f&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,4,4294967295,0),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4};function $(b,f,m,S,E){le(f,S,E,b,m,7);let M=Number(f&BigInt(4294967295));b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M;let P=Number(f>>BigInt(32)&BigInt(4294967295));return b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,m}function se(b,f,m,S,E){le(f,S,E,b,m,7);let M=Number(f&BigInt(4294967295));b[m+7]=M,M=M>>8,b[m+6]=M,M=M>>8,b[m+5]=M,M=M>>8,b[m+4]=M;let P=Number(f>>BigInt(32)&BigInt(4294967295));return b[m+3]=P,P=P>>8,b[m+2]=P,P=P>>8,b[m+1]=P,P=P>>8,b[m]=P,m+8}a.prototype.writeBigUInt64LE=pt(function(f,m=0){return $(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=pt(function(f,m=0){return se(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(f,m,S,E){if(f=+f,m=m>>>0,!E){const Pe=Math.pow(2,8*S-1);H(this,f,m,S,Pe-1,-Pe)}let M=0,P=1,re=0;for(this[m]=f&255;++M<S&&(P*=256);)f<0&&re===0&&this[m+M-1]!==0&&(re=1),this[m+M]=(f/P>>0)-re&255;return m+S},a.prototype.writeIntBE=function(f,m,S,E){if(f=+f,m=m>>>0,!E){const Pe=Math.pow(2,8*S-1);H(this,f,m,S,Pe-1,-Pe)}let M=S-1,P=1,re=0;for(this[m+M]=f&255;--M>=0&&(P*=256);)f<0&&re===0&&this[m+M+1]!==0&&(re=1),this[m+M]=(f/P>>0)-re&255;return m+S},a.prototype.writeInt8=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,1,127,-128),f<0&&(f=255+f+1),this[m]=f&255,m+1},a.prototype.writeInt16LE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,2,32767,-32768),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeInt16BE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,2,32767,-32768),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeInt32LE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,4,2147483647,-2147483648),this[m]=f&255,this[m+1]=f>>>8,this[m+2]=f>>>16,this[m+3]=f>>>24,m+4},a.prototype.writeInt32BE=function(f,m,S){return f=+f,m=m>>>0,S||H(this,f,m,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4},a.prototype.writeBigInt64LE=pt(function(f,m=0){return $(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=pt(function(f,m=0){return se(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ue(b,f,m,S,E,M){if(m+S>b.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function z(b,f,m,S,E){return f=+f,m=m>>>0,E||ue(b,f,m,4),t.write(b,f,m,S,23,4),m+4}a.prototype.writeFloatLE=function(f,m,S){return z(this,f,m,!0,S)},a.prototype.writeFloatBE=function(f,m,S){return z(this,f,m,!1,S)};function Q(b,f,m,S,E){return f=+f,m=m>>>0,E||ue(b,f,m,8),t.write(b,f,m,S,52,8),m+8}a.prototype.writeDoubleLE=function(f,m,S){return Q(this,f,m,!0,S)},a.prototype.writeDoubleBE=function(f,m,S){return Q(this,f,m,!1,S)},a.prototype.copy=function(f,m,S,E){if(!a.isBuffer(f))throw new TypeError("argument should be a Buffer");if(S||(S=0),!E&&E!==0&&(E=this.length),m>=f.length&&(m=f.length),m||(m=0),E>0&&E<S&&(E=S),E===S||f.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(S<0||S>=this.length)throw new RangeError("Index out of range");if(E<0)throw new RangeError("sourceEnd out of bounds");E>this.length&&(E=this.length),f.length-m<E-S&&(E=f.length-m+S);const M=E-S;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,S,E):Uint8Array.prototype.set.call(f,this.subarray(S,E),m),M},a.prototype.fill=function(f,m,S,E){if(typeof f=="string"){if(typeof m=="string"?(E=m,m=0,S=this.length):typeof S=="string"&&(E=S,S=this.length),E!==void 0&&typeof E!="string")throw new TypeError("encoding must be a string");if(typeof E=="string"&&!a.isEncoding(E))throw new TypeError("Unknown encoding: "+E);if(f.length===1){const P=f.charCodeAt(0);(E==="utf8"&&P<128||E==="latin1")&&(f=P)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(m<0||this.length<m||this.length<S)throw new RangeError("Out of range index");if(S<=m)return this;m=m>>>0,S=S===void 0?this.length:S>>>0,f||(f=0);let M;if(typeof f=="number")for(M=m;M<S;++M)this[M]=f;else{const P=a.isBuffer(f)?f:a.from(f,E),re=P.length;if(re===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(M=0;M<S-m;++M)this[M+m]=P[M%re]}return this};const ae={};function j(b,f,m){ae[b]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(E){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:E,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(b,f){return`The "${b}" argument must be of type number. Received type ${typeof f}`},TypeError),j("ERR_OUT_OF_RANGE",function(b,f,m){let S=`The value of "${b}" is out of range.`,E=m;return Number.isInteger(m)&&Math.abs(m)>2**32?E=_e(String(m)):typeof m=="bigint"&&(E=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(E=_e(E)),E+="n"),S+=` It must be ${f}. Received ${E}`,S},RangeError);function _e(b){let f="",m=b.length;const S=b[0]==="-"?1:0;for(;m>=S+4;m-=3)f=`_${b.slice(m-3,m)}${f}`;return`${b.slice(0,m)}${f}`}function ee(b,f,m){Re(f,"offset"),(b[f]===void 0||b[f+m]===void 0)&&pe(f,b.length-(m+1))}function le(b,f,m,S,E,M){if(b>m||b<f){const P=typeof f=="bigint"?"n":"";let re;throw f===0||f===BigInt(0)?re=`>= 0${P} and < 2${P} ** ${(M+1)*8}${P}`:re=`>= -(2${P} ** ${(M+1)*8-1}${P}) and < 2 ** ${(M+1)*8-1}${P}`,new ae.ERR_OUT_OF_RANGE("value",re,b)}ee(S,E,M)}function Re(b,f){if(typeof b!="number")throw new ae.ERR_INVALID_ARG_TYPE(f,"number",b)}function pe(b,f,m){throw Math.floor(b)!==b?(Re(b,m),new ae.ERR_OUT_OF_RANGE("offset","an integer",b)):f<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,b)}const Ve=/[^+/0-9A-Za-z-_]/g;function Jt(b){if(b=b.split("=")[0],b=b.trim().replace(Ve,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function St(b,f){f=f||1/0;let m;const S=b.length;let E=null;const M=[];for(let P=0;P<S;++P){if(m=b.charCodeAt(P),m>55295&&m<57344){if(!E){if(m>56319){(f-=3)>-1&&M.push(239,191,189);continue}else if(P+1===S){(f-=3)>-1&&M.push(239,191,189);continue}E=m;continue}if(m<56320){(f-=3)>-1&&M.push(239,191,189),E=m;continue}m=(E-55296<<10|m-56320)+65536}else E&&(f-=3)>-1&&M.push(239,191,189);if(E=null,m<128){if((f-=1)<0)break;M.push(m)}else if(m<2048){if((f-=2)<0)break;M.push(m>>6|192,m&63|128)}else if(m<65536){if((f-=3)<0)break;M.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((f-=4)<0)break;M.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return M}function fi(b){const f=[];for(let m=0;m<b.length;++m)f.push(b.charCodeAt(m)&255);return f}function Yi(b,f){let m,S,E;const M=[];for(let P=0;P<b.length&&!((f-=2)<0);++P)m=b.charCodeAt(P),S=m>>8,E=m%256,M.push(E),M.push(S);return M}function Ft(b){return e.toByteArray(Jt(b))}function ft(b,f,m,S){let E;for(E=0;E<S&&!(E+m>=f.length||E>=b.length);++E)f[E+m]=b[E];return E}function et(b,f){return b instanceof f||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===f.name}function Ki(b){return b!==b}const wr=(function(){const b="0123456789abcdef",f=new Array(256);for(let m=0;m<16;++m){const S=m*16;for(let E=0;E<16;++E)f[S+E]=b[m]+b[E]}return f})();function pt(b){return typeof BigInt>"u"?Ir:b}function Ir(){throw new Error("BigInt not supported")}})(wo)),wo}var hx=cx();const ux="https://api.anam.ai",dx="/v1",Mu={client:"js-sdk",version:"4.12.0"};var fx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Pu="https://api.anam.ai",Io="/v1";var Nt;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Nt||(Nt={}));let Ao=Pu,ku=Io,jt,Bu=!1;const px=(s,e=Io)=>{Ao=s,ku=e},mx=s=>{jt=s},gx=s=>{Bu=s};let Xt={sessionId:null,organizationId:null,attemptCorrelationId:null};const Gi=s=>{Xt=Object.assign(Object.assign({},Xt),s)},ui=(s,e,t)=>fx(void 0,void 0,void 0,function*(){if(!Bu)try{const i=Object.assign(Object.assign({},Mu),t);Xt.sessionId&&(i.sessionId=Xt.sessionId),Xt.organizationId&&(i.organizationId=Xt.organizationId),Xt.attemptCorrelationId&&(i.attemptCorrelationId=Xt.attemptCorrelationId);const r=`${ku}/metrics/client`;let n,o={"Content-Type":"application/json"};jt!=null&&jt.enabled&&(jt!=null&&jt.baseUrl)?(n=`${jt.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Ao}${r}`):n=`${Ao}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:e,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),_x=(s,e="console")=>{var t,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var p,d,g,_,y;const x={framesReceived:(p=u.framesReceived)!==null&&p!==void 0?p:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(y=u.packetsLost)!==null&&y!==void 0?y:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(x)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var p,d,g;const _={packetsReceived:(p=u.packetsReceived)!==null&&p!==void 0?p:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var p,d;const g={packetsSent:(p=u.packetsSent)!==null&&p!==void 0?p:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const p={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(p)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const p={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(p)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var $e;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})($e||($e={}));class Ne extends Error{constructor(e,t,i=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Ne.prototype),ui(Nt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:i})}}function Ou(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function yx(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Ye;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Ye||(Ye={}));var vt;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(vt||(vt={}));var Yt;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(Yt||(Yt={}));var _r;(function(s){s.USER="user",s.PERSONA="persona"})(_r||(_r={}));var oe;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(oe||(oe={}));var Fe;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Fe||(Fe={}));var Kt;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Kt||(Kt={}));class bx{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const i={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Li=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const xx=5,vx=5;class Sx{constructor(e,t,i,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:p,url:d}=t;if(this.heartbeatIntervalSeconds=u||xx,this.maxWsReconnectionAttempts=p||vx,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const y=d.protocol||"https",x=y==="http"?"ws":"wss",v=`${y}://${d.baseUrl}`,C=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",T=new URL(v);T.protocol=x==="ws"?"ws:":"wss:",d.port&&(T.port=d.port),T.pathname=C,T.searchParams.append("session_id",e),this.url.searchParams.append("target_url",T.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Li(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},i={actionType:Ye.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return Li(this,void 0,void 0,function*(){const t={actionType:Ye.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Li(this,void 0,void 0,function*(){const t={actionType:Ye.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Ye.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Ye.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Li(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Fe.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Li(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Li(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Fe.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Ye.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},e)}}function Cx(s){return"brainType"in s||"llmId"in s}var Du=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Tx{constructor(e,t,i){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(i==null?void 0:i.baseUrl)||ux,this.apiVersion=(i==null?void 0:i.apiVersion)||dx,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Du(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Mu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",$e.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",$e.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Ne?i:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(e){return Du(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};Cx(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Ex=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class wx{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){return Ex(this,void 0,void 0,function*(){var t,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Ix{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}class Ax{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(r=>r.id===t.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(oe.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case _r.USER:this.processUserMessage(t);break;case _r.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(oe.MESSAGE_HISTORY_UPDATED,this.messages)}}class Rx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===oe.CONNECTION_ESTABLISHED&&ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===oe.CONNECTION_CLOSED){const[i,r]=t;ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}var qe;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(qe||(qe={}));var Ro=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Mx{constructor(e,t,i){this.state=qe.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Ro(this,void 0,void 0,function*(){e.actionType===Ye.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=qe.INTERRUPTED,this.onDeactivate())})}endMessage(){return Ro(this,void 0,void 0,function*(){if(this.state===qe.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==qe.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=qe.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Ro(this,void 0,void 0,function*(){if(this.state!==qe.STREAMING&&this.state!==qe.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:e,startOfSpeech:this.state===qe.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?qe.ENDED:qe.STREAMING,this.state===qe.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===qe.STREAMING||this.state===qe.UNSTARTED}getState(){return this.state}}var Mo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Nu=(s,e)=>{if(isNaN(s)||isNaN(e))return 0;const t=e-s;return t>0?t:0};class Fu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,timestamp:i}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var st=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Px=15e3,kx=5e3,Bx=2;class Ox{constructor(e,t,i,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Fe.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new Sx(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new wx(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>st(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),kx))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Px);this.successMetricPoller=setInterval(()=>st(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let i=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(oe.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return st(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Mx(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new bx(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return st(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Bx}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Ye.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Ye.ICE_CANDIDATE:const i=e.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Ye.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Ye.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(oe.SERVER_WARNING,o);break;case Ye.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(oe.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Ye.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(oe.SESSION_READY,l);break;case Ye.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return st(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(oe.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(oe.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(oe.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(oe.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var i,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case vt.SPEECH_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case vt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Fe.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Fu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(oe.CLIENT_TOOL_EVENT_RECEIVED,c);break;case vt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case vt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case vt.TOOL_CALL_FAILED_EVENT:const p=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(p)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,p);break;case vt.REASONING_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case vt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(oe.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case vt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(oe.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return st(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==Yt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.PENDING}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.GRANTED}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(oe.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return st(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(oe.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return st(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return st(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const i=_x(t,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Dx{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(oe.REASONING_STREAM_EVENT_RECEIVED,t);const i={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(oe.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var qt=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Nx{constructor(e,t,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,i);if(c)throw new Ne(c,$e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&px(i.api.baseUrl||Pu,i.api.apiVersion||Io),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&mx(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&gx(!0),this.publicEventEmitter=new Rx,this.internalEventEmitter=new Ix,this.toolCallManager=new Fu(this.publicEventEmitter),this.apiClient=new Tx(e,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new Ax(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Dx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],i=hx.Buffer.from(t,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,i){var r,n;if(!e&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=yx((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,Gi({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return qt(this,void 0,void 0,function*(){var t,i,r,n,o,a,l,c,h,u,p,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),y=yield this.apiClient.startSession(g,_),{sessionId:x,clientConfig:v,engineHost:C,engineProtocol:T,signallingEndpoint:A}=y,{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,iceServers:D}=v;this.sessionId=x,Gi({sessionId:this.sessionId});const B=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new Ox(x,{engine:{baseUrl:`${T}://${C}`},signalling:{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,url:{baseUrl:C,protocol:T,signallingPath:A}},iceServers:B,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(p=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||p===void 0?void 0:p.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Gi({sessionId:null}),new Ne("Failed to initialize streaming client",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:x})}return x})}startSessionIfNeeded(e){return qt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return qt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const i=Ou();return Gi({attemptCorrelationId:i,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(oe.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(oe.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return qt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return qt(this,void 0,void 0,function*(){var i;const r=Ou();Gi({attemptCorrelationId:r,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return qt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:i,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return qt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Gi({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return qt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Fx=(s,e)=>new Nx(s,void 0,e);let Gx=0;class Lx{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.client=Fx(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++Gx}`;this.videoElement=document.createElement("video"),this.videoElement.id=t,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.videoElement.style.display="none",document.body.appendChild(this.videoElement),this.client.addListener(oe.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(oe.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&((i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(oe.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(oe.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(t),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(t){const i=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",i.message),(e=this.onError)==null||e.call(this,i),this.close(),i}}sendAudioChunk(e){var t;(t=this.audioInputStream)==null||t.sendAudioChunk(e)}endSequence(){var e;(e=this.audioInputStream)==null||e.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),this.audioInputStream=null,this._connected=!1}}}const Ux=new Set(["a","button","input","select","textarea","details","summary","label","option"]),Wx=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),Hx=new Set(["h1","h2","h3","h4","h5","h6"]),Vx=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class zx{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let e=0;const t=[];t.push(`Page: ${document.title}`),t.push(`URL: ${location.href}`),t.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const c=(r.textContent??"").trim();c&&c.length>1&&t.push(c);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=Hx.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",p=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${p}`)}else t.push(`[${c}]<${o}${u}>${p}</${o}>`);return}for(const c of n.childNodes)i(c)};return i(document.body),{text:t.join(`
|
|
938
|
+
`),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){if(e.offsetWidth===0&&e.offsetHeight===0){const i=e.getBoundingClientRect();if(i.width===0&&i.height===0)return!1}const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden"||t.opacity==="0")}isInteractive(e){const t=e.tagName.toLowerCase();if(Ux.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&Wx.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of Vx){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const $x=new Set(["scroll_to","click","highlight"]);class jx{constructor(e){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const{text:i}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${i.length} chars, instruction: "${t}"`);const n=(await qd(this.staffId,i,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${n.length} actions:`,n);const o=[];for(const a of n){if(a.action==="describe"){o.push({action:"describe",status:"ok",description:a.description});continue}if($x.has(a.action)&&!await this.confirmationPrompt.ask(`${a.description}?`)){o.push({action:a.action,status:"declined",description:"Visitor declined"});continue}let l;switch(a.action){case"scroll_to":l=this.pageActions.scrollTo(a.index);break;case"highlight":l=this.pageActions.highlight(a.index);break;case"click":l=this.pageActions.click(a.index);break;case"fill":l=this.pageActions.fill(a.index,a.value??"");break;default:l={status:"error",description:`Unknown action: ${a.action}`}}o.push({action:a.action,...l})}this.sendToolResult(e,{results:o})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class Xx{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});const i=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${i}`),{status:"scrolled",description:i}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class Yx{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}class Kx{constructor(){this.activeHighlights=[]}highlight(e,t=3e3){const i=e.getBoundingClientRect(),r=document.createElement("div");Object.assign(r.style,{position:"fixed",left:`${i.left-4}px`,top:`${i.top-4}px`,width:`${i.width+8}px`,height:`${i.height+8}px`,border:"3px solid #4a6fa5",borderRadius:"8px",boxShadow:"0 0 12px rgba(74, 111, 165, 0.5)",pointerEvents:"none",zIndex:"2147483645",animation:"hs-highlight-pulse 1.2s ease-in-out infinite",transition:"opacity 0.3s ease"}),this.ensureKeyframes(),document.body.appendChild(r),this.activeHighlights.push(r);const n=()=>{const o=e.getBoundingClientRect();r.style.left=`${o.left-4}px`,r.style.top=`${o.top-4}px`,r.style.width=`${o.width+8}px`,r.style.height=`${o.height+8}px`};window.addEventListener("scroll",n,{passive:!0}),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>{r.remove(),window.removeEventListener("scroll",n),this.activeHighlights=this.activeHighlights.filter(o=>o!==r)},300)},t)}clearAll(){for(const e of this.activeHighlights)e.remove();this.activeHighlights=[]}ensureKeyframes(){if(document.getElementById("hs-highlight-keyframes"))return;const e=document.createElement("style");e.id="hs-highlight-keyframes",e.textContent=`
|
|
939
939
|
@keyframes hs-highlight-pulse {
|
|
940
940
|
0%, 100% { box-shadow: 0 0 8px rgba(74, 111, 165, 0.4); border-color: #4a6fa5; }
|
|
941
941
|
50% { box-shadow: 0 0 20px rgba(74, 111, 165, 0.8); border-color: #6b8fc5; }
|
|
942
942
|
}
|
|
943
|
-
`,document.head.appendChild(
|
|
943
|
+
`,document.head.appendChild(e)}}const qx=1e4;class Zx{constructor(){this.container=null}ask(e){return new Promise(t=>{this.dismiss(),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"300px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",background:"rgba(255, 255, 255, 0.97)",border:"1.5px solid #c8d0da",borderRadius:"16px",padding:"14px 18px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.12)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"13px",color:"#2a2a3e",display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"280px",textAlign:"center",animation:"hs-confirm-in 0.25s ease-out"}),this.ensureKeyframes(),this.container.setAttribute("role","alertdialog"),this.container.setAttribute("aria-label","Confirm action");const i=document.createElement("div");i.textContent=e,i.style.lineHeight="1.4",this.container.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"8px",width:"100%"});const n=this.createButton("Yes","#4a6fa5","#ffffff"),o=this.createButton("No","#e8ecf0","#2a2a3e");r.appendChild(n),r.appendChild(o),this.container.appendChild(r),document.body.appendChild(this.container);let a=!1;const l=h=>{a||(a=!0,clearTimeout(c),this.dismiss(),t(h))};n.addEventListener("click",()=>l(!0)),o.addEventListener("click",()=>l(!1));const c=setTimeout(()=>l(!1),qx)})}dismiss(){this.container&&(this.container.remove(),this.container=null)}createButton(e,t,i){const r=document.createElement("button");return r.textContent=e,Object.assign(r.style,{flex:"1",padding:"8px 0",border:"none",borderRadius:"10px",background:t,color:i,fontSize:"13px",fontWeight:"600",cursor:"pointer",transition:"opacity 0.15s"}),r.addEventListener("mouseenter",()=>{r.style.opacity="0.85"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1"}),r}ensureKeyframes(){if(document.getElementById("hs-confirm-keyframes"))return;const e=document.createElement("style");e.id="hs-confirm-keyframes",e.textContent=`
|
|
944
944
|
@keyframes hs-confirm-in {
|
|
945
945
|
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
|
|
946
946
|
to { opacity: 1; transform: translateX(-50%) translateY(0); }
|
|
947
947
|
}
|
|
948
|
-
`,document.head.appendChild(t)}}const Ix=15e3,Px=320;function Mx(){return Math.min(300,window.innerWidth-32)}class kx{constructor(){this.cards=[]}showTextCard(t,e){const i=this.createCard();if(t){const r=document.createElement("div");r.textContent=t,Object.assign(r.style,{fontWeight:"700",fontSize:"14px",marginBottom:"6px",color:"#1a1a2e"}),i.appendChild(r)}if(e){const r=document.createElement("div");r.textContent=e,Object.assign(r.style,{fontSize:"13px",lineHeight:"1.5",color:"#3a3a4e",whiteSpace:"pre-wrap"}),i.appendChild(r)}this.mount(i)}showImageCard(t,e){const i=this.createCard(),r=document.createElement("img");if(r.src=t,r.alt=e??"",Object.assign(r.style,{width:"100%",borderRadius:"8px",marginBottom:e?"8px":"0",display:"block"}),i.appendChild(r),e){const n=document.createElement("div");n.textContent=e,Object.assign(n.style,{fontSize:"12px",color:"#6a6a7e",textAlign:"center"}),i.appendChild(n)}this.mount(i)}showBulletList(t,e){const i=this.createCard();if(t){const n=document.createElement("div");n.textContent=t,Object.assign(n.style,{fontWeight:"700",fontSize:"14px",marginBottom:"8px",color:"#1a1a2e"}),i.appendChild(n)}const r=document.createElement("ul");Object.assign(r.style,{margin:"0",paddingLeft:"18px",fontSize:"13px",lineHeight:"1.6",color:"#3a3a4e"});for(const n of e){const o=document.createElement("li");o.textContent=n,o.style.marginBottom="4px",r.appendChild(o)}i.appendChild(r),this.mount(i)}dismissAll(){for(const t of[...this.cards])this.removeCard(t)}createCard(){var i,r;const t=document.createElement("div");Object.assign(t.style,{position:"fixed",maxWidth:`${Mx()}px`,padding:"14px 16px",background:"rgba(255, 255, 255, 0.92)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(200, 208, 218, 0.6)",borderRadius:"16px",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.10)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',zIndex:"2147483645",opacity:"0",transform:"translateY(12px)",transition:(r=(i=globalThis.matchMedia)==null?void 0:i.call(globalThis,"(prefers-reduced-motion: reduce)"))!=null&&r.matches?"none":"opacity 0.3s ease, transform 0.3s ease",pointerEvents:"auto"});const e=document.createElement("button");return e.textContent="×",Object.assign(e.style,{position:"absolute",top:"6px",right:"8px",background:"none",border:"none",fontSize:"18px",color:"#9a9ab0",cursor:"pointer",lineHeight:"1",padding:"2px 4px"}),e.addEventListener("click",()=>this.removeCard(t)),t.appendChild(e),t}mount(t){const e=this.cards.length,i=Px+e*10;t.style.bottom=`${i}px`,t.style.left="50%",t.style.transform="translateX(-50%) translateY(12px)",document.body.appendChild(t),this.cards.push(t),requestAnimationFrame(()=>{t.style.opacity="1",t.style.transform="translateX(-50%) translateY(0)"});const r=setTimeout(()=>this.removeCard(t),Ix);t._dismissTimer=r}removeCard(t){clearTimeout(t._dismissTimer),t.style.opacity="0",t.style.transform="translateX(-50%) translateY(12px)",setTimeout(()=>{t.remove(),this.cards=this.cards.filter(e=>e!==t)},300)}}class Bx{constructor(){this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.onMinimize=null,this.onRestore=null,this.onClose=null,this.minimized=!1}show(){this.container||(this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"8px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",gap:"6px",opacity:"0",transition:"opacity 0.3s ease"}),this.minimizeBtn=this.createButton("–","Minimize conversation"),this.closeBtn=this.createButton("×","Close conversation"),this.minimizeBtn.addEventListener("click",()=>{var t,e;this.minimized?(this.minimized=!1,this.minimizeBtn.textContent="–",this.minimizeBtn.title="Minimize",(t=this.onRestore)==null||t.call(this)):(this.minimized=!0,this.minimizeBtn.textContent="□",this.minimizeBtn.title="Restore",(e=this.onMinimize)==null||e.call(this))}),this.closeBtn.addEventListener("click",()=>{var t;(t=this.onClose)==null||t.call(this)}),this.container.appendChild(this.minimizeBtn),this.container.appendChild(this.closeBtn),document.body.appendChild(this.container),requestAnimationFrame(()=>{this.container&&(this.container.style.opacity="1")}))}hide(){this.container&&(this.container.remove(),this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.minimized=!1)}createButton(t,e){const i=document.createElement("button");return i.textContent=t,i.title=e,i.setAttribute("aria-label",e),Object.assign(i.style,{width:"28px",height:"28px",borderRadius:"50%",border:"1px solid rgba(200, 208, 218, 0.6)",background:"rgba(255, 255, 255, 0.85)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",color:"#4a4a6a",fontSize:"14px",fontWeight:"700",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",lineHeight:"1",transition:"background 0.15s, transform 0.15s",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"}),i.addEventListener("mouseenter",()=>{i.style.background="rgba(240, 242, 245, 0.95)",i.style.transform="scale(1.1)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(255, 255, 255, 0.85)",i.style.transform="scale(1)"}),i}}const Ox="https://us-central1-holostaff-ai.cloudfunctions.net";class Dx{constructor(t){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=t.staffId,this.staffName=t.staffName,this.backendUrl=t.backendUrl??Ox,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(t){if(!t.trim())return;const e=`msg_${this.msgCounter++}`;this.messages[e]={sender:"user",text:t.trim(),timestamp:new Date().toISOString()}}addStaffMessage(t){if(!t.trim())return;const e=`msg_${this.msgCounter++}`;this.messages[e]={sender:"staff",text:t.trim(),timestamp:new Date().toISOString()}}addAction(t,e){this.actions.push({tool:t,args:e,timestamp:new Date().toISOString()})}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const t=Object.values(this.messages).pop(),e={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(t==null?void 0:t.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});try{const i=await fetch(`${this.backendUrl}/logConversation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.ok){const r=await i.json();console.log("[Logger] Conversation logged:",r.id)}else console.warn("[Logger] Failed to log conversation:",i.status)}catch(i){console.warn("[Logger] Error logging conversation:",i)}}}const Gx=8,Ux=800,Lx=600*1e3,Nx=540*1e3,eu=60*1e3,Fx=90*1e3,Hx=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class iu{constructor(t,e){this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.highlightRenderer=null,this.confirmationPrompt=null,this.overlayRenderer=null,this.controls=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.config=t,this.widgetPrompts=e??null}async init(){this.stage=new _y,await this.stage.init(),this.avatar=new yy(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.bubble=new Iy(this.stage.app.ticker,this.widgetPrompts??void 0),this.bubble.container.x=0,this.bubble.container.y=-de-Gx,this.avatar.container.addChild(this.bubble.container),this.avatar.setInteractive(()=>this.onAvatarClick()),this.bubble.onClick(()=>this.onAvatarClick()),this.setupTrigger(),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger})}async loadIdleAsset(){if(this.avatar){if(this.idleVideoUrl)try{await this.avatar.loadIdleVideo(this.idleVideoUrl);return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(t){this.idleVideoUrl=t}setIdleImage(t){this.idleImageUrl=t}setupTrigger(){switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const t=window.scrollY,e=document.documentElement.scrollHeight-window.innerHeight,i=e>0?t/e:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var t;return(t=this.bubble)==null?void 0:t.start()},Ux))}hideTeaser(){var t;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(t=this.bubble)==null||t.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var t;if(this.state==="teasing"){this.state="connecting",(t=this.bubble)==null||t.stop(),console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await wu(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new Dx({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),this.showControls(),this.startSessionTimers(),console.log("[HolostaffWidget] Conversation active")}catch(e){console.error("[HolostaffWidget] Failed to start conversation:",e),this.endConversation()}}}async connectAnam(){this.sessionResponse&&(this.anamSession=new gx({sessionToken:this.sessionResponse.anamSessionToken}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=t=>{console.log("[HolostaffWidget] Anam avatar video ready"),this.avatar&&this.stage&&this.avatar.setLiveVideo(t,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=t=>{console.log("[HolostaffWidget] Anam disconnected:",t),this.endConversation()},this.anamSession.onError=t=>{console.error("[HolostaffWidget] Anam error:",t.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){if(!this.sessionResponse)return;const t=(this.sessionResponse.staff.instructions??"")+`
|
|
948
|
+
`,document.head.appendChild(e)}}const Jx=15e3,Qx=320;function ev(){return Math.min(300,window.innerWidth-32)}class tv{constructor(){this.cards=[]}showTextCard(e,t){const i=this.createCard();if(e){const r=document.createElement("div");r.textContent=e,Object.assign(r.style,{fontWeight:"700",fontSize:"14px",marginBottom:"6px",color:"#1a1a2e"}),i.appendChild(r)}if(t){const r=document.createElement("div");r.textContent=t,Object.assign(r.style,{fontSize:"13px",lineHeight:"1.5",color:"#3a3a4e",whiteSpace:"pre-wrap"}),i.appendChild(r)}this.mount(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t??"",Object.assign(r.style,{width:"100%",borderRadius:"8px",marginBottom:t?"8px":"0",display:"block"}),i.appendChild(r),t){const n=document.createElement("div");n.textContent=t,Object.assign(n.style,{fontSize:"12px",color:"#6a6a7e",textAlign:"center"}),i.appendChild(n)}this.mount(i)}showBulletList(e,t){const i=this.createCard();if(e){const n=document.createElement("div");n.textContent=e,Object.assign(n.style,{fontWeight:"700",fontSize:"14px",marginBottom:"8px",color:"#1a1a2e"}),i.appendChild(n)}const r=document.createElement("ul");Object.assign(r.style,{margin:"0",paddingLeft:"18px",fontSize:"13px",lineHeight:"1.6",color:"#3a3a4e"});for(const n of t){const o=document.createElement("li");o.textContent=n,o.style.marginBottom="4px",r.appendChild(o)}i.appendChild(r),this.mount(i)}dismissAll(){for(const e of[...this.cards])this.removeCard(e)}createCard(){var i,r;const e=document.createElement("div");Object.assign(e.style,{position:"fixed",maxWidth:`${ev()}px`,padding:"14px 16px",background:"rgba(255, 255, 255, 0.92)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(200, 208, 218, 0.6)",borderRadius:"16px",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.10)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',zIndex:"2147483645",opacity:"0",transform:"translateY(12px)",transition:(r=(i=globalThis.matchMedia)==null?void 0:i.call(globalThis,"(prefers-reduced-motion: reduce)"))!=null&&r.matches?"none":"opacity 0.3s ease, transform 0.3s ease",pointerEvents:"auto"});const t=document.createElement("button");return t.textContent="×",Object.assign(t.style,{position:"absolute",top:"6px",right:"8px",background:"none",border:"none",fontSize:"18px",color:"#9a9ab0",cursor:"pointer",lineHeight:"1",padding:"2px 4px"}),t.addEventListener("click",()=>this.removeCard(e)),e.appendChild(t),e}mount(e){const t=this.cards.length,i=Qx+t*10;e.style.bottom=`${i}px`,e.style.left="50%",e.style.transform="translateX(-50%) translateY(12px)",document.body.appendChild(e),this.cards.push(e),requestAnimationFrame(()=>{e.style.opacity="1",e.style.transform="translateX(-50%) translateY(0)"});const r=setTimeout(()=>this.removeCard(e),Jx);e._dismissTimer=r}removeCard(e){clearTimeout(e._dismissTimer),e.style.opacity="0",e.style.transform="translateX(-50%) translateY(12px)",setTimeout(()=>{e.remove(),this.cards=this.cards.filter(t=>t!==e)},300)}}class iv{constructor(){this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.onMinimize=null,this.onRestore=null,this.onClose=null,this.minimized=!1}show(){this.container||(this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"8px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",gap:"6px",opacity:"0",transition:"opacity 0.3s ease"}),this.minimizeBtn=this.createButton("–","Minimize conversation"),this.closeBtn=this.createButton("×","Close conversation"),this.minimizeBtn.addEventListener("click",()=>{var e,t;this.minimized?(this.minimized=!1,this.minimizeBtn.textContent="–",this.minimizeBtn.title="Minimize",(e=this.onRestore)==null||e.call(this)):(this.minimized=!0,this.minimizeBtn.textContent="□",this.minimizeBtn.title="Restore",(t=this.onMinimize)==null||t.call(this))}),this.closeBtn.addEventListener("click",()=>{var e;(e=this.onClose)==null||e.call(this)}),this.container.appendChild(this.minimizeBtn),this.container.appendChild(this.closeBtn),document.body.appendChild(this.container),requestAnimationFrame(()=>{this.container&&(this.container.style.opacity="1")}))}hide(){this.container&&(this.container.remove(),this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.minimized=!1)}createButton(e,t){const i=document.createElement("button");return i.textContent=e,i.title=t,i.setAttribute("aria-label",t),Object.assign(i.style,{width:"28px",height:"28px",borderRadius:"50%",border:"1px solid rgba(200, 208, 218, 0.6)",background:"rgba(255, 255, 255, 0.85)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",color:"#4a4a6a",fontSize:"14px",fontWeight:"700",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",lineHeight:"1",transition:"background 0.15s, transform 0.15s",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"}),i.addEventListener("mouseenter",()=>{i.style.background="rgba(240, 242, 245, 0.95)",i.style.transform="scale(1.1)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(255, 255, 255, 0.85)",i.style.transform="scale(1)"}),i}}const sv="https://us-central1-holostaff-ai.cloudfunctions.net";class rv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??sv,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"user",text:e.trim(),timestamp:new Date().toISOString()}}addStaffMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"staff",text:e.trim(),timestamp:new Date().toISOString()}}addAction(e,t){this.actions.push({tool:e,args:t,timestamp:new Date().toISOString()})}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const e=Object.values(this.messages).pop(),t={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(e==null?void 0:e.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});try{const i=await fetch(`${this.backendUrl}/logConversation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok){const r=await i.json();console.log("[Logger] Conversation logged:",r.id)}else console.warn("[Logger] Failed to log conversation:",i.status)}catch(i){console.warn("[Logger] Error logging conversation:",i)}}}var He;(function(s){s[s.Document=0]="Document",s[s.DocumentType=1]="DocumentType",s[s.Element=2]="Element",s[s.Text=3]="Text",s[s.CDATA=4]="CDATA",s[s.Comment=5]="Comment"})(He||(He={}));function nv(s){return s.nodeType===s.ELEMENT_NODE}function Is(s){var e=s==null?void 0:s.host;return(e==null?void 0:e.shadowRoot)===s}function As(s){return Object.prototype.toString.call(s)==="[object ShadowRoot]"}function ov(s){return s.includes(" background-clip: text;")&&!s.includes(" -webkit-background-clip: text;")&&(s=s.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),s}function Po(s){try{var e=s.rules||s.cssRules;return e?ov(Array.from(e).map(Gu).join("")):null}catch{return null}}function Gu(s){var e=s.cssText;if(av(s))try{e=Po(s.styleSheet)||e}catch{}return e}function av(s){return"styleSheet"in s}var Lu=(function(){function s(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return s.prototype.getId=function(e){var t;if(!e)return-1;var i=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return i??-1},s.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},s.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},s.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},s.prototype.removeNodeFromMap=function(e){var t=this,i=this.getId(e);this.idNodeMap.delete(i),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},s.prototype.has=function(e){return this.idNodeMap.has(e)},s.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},s.prototype.add=function(e,t){var i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)},s.prototype.replace=function(e,t){var i=this.getNode(e);if(i){var r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},s.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},s})();function lv(){return new Lu}function ko(s){var e=s.maskInputOptions,t=s.tagName,i=s.type,r=s.value,n=s.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[i])&&(n?o=n(o):o="*".repeat(o.length)),o}var Uu="__rrweb_original__";function cv(s){var e=s.getContext("2d");if(!e)return!0;for(var t=50,i=0;i<s.width;i+=t)for(var r=0;r<s.height;r+=t){var n=e.getImageData,o=Uu in n?n[Uu]:n,a=new Uint32Array(o.call(e,i,r,Math.min(t,s.width-i),Math.min(t,s.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var hv=1,uv=new RegExp("[^a-z0-9-_:]"),Rs=-2;function Wu(){return hv++}function dv(s){if(s instanceof HTMLFormElement)return"form";var e=s.tagName.toLowerCase().trim();return uv.test(e)?"div":e}function fv(s){return s.cssRules?Array.from(s.cssRules).map(function(e){return e.cssText||""}).join(""):""}function pv(s){var e="";return s.indexOf("//")>-1?e=s.split("/").slice(0,3).join("/"):e=s.split("/")[0],e=e.split("?")[0],e}var Ui,Hu,mv=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,gv=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,_v=/^(data:)([^,]*),(.*)/i;function yr(s,e){return(s||"").replace(mv,function(t,i,r,n,o,a){var l=r||o||a,c=i||n||"";if(!l)return t;if(!gv.test(l)||_v.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(pv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var p=0,d=u;p<d.length;p++){var g=d[p];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var yv=/^[^ \t\n\r\u000c]+/,bv=/^[, \t\n\r\u000c]+/;function xv(s,e){if(e.trim()==="")return e;var t=0;function i(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];i(bv),!(t>=e.length);){var n=i(yv);if(n.slice(-1)===",")n=Wi(s,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Wi(s,n);for(var a=!1;;){var l=e.charAt(t);if(l===""){r.push((n+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((n+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Wi(s,e){if(!e||e.trim()==="")return e;var t=s.createElement("a");return t.href=e,t.href}function vv(s){return!!(s.tagName==="svg"||s.ownerSVGElement)}function Bo(){var s=document.createElement("a");return s.href="",s.href}function Vu(s,e,t,i){return t==="src"||t==="href"&&i&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i&&i[0]!=="#"||t==="background"&&i&&(e==="table"||e==="td"||e==="th")?Wi(s,i):t==="srcset"&&i?xv(s,i):t==="style"&&i?yr(i,Bo()):e==="object"&&t==="data"&&i?Wi(s,i):i}function Sv(s,e,t){if(typeof e=="string"){if(s.classList.contains(e))return!0}else for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?s.matches(t):!1}function br(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?br(s.parentNode,e,t):!1;for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?br(s.parentNode,e,t):!1}function zu(s,e,t){var i=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(i===null)return!1;if(typeof e=="string"){if(i.classList.contains(e)||i.closest(".".concat(e)))return!0}else if(br(i,e,!0))return!0;return!!(t&&(i.matches(t)||i.closest(t)))}function Cv(s,e,t){var i=s.contentWindow;if(i){var r=!1,n;try{n=i.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);s.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(i.location.href!==a||s.src===a||s.src==="")return setTimeout(e,0),s.addEventListener("load",e);s.addEventListener("load",e)}}function Tv(s,e,t){var i=!1,r;try{r=s.sheet}catch{return}if(!r){var n=setTimeout(function(){i||(e(),i=!0)},t);s.addEventListener("load",function(){clearTimeout(n),i=!0,e()})}}function Ev(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.inlineStylesheet,c=e.maskInputOptions,h=c===void 0?{}:c,u=e.maskTextFn,p=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,y=e.recordCanvas,x=e.keepIframeSrcFn,v=e.newlyAddedElement,C=v===void 0?!1:v,T=wv(t,i);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!=="CSS1Compat"?{type:He.Document,childNodes:[],compatMode:s.compatMode}:{type:He.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:He.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:T};case s.ELEMENT_NODE:return Av(s,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:p,dataURLOptions:g,inlineImages:_,recordCanvas:y,keepIframeSrcFn:x,newlyAddedElement:C,rootId:T});case s.TEXT_NODE:return Iv(s,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:T});case s.CDATA_SECTION_NODE:return{type:He.CDATA,textContent:"",rootId:T};case s.COMMENT_NODE:return{type:He.Comment,textContent:s.textContent||"",rootId:T};default:return!1}}function wv(s,e){if(e.hasNode(s)){var t=e.getId(s);return t===1?void 0:t}}function Iv(s,e){var t,i=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=s.parentNode&&s.parentNode.tagName,l=s.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{s.nextSibling||s.previousSibling||!((t=s.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=fv(s.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),s)}l=yr(l,Bo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&zu(s,i,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:He.Text,textContent:l||"",isStyle:c,rootId:o}}function Av(s,e){for(var t=e.doc,i=e.blockClass,r=e.blockSelector,n=e.inlineStylesheet,o=e.maskInputOptions,a=o===void 0?{}:o,l=e.maskInputFn,c=e.dataURLOptions,h=c===void 0?{}:c,u=e.inlineImages,p=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,y=e.rootId,x=Sv(s,i,r),v=dv(s),C={},T=s.attributes.length,A=0;A<T;A++){var w=s.attributes[A];C[w.name]=Vu(t,v,w.name,w.value)}if(v==="link"&&n){var R=Array.from(t.styleSheets).find(function(V){return V.href===s.href}),D=null;R&&(D=Po(R)),D&&(delete C.rel,delete C.href,C._cssText=yr(D,R.href))}if(v==="style"&&s.sheet&&!(s.innerText||s.textContent||"").trim().length){var D=Po(s.sheet);D&&(C._cssText=yr(D,Bo()))}if(v==="input"||v==="textarea"||v==="select"){var B=s.value,k=s.checked;C.type!=="radio"&&C.type!=="checkbox"&&C.type!=="submit"&&C.type!=="button"&&B?C.value=ko({type:C.type,tagName:v,value:B,maskInputOptions:a,maskInputFn:l}):k&&(C.checked=k)}if(v==="option"&&(s.selected&&!a.select?C.selected=!0:delete C.selected),v==="canvas"&&p){if(s.__context==="2d")cv(s)||(C.rr_dataURL=s.toDataURL(h.type,h.quality));else if(!("__context"in s)){var O=s.toDataURL(h.type,h.quality),G=document.createElement("canvas");G.width=s.width,G.height=s.height;var U=G.toDataURL(h.type,h.quality);O!==U&&(C.rr_dataURL=O)}}if(v==="img"&&u){Ui||(Ui=t.createElement("canvas"),Hu=Ui.getContext("2d"));var W=s,te=W.crossOrigin;W.crossOrigin="anonymous";var F=function(){try{Ui.width=W.naturalWidth,Ui.height=W.naturalHeight,Hu.drawImage(W,0,0),C.rr_dataURL=Ui.toDataURL(h.type,h.quality)}catch(V){console.warn("Cannot inline img src=".concat(W.currentSrc,"! Error: ").concat(V))}te?C.crossOrigin=te:W.removeAttribute("crossorigin")};W.complete&&W.naturalWidth!==0?F():W.onload=F}if((v==="audio"||v==="video")&&(C.rr_mediaState=s.paused?"paused":"played",C.rr_mediaCurrentTime=s.currentTime),_||(s.scrollLeft&&(C.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(C.rr_scrollTop=s.scrollTop)),x){var L=s.getBoundingClientRect(),X=L.width,N=L.height;C={class:C.class,rr_width:"".concat(X,"px"),rr_height:"".concat(N,"px")}}return v==="iframe"&&!d(C.src)&&(s.contentDocument||(C.rr_src=C.src),delete C.src),{type:He.Element,tagName:v,attributes:C,childNodes:[],isSVG:vv(s)||void 0,needBlock:x,rootId:y}}function Te(s){return s===void 0?"":s.toLowerCase()}function Rv(s,e){if(e.comment&&s.type===He.Comment)return!0;if(s.type===He.Element){if(e.script&&(s.tagName==="script"||s.tagName==="link"&&s.attributes.rel==="preload"&&s.attributes.as==="script"||s.tagName==="link"&&s.attributes.rel==="prefetch"&&typeof s.attributes.href=="string"&&s.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(s.tagName==="link"&&s.attributes.rel==="shortcut icon"||s.tagName==="meta"&&(Te(s.attributes.name).match(/^msapplication-tile(image|color)$/)||Te(s.attributes.name)==="application-name"||Te(s.attributes.rel)==="icon"||Te(s.attributes.rel)==="apple-touch-icon"||Te(s.attributes.rel)==="shortcut icon")))return!0;if(s.tagName==="meta"){if(e.headMetaDescKeywords&&Te(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(Te(s.attributes.property).match(/^(og|twitter|fb):/)||Te(s.attributes.name).match(/^(og|twitter):/)||Te(s.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(Te(s.attributes.name)==="robots"||Te(s.attributes.name)==="googlebot"||Te(s.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&s.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(Te(s.attributes.name)==="author"||Te(s.attributes.name)==="generator"||Te(s.attributes.name)==="framework"||Te(s.attributes.name)==="publisher"||Te(s.attributes.name)==="progid"||Te(s.attributes.property).match(/^article:/)||Te(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(Te(s.attributes.name)==="google-site-verification"||Te(s.attributes.name)==="yandex-verification"||Te(s.attributes.name)==="csrf-token"||Te(s.attributes.name)==="p:domain_verify"||Te(s.attributes.name)==="verify-v1"||Te(s.attributes.name)==="verification"||Te(s.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Hi(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.skipChild,c=l===void 0?!1:l,h=e.inlineStylesheet,u=h===void 0?!0:h,p=e.maskInputOptions,d=p===void 0?{}:p,g=e.maskTextFn,_=e.maskInputFn,y=e.slimDOMOptions,x=e.dataURLOptions,v=x===void 0?{}:x,C=e.inlineImages,T=C===void 0?!1:C,A=e.recordCanvas,w=A===void 0?!1:A,R=e.onSerialize,D=e.onIframeLoad,B=e.iframeLoadTimeout,k=B===void 0?5e3:B,O=e.onStylesheetLoad,G=e.stylesheetLoadTimeout,U=G===void 0?5e3:G,W=e.keepIframeSrcFn,te=W===void 0?function(){return!1}:W,F=e.newlyAddedElement,L=F===void 0?!1:F,X=e.preserveWhiteSpace,N=X===void 0?!0:X,V=Ev(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:v,inlineImages:T,recordCanvas:w,keepIframeSrcFn:te,newlyAddedElement:L});if(!V)return console.warn(s,"not serialized"),null;var K;i.hasNode(s)?K=i.getId(s):Rv(V,y)||!N&&V.type===He.Text&&!V.isStyle&&!V.textContent.replace(/^\s+|\s+$/gm,"").length?K=Rs:K=Wu();var H=Object.assign(V,{id:K});if(i.add(s,H),K===Rs)return null;R&&R(s);var $=!c;if(H.type===He.Element){$=$&&!H.needBlock,delete H.needBlock;var se=s.shadowRoot;se&&As(se)&&(H.isShadowHost=!0)}if((H.type===He.Document||H.type===He.Element)&&$){y.headWhitespace&&H.type===He.Element&&H.tagName==="head"&&(N=!1);for(var ue={doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:v,inlineImages:T,recordCanvas:w,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:U,keepIframeSrcFn:te},z=0,Q=Array.from(s.childNodes);z<Q.length;z++){var ae=Q[z],j=Hi(ae,ue);j&&H.childNodes.push(j)}if(nv(s)&&s.shadowRoot)for(var _e=0,ee=Array.from(s.shadowRoot.childNodes);_e<ee.length;_e++){var ae=ee[_e],j=Hi(ae,ue);j&&(As(s.shadowRoot)&&(j.isShadow=!0),H.childNodes.push(j))}}return s.parentNode&&Is(s.parentNode)&&As(s.parentNode)&&(H.isShadow=!0),H.type===He.Element&&H.tagName==="iframe"&&Cv(s,function(){var le=s.contentDocument;if(le&&D){var Re=Hi(le,{doc:le,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:v,inlineImages:T,recordCanvas:w,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:U,keepIframeSrcFn:te});Re&&D(s,Re)}},k),H.type===He.Element&&H.tagName==="link"&&H.attributes.rel==="stylesheet"&&Tv(s,function(){if(O){var le=Hi(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:v,inlineImages:T,recordCanvas:w,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:U,keepIframeSrcFn:te});le&&O(s,le)}},U),H}function Mv(s,e){var t=e||{},i=t.mirror,r=i===void 0?new Lu:i,n=t.blockClass,o=n===void 0?"rr-block":n,a=t.blockSelector,l=a===void 0?null:a,c=t.maskTextClass,h=c===void 0?"rr-mask":c,u=t.maskTextSelector,p=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,y=_===void 0?!1:_,x=t.recordCanvas,v=x===void 0?!1:x,C=t.maskAllInputs,T=C===void 0?!1:C,A=t.maskTextFn,w=t.maskInputFn,R=t.slimDOM,D=R===void 0?!1:R,B=t.dataURLOptions,k=t.preserveWhiteSpace,O=t.onSerialize,G=t.onIframeLoad,U=t.iframeLoadTimeout,W=t.onStylesheetLoad,te=t.stylesheetLoadTimeout,F=t.keepIframeSrcFn,L=F===void 0?function(){return!1}:F,X=T===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:T===!1?{password:!0}:T,N=D===!0||D==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:D==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:D===!1?{}:D;return Hi(s,{doc:s,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:p,skipChild:!1,inlineStylesheet:g,maskInputOptions:X,maskTextFn:A,maskInputFn:w,slimDOMOptions:N,dataURLOptions:B,inlineImages:y,recordCanvas:v,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:G,iframeLoadTimeout:U,onStylesheetLoad:W,stylesheetLoadTimeout:te,keepIframeSrcFn:L,newlyAddedElement:!1})}function Ze(s,e,t=document){const i={capture:!0,passive:!0};return t.addEventListener(s,e,i),()=>t.removeEventListener(s,e,i)}const Vi=`Please stop import mirror directly. Instead of that,\r
|
|
949
|
+
now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
|
|
950
|
+
or you can use record.mirror to access the mirror instance during recording.`;let $u={map:{},getId(){return console.error(Vi),-1},getNode(){return console.error(Vi),null},removeNodeFromMap(){console.error(Vi)},has(){return console.error(Vi),!1},reset(){console.error(Vi)}};typeof window<"u"&&window.Proxy&&window.Reflect&&($u=new Proxy($u,{get(s,e,t){return e==="map"&&console.error(Vi),Reflect.get(s,e,t)}}));function Ms(s,e,t={}){let i=null,r=0;return function(...n){const o=Date.now();!r&&t.leading===!1&&(r=o);const a=e-(o-r),l=this;a<=0||a>e?(i&&(clearTimeout(i),i=null),r=o,s.apply(l,n)):!i&&t.trailing!==!1&&(i=setTimeout(()=>{r=t.leading===!1?0:Date.now(),i=null,s.apply(l,n)},a))}}function xr(s,e,t,i,r=window){const n=r.Object.getOwnPropertyDescriptor(s,e);return r.Object.defineProperty(s,e,i?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>xr(s,e,n||{},!0)}function zi(s,e,t){try{if(!(e in s))return()=>{};const i=s[e],r=t(i);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:i}})),s[e]=r,()=>{s[e]=i}}catch{return()=>{}}}function ju(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Xu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(s,e,t,i){if(!s)return!1;const r=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||i&&r.closest("."+e)!==null)return!0}else if(br(r,e,i))return!0;return!!(t&&(s.matches(t)||i&&r.closest(t)!==null))}function Pv(s,e){return e.getId(s)!==-1}function Oo(s,e){return e.getId(s)===Rs}function Yu(s,e){if(Is(s))return!1;const t=e.getId(s);return e.has(t)?s.parentNode&&s.parentNode.nodeType===s.DOCUMENT_NODE?!1:s.parentNode?Yu(s.parentNode,e):!0:!0}function Ku(s){return!!s.changedTouches}function kv(s=window){"NodeList"in s&&!s.NodeList.prototype.forEach&&(s.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in s&&!s.DOMTokenList.prototype.forEach&&(s.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...e)=>{let t=e[0];if(!(0 in e))throw new TypeError("1 argument is required");do if(this===t)return!0;while(t=t&&t.parentNode);return!1})}function qu(s,e){return!!(s.nodeName==="IFRAME"&&e.getMeta(s))}function Zu(s,e){return!!(s.nodeName==="LINK"&&s.nodeType===s.ELEMENT_NODE&&s.getAttribute&&s.getAttribute("rel")==="stylesheet"&&e.getMeta(s))}function Ju(s){return!!(s!=null&&s.shadowRoot)}class Bv{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(e){var t;return(t=this.styleIDMap.get(e))!==null&&t!==void 0?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let i;return t===void 0?i=this.id++:i=t,this.styleIDMap.set(e,i),this.idStyleMap.set(i,e),i}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}var ge=(s=>(s[s.DomContentLoaded=0]="DomContentLoaded",s[s.Load=1]="Load",s[s.FullSnapshot=2]="FullSnapshot",s[s.IncrementalSnapshot=3]="IncrementalSnapshot",s[s.Meta=4]="Meta",s[s.Custom=5]="Custom",s[s.Plugin=6]="Plugin",s))(ge||{}),fe=(s=>(s[s.Mutation=0]="Mutation",s[s.MouseMove=1]="MouseMove",s[s.MouseInteraction=2]="MouseInteraction",s[s.Scroll=3]="Scroll",s[s.ViewportResize=4]="ViewportResize",s[s.Input=5]="Input",s[s.TouchMove=6]="TouchMove",s[s.MediaInteraction=7]="MediaInteraction",s[s.StyleSheetRule=8]="StyleSheetRule",s[s.CanvasMutation=9]="CanvasMutation",s[s.Font=10]="Font",s[s.Log=11]="Log",s[s.Drag=12]="Drag",s[s.StyleDeclaration=13]="StyleDeclaration",s[s.Selection=14]="Selection",s[s.AdoptedStyleSheet=15]="AdoptedStyleSheet",s))(fe||{}),Do=(s=>(s[s.MouseUp=0]="MouseUp",s[s.MouseDown=1]="MouseDown",s[s.Click=2]="Click",s[s.ContextMenu=3]="ContextMenu",s[s.DblClick=4]="DblClick",s[s.Focus=5]="Focus",s[s.Blur=6]="Blur",s[s.TouchStart=7]="TouchStart",s[s.TouchMove_Departed=8]="TouchMove_Departed",s[s.TouchEnd=9]="TouchEnd",s[s.TouchCancel=10]="TouchCancel",s))(Do||{}),$i=(s=>(s[s["2D"]=0]="2D",s[s.WebGL=1]="WebGL",s[s.WebGL2=2]="WebGL2",s))($i||{});function Qu(s){return"__ln"in s}class Ov{constructor(){this.length=0,this.head=null}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let i=0;i<e;i++)t=(t==null?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&Qu(e.previousSibling)){const i=e.previousSibling.__ln.next;t.next=i,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,i&&(i.previous=t)}else if(e.nextSibling&&Qu(e.nextSibling)&&e.nextSibling.__ln.previous){const i=e.nextSibling.__ln.previous;t.previous=i,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,i&&(i.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next&&(t.next.previous=t.previous)):(this.head=t.next,this.head&&(this.head.previous=null)),e.__ln&&delete e.__ln,this.length--)}}const ed=(s,e)=>`${s}@${e}`;class Dv{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=e=>{e.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const e=[],t=new Ov,i=a=>{let l=a,c=Rs;for(;c===Rs;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let p=null;((c=(l=a.getRootNode)===null||l===void 0?void 0:l.call(a))===null||c===void 0?void 0:c.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&a.getRootNode().host&&(p=a.getRootNode().host);let d=p;for(;((u=(h=d==null?void 0:d.getRootNode)===null||h===void 0?void 0:h.call(d))===null||u===void 0?void 0:u.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&d.getRootNode().host;)d=d.getRootNode().host;const g=!this.doc.contains(a)&&(!d||!this.doc.contains(d));if(!a.parentNode||g)return;const _=Is(a.parentNode)?this.mirror.getId(p):this.mirror.getId(a.parentNode),y=i(a);if(_===-1||y===-1)return t.addNode(a);const x=Hi(a,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:v=>{qu(v,this.mirror)&&this.iframeManager.addIframe(v),Zu(v,this.mirror)&&this.stylesheetManager.trackLinkElement(v),Ju(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(v,C)=>{this.iframeManager.attachIframe(v,C),this.shadowDomManager.observeAttachShadow(v)},onStylesheetLoad:(v,C)=>{this.stylesheetManager.attachLinkElement(v,C)}});x&&e.push({parentId:_,nextId:y,node:x})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))td(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!sd(this.droppedSet,a)&&!td(this.removes,a,this.mirror)||sd(this.movedSet,a)?r(a):this.droppedSet.add(a);let n=null;for(;t.length;){let a=null;if(n){const l=this.mirror.getId(n.value.parentNode),c=i(n.value);l!==-1&&c!==-1&&(a=n)}if(!a)for(let l=t.length-1;l>=0;l--){const c=t.get(l);if(c){const h=this.mirror.getId(c.value.parentNode);if(i(c.value)===-1)continue;if(h!==-1){a=c;break}else{const p=c.value;if(p.parentNode&&p.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=p.parentNode.host;if(this.mirror.getId(d)!==-1){a=c;break}}}}}if(!a){for(;t.head;)t.removeNode(t.head.value);break}n=a.previous,t.removeNode(a.value),r(a.value)}const o={texts:this.texts.map(a=>({id:this.mirror.getId(a.node),value:a.value})).filter(a=>this.mirror.has(a.id)),attributes:this.attributes.map(a=>({id:this.mirror.getId(a.node),attributes:a.attributes})).filter(a=>this.mirror.has(a.id)),removes:this.removes,adds:e};!o.texts.length&&!o.attributes.length&&!o.removes.length&&!o.adds.length||(this.texts=[],this.attributes=[],this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(o))},this.processMutation=e=>{if(!Oo(e.target,this.mirror))switch(e.type){case"characterData":{const t=e.target.textContent;!Je(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:zu(e.target,this.maskTextClass,this.maskTextSelector)&&t?this.maskTextFn?this.maskTextFn(t):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let i=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(i=ko({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:i,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||i===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(i))if(!t.contentDocument)e.attributeName="rr_src";else return;if(r||(r={node:e.target,attributes:{}},this.attributes.push(r)),e.attributeName==="style"){const n=this.doc.createElement("span");e.oldValue&&n.setAttribute("style",e.oldValue),(r.attributes.style===void 0||r.attributes.style===null)&&(r.attributes.style={});const o=r.attributes.style;for(const a of Array.from(t.style)){const l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);(l!==n.style.getPropertyValue(a)||c!==n.style.getPropertyPriority(a))&&(c===""?o[a]=l:o[a]=[l,c])}for(const a of Array.from(n.style))t.style.getPropertyValue(a)===""&&(o[a]=!1)}else r.attributes[e.attributeName]=Vu(this.doc,t.tagName,e.attributeName,i);break}case"childList":{if(Je(e.target,this.blockClass,this.blockSelector,!0))return;e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const i=this.mirror.getId(t),r=Is(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Oo(t,this.mirror)||!Pv(t,this.mirror)||(this.addedSet.has(t)?(No(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&i===-1||Yu(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ed(i,r)]?No(this.movedSet,t):this.removes.push({parentId:r,id:i,isShadow:Is(e.target)&&As(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Oo(e,this.mirror))return;this.movedSet.add(e);let i=null;t&&this.mirror.hasNode(t)&&(i=this.mirror.getId(t)),i&&i!==-1&&(this.movedMap[ed(this.mirror.getId(e),i)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(i=>this.genAdds(i))}}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function No(s,e){s.delete(e),e.childNodes.forEach(t=>No(s,t))}function td(s,e,t){return s.length===0?!1:id(s,e,t)}function id(s,e,t){const{parentNode:i}=e;if(!i)return!1;const r=t.getId(i);return s.some(n=>n.id===r)?!0:id(s,i,t)}function sd(s,e){return s.size===0?!1:rd(s,e)}function rd(s,e){const{parentNode:t}=e;return t?s.has(t)?!0:rd(s,t):!1}const di=[],nd=typeof CSSGroupingRule<"u",od=typeof CSSMediaRule<"u",ad=typeof CSSSupportsRule<"u",ld=typeof CSSConditionRule<"u";function Ps(s){try{if("composedPath"in s){const e=s.composedPath();if(e.length)return e[0]}else if("path"in s&&s.path.length)return s.path[0];return s.target}catch{return s.target}}function cd(s,e){var t,i;const r=new Dv;di.push(r),r.init(s);let n=window.MutationObserver||window.__rrMutationObserver;const o=(i=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||i===void 0?void 0:i.call(t,"MutationObserver");o&&window[o]&&(n=window[o]);const a=new n(r.processMutations.bind(r));return a.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),a}function Nv({mousemoveCb:s,sampling:e,doc:t,mirror:i}){if(e.mousemove===!1)return()=>{};const r=typeof e.mousemove=="number"?e.mousemove:50,n=typeof e.mousemoveCallback=="number"?e.mousemoveCallback:500;let o=[],a;const l=Ms(u=>{const p=Date.now()-a;s(o.map(d=>(d.timeOffset-=p,d)),u),o=[],a=null},n),c=Ms(u=>{const p=Ps(u),{clientX:d,clientY:g}=Ku(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:i.getId(p),timeOffset:Date.now()-a}),l(typeof DragEvent<"u"&&u instanceof DragEvent?fe.Drag:u instanceof MouseEvent?fe.MouseMove:fe.TouchMove)},r,{trailing:!1}),h=[Ze("mousemove",c,t),Ze("touchmove",c,t),Ze("drag",c,t)];return()=>{h.forEach(u=>u())}}function Fv({mouseInteractionCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){if(n.mouseInteraction===!1)return()=>{};const o=n.mouseInteraction===!0||n.mouseInteraction===void 0?{}:n.mouseInteraction,a=[],l=c=>h=>{const u=Ps(h);if(Je(u,i,r,!0))return;const p=Ku(h)?h.changedTouches[0]:h;if(!p)return;const d=t.getId(u),{clientX:g,clientY:_}=p;s({type:Do[c],id:d,x:g,y:_})};return Object.keys(Do).filter(c=>Number.isNaN(Number(c))&&!c.endsWith("_Departed")&&o[c]!==!1).forEach(c=>{const h=c.toLowerCase(),u=l(c);a.push(Ze(h,u,e))}),()=>{a.forEach(c=>c())}}function hd({scrollCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){const o=Ms(a=>{const l=Ps(a);if(!l||Je(l,i,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;s({id:c,x:h.scrollLeft,y:h.scrollTop})}else s({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function Gv({viewportResizeCb:s}){let e=-1,t=-1;const i=Ms(()=>{const r=ju(),n=Xu();(e!==r||t!==n)&&(s({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",i,window)}function ud(s,e){const t=Object.assign({},s);return e||delete t.userTriggered,t}const Lv=["INPUT","TEXTAREA","SELECT"],dd=new WeakMap;function Uv({inputCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(x){let v=Ps(x);const C=x.isTrusted;if(v&&v.tagName==="OPTION"&&(v=v.parentElement),!v||!v.tagName||Lv.indexOf(v.tagName)<0||Je(v,i,r,!0))return;const T=v.type;if(v.classList.contains(n))return;let A=v.value,w=!1;T==="radio"||T==="checkbox"?w=v.checked:(o[v.tagName.toLowerCase()]||o[T])&&(A=ko({maskInputOptions:o,tagName:v.tagName,type:T,value:A,maskInputFn:a})),u(v,ud({text:A,isChecked:w,userTriggered:C},c));const R=v.name;T==="radio"&&R&&w&&e.querySelectorAll(`input[type="radio"][name="${R}"]`).forEach(D=>{D!==v&&u(D,ud({text:D.value,isChecked:!w,userTriggered:!1},c))})}function u(x,v){const C=dd.get(x);if(!C||C.text!==v.text||C.isChecked!==v.isChecked){dd.set(x,v);const T=t.getId(x);s(Object.assign(Object.assign({},v),{id:T}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(x=>Ze(x,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(x=>x())};const _=g.Object.getOwnPropertyDescriptor(g.HTMLInputElement.prototype,"value"),y=[[g.HTMLInputElement.prototype,"value"],[g.HTMLInputElement.prototype,"checked"],[g.HTMLSelectElement.prototype,"value"],[g.HTMLTextAreaElement.prototype,"value"],[g.HTMLSelectElement.prototype,"selectedIndex"],[g.HTMLOptionElement.prototype,"selected"]];return _&&_.set&&d.push(...y.map(x=>xr(x[0],x[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(x=>x())}}function vr(s){const e=[];function t(i,r){if(nd&&i.parentRule instanceof CSSGroupingRule||od&&i.parentRule instanceof CSSMediaRule||ad&&i.parentRule instanceof CSSSupportsRule||ld&&i.parentRule instanceof CSSConditionRule){const o=Array.from(i.parentRule.cssRules).indexOf(i);r.unshift(o)}else if(i.parentStyleSheet){const o=Array.from(i.parentStyleSheet.cssRules).indexOf(i);r.unshift(o)}return r}return t(s,e)}function Zt(s,e,t){let i,r;return s?(s.ownerNode?i=e.getId(s.ownerNode):r=t.getId(s),{styleId:r,id:i}):{}}function Wv({styleSheetRuleCb:s,mirror:e,stylesheetManager:t},{win:i}){const r=i.CSSStyleSheet.prototype.insertRule;i.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:p,styleId:d}=Zt(this,e,t.styleMirror);return(p&&p!==-1||d&&d!==-1)&&s({id:p,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=i.CSSStyleSheet.prototype.deleteRule;i.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:p}=Zt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&s({id:u,styleId:p,removes:[{index:h}]}),n.apply(this,[h])};let o;i.CSSStyleSheet.prototype.replace&&(o=i.CSSStyleSheet.prototype.replace,i.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:p}=Zt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&s({id:u,styleId:p,replace:h}),o.apply(this,[h])});let a;i.CSSStyleSheet.prototype.replaceSync&&(a=i.CSSStyleSheet.prototype.replaceSync,i.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:p}=Zt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&s({id:u,styleId:p,replaceSync:h}),a.apply(this,[h])});const l={};nd?l.CSSGroupingRule=i.CSSGroupingRule:(od&&(l.CSSMediaRule=i.CSSMediaRule),ld&&(l.CSSConditionRule=i.CSSConditionRule),ad&&(l.CSSSupportsRule=i.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(p,d){const{id:g,styleId:_}=Zt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&s({id:g,styleId:_,adds:[{rule:p,index:[...vr(this),d||0]}]}),c[h].insertRule.apply(this,[p,d])},u.prototype.deleteRule=function(p){const{id:d,styleId:g}=Zt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&s({id:d,styleId:g,removes:[{index:[...vr(this),p]}]}),c[h].deleteRule.apply(this,[p])}}),()=>{i.CSSStyleSheet.prototype.insertRule=r,i.CSSStyleSheet.prototype.deleteRule=n,o&&(i.CSSStyleSheet.prototype.replace=o),a&&(i.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function fd({mirror:s,stylesheetManager:e},t){var i,r,n;let o=null;t.nodeName==="#document"?o=s.getId(t):o=s.getId(t.host);const a=t.nodeName==="#document"?(i=t.defaultView)===null||i===void 0?void 0:i.Document:(n=(r=t.ownerDocument)===null||r===void 0?void 0:r.defaultView)===null||n===void 0?void 0:n.ShadowRoot,l=Object.getOwnPropertyDescriptor(a==null?void 0:a.prototype,"adoptedStyleSheets");return o===null||o===-1||!a||!l?()=>{}:(Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var c;return(c=l.get)===null||c===void 0?void 0:c.call(this)},set(c){var h;const u=(h=l.set)===null||h===void 0?void 0:h.call(this,c);if(o!==null&&o!==-1)try{e.adoptStyleSheets(c,o)}catch{}return u}}),()=>{Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})}function Hv({styleDeclarationCb:s,mirror:e,ignoreCSSAttributes:t,stylesheetManager:i},{win:r}){const n=r.CSSStyleDeclaration.prototype.setProperty;r.CSSStyleDeclaration.prototype.setProperty=function(a,l,c){var h;if(t.has(a))return n.apply(this,[a,l,c]);const{id:u,styleId:p}=Zt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,i.styleMirror);return(u&&u!==-1||p&&p!==-1)&&s({id:u,styleId:p,set:{property:a,value:l,priority:c},index:vr(this.parentRule)}),n.apply(this,[a,l,c])};const o=r.CSSStyleDeclaration.prototype.removeProperty;return r.CSSStyleDeclaration.prototype.removeProperty=function(a){var l;if(t.has(a))return o.apply(this,[a]);const{id:c,styleId:h}=Zt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,i.styleMirror);return(c&&c!==-1||h&&h!==-1)&&s({id:c,styleId:h,remove:{property:a},index:vr(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Vv({mediaInteractionCb:s,blockClass:e,blockSelector:t,mirror:i,sampling:r}){const n=a=>Ms(l=>{const c=Ps(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:p,playbackRate:d}=c;s({type:a,id:i.getId(c),currentTime:h,volume:u,muted:p,playbackRate:d})},r.media||500),o=[Ze("play",n(0)),Ze("pause",n(1)),Ze("seeked",n(2)),Ze("volumechange",n(3)),Ze("ratechange",n(4))];return()=>{o.forEach(a=>a())}}function zv({fontCb:s,doc:e}){const t=e.defaultView;if(!t)return()=>{};const i=[],r=new WeakMap,n=t.FontFace;t.FontFace=function(l,c,h){const u=new n(l,c,h);return r.set(u,{family:l,buffer:typeof c!="string",descriptors:h,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),u};const o=zi(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(s(c),r.delete(l))},0),a.apply(this,[l])}});return i.push(()=>{t.FontFace=n}),i.push(o),()=>{i.forEach(a=>a())}}function $v(s){const{doc:e,mirror:t,blockClass:i,blockSelector:r,selectionCb:n}=s;let o=!0;const a=()=>{const l=e.getSelection();if(!l||o&&(l!=null&&l.isCollapsed))return;o=l.isCollapsed||!1;const c=[],h=l.rangeCount||0;for(let u=0;u<h;u++){const p=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:y}=p;Je(d,i,r,!0)||Je(_,i,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:y})}n({ranges:c})};return a(),Ze("selectionchange",a)}function jv(s,e){const{mutationCb:t,mousemoveCb:i,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:p,selectionCb:d}=s;s.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},s.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),i(...g)},s.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},s.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},s.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},s.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},s.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},s.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},s.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},s.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},s.fontCb=(...g)=>{e.font&&e.font(...g),p(...g)},s.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function Xv(s,e={}){const t=s.doc.defaultView;if(!t)return()=>{};jv(s,e);const i=cd(s,s.doc),r=Nv(s),n=Fv(s),o=hd(s),a=Gv(s),l=Uv(s),c=Vv(s),h=Wv(s,{win:t}),u=fd(s,s.doc),p=Hv(s,{win:t}),d=s.collectFonts?zv(s):()=>{},g=$v(s),_=[];for(const y of s.plugins)_.push(y.observer(y.callback,t,y.options));return()=>{di.forEach(y=>y.reset()),i.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),p(),d(),g(),_.forEach(y=>y())}}class pd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,i,r){const n=i||this.getIdToRemoteIdMap(e),o=r||this.getRemoteIdToIdMap(e);let a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){const i=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,i,r))}getRemoteId(e,t,i){const r=i||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const i=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,i))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class Yv{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new pd(Wu),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new pd(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var i;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(i=this.loadListener)===null||i===void 0||i.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){if(e.data.type==="rrweb"){if(!e.source)return;const i=this.crossOriginIframeMap.get(e.source);if(!i)return;const r=this.transformCrossOriginEvent(i,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var i;switch(t.type){case ge.FullSnapshot:return this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e),{timestamp:t.timestamp,type:ge.IncrementalSnapshot,data:{source:fe.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case ge.Meta:case ge.Load:case ge.DomContentLoaded:return!1;case ge.Plugin:return t;case ge.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case ge.IncrementalSnapshot:switch(t.data.source){case fe.Mutation:return t.data.adds.forEach(r=>{this.replaceIds(r,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,e)}),t.data.removes.forEach(r=>{this.replaceIds(r,e,["parentId","id"])}),t.data.attributes.forEach(r=>{this.replaceIds(r,e,["id"])}),t.data.texts.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case fe.Drag:case fe.TouchMove:case fe.MouseMove:return t.data.positions.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case fe.ViewportResize:return!1;case fe.MediaInteraction:case fe.MouseInteraction:case fe.Scroll:case fe.CanvasMutation:case fe.Input:return this.replaceIds(t.data,e,["id"]),t;case fe.StyleSheetRule:case fe.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case fe.Font:return t;case fe.Selection:return t.data.ranges.forEach(r=>{this.replaceIds(r,e,["start","end"])}),t;case fe.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(i=t.data.styles)===null||i===void 0||i.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,i,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(i,t[n]):t[n]=e.getId(i,t[n]));return t}replaceIds(e,t,i){return this.replace(this.crossOriginIframeMirror,e,t,i)}replaceStyleIds(e,t,i){return this.replace(this.crossOriginIframeStyleMirror,e,t,i)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(i=>{this.replaceIdOnNode(i,t)})}}class Kv{constructor(e){this.shadowDoms=new WeakSet,this.restorePatches=[],this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror;const t=this;this.restorePatches.push(zi(Element.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){As(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),cd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),hd(Object.assign(Object.assign({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(e.host)),fd({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(zi(e.contentWindow.HTMLElement.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
|
|
951
|
+
Copyright (c) Microsoft Corporation.
|
|
952
|
+
|
|
953
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
954
|
+
purpose with or without fee is hereby granted.
|
|
955
|
+
|
|
956
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
957
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
958
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
959
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
960
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
961
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
962
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
963
|
+
***************************************************************************** */function qv(s,e){var t={};for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(s);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(s,i[r])&&(t[i[r]]=s[i[r]]);return t}function Zv(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,[])).next())})}for(var ji="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jv=typeof Uint8Array>"u"?[]:new Uint8Array(256),Sr=0;Sr<ji.length;Sr++)Jv[ji.charCodeAt(Sr)]=Sr;var Qv=function(s){var e=new Uint8Array(s),t,i=e.length,r="";for(t=0;t<i;t+=3)r+=ji[e[t]>>2],r+=ji[(e[t]&3)<<4|e[t+1]>>4],r+=ji[(e[t+1]&15)<<2|e[t+2]>>6],r+=ji[e[t+2]&63];return i%3===2?r=r.substring(0,r.length-1)+"=":i%3===1&&(r=r.substring(0,r.length-2)+"=="),r};const md=new Map;function e0(s,e){let t=md.get(s);return t||(t=new Map,md.set(s,t)),t.has(e)||t.set(e,[]),t.get(e)}const gd=(s,e,t)=>{if(!s||!(yd(s,e)||typeof s=="object"))return;const i=s.constructor.name,r=e0(t,i);let n=r.indexOf(s);return n===-1&&(n=r.length,r.push(s)),n};function Cr(s,e,t){if(s instanceof Array)return s.map(i=>Cr(i,e,t));if(s===null)return s;if(s instanceof Float32Array||s instanceof Float64Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Uint8Array||s instanceof Uint16Array||s instanceof Int16Array||s instanceof Int8Array||s instanceof Uint8ClampedArray)return{rr_type:s.constructor.name,args:[Object.values(s)]};if(s instanceof ArrayBuffer){const i=s.constructor.name,r=Qv(s);return{rr_type:i,base64:r}}else{if(s instanceof DataView)return{rr_type:s.constructor.name,args:[Cr(s.buffer,e,t),s.byteOffset,s.byteLength]};if(s instanceof HTMLImageElement){const i=s.constructor.name,{src:r}=s;return{rr_type:i,src:r}}else if(s instanceof HTMLCanvasElement){const i="HTMLImageElement",r=s.toDataURL();return{rr_type:i,src:r}}else{if(s instanceof ImageData)return{rr_type:s.constructor.name,args:[Cr(s.data,e,t),s.width,s.height]};if(yd(s,e)||typeof s=="object"){const i=s.constructor.name,r=gd(s,e,t);return{rr_type:i,index:r}}}}return s}const _d=(s,e,t)=>[...s].map(i=>Cr(i,e,t)),yd=(s,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(r=>typeof e[r]=="function").find(r=>s instanceof e[r]);function t0(s,e,t,i){const r=[],n=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of n)try{if(typeof e.CanvasRenderingContext2D.prototype[o]!="function")continue;const a=zi(e.CanvasRenderingContext2D.prototype,o,function(l){return function(...c){return Je(this.canvas,t,i,!0)||setTimeout(()=>{const h=_d([...c],e,this);s(this.canvas,{type:$i["2D"],property:o,args:h})},0),l.apply(this,c)}});r.push(a)}catch{const l=xr(e.CanvasRenderingContext2D.prototype,o,{set(c){s(this.canvas,{type:$i["2D"],property:o,args:[c],setter:!0})}});r.push(l)}return()=>{r.forEach(o=>o())}}function bd(s,e,t){const i=[];try{const r=zi(s.HTMLCanvasElement.prototype,"getContext",function(n){return function(o,...a){return Je(this,e,t,!0)||"__context"in this||(this.__context=o),n.apply(this,[o,...a])}});i.push(r)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{i.forEach(r=>r())}}function xd(s,e,t,i,r,n,o){const a=[],l=Object.getOwnPropertyNames(s);for(const c of l)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if(typeof s[c]!="function")continue;const h=zi(s,c,function(u){return function(...p){const d=u.apply(this,p);if(gd(d,o,this),!Je(this.canvas,i,r,!0)){const g=_d([...p],o,this),_={type:e,property:c,args:g};t(this.canvas,_)}return d}});a.push(h)}catch{const u=xr(s,c,{set(p){t(this.canvas,{type:e,property:c,args:[p],setter:!0})}});a.push(u)}return a}function i0(s,e,t,i,r){const n=[];return n.push(...xd(e.WebGLRenderingContext.prototype,$i.WebGL,s,t,i,r,e)),typeof e.WebGL2RenderingContext<"u"&&n.push(...xd(e.WebGL2RenderingContext.prototype,$i.WebGL2,s,t,i,r,e)),()=>{n.forEach(o=>o())}}var vd=null;try{var s0=typeof module<"u"&&typeof module.require=="function"&&module.require("worker_threads")||typeof __non_webpack_require__=="function"&&__non_webpack_require__("worker_threads")||typeof require=="function"&&require("worker_threads");vd=s0.Worker}catch{}function r0(s,e){return Buffer.from(s,"base64").toString("utf8")}function n0(s,e,t){var i=r0(s),r=i.indexOf(`
|
|
964
|
+
`,10)+1,n=i.substring(r)+"";return function(a){return new vd(n,Object.assign({},a,{eval:!0}))}}function o0(s,e){var t=atob(s);return t}function a0(s,e,t){var i=o0(s),r=i.indexOf(`
|
|
965
|
+
`,10)+1,n=i.substring(r)+"",o=new Blob([n],{type:"application/javascript"});return URL.createObjectURL(o)}function l0(s,e,t){var i;return function(n){return i=i||a0(s),new Worker(i,n)}}var c0=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";function h0(){return c0}function u0(s,e,t){return h0()?n0(s):l0(s)}var d0=u0("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=");class f0{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)};const{sampling:t="all",win:i,blockClass:r,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(i,r,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,i,r,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,i,r,n){const o=bd(t,i,r),a=new Map,l=new d0;l.onmessage=g=>{const{id:_}=g.data;if(a.set(_,!1),!("base64"in g.data))return;const{base64:y,type:x,width:v,height:C}=g.data;this.mutationCb({id:_,type:$i["2D"],commands:[{property:"clearRect",args:[0,0,v,C]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:y}],type:x}]},0,0]}]})};const c=1e3/e;let h=0,u;const p=()=>{const g=[];return t.document.querySelectorAll("canvas").forEach(_=>{Je(_,i,r,!0)||g.push(_)}),g},d=g=>{if(h&&g-h<c){u=requestAnimationFrame(d);return}h=g,p().forEach(_=>Zv(this,void 0,void 0,function*(){var y;const x=this.mirror.getId(_);if(a.get(x))return;if(a.set(x,!0),["webgl","webgl2"].includes(_.__context)){const C=_.getContext(_.__context);((y=C==null?void 0:C.getContextAttributes())===null||y===void 0?void 0:y.preserveDrawingBuffer)===!1&&(C==null||C.clear(C.COLOR_BUFFER_BIT))}const v=yield createImageBitmap(_);l.postMessage({id:x,bitmap:v,width:_.width,height:_.height,dataURLOptions:n.dataURLOptions},[v])})),u=requestAnimationFrame(d)};u=requestAnimationFrame(d),this.resetObservers=()=>{o(),cancelAnimationFrame(u)}}initCanvasMutationObserver(e,t,i){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=bd(e,t,i),n=t0(this.processMutation.bind(this),e,t,i),o=i0(this.processMutation.bind(this),e,t,i,this.mirror);this.resetObservers=()=>{r(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const i=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,i)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const i=this.pendingCanvasMutations.get(e);if(!i||t===-1)return;const r=i.map(o=>qv(o,["type"])),{type:n}=i[0];this.mutationCb({id:t,type:n,commands:r}),this.pendingCanvasMutations.delete(e)}}class p0{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new Bv,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const i={id:t,styleIds:[]},r=[];for(const n of e){let o;if(this.styleMirror.has(n))o=this.styleMirror.getId(n);else{o=this.styleMirror.add(n);const a=Array.from(n.rules||CSSRule);r.push({styleId:o,rules:a.map((l,c)=>({rule:Gu(l),index:c}))})}i.styleIds.push(o)}r.length>0&&(i.styles=r),this.adoptedStyleSheetCb(i)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}function Ge(s){return Object.assign(Object.assign({},s),{timestamp:Date.now()})}let Oe,Tr,Fo,Er=!1;const dt=lv();function Xi(s={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:i,blockClass:r="rr-block",blockSelector:n=null,ignoreClass:o="rr-ignore",maskTextClass:a="rr-mask",maskTextSelector:l=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:u,slimDOMOptions:p,maskInputFn:d,maskTextFn:g,hooks:_,packFn:y,sampling:x={},dataURLOptions:v={},mousemoveWait:C,recordCanvas:T=!1,recordCrossOriginIframes:A=!1,userTriggeredOnInput:w=!1,collectFonts:R=!1,inlineImages:D=!1,plugins:B,keepIframeSrcFn:k=()=>!1,ignoreCSSAttributes:O=new Set([])}=s,G=A?window.parent===window:!0;let U=!1;if(!G)try{window.parent.document,U=!1}catch{U=!0}if(G&&!e)throw new Error("emit function is required");C!==void 0&&x.mousemove===void 0&&(x.mousemove=C),dt.reset();const W=h===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:u!==void 0?u:{password:!0},te=p===!0||p==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:p==="all",headMetaDescKeywords:p==="all"}:p||{};kv();let F,L=0;const X=z=>{for(const Q of B||[])Q.eventProcessor&&(z=Q.eventProcessor(z));return y&&(z=y(z)),z};Oe=(z,Q)=>{var ae;if(!((ae=di[0])===null||ae===void 0)&&ae.isFrozen()&&z.type!==ge.FullSnapshot&&!(z.type===ge.IncrementalSnapshot&&z.data.source===fe.Mutation)&&di.forEach(j=>j.unfreeze()),G)e==null||e(X(z),Q);else if(U){const j={type:"rrweb",event:X(z),isCheckout:Q};window.parent.postMessage(j,"*")}if(z.type===ge.FullSnapshot)F=z,L=0;else if(z.type===ge.IncrementalSnapshot){if(z.data.source===fe.Mutation&&z.data.isAttachIframe)return;L++;const j=i&&L>=i,_e=t&&z.timestamp-F.timestamp>t;(j||_e)&&Tr(!0)}};const N=z=>{Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.Mutation},z)}))},V=z=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.Scroll},z)})),K=z=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.CanvasMutation},z)})),H=z=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.AdoptedStyleSheet},z)})),$=new p0({mutationCb:N,adoptedStyleSheetCb:H}),se=new Yv({mirror:dt,mutationCb:N,stylesheetManager:$,recordCrossOriginIframes:A,wrappedEmit:Oe});for(const z of B||[])z.getMirror&&z.getMirror({nodeMirror:dt,crossOriginIframeMirror:se.crossOriginIframeMirror,crossOriginIframeStyleMirror:se.crossOriginIframeStyleMirror});Fo=new f0({recordCanvas:T,mutationCb:K,win:window,blockClass:r,blockSelector:n,mirror:dt,sampling:x.canvas,dataURLOptions:v});const ue=new Kv({mutationCb:N,scrollCb:V,bypassOptions:{blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskInputOptions:W,dataURLOptions:v,maskTextFn:g,maskInputFn:d,recordCanvas:T,inlineImages:D,sampling:x,slimDOMOptions:te,iframeManager:se,stylesheetManager:$,canvasManager:Fo,keepIframeSrcFn:k},mirror:dt});Tr=(z=!1)=>{var Q,ae,j,_e,ee,le;Oe(Ge({type:ge.Meta,data:{href:window.location.href,width:Xu(),height:ju()}}),z),$.reset(),di.forEach(pe=>pe.lock());const Re=Mv(document,{mirror:dt,blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskAllInputs:W,maskTextFn:g,slimDOM:te,dataURLOptions:v,recordCanvas:T,inlineImages:D,onSerialize:pe=>{qu(pe,dt)&&se.addIframe(pe),Zu(pe,dt)&&$.trackLinkElement(pe),Ju(pe)&&ue.addShadowRoot(pe.shadowRoot,document)},onIframeLoad:(pe,Ve)=>{se.attachIframe(pe,Ve),ue.observeAttachShadow(pe)},onStylesheetLoad:(pe,Ve)=>{$.attachLinkElement(pe,Ve)},keepIframeSrcFn:k});if(!Re)return console.warn("Failed to snapshot the document");Oe(Ge({type:ge.FullSnapshot,data:{node:Re,initialOffset:{left:window.pageXOffset!==void 0?window.pageXOffset:(document==null?void 0:document.documentElement.scrollLeft)||((ae=(Q=document==null?void 0:document.body)===null||Q===void 0?void 0:Q.parentElement)===null||ae===void 0?void 0:ae.scrollLeft)||((j=document==null?void 0:document.body)===null||j===void 0?void 0:j.scrollLeft)||0,top:window.pageYOffset!==void 0?window.pageYOffset:(document==null?void 0:document.documentElement.scrollTop)||((ee=(_e=document==null?void 0:document.body)===null||_e===void 0?void 0:_e.parentElement)===null||ee===void 0?void 0:ee.scrollTop)||((le=document==null?void 0:document.body)===null||le===void 0?void 0:le.scrollTop)||0}}})),di.forEach(pe=>pe.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&$.adoptStyleSheets(document.adoptedStyleSheets,dt.getId(document))};try{const z=[];z.push(Ze("DOMContentLoaded",()=>{Oe(Ge({type:ge.DomContentLoaded,data:{}}))}));const Q=j=>{var _e;return Xv({mutationCb:N,mousemoveCb:(ee,le)=>Oe(Ge({type:ge.IncrementalSnapshot,data:{source:le,positions:ee}})),mouseInteractionCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.MouseInteraction},ee)})),scrollCb:V,viewportResizeCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.ViewportResize},ee)})),inputCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.Input},ee)})),mediaInteractionCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.MediaInteraction},ee)})),styleSheetRuleCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.StyleSheetRule},ee)})),styleDeclarationCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.StyleDeclaration},ee)})),canvasMutationCb:K,fontCb:ee=>Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.Font},ee)})),selectionCb:ee=>{Oe(Ge({type:ge.IncrementalSnapshot,data:Object.assign({source:fe.Selection},ee)}))},blockClass:r,ignoreClass:o,maskTextClass:a,maskTextSelector:l,maskInputOptions:W,inlineStylesheet:c,sampling:x,recordCanvas:T,inlineImages:D,userTriggeredOnInput:w,collectFonts:R,doc:j,maskInputFn:d,maskTextFn:g,keepIframeSrcFn:k,blockSelector:n,slimDOMOptions:te,dataURLOptions:v,mirror:dt,iframeManager:se,stylesheetManager:$,shadowDomManager:ue,canvasManager:Fo,ignoreCSSAttributes:O,plugins:((_e=B==null?void 0:B.filter(ee=>ee.observer))===null||_e===void 0?void 0:_e.map(ee=>({observer:ee.observer,options:ee.options,callback:le=>Oe(Ge({type:ge.Plugin,data:{plugin:ee.name,payload:le}}))})))||[]},_)};se.addLoadListener(j=>{z.push(Q(j.contentDocument))});const ae=()=>{Tr(),z.push(Q(document)),Er=!0};return document.readyState==="interactive"||document.readyState==="complete"?ae():z.push(Ze("load",()=>{Oe(Ge({type:ge.Load,data:{}})),ae()},window)),()=>{z.forEach(j=>j()),Er=!1}}catch(z){console.warn(z)}}Xi.addCustomEvent=(s,e)=>{if(!Er)throw new Error("please add custom event after start recording");Oe(Ge({type:ge.Custom,data:{tag:s,payload:e}}))},Xi.freezePage=()=>{di.forEach(s=>s.freeze())},Xi.takeFullSnapshot=s=>{if(!Er)throw new Error("please take full snapshot after start recording");Tr(s)},Xi.mirror=dt;const m0=3e4;class g0{constructor(){this.onEvent=null,this.stopFn=null,this._recording=!1,this._paused=!1}get isRecording(){return this._recording}get isPaused(){return this._paused}start(){if(this._recording)return;const e=Xi({emit:t=>{var i;this._paused||(i=this.onEvent)==null||i.call(this,t)},checkoutEveryNms:m0,blockSelector:'#holostaff-widget-root, [autocomplete^="cc-"]',maskAllInputs:!1,maskInputOptions:{password:!0,email:!0,tel:!0}});e?(this.stopFn=e,this._recording=!0,this._paused=!1,console.log("[RRWebRecorder] Started recording")):console.warn("[RRWebRecorder] record() returned undefined — recording may have failed")}stop(){var e;this._recording&&((e=this.stopFn)==null||e.call(this),this.stopFn=null,this._recording=!1,this._paused=!1,console.log("[RRWebRecorder] Stopped recording"))}pause(){!this._recording||this._paused||(this._paused=!0,console.log("[RRWebRecorder] Paused"))}resume(){!this._recording||!this._paused||(this._paused=!1,Xi.takeFullSnapshot(),console.log("[RRWebRecorder] Resumed (full snapshot taken)"))}}function _0(s){return s.startsWith("ws://")||s.startsWith("wss://")?s:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${s.startsWith("/")?"":"/"}${s}`}const Sd=1e3,y0=3e4,b0=500;class x0{constructor(e,t){this.onIntervention=null,this.onStatus=null,this.onConnected=null,this.onDisconnected=null,this.ws=null,this.eventBuffer=[],this.reconnectDelay=Sd,this.reconnectTimer=null,this._connected=!1,this._closed=!1,this.url=_0(e),this.initPayload={type:"init",...t}}get isConnected(){return this._connected}connect(){this._closed||this.doConnect()}close(){if(this._closed=!0,this.clearReconnectTimer(),this.ws){try{this.ws.close()}catch{}this.ws=null}this._connected=!1}sendRRWebEvent(e){this.send({type:"rrweb",event:e})}sendActionComplete(e,t){this.send({type:"action_complete",actionId:e,result:t})}sendConversationStarted(){this.send({type:"conversation_started"})}sendConversationEnded(e){this.send({type:"conversation_ended",summary:e})}doConnect(){if(!this._closed){try{this.ws=new WebSocket(this.url)}catch(e){console.warn("[VisionWS] Failed to create WebSocket:",e),this.scheduleReconnect();return}this.ws.onopen=()=>{var e;console.log("[VisionWS] Connected"),this._connected=!0,this.reconnectDelay=Sd,this.ws.send(JSON.stringify(this.initPayload)),this.flushBuffer(),(e=this.onConnected)==null||e.call(this)},this.ws.onmessage=e=>{const t=e.data;typeof t=="string"?this.parseAndHandle(t):t instanceof Blob?t.text().then(i=>this.parseAndHandle(i)):t instanceof ArrayBuffer?this.parseAndHandle(new TextDecoder().decode(t)):console.warn("[VisionWS] Unknown message data type:",typeof t)},this.ws.onclose=()=>{var t;const e=this._connected;this._connected=!1,this.ws=null,e&&(console.log("[VisionWS] Disconnected"),(t=this.onDisconnected)==null||t.call(this)),this._closed||this.scheduleReconnect()},this.ws.onerror=e=>{console.warn("[VisionWS] Error:",e)}}}parseAndHandle(e){var t,i;try{const r=JSON.parse(e);switch(r.type){case"suggest_intervention":(t=this.onIntervention)==null||t.call(this,r);break;case"status":(i=this.onStatus)==null||i.call(this,r);break;default:console.log("[VisionWS] Unknown message type:",r.type)}}catch(r){console.warn("[VisionWS] Failed to parse message:",r)}}send(e){var t;this._connected&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):(this.eventBuffer.length>=b0&&this.eventBuffer.shift(),this.eventBuffer.push(e))}flushBuffer(){if(!(!this._connected||!this.ws)){for(const e of this.eventBuffer)this.ws.send(JSON.stringify(e));this.eventBuffer.length>0&&console.log(`[VisionWS] Flushed ${this.eventBuffer.length} buffered messages`),this.eventBuffer=[]}}scheduleReconnect(){if(this._closed||this.reconnectTimer)return;const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,y0),console.log(`[VisionWS] Reconnecting in ${e}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}}class v0{constructor(){this.button=null,this.onClick=null}show(){if(this.button)return;this.button=document.createElement("button"),this.button.textContent="×",this.button.setAttribute("aria-label","Dismiss suggestion"),Object.assign(this.button.style,{position:"fixed",bottom:"260px",left:"50%",transform:"translateX(50px)",zIndex:"2147483647",width:"28px",height:"28px",borderRadius:"50%",border:"1px solid rgba(200, 208, 218, 0.6)",background:"rgba(255, 255, 255, 0.85)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",color:"#4a4a6a",fontSize:"16px",fontWeight:"700",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",lineHeight:"1",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",pointerEvents:"auto",opacity:"0",transition:"opacity 0.3s ease, background 0.15s, transform 0.15s"}),this.button.addEventListener("click",t=>{var i;t.stopPropagation(),(i=this.onClick)==null||i.call(this)}),this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.background="rgba(240, 242, 245, 0.95)",this.button.style.transform="translateX(50px) scale(1.1)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.background="rgba(255, 255, 255, 0.85)",this.button.style.transform="translateX(50px) scale(1)")}),(document.getElementById("holostaff-widget-root")??document.body).appendChild(this.button),requestAnimationFrame(()=>{this.button&&(this.button.style.opacity="1")})}hide(){this.button&&(this.button.remove(),this.button=null)}}const S0=15e3;class C0{constructor(e){this.currentIntervention=null,this.autoDismissTimer=null,this.acceptHandler=null,this._active=!1,this.onAccept=null,this.wsClient=e.wsClient,this.avatar=e.avatar,this.bubble=e.bubble,this.ticker=e.ticker,this.dismissButton=new v0,this.dismissButton.onClick=()=>this.handleDecline(),this.wsClient.onIntervention=t=>this.handleIntervention(t)}get isActive(){return this._active}destroy(){this.cleanup(),this.wsClient.onIntervention=null}handleIntervention(e){this._active||(console.log(`[ActionExecutor] Showing suggestion: "${e.message}"`),this.currentIntervention=e,this._active=!0,this.avatar.slideIn(this.ticker),this.bubble.showStatic(e.message),this.dismissButton.show(),this.acceptHandler=()=>this.handleAccept(),this.avatar.container.on("pointertap",this.acceptHandler),this.autoDismissTimer=setTimeout(()=>this.handleIgnore(),S0))}handleAccept(){var i;if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User accepted suggestion");const e=this.currentIntervention.context,t=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(t,"accepted"),(i=this.onAccept)==null||i.call(this,e)}handleDecline(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User declined suggestion");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"declined"),this.avatar.slideOut(this.ticker)}handleIgnore(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] Suggestion auto-dismissed (ignored)");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"ignored"),this.avatar.slideOut(this.ticker)}cleanup(){this._active=!1,this.autoDismissTimer&&(clearTimeout(this.autoDismissTimer),this.autoDismissTimer=null),this.dismissButton.hide(),this.bubble.hideStatic(),this.acceptHandler&&(this.avatar.container.off("pointertap",this.acceptHandler),this.acceptHandler=null),this.currentIntervention=null}}const T0=8,E0=800,w0=600*1e3,I0=540*1e3,Cd=60*1e3,A0=90*1e3,R0=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class Td{constructor(e,t){this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.highlightRenderer=null,this.confirmationPrompt=null,this.overlayRenderer=null,this.controls=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.actionExecutor=null,this.visionContext=null,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}async init(){this.stage=new Lb,await this.stage.init(),this.avatar=new Wb(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.bubble=new Jb(this.stage.app.ticker,this.widgetPrompts??void 0),this.bubble.container.x=0,this.bubble.container.y=-Dt-T0,this.avatar.container.addChild(this.bubble.container),this.avatar.setInteractive(()=>this.onAvatarClick()),this.bubble.onClick(()=>this.onAvatarClick()),this.setupTrigger(),this.startVisionLoop(),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e);return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setupTrigger(){switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},E0))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r;if(!(this.state!=="teasing"&&this.state!=="idle")){this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Yd(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new rv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),this.showControls(),this.startSessionTimers(),(i=this.visionWs)==null||i.sendConversationStarted(),(r=this.rrwebRecorder)==null||r.pause(),console.log("[HolostaffWidget] Conversation active")}catch(n){console.error("[HolostaffWidget] Failed to start conversation:",n),this.endConversation()}}}async connectAnam(){this.sessionResponse&&(this.anamSession=new Lx({sessionToken:this.sessionResponse.anamSessionToken}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{console.log("[HolostaffWidget] Anam avatar video ready"),this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){if(!this.sessionResponse)return;let e=(this.sessionResponse.staff.instructions??"")+`
|
|
949
966
|
|
|
950
967
|
## Page Interaction
|
|
951
968
|
You can interact with the webpage the visitor is viewing by calling the page_action tool.
|
|
952
969
|
Call it with instruction "read the page content" first to understand what is on the page.
|
|
953
970
|
Then you can scroll to elements, highlight them, click links/buttons, or fill form fields.
|
|
954
|
-
All actions except form filling require the visitor to confirm before executing.`;this.
|
|
971
|
+
All actions except form filling require the visitor to confirm before executing.`;this.visionContext&&(e+=`
|
|
972
|
+
|
|
973
|
+
## Context from observing the user's session
|
|
974
|
+
`+this.visionContext,this.visionContext=null),this.realtimeSession=new ix({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:e,tools:R0}),this.domAnalyzer=new zx,this.highlightRenderer=new Kx,this.confirmationPrompt=new Zx,this.realtimeSession.onConnected=()=>{var i,r,n,o;console.log("[HolostaffWidget] Realtime API connected");const t=(i=this.sessionResponse)==null?void 0:i.staff.openingText;t!=null&&t.trim()&&((r=this.realtimeSession)==null||r.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(n=this.realtimeSession)==null||n.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:t}]}}),(o=this.realtimeSession)==null||o.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async t=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new ox,this.audioForwarder.onAudioChunk=i=>{var r;(r=this.anamSession)==null||r.sendAudioChunk(i)},await this.audioForwarder.start(t)},this.overlayRenderer=new tv,this.toolHandler=new jx({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new Xx(this.domAnalyzer,this.highlightRenderer),overlayActions:new Yx(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl}),this.toolHandler.onToolCall=(t,i)=>{var r;(r=this.logger)==null||r.addAction(t,i)},this.realtimeSession.onDataMessage=t=>{this.handleDataChannelMessage(t)},this.realtimeSession.onError=t=>{console.error("[HolostaffWidget] Realtime error:",t.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.resetInactivityTimer(),this.extractAiTranscript(e.response);break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new iv,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},I0),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},w0),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},A0-Cd))},Cd)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var e,t,i,r,n,o,a,l,c,h;(e=this.logger)==null||e.flush(),this.logger=null,this.clearSessionTimers(),(t=this.controls)==null||t.hide(),this.controls=null,(i=this.audioForwarder)==null||i.stop(),this.audioForwarder=null,(r=this.anamSession)==null||r.close(),this.anamSession=null,(n=this.realtimeSession)==null||n.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.toolHandler=null,this.domAnalyzer=null,(o=this.highlightRenderer)==null||o.clearAll(),this.highlightRenderer=null,(a=this.confirmationPrompt)==null||a.dismiss(),this.confirmationPrompt=null,(l=this.overlayRenderer)==null||l.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker),(c=this.visionWs)==null||c.sendConversationEnded("Conversation ended"),(h=this.rrwebRecorder)==null||h.resume(),this.state="idle",console.log("[HolostaffWidget] Conversation ended")}startVisionLoop(){const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new g0,this.visionWs=new x0(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.avatar&&this.bubble&&this.stage&&(this.actionExecutor=new C0({wsClient:this.visionWs,avatar:this.avatar,bubble:this.bubble,ticker:this.stage.app.ticker}),this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()}),this.visionWs.connect(),this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId}))}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,(t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function M0(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{const e=Vd(s);async function t(){let i=e,r=null,n=null;try{n=await Kd(e.staffId,e.backendUrl),i=Xd(e,s,n),r=n.widgetPrompts}catch(a){console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",a)}const o=new Td(i,r);n!=null&&n.idleVideoUrl?o.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&o.setIdleImage(n.avatarImageUrl),window.holostaffWidget=o,o.init()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t()}catch(e){console.error("[HolostaffWidget]",e)}}M0(),ie.add(ap),ie.mixin(We,lp),ie.add(Tc),ie.add(Ec),ie.mixin(We,Og),ie.add(Rc),ie.add(Ic);const P0=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),k0=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));gi.HolostaffWidget=Td,Object.defineProperty(gi,Symbol.toStringTag,{value:"Module"})}));
|
|
955
975
|
//# sourceMappingURL=hs-widget.umd.js.map
|