agent-theatre 0.1.2 → 0.1.3

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.
@@ -1,8 +1,8 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browserAll-D9J1RvsL.js","assets/webworkerAll-NgikUusG.js"])))=>i.map(i=>d[i]);
2
- (function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function s(i){if(i.ep)return;i.ep=!0;const n=t(i);fetch(i.href,n)}})();const Gg="modulepreload",Dg=function(r){return"/"+r},mh={},wt=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){let o=function(h){return Promise.all(h.map(c=>Promise.resolve(c).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");i=o(t.map(h=>{if(h=Dg(h),h in mh)return;mh[h]=!0;const c=h.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":Gg,c||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),c)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${h}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};var C=(r=>(r.Application="application",r.WebGLPipes="webgl-pipes",r.WebGLPipesAdaptor="webgl-pipes-adaptor",r.WebGLSystem="webgl-system",r.WebGLLoader="webgl-loader",r.WebGPUPipes="webgpu-pipes",r.WebGPUPipesAdaptor="webgpu-pipes-adaptor",r.WebGPUSystem="webgpu-system",r.WebGPULoader="webgpu-loader",r.CanvasSystem="canvas-system",r.CanvasPipesAdaptor="canvas-pipes-adaptor",r.CanvasPipes="canvas-pipes",r.CanvasLoader="canvas-loader",r.Asset="asset",r.LoadParser="load-parser",r.ResolveParser="resolve-parser",r.CacheParser="cache-parser",r.DetectionParser="detection-parser",r.MaskEffect="mask-effect",r.BlendMode="blend-mode",r.TextureSource="texture-source",r.TextureUploaderWebGL="texture-uploader-webgl",r.TextureUploaderWebGPU="texture-uploader-webgpu",r.Environment="environment",r.ShapeBuilder="shape-builder",r.Batcher="batcher",r))(C||{});const Fn=r=>{if(typeof r=="function"||typeof r=="object"&&r.extension){if(!r.extension)throw new Error("Extension class must have an extension object");r={...typeof r.extension!="object"?{type:r.extension}:r.extension,ref:r}}if(typeof r=="object")r={...r};else throw new Error("Invalid extension type");return typeof r.type=="string"&&(r.type=[r.type]),r},Ys=(r,e)=>Fn(r).priority??e,q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...r){return r.map(Fn).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...r){return r.map(Fn).forEach(e=>{e.type.forEach(t=>{const s=this._addHandlers,i=this._queue;s[t]?s[t]?.(e):(i[t]=i[t]||[],i[t]?.push(e))})}),this},handle(r,e,t){const s=this._addHandlers,i=this._removeHandlers;if(s[r]||i[r])throw new Error(`Extension type ${r} already has a handler`);s[r]=e,i[r]=t;const n=this._queue;return n[r]&&(n[r]?.forEach(o=>e(o)),delete n[r]),this},handleByMap(r,e){return this.handle(r,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(r,e,t=-1){return this.handle(r,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Ys(o.value,t)-Ys(n.value,t)))},s=>{const i=e.findIndex(n=>n.name===s.name);i!==-1&&e.splice(i,1)})},handleByList(r,e,t=-1){return this.handle(r,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((i,n)=>Ys(n,t)-Ys(i,t)))},s=>{const i=e.indexOf(s.ref);i!==-1&&e.splice(i,1)})},mixin(r,...e){for(const t of e)Object.defineProperties(r.prototype,Object.getOwnPropertyDescriptors(t))}},du={extension:{type:C.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await wt(()=>import("./browserAll-D9J1RvsL.js"),__vite__mapDeps([0,1]))}},fu={extension:{type:C.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await wt(()=>import("./webworkerAll-NgikUusG.js"),[])}};class Ce{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new Ce(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 Fg(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Zi={exports:{}},gh;function Lg(){return gh||(gh=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,u,d){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new i(c,u||l,d),p=t?t+h:h;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new s:delete l._events[h]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)e.call(c,u)&&h.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=t?t+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(h){var c=t?t+h:h,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(h,c,u,d,f,p){var m=t?t+h:h;if(!this._events[m])return!1;var g=this._events[m],_=arguments.length,x,y;if(g.fn){switch(g.once&&this.removeListener(h,g.fn,void 0,!0),_){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,c),!0;case 3:return g.fn.call(g.context,c,u),!0;case 4:return g.fn.call(g.context,c,u,d),!0;case 5:return g.fn.call(g.context,c,u,d,f),!0;case 6:return g.fn.call(g.context,c,u,d,f,p),!0}for(y=1,x=new Array(_-1);y<_;y++)x[y-1]=arguments[y];g.fn.apply(g.context,x)}else{var b=g.length,w;for(y=0;y<b;y++)switch(g[y].once&&this.removeListener(h,g[y].fn,void 0,!0),_){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,c);break;case 3:g[y].fn.call(g[y].context,c,u);break;case 4:g[y].fn.call(g[y].context,c,u,d);break;default:if(!x)for(w=1,x=new Array(_-1);w<_;w++)x[w-1]=arguments[w];g[y].fn.apply(g[y].context,x)}}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,d){var f=t?t+h:h;if(!this._events[f])return this;if(!c)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&o(this,f);else{for(var m=0,g=[],_=p.length;m<_;m++)(p[m].fn!==c||d&&!p[m].once||u&&p[m].context!==u)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:o(this,f)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=t?t+h:h,this._events[c]&&o(this,c)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a})(Zi)),Zi.exports}var Og=Lg();const Re=Fg(Og),pu=Math.PI*2,mu=180/Math.PI,gu=Math.PI/180;class he{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new he(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 Qi.x=0,Qi.y=0,Qi}}const Qi=new he;class L{constructor(e=1,t=0,s=0,i=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=i,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,s,i,n,o){return this.a=e,this.b=t,this.c=s,this.d=i,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new he;const s=e.x,i=e.y;return t.x=this.a*s+this.c*i+this.tx,t.y=this.b*s+this.d*i+this.ty,t}applyInverse(e,t){t=t||new he;const s=this.a,i=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(s*o+n*-i),c=e.x,u=e.y;return t.x=o*h*c+-n*h*u+(l*n-a*o)*h,t.y=s*h*u+-i*h*c+(-l*s+a*i)*h,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),s=Math.sin(e),i=this.a,n=this.c,o=this.tx;return this.a=i*t-this.b*s,this.b=i*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,i=this.c,n=this.d;return this.a=e.a*t+e.b*i,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*i,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*i+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,i=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,h=t.a,c=t.b,u=t.c,d=t.d;return this.a=s*h+i*u,this.b=s*c+i*d,this.c=n*h+o*u,this.d=n*c+o*d,this.tx=a*h+l*u+t.tx,this.ty=a*c+l*d+t.ty,this}setTransform(e,t,s,i,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=e-(s*this.a+i*this.c),this.ty=t-(s*this.b+i*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,i=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=i*e.a+this.d*e.c,this.d=i*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,s=this.b,i=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-i,n),l=Math.atan2(s,t),h=Math.abs(a+l);let c=Math.sqrt(t*t+s*s);return h<1e-5||Math.abs(pu-h)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):Math.abs(Math.PI-h)<1e-5?(e.rotation=l-Math.PI,e.skew.x=e.skew.y=0,c=-c):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=c,e.scale.y=Math.sqrt(i*i+n*n),e.position.x=this.tx+(o.x*t+o.y*i),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,i=this.d,n=this.tx,o=e*i-t*s;return this.a=i/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-i*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 L;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 Ng.identity()}static get shared(){return Ug.identity()}}const Ug=new L,Ng=new L,Ht=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],zt=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Wt=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],$t=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Ln=[],_u=[],Sr=Math.sign;function Hg(){for(let r=0;r<16;r++){const e=[];Ln.push(e);for(let t=0;t<16;t++){const s=Sr(Ht[r]*Ht[t]+Wt[r]*zt[t]),i=Sr(zt[r]*Ht[t]+$t[r]*zt[t]),n=Sr(Ht[r]*Wt[t]+Wt[r]*$t[t]),o=Sr(zt[r]*Wt[t]+$t[r]*$t[t]);for(let a=0;a<16;a++)if(Ht[a]===s&&zt[a]===i&&Wt[a]===n&&$t[a]===o){e.push(a);break}}}for(let r=0;r<16;r++){const e=new L;e.set(Ht[r],zt[r],Wt[r],$t[r],0,0),_u.push(e)}}Hg();const Z={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:r=>Ht[r],uY:r=>zt[r],vX:r=>Wt[r],vY:r=>$t[r],inv:r=>r&8?r&15:-r&7,add:(r,e)=>Ln[r][e],sub:(r,e)=>Ln[r][Z.inv(e)],rotate180:r=>r^4,isVertical:r=>(r&3)===2,byDirection:(r,e)=>Math.abs(r)*2<=Math.abs(e)?e>=0?Z.S:Z.N:Math.abs(e)*2<=Math.abs(r)?r>0?Z.E:Z.W:e>0?r>0?Z.SE:Z.SW:r>0?Z.NE:Z.NW,matrixAppendRotationInv:(r,e,t=0,s=0,i=0,n=0)=>{const o=_u[Z.inv(e)],a=o.a,l=o.b,h=o.c,c=o.d,u=t-Math.min(0,a*i,h*n,a*i+h*n),d=s-Math.min(0,l*i,c*n,l*i+c*n),f=r.a,p=r.b,m=r.c,g=r.d;r.a=a*f+l*m,r.b=a*p+l*g,r.c=h*f+c*m,r.d=h*p+c*g,r.tx=u*f+d*m+r.tx,r.ty=u*p+d*g+r.ty},transformRectCoords:(r,e,t,s)=>{const{x:i,y:n,width:o,height:a}=r,{x:l,y:h,width:c,height:u}=e;return t===Z.E?(s.set(i+l,n+h,o,a),s):t===Z.S?s.set(c-n-a+l,i+h,a,o):t===Z.W?s.set(c-i-o+l,u-n-a+h,o,a):t===Z.N?s.set(n+l,u-i-o+h,a,o):s.set(i+l,n+h,o,a)}},Cr=[new he,new he,new he,new he];class ee{constructor(e=0,t=0,s=0,i=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(i)}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 ee(0,0,0,0)}clone(){return new ee(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,s,i=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,h=s*(1-i),c=s-h,u=a-h,d=a+n+h,f=l-h,p=l+o+h,m=a+c,g=a+n-c,_=l+c,x=l+o-c;return e>=u&&e<=d&&t>=f&&t<=p&&!(e>m&&e<g&&t>_&&t<x)}intersects(e,t){if(!t){const E=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=E)return!1;const P=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>P}const s=this.left,i=this.right,n=this.top,o=this.bottom;if(i<=s||o<=n)return!1;const a=Cr[0].set(e.left,e.top),l=Cr[1].set(e.left,e.bottom),h=Cr[2].set(e.right,e.top),c=Cr[3].set(e.right,e.bottom);if(h.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(h,h),t.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=s||Math.min(a.x,l.x,h.x,c.x)>=i||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 d=u*(l.y-a.y),f=u*(a.x-l.x),p=d*s+f*n,m=d*i+f*n,g=d*s+f*o,_=d*i+f*o;if(Math.max(p,m,g,_)<=d*a.x+f*a.y||Math.min(p,m,g,_)>=d*c.x+f*c.y)return!1;const x=u*(a.y-h.y),y=u*(h.x-a.x),b=x*s+y*n,w=x*i+y*n,v=x*s+y*o,S=x*i+y*o;return!(Math.max(b,w,v,S)<=x*a.x+y*a.y||Math.min(b,w,v,S)>=x*c.x+y*c.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),s=Math.min(this.x+this.width,e.x+e.width),i=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(s-t,0),this.y=i,this.height=Math.max(n-i,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,i=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=s-this.x,this.height=i-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),s=Math.max(this.x+this.width,e.x+e.width),i=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=i,this.height=n-i,this}getBounds(e){return e||(e=new ee),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,i=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&i>=this.x&&i<=this.x+this.width&&n>=this.y&&n<=this.y+this.height}set(e,t,s,i){return this.x=e,this.y=t,this.width=s,this.height=i,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Ji={default:-1};function ne(r="default"){return Ji[r]===void 0&&(Ji[r]=-1),++Ji[r]}const _h=new Set,ue="8.0.0",yu="8.3.4",lt="8.21.0",xu="8.22.0",vs={quiet:!1,noColor:!1},O=((r,e,t=3)=>{if(vs.quiet||_h.has(e))return;let s=new Error().stack;const i=`${e}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browserAll-CZuhb8E5.js","assets/webworkerAll-C8_bDDrL.js"])))=>i.map(i=>d[i]);
2
+ (function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function s(i){if(i.ep)return;i.ep=!0;const n=t(i);fetch(i.href,n)}})();const Gg="modulepreload",Dg=function(r){return"/"+r},mh={},wt=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){let o=function(h){return Promise.all(h.map(c=>Promise.resolve(c).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");i=o(t.map(h=>{if(h=Dg(h),h in mh)return;mh[h]=!0;const c=h.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":Gg,c||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),c)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${h}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};var S=(r=>(r.Application="application",r.WebGLPipes="webgl-pipes",r.WebGLPipesAdaptor="webgl-pipes-adaptor",r.WebGLSystem="webgl-system",r.WebGLLoader="webgl-loader",r.WebGPUPipes="webgpu-pipes",r.WebGPUPipesAdaptor="webgpu-pipes-adaptor",r.WebGPUSystem="webgpu-system",r.WebGPULoader="webgpu-loader",r.CanvasSystem="canvas-system",r.CanvasPipesAdaptor="canvas-pipes-adaptor",r.CanvasPipes="canvas-pipes",r.CanvasLoader="canvas-loader",r.Asset="asset",r.LoadParser="load-parser",r.ResolveParser="resolve-parser",r.CacheParser="cache-parser",r.DetectionParser="detection-parser",r.MaskEffect="mask-effect",r.BlendMode="blend-mode",r.TextureSource="texture-source",r.TextureUploaderWebGL="texture-uploader-webgl",r.TextureUploaderWebGPU="texture-uploader-webgpu",r.Environment="environment",r.ShapeBuilder="shape-builder",r.Batcher="batcher",r))(S||{});const Fn=r=>{if(typeof r=="function"||typeof r=="object"&&r.extension){if(!r.extension)throw new Error("Extension class must have an extension object");r={...typeof r.extension!="object"?{type:r.extension}:r.extension,ref:r}}if(typeof r=="object")r={...r};else throw new Error("Invalid extension type");return typeof r.type=="string"&&(r.type=[r.type]),r},Ys=(r,e)=>Fn(r).priority??e,q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...r){return r.map(Fn).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...r){return r.map(Fn).forEach(e=>{e.type.forEach(t=>{const s=this._addHandlers,i=this._queue;s[t]?s[t]?.(e):(i[t]=i[t]||[],i[t]?.push(e))})}),this},handle(r,e,t){const s=this._addHandlers,i=this._removeHandlers;if(s[r]||i[r])throw new Error(`Extension type ${r} already has a handler`);s[r]=e,i[r]=t;const n=this._queue;return n[r]&&(n[r]?.forEach(o=>e(o)),delete n[r]),this},handleByMap(r,e){return this.handle(r,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(r,e,t=-1){return this.handle(r,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Ys(o.value,t)-Ys(n.value,t)))},s=>{const i=e.findIndex(n=>n.name===s.name);i!==-1&&e.splice(i,1)})},handleByList(r,e,t=-1){return this.handle(r,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((i,n)=>Ys(n,t)-Ys(i,t)))},s=>{const i=e.indexOf(s.ref);i!==-1&&e.splice(i,1)})},mixin(r,...e){for(const t of e)Object.defineProperties(r.prototype,Object.getOwnPropertyDescriptors(t))}},du={extension:{type:S.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await wt(()=>import("./browserAll-CZuhb8E5.js"),__vite__mapDeps([0,1]))}},fu={extension:{type:S.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await wt(()=>import("./webworkerAll-C8_bDDrL.js"),[])}};class Ce{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new Ce(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 Fg(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Zi={exports:{}},gh;function Lg(){return gh||(gh=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,u,d){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new i(c,u||l,d),p=t?t+h:h;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new s:delete l._events[h]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)e.call(c,u)&&h.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=t?t+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(h){var c=t?t+h:h,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(h,c,u,d,f,p){var m=t?t+h:h;if(!this._events[m])return!1;var g=this._events[m],_=arguments.length,x,y;if(g.fn){switch(g.once&&this.removeListener(h,g.fn,void 0,!0),_){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,c),!0;case 3:return g.fn.call(g.context,c,u),!0;case 4:return g.fn.call(g.context,c,u,d),!0;case 5:return g.fn.call(g.context,c,u,d,f),!0;case 6:return g.fn.call(g.context,c,u,d,f,p),!0}for(y=1,x=new Array(_-1);y<_;y++)x[y-1]=arguments[y];g.fn.apply(g.context,x)}else{var b=g.length,w;for(y=0;y<b;y++)switch(g[y].once&&this.removeListener(h,g[y].fn,void 0,!0),_){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,c);break;case 3:g[y].fn.call(g[y].context,c,u);break;case 4:g[y].fn.call(g[y].context,c,u,d);break;default:if(!x)for(w=1,x=new Array(_-1);w<_;w++)x[w-1]=arguments[w];g[y].fn.apply(g[y].context,x)}}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,d){var f=t?t+h:h;if(!this._events[f])return this;if(!c)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&o(this,f);else{for(var m=0,g=[],_=p.length;m<_;m++)(p[m].fn!==c||d&&!p[m].once||u&&p[m].context!==u)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:o(this,f)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=t?t+h:h,this._events[c]&&o(this,c)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a})(Zi)),Zi.exports}var Og=Lg();const Re=Fg(Og),pu=Math.PI*2,mu=180/Math.PI,gu=Math.PI/180;class he{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new he(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 Qi.x=0,Qi.y=0,Qi}}const Qi=new he;class L{constructor(e=1,t=0,s=0,i=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=i,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,s,i,n,o){return this.a=e,this.b=t,this.c=s,this.d=i,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new he;const s=e.x,i=e.y;return t.x=this.a*s+this.c*i+this.tx,t.y=this.b*s+this.d*i+this.ty,t}applyInverse(e,t){t=t||new he;const s=this.a,i=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(s*o+n*-i),c=e.x,u=e.y;return t.x=o*h*c+-n*h*u+(l*n-a*o)*h,t.y=s*h*u+-i*h*c+(-l*s+a*i)*h,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),s=Math.sin(e),i=this.a,n=this.c,o=this.tx;return this.a=i*t-this.b*s,this.b=i*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,i=this.c,n=this.d;return this.a=e.a*t+e.b*i,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*i,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*i+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,i=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,h=t.a,c=t.b,u=t.c,d=t.d;return this.a=s*h+i*u,this.b=s*c+i*d,this.c=n*h+o*u,this.d=n*c+o*d,this.tx=a*h+l*u+t.tx,this.ty=a*c+l*d+t.ty,this}setTransform(e,t,s,i,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=e-(s*this.a+i*this.c),this.ty=t-(s*this.b+i*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,i=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=i*e.a+this.d*e.c,this.d=i*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,s=this.b,i=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-i,n),l=Math.atan2(s,t),h=Math.abs(a+l);let c=Math.sqrt(t*t+s*s);return h<1e-5||Math.abs(pu-h)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):Math.abs(Math.PI-h)<1e-5?(e.rotation=l-Math.PI,e.skew.x=e.skew.y=0,c=-c):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=c,e.scale.y=Math.sqrt(i*i+n*n),e.position.x=this.tx+(o.x*t+o.y*i),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,i=this.d,n=this.tx,o=e*i-t*s;return this.a=i/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-i*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 L;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 Ng.identity()}static get shared(){return Ug.identity()}}const Ug=new L,Ng=new L,Ht=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],zt=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Wt=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],$t=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Ln=[],_u=[],Sr=Math.sign;function Hg(){for(let r=0;r<16;r++){const e=[];Ln.push(e);for(let t=0;t<16;t++){const s=Sr(Ht[r]*Ht[t]+Wt[r]*zt[t]),i=Sr(zt[r]*Ht[t]+$t[r]*zt[t]),n=Sr(Ht[r]*Wt[t]+Wt[r]*$t[t]),o=Sr(zt[r]*Wt[t]+$t[r]*$t[t]);for(let a=0;a<16;a++)if(Ht[a]===s&&zt[a]===i&&Wt[a]===n&&$t[a]===o){e.push(a);break}}}for(let r=0;r<16;r++){const e=new L;e.set(Ht[r],zt[r],Wt[r],$t[r],0,0),_u.push(e)}}Hg();const Z={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:r=>Ht[r],uY:r=>zt[r],vX:r=>Wt[r],vY:r=>$t[r],inv:r=>r&8?r&15:-r&7,add:(r,e)=>Ln[r][e],sub:(r,e)=>Ln[r][Z.inv(e)],rotate180:r=>r^4,isVertical:r=>(r&3)===2,byDirection:(r,e)=>Math.abs(r)*2<=Math.abs(e)?e>=0?Z.S:Z.N:Math.abs(e)*2<=Math.abs(r)?r>0?Z.E:Z.W:e>0?r>0?Z.SE:Z.SW:r>0?Z.NE:Z.NW,matrixAppendRotationInv:(r,e,t=0,s=0,i=0,n=0)=>{const o=_u[Z.inv(e)],a=o.a,l=o.b,h=o.c,c=o.d,u=t-Math.min(0,a*i,h*n,a*i+h*n),d=s-Math.min(0,l*i,c*n,l*i+c*n),f=r.a,p=r.b,m=r.c,g=r.d;r.a=a*f+l*m,r.b=a*p+l*g,r.c=h*f+c*m,r.d=h*p+c*g,r.tx=u*f+d*m+r.tx,r.ty=u*p+d*g+r.ty},transformRectCoords:(r,e,t,s)=>{const{x:i,y:n,width:o,height:a}=r,{x:l,y:h,width:c,height:u}=e;return t===Z.E?(s.set(i+l,n+h,o,a),s):t===Z.S?s.set(c-n-a+l,i+h,a,o):t===Z.W?s.set(c-i-o+l,u-n-a+h,o,a):t===Z.N?s.set(n+l,u-i-o+h,a,o):s.set(i+l,n+h,o,a)}},Cr=[new he,new he,new he,new he];class ee{constructor(e=0,t=0,s=0,i=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(i)}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 ee(0,0,0,0)}clone(){return new ee(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,s,i=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,h=s*(1-i),c=s-h,u=a-h,d=a+n+h,f=l-h,p=l+o+h,m=a+c,g=a+n-c,_=l+c,x=l+o-c;return e>=u&&e<=d&&t>=f&&t<=p&&!(e>m&&e<g&&t>_&&t<x)}intersects(e,t){if(!t){const k=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=k)return!1;const A=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>A}const s=this.left,i=this.right,n=this.top,o=this.bottom;if(i<=s||o<=n)return!1;const a=Cr[0].set(e.left,e.top),l=Cr[1].set(e.left,e.bottom),h=Cr[2].set(e.right,e.top),c=Cr[3].set(e.right,e.bottom);if(h.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(h,h),t.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=s||Math.min(a.x,l.x,h.x,c.x)>=i||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 d=u*(l.y-a.y),f=u*(a.x-l.x),p=d*s+f*n,m=d*i+f*n,g=d*s+f*o,_=d*i+f*o;if(Math.max(p,m,g,_)<=d*a.x+f*a.y||Math.min(p,m,g,_)>=d*c.x+f*c.y)return!1;const x=u*(a.y-h.y),y=u*(h.x-a.x),b=x*s+y*n,w=x*i+y*n,v=x*s+y*o,T=x*i+y*o;return!(Math.max(b,w,v,T)<=x*a.x+y*a.y||Math.min(b,w,v,T)>=x*c.x+y*c.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),s=Math.min(this.x+this.width,e.x+e.width),i=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(s-t,0),this.y=i,this.height=Math.max(n-i,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,i=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=s-this.x,this.height=i-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),s=Math.max(this.x+this.width,e.x+e.width),i=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=i,this.height=n-i,this}getBounds(e){return e||(e=new ee),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,i=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&i>=this.x&&i<=this.x+this.width&&n>=this.y&&n<=this.y+this.height}set(e,t,s,i){return this.x=e,this.y=t,this.width=s,this.height=i,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Ji={default:-1};function ne(r="default"){return Ji[r]===void 0&&(Ji[r]=-1),++Ji[r]}const _h=new Set,ue="8.0.0",yu="8.3.4",lt="8.21.0",xu="8.22.0",vs={quiet:!1,noColor:!1},O=((r,e,t=3)=>{if(vs.quiet||_h.has(e))return;let s=new Error().stack;const i=`${e}
3
3
  Deprecated since v${r}`,n=typeof console.groupCollapsed=="function"&&!vs.noColor;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",i):(s=s.split(`
4
4
  `).splice(t).join(`
5
- `),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",i),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",i),console.warn(s))),_h.add(e)});Object.defineProperties(O,{quiet:{get:()=>vs.quiet,set:r=>{vs.quiet=r},enumerable:!0,configurable:!1},noColor:{get:()=>vs.noColor,set:r=>{vs.noColor=r},enumerable:!0,configurable:!1}});const Go=()=>{};function ti(r){return r.endsWith("int")}function es(r){return r+=r===0?1:0,--r,r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r+1}function ts(r){return!(r&r-1)&&!!r}function Do(r){const e={};for(const t in r)r[t]!==void 0&&(e[t]=r[t]);return e}const yh=Object.create(null);function zg(r){const e=yh[r];return e===void 0&&(yh[r]=ne("resource")),e}const bu=class vu extends Re{constructor(e={}){super(),this._resourceType="textureSampler",this._maxAnisotropy=1,this.destroyed=!1,e={...vu.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){O(ue,"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=zg(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};bu.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Dt=bu;const wu=class Tu extends Re{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=ne("textureSource"),this._resourceType="textureSource",this._resourceId=ne("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.depth=1,this._ownsStyle=!1,this.antialias=!1,this.transient=!1,this.storage=!1,this._batchTick=-1,this._textureBindLocation=-1;const t=e;e={...Tu.defaultOptions,...e};const s=Wg(e),i=s==="3d"||s==="1d"?s:"2d";$g(t,s,i),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=i,this.viewDimension=s,this.arrayLayerCount=e.arrayLayerCount,this.depth=i==="3d"?e.depth??1:1,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=i==="3d"?!1:e.antialias,this.transient=e.transient??!1,this.storage=e.storage??!1,this.alphaMode=e.alphaMode,this.style=new Dt(Do(e)),this._ownsStyle=!0,this.destroyed=!1,this._refreshPOT()}get depthOrArrayLayers(){return this.dimension==="3d"?this.depth:this.arrayLayerCount||1}get source(){return this}get style(){return this._style}set style(e){this.style!==e&&(this._ownsStyle=!1,this._style?.off("change",this._onStyleChange,this),this._style=e,this._style?.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._ownsStyle&&this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=ne("resource"),this.emit("change",this),this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy?.();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,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const i=Math.round(e*s),n=Math.round(t*s);return this.width=i/s,this.height=n/s,this._resolution=s,this.pixelWidth===i&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=i,this.pixelHeight=n,this.emit("resize",this),this._resourceId=ne("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=ts(this.pixelWidth)&&ts(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};wu.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let de=wu;function Wg(r){return r.viewDimension?r.viewDimension:r.depth?"3d":r.arrayLayerCount>1?"2d-array":"2d"}function $g(r,e,t){if(r.depth!==void 0&&typeof r.depth!="number")throw new Error(`[TextureSource] depth is a 3D texture's depth in texels, but got ${r.depth}. For a depth buffer, use the depth option of a RenderTarget or the renderer.`);if(r.depth&&r.arrayLayerCount>1)throw new Error("[TextureSource] depth and arrayLayerCount can't be combined: use depth for a 3D texture or arrayLayerCount for a 2D array.");if(r.depth&&e!=="3d")throw new Error(`[TextureSource] depth makes a 3D texture, but viewDimension is '${e}'. Use arrayLayerCount for layered textures.`);if(e==="3d"&&r.arrayLayerCount>1)throw new Error("[TextureSource] a 3D texture takes depth, not arrayLayerCount.");if(r.dimensions&&r.dimensions!==t)throw new Error(`[TextureSource] dimensions '${r.dimensions}' doesn't match viewDimension '${e}'. Leave dimensions out; it is derived from the view.`);if(r.dimensions&&O(xu,"TextureSource dimensions is derived from viewDimension and depth; leave it out."),t==="3d"&&r.antialias)throw new Error("[TextureSource] a 3D texture can't be antialiased: WebGPU has no multisampled 3D textures.")}class mi extends de{constructor(e){const t=e.depth??e.arrayLayerCount??1,s=e.resource||new Float32Array(e.width*e.height*t*4);let i=e.format;i||(s instanceof Float32Array?i="rgba32float":s instanceof Int32Array||s instanceof Uint32Array?i="rgba32uint":s instanceof Int16Array||s instanceof Uint16Array?i="rgba16uint":(s instanceof Int8Array,i="bgra8unorm"));const n=ti(i)||t>1;super({...n&&{alphaMode:"no-premultiply-alpha"},...e,resource:s,format:i}),this.uploadMethodId="buffer",this._updateStart=0,this._updateEnd=1/0}update(e=0,t=1/0){if((e>0||t<1/0)&&this.depthOrArrayLayers>1)throw new Error("[BufferImageSource] a 3D texture or 2D array uploads whole: call update() with no range.");this._updateStart=e,this._updateEnd=t,super.update(),this._updateStart=0,this._updateEnd=1/0}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}}mi.extension=C.TextureSource;const xh=new L;class Fo{constructor(e,t){this.mapCoord=new L,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),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){this._texture!==e&&(this._texture?.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this)),this.update()}destroy(){this._texture?.removeListener("update",this.update,this),this._texture=null}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let i=0;i<e.length;i+=2){const n=e[i],o=e[i+1];t[i]=n*s.a+o*s.c+s.tx,t[i+1]=n*s.b+o*s.d+s.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 s=e.orig,i=e.trim;i&&(xh.set(s.width/i.width,0,0,s.height/i.height,-i.x/i.width,-i.y/i.height),this.mapCoord.append(xh));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 H extends Re{constructor({source:e,label:t,frame:s,orig:i,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:h}={}){if(super(),this.uid=ne("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new ee,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=e?.source??new de,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:c,height:u}=this._source;this.frame.width=c,this.frame.height=u}this.orig=i||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(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 Fo(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:i}=this._source,n=t.x/s,o=t.y/i,a=t.width/s,l=t.height/i;let h=this.rotate;if(h){const c=a/2,u=l/2,d=n+c,f=o+u;h=Z.add(h,Z.NW),e.x0=d+c*Z.uX(h),e.y0=f+u*Z.uY(h),h=Z.add(h,2),e.x1=d+c*Z.uX(h),e.y1=f+u*Z.uY(h),h=Z.add(h,2),e.x2=d+c*Z.uX(h),e.y2=f+u*Z.uY(h),h=Z.add(h,2),e.x3=d+c*Z.uX(h),e.y3=f+u*Z.uY(h)}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 O(ue,"Texture.baseTexture is now Texture.source"),this._source}}H.EMPTY=new H({label:"EMPTY",source:new de({label:"EMPTY"})});H.EMPTY.destroy=Go;H.WHITE=new H({source:new mi({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});H.WHITE.destroy=Go;function Lo(r,e,t){const{width:s,height:i}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;r.minX=n.x-e._x*s,r.maxX=r.minX+o,r.minY=n.y-e._y*i,r.maxY=r.minY+a}else r.minX=-e._x*s,r.maxX=r.minX+s,r.minY=-e._y*i,r.maxY=r.minY+i}const bh=new L;class ke{constructor(e=1/0,t=1/0,s=-1/0,i=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=bh,this.minX=e,this.minY=t,this.maxX=s,this.maxY=i}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new ee);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=bh,this}set(e,t,s,i){this.minX=e,this.minY=t,this.maxX=s,this.maxY=i}addFrame(e,t,s,i,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 d=this.minX,f=this.minY,p=this.maxX,m=this.maxY,g=o*e+l*t+c,_=a*e+h*t+u;g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*s+l*t+c,_=a*s+h*t+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*e+l*i+c,_=a*e+h*i+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*s+l*i+c,_=a*s+h*i+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),this.minX=d,this.minY=f,this.maxX=p,this.maxY=m}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,s=this.minY,i=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:h,tx:c,ty:u}=e;let d=o*t+l*s+c,f=a*t+h*s+u;this.minX=d,this.minY=f,this.maxX=d,this.maxY=f,d=o*i+l*s+c,f=a*i+h*s+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*t+l*n+c,f=a*t+h*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*i+l*n+c,f=a*i+h*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f: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,s,i){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>i&&(this.maxY=i),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 ke(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,s,i){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;i||(i=this.matrix);const h=i.a,c=i.b,u=i.c,d=i.d,f=i.tx,p=i.ty;for(let m=t;m<s;m+=2){const g=e[m],_=e[m+1],x=h*g+u*_+f,y=c*g+d*_+p;n=x<n?x:n,o=y<o?y:o,a=x>a?x:a,l=y>l?y: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 Vg={grad:.9,turn:360,rad:360/(2*Math.PI)},gt=function(r){return typeof r=="string"?r.length>0:typeof r=="number"},Me=function(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*r)/t+0},Ye=function(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),r>t?t:r>e?r:e},Su=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},vh=function(r){return{r:Ye(r.r,0,255),g:Ye(r.g,0,255),b:Ye(r.b,0,255),a:Ye(r.a)}},en=function(r){return{r:Me(r.r),g:Me(r.g),b:Me(r.b),a:Me(r.a,3)}},Xg=/^#([0-9a-f]{3,8})$/i,Mr=function(r){var e=r.toString(16);return e.length<2?"0"+e:e},Cu=function(r){var e=r.r,t=r.g,s=r.b,i=r.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-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:i}},Mu=function(r){var e=r.h,t=r.s,s=r.v,i=r.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:i}},wh=function(r){return{h:Su(r.h),s:Ye(r.s,0,100),l:Ye(r.l,0,100),a:Ye(r.a)}},Th=function(r){return{h:Me(r.h),s:Me(r.s),l:Me(r.l),a:Me(r.a,3)}},Sh=function(r){return Mu((t=(e=r).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},Js=function(r){return{h:(e=Cu(r)).h,s:(i=(200-(t=e.s))*(s=e.v)/100)>0&&i<200?t*s/100/(i<=100?i:200-i)*100:0,l:i/2,a:e.a};var e,t,s,i},jg=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,qg=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Yg=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kg=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,On={string:[[function(r){var e=Xg.exec(r);return e?(r=e[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:r.length===4?Me(parseInt(r[3]+r[3],16)/255,2):1}:r.length===6||r.length===8?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:r.length===8?Me(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var e=Yg.exec(r)||Kg.exec(r);return e?e[2]!==e[4]||e[4]!==e[6]?null:vh({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(r){var e=jg.exec(r)||qg.exec(r);if(!e)return null;var t,s,i=wh({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(Vg[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return Sh(i)},"hsl"]],object:[[function(r){var e=r.r,t=r.g,s=r.b,i=r.a,n=i===void 0?1:i;return gt(e)&&gt(t)&&gt(s)?vh({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(r){var e=r.h,t=r.s,s=r.l,i=r.a,n=i===void 0?1:i;if(!gt(e)||!gt(t)||!gt(s))return null;var o=wh({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return Sh(o)},"hsl"],[function(r){var e=r.h,t=r.s,s=r.v,i=r.a,n=i===void 0?1:i;if(!gt(e)||!gt(t)||!gt(s))return null;var o=(function(a){return{h:Su(a.h),s:Ye(a.s,0,100),v:Ye(a.v,0,100),a:Ye(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Mu(o)},"hsv"]]},Ch=function(r,e){for(var t=0;t<e.length;t++){var s=e[t][0](r);if(s)return[s,e[t][1]]}return[null,void 0]},Zg=function(r){return typeof r=="string"?Ch(r.trim(),On.string):typeof r=="object"&&r!==null?Ch(r,On.object):[null,void 0]},tn=function(r,e){var t=Js(r);return{h:t.h,s:Ye(t.s+100*e,0,100),l:t.l,a:t.a}},sn=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},Mh=function(r,e){var t=Js(r);return{h:t.h,s:t.s,l:Ye(t.l+100*e,0,100),a:t.a}},Un=(function(){function r(e){this.parsed=Zg(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return this.parsed!==null},r.prototype.brightness=function(){return Me(sn(this.rgba),2)},r.prototype.isDark=function(){return sn(this.rgba)<.5},r.prototype.isLight=function(){return sn(this.rgba)>=.5},r.prototype.toHex=function(){return e=en(this.rgba),t=e.r,s=e.g,i=e.b,o=(n=e.a)<1?Mr(Me(255*n)):"","#"+Mr(t)+Mr(s)+Mr(i)+o;var e,t,s,i,n,o},r.prototype.toRgb=function(){return en(this.rgba)},r.prototype.toRgbString=function(){return e=en(this.rgba),t=e.r,s=e.g,i=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+i+", "+n+")":"rgb("+t+", "+s+", "+i+")";var e,t,s,i,n},r.prototype.toHsl=function(){return Th(Js(this.rgba))},r.prototype.toHslString=function(){return e=Th(Js(this.rgba)),t=e.h,s=e.s,i=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+i+"%, "+n+")":"hsl("+t+", "+s+"%, "+i+"%)";var e,t,s,i,n},r.prototype.toHsv=function(){return e=Cu(this.rgba),{h:Me(e.h),s:Me(e.s),v:Me(e.v),a:Me(e.a,3)};var e},r.prototype.invert=function(){return nt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},r.prototype.saturate=function(e){return e===void 0&&(e=.1),nt(tn(this.rgba,e))},r.prototype.desaturate=function(e){return e===void 0&&(e=.1),nt(tn(this.rgba,-e))},r.prototype.grayscale=function(){return nt(tn(this.rgba,-1))},r.prototype.lighten=function(e){return e===void 0&&(e=.1),nt(Mh(this.rgba,e))},r.prototype.darken=function(e){return e===void 0&&(e=.1),nt(Mh(this.rgba,-e))},r.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},r.prototype.alpha=function(e){return typeof e=="number"?nt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Me(this.rgba.a,3);var t},r.prototype.hue=function(e){var t=Js(this.rgba);return typeof e=="number"?nt({h:e,s:t.s,l:t.l,a:t.a}):Me(t.h)},r.prototype.isEqual=function(e){return this.toHex()===nt(e).toHex()},r})(),nt=function(r){return r instanceof Un?r:new Un(r)},Eh=[],Qg=function(r){r.forEach(function(e){Eh.indexOf(e)<0&&(e(Un,On),Eh.push(e))})};function Jg(r,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"},s={};for(var i in t)s[t[i]]=i;var n={};r.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,h=s[this.toHex()];if(h)return h;if(o?.closest){var c=this.toRgb(),u=1/0,d="black";if(!n.length)for(var f in t)n[f]=new r(t[f]).toRgb();for(var p in t){var m=(a=c,l=n[p],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));m<u&&(u=m,d=p)}return d}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new r(l).toRgb():null},"name"])}Qg([Jg]);const Ss=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 s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="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,s,i]=this._components;return{r:e,g:t,b:s,a:i}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,i]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(i*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,i,n]=this._components;return e[0]=t,e[1]=s,e[2]=i,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,i]=this._components;return e[0]=t,e[1]=s,e[2]=i,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,i,n]=Ks._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=i,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 s=this._int>>16&255,i=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,i=i*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(i<<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,s,i,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,i=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,i,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,i,n=255]=e,t/=255,s/=255,i/=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=nt(e);o.isValid()&&({r:t,g:s,b:i,a:n}=o.rgba,t/=255,s/=255,i/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=i,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((i,n)=>{e[n]=Math.min(Math.max(i,t),s)}),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}};Ss.shared=new Ss;Ss._temp=new Ss;Ss.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let oe=Ss;const Eu={cullArea:null,cullable:!1,cullableChildren:!0};let rn=0;const kh=500;function N(...r){rn!==kh&&(rn++,rn===kh?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...r))}const as={_registeredResources:new Set,register(r){this._registeredResources.add(r)},unregister(r){this._registeredResources.delete(r)},release(){this._registeredResources.forEach(r=>r.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(r){return this._registeredResources.has(r)},reset(){this._registeredResources.clear()}};class ku{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){let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),t.init?.(e),t}return(e){e.reset?.(),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 Pu{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 ku(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Se=new Pu;as.register(Se);const Au={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(r){typeof r=="boolean"&&r===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(r===!0?{}:r))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(r){O("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(r)}};function Oo(r,e,t){const s=r.length;let i;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(i=e;i<n;++i)r[i]=r[i+t];r.length=n}const Ru={allowChildren:!0,removeChildren(r=0,e){const t=e??this.children.length,s=t-r,i=[];if(s>0&&s<=t){for(let o=t-1;o>=r;o--){const a=this.children[o];a&&(i.push(a),a.parent=null)}Oo(this.children,r,t);const n=this.renderGroup||this.parentRenderGroup;n&&n.removeChildren(i);for(let o=0;o<i.length;++o){const a=i[o];a.parentRenderLayer?.detach(a),this.emit("childRemoved",a,this,o),i[o].emit("removed",this)}return i.length>0&&this._didViewChangeTick++,i}else if(s===0&&this.children.length===0)return i;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(r){const e=this.getChildAt(r);return this.removeChild(e)},getChildAt(r){if(r<0||r>=this.children.length)throw new Error(`getChildAt: Index (${r}) does not exist.`);return this.children[r]},setChildIndex(r,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(r),this.addChildAt(r,e)},getChildIndex(r){const e=this.children.indexOf(r);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(r,e){this.allowChildren||O(ue,"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(`${r}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const s=r.parent===this;if(r.parent){const n=r.parent.children.indexOf(r);if(s){if(n===e)return r;r.parent.children.splice(n,1)}else r.removeFromParent()}e===t.length?t.push(r):t.splice(e,0,r);const i=this.renderGroup||this.parentRenderGroup;return this.sortableChildren&&(this.sortDirty=!0),s?(i&&(i.structureDidChange=!0),r):(r.parent=this,r.didChange=!0,r._updateFlags=15,i&&i.addChild(r),this.emit("childAdded",r,this,e),r.emit("added",this),r)},swapChildren(r,e){if(r===e)return;const t=this.getChildIndex(r),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=r;const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...r){return r.length===1?this.reparentChildAt(r[0],this.children.length):(r.forEach(e=>this.reparentChildAt(e,this.children.length)),r[0])},reparentChildAt(r,e){if(r.parent===this)return this.setChildIndex(r,e),r;const t=r.worldTransform.clone();r.removeFromParent(),this.addChildAt(r,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),r.setFromMatrix(t),r},replaceChild(r,e){r.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(r)),e.setFromMatrix(r.localTransform),e.updateLocalTransform(),this.removeChild(r)}},Bu={collectRenderables(r,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(r,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,r):this.collectRenderablesWithEffects(r,e,t))},collectRenderablesSimple(r,e,t){const s=this.children,i=s.length;for(let n=0;n<i;n++)s[n].collectRenderables(r,e,t)},collectRenderablesWithEffects(r,e,t){const{renderPipes:s}=e;for(let i=0;i<this.effects.length;i++){const n=this.effects[i];s[n.pipe].push(n,this,r)}this.collectRenderablesSimple(r,e,t);for(let i=this.effects.length-1;i>=0;i--){const n=this.effects[i];s[n.pipe].pop(n,this,r)}}};class lr{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 Iu{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 s=this._tests[t];if(s.test(e))return Se.get(s.maskClass,e)}return e}returnMaskEffect(e){Se.return(e)}}const si=new Iu;q.handleByList(C.MaskEffect,si._effectClasses);const Gu={_maskEffect:null,_maskOptions:{inverse:!1,channel:"red"},_filterEffect:null,effects:[],_markStructureAsChanged(){const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0)},addEffect(r){this.effects.indexOf(r)===-1&&(this.effects.push(r),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(r){const e=this.effects.indexOf(r);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(r){const e=this._maskEffect;e?.mask!==r&&(e&&(this.removeEffect(e),si.returnMaskEffect(e),this._maskEffect=null),r!=null&&(this._maskEffect=si.getMaskEffect(r),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(r){this._maskOptions={...this._maskOptions,...r},r.mask&&(this.mask=r.mask),this._markStructureAsChanged()},set filters(r){!Array.isArray(r)&&r&&(r=[r]);const e=this._filterEffect||(this._filterEffect=new lr);r=r;const t=r?.length>0,s=e.filters?.length>0,i=t!==s;r=Array.isArray(r)?r.slice(0):r,e.filters=Object.freeze(r),i&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=r??null))},get filters(){return this._filterEffect?.filters},set filterArea(r){this._filterEffect||(this._filterEffect=new lr),this._filterEffect.filterArea=r},get filterArea(){return this._filterEffect?.filterArea}},Du={label:null,get name(){return O(ue,"Container.name property has been removed, use Container.label instead"),this.label},set name(r){O(ue,"Container.name property has been removed, use Container.label instead"),this.label=r},getChildByName(r,e=!1){return this.getChildByLabel(r,e)},getChildByLabel(r,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const i=t[s];if(i.label===r||r instanceof RegExp&&r.test(i.label))return i}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(r,!0);if(n)return n}return null},getChildrenByLabel(r,e=!1,t=[]){const s=this.children;for(let i=0;i<s.length;i++){const n=s[i];(n.label===r||r instanceof RegExp&&r.test(n.label))&&t.push(n)}if(e)for(let i=0;i<s.length;i++)s[i].getChildrenByLabel(r,!0,t);return t}},Ae=Se.getPool(L),ct=Se.getPool(ke),e_=new L,Fu={getFastGlobalBounds(r,e){e||(e=new ke),e.clear(),this._getGlobalBoundsRecursive(!!r,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(r,e,t){let s=e;if(r&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const i=!!this.effects.length;if((this.renderGroup||i)&&(s=ct.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.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(r,s,t)}if(i){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,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(e_).invert()),e.addBounds(s),ct.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),ct.return(s))}};function gi(r,e,t){t.clear();let s,i;return r.parent?e?s=r.parent.worldTransform:(i=Ae.get().identity(),s=_i(r,i)):s=L.IDENTITY,Lu(r,t,s,e),i&&Ae.return(i),t.isValid||t.set(0,0,0,0),t}function Lu(r,e,t,s){if(!r.visible||!r.measurable)return;let i;s?i=r.worldTransform:(r.updateLocalTransform(),i=Ae.get(),i.appendFrom(r.localTransform,t));const n=e,o=!!r.effects.length;if(o&&(e=ct.get().clear()),r.boundsArea)e.addRect(r.boundsArea,i);else{const a=r.bounds;a&&!a.isEmpty()&&(e.matrix=i,e.addBounds(a));for(let l=0;l<r.children.length;l++)Lu(r.children[l],e,i,s)}if(o){for(let a=0;a<r.effects.length;a++)r.effects[a].addBounds?.(e);n.addBounds(e,L.IDENTITY),ct.return(e)}s||Ae.return(i)}function _i(r,e){const t=r.parent;return t&&(_i(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function Kt(r,e){if(r===16777215||!e)return e;if(e===16777215||!r)return r;const t=r>>16&255,s=r>>8&255,i=r&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,h=s*o/255|0,c=i*a/255|0;return(l<<16)+(h<<8)+c}const Ph=16777215;function hr(r,e){return r===Ph?e:e===Ph?r:Kt(r,e)}function Zt(r){return((r&255)<<16)+(r&65280)+(r>>16&255)}const Ou={getGlobalAlpha(r){if(r)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(r=new L,e){if(e)return r.copyFrom(this.worldTransform);this.updateLocalTransform();const t=_i(this,Ae.get().identity());return r.appendFrom(this.localTransform,t),Ae.return(t),r},getGlobalTint(r){if(r)return this.renderGroup?Zt(this.renderGroup.worldColor):this.parentRenderGroup?Zt(hr(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=hr(e,t.localColor),t=t.parent;return Zt(e)}};function yi(r,e,t){return e.clear(),t||(t=L.IDENTITY),Uu(r,e,t,r,!0),e.isValid||e.set(0,0,0,0),e}function Uu(r,e,t,s,i){let n;if(i)n=Ae.get(),n=t.copyTo(n);else{if(!r.visible||!r.measurable)return;r.updateLocalTransform();const l=r.localTransform;n=Ae.get(),n.appendFrom(l,t)}const o=e,a=!!r.effects.length;if(a&&(e=ct.get().clear()),r.boundsArea)e.addRect(r.boundsArea,n);else{r.renderPipeId&&(e.matrix=n,e.addBounds(r.bounds));const l=r.children;for(let h=0;h<l.length;h++)Uu(l[h],e,n,s,!1)}if(a){for(let l=0;l<r.effects.length;l++)r.effects[l].addLocalBounds?.(e,s);o.addBounds(e,L.IDENTITY),ct.return(e)}Ae.return(n)}function Uo(r,e){const t=r.children;for(let s=0;s<t.length;s++){const i=t[s],n=i.uid,o=(i._didViewChangeTick&65535)<<16|i._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,i.children.length&&Uo(i,e)}return e.didChange}const t_=new L,Nu={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(r,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=r/e*t:this.scale.x=t},_setHeight(r,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=r/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new ke});const r=this._localBoundsCacheData;return r.index=1,r.didChange=!1,r.data[0]!==this._didViewChangeTick&&(r.didChange=!0,r.data[0]=this._didViewChangeTick),Uo(this,r),r.didChange&&yi(this,r.localBounds,t_),r.localBounds},getBounds(r,e){return gi(this,r,e||new ke)}},Hu={_onRender:null,set onRender(r){const e=this.renderGroup||this.parentRenderGroup;if(!r){this._onRender&&e?.removeOnRender(this),this._onRender=null;return}this._onRender||e?.addOnRender(this),this._onRender=r},get onRender(){return this._onRender}},zu={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(r){this._zIndex!==r&&(this._zIndex=r,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(s_))}};function s_(r,e){return r._zIndex-e._zIndex}const Wu={getGlobalPosition(r=new he,e=!1){return this.parent?this.parent.toGlobal(this._position,r,e):(r.x=this._position.x,r.y=this._position.y),r},toGlobal(r,e,t=!1){const s=this.getGlobalTransform(Ae.get(),t);return e=s.apply(r,e),Ae.return(s),e},toLocal(r,e,t,s){e&&(r=e.toGlobal(r,t,s));const i=this.getGlobalTransform(Ae.get(),s);return t=i.applyInverse(r,t),Ae.return(i),t}};class xi{constructor(){this.uid=ne("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){if(this.renderPipes)for(const e in this.renderPipes)this.renderPipes[e].destroyInstructionSet?.(this);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"])}}class No{constructor(){this._screenSizes=new Map,this._widths=[],this._heights=[]}get size(){return this._screenSizes.size}set(e,t,s){const i=this._screenSizes.get(e);return i&&i.pixelWidth===t&&i.pixelHeight===s?!1:(this._screenSizes.set(e,{pixelWidth:t,pixelHeight:s}),this._update(),!0)}remove(e){return this._screenSizes.delete(e)?(this._update(),!0):!1}getFittingWidth(e){return this._getFittingAxis(e,this._widths)}getFittingHeight(e){return this._getFittingAxis(e,this._heights)}hasWidth(e){return this._widths.includes(e)}hasHeight(e){return this._heights.includes(e)}_getFittingAxis(e,t){for(let s=0;s<t.length;s++){const i=t[s];if(i>=e)return i}}_update(){this._widths=[...this._screenSizes.values()].map(e=>e.pixelWidth).filter((e,t,s)=>s.indexOf(e)===t).sort((e,t)=>e-t),this._heights=[...this._screenSizes.values()].map(e=>e.pixelHeight).filter((e,t,s)=>s.indexOf(e)===t).sort((e,t)=>e-t)}}let r_=0;const nn=32767,i_=4294967296,n_=8589934592,Ah=Object.create(null);let o_=0;function a_(r){const e=Ah[r];return e!==void 0?e:Ah[r]=o_++}function l_(r,e,t,s,i,n){return(r<<17)+(e<<2)+((s?1:0)<<1)+(t?1:0)+(n==="nearest"?1:0)*i_+a_(i)*n_}class $u{constructor(e){this._buckets=new Map,this._poolKey=Object.create(null),this._poolStyle=Object.create(null),this._screens=new No,this._enableFullScreen=!1,this.textureOptions=e||{}}get textureStyle(){return O(lt,"TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead."),this._textureStyle||(this._textureStyle=new Dt(this.textureOptions)),this._textureStyle}set textureStyle(e){O(lt,"TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead."),this._textureStyle=e}get enableFullScreen(){return O(lt,"TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize."),this._enableFullScreen}set enableFullScreen(e){O(lt,"TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize."),this._enableFullScreen=e}createTexture(...e){let t=e[0];typeof t=="number"&&(O(lt,"TexturePool.createTexture params are now an options object. See params: { width, height, antialias, autoGenerateMipmaps }"),t={width:t,height:e[1],antialias:e[2]??!1,autoGenerateMipmaps:e[3]??!1});const s=t.format??this.textureOptions.format??de.defaultOptions.format,i=t.scaleMode??this.textureOptions.scaleMode??Dt.defaultOptions.scaleMode,n=new de({...this.textureOptions,width:t.width,height:t.height,resolution:1,antialias:t.antialias??!1,autoGarbageCollect:!1,autoGenerateMipmaps:t.autoGenerateMipmaps??!1,format:s,scaleMode:i});return new H({source:n,label:`texturePool_${r_++}`})}getOptimalTexture(...e){let t=e[0];typeof t=="number"&&(O(lt,"TexturePool.getOptimalTexture params are now an options object. See params: { width, height, resolution, antialias, autoGenerateMipmaps }"),t={width:t,height:e[1],resolution:e[2]??1,antialias:e[3]??!1,autoGenerateMipmaps:e[4]??!1});const s=t.width,i=t.height,n=t.resolution??1,o=t.antialias??!1,a=t.autoGenerateMipmaps??!1,l=t.format??this.textureOptions.format??de.defaultOptions.format,h=t.scaleMode??this.textureOptions.scaleMode??Dt.defaultOptions.scaleMode,{width:c,height:u}=this.getOptimalSize(s,i,n);(c>nn||u>nn)&&N(`TexturePool: ${c}x${u} is larger than the ${nn}px pool key limit, textures of this size may be pooled together`);const d=l_(c,u,o,a,l,h);let f=this._buckets.get(d);f||(f=[],this._buckets.set(d,f));let p=f.pop();return p||(p=this.createTexture({width:c,height:u,antialias:o,autoGenerateMipmaps:a,format:l,scaleMode:h}),this._poolStyle[p.uid]=p.source.style),p.source._resolution=n,p.source.width=c/n,p.source.height=u/n,p.source.pixelWidth=c,p.source.pixelHeight=u,p.frame.x=0,p.frame.y=0,p.frame.width=s,p.frame.height=i,p.updateUvs(),this._poolKey[p.uid]=d,p}getOptimalSize(e,t,s=1){const i=Math.ceil(e*s-1e-6),n=Math.ceil(t*s-1e-6),o=es(i),a=this._screens.getFittingWidth(i),l=es(n),h=this._screens.getFittingHeight(n);return{width:a!==void 0?Math.min(a,o):o,height:h!==void 0?Math.min(h,l):l}}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture({width:e.width,height:e.height,resolution:s._resolution,antialias:t})}returnTexture(e,t=!1){const s=e.uid,i=this._poolKey[s];if(i===void 0){N("TexturePool: returnTexture was passed a texture that did not come from this pool, ignoring it");return}const n=this._poolStyle[s];t&&e.source.style!==n&&(e.source.style=n);const o=this._buckets.get(i);if(!o){delete this._poolKey[s],delete this._poolStyle[s],e.destroy(!0);return}o.push(e)}setScreenSize(e,t,s){this._screens.set(e,t,s)&&this._pruneScreenTextures()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenTextures()}_pruneScreenTextures(){for(const[e,t]of this._buckets){const s=e>>>0,i=s>>>17,n=s>>>2&32767;(ts(i)||this._screens.hasWidth(i))&&(ts(n)||this._screens.hasHeight(n))||(this._dropTextures(t,!0),this._buckets.delete(e))}}_dropTextures(e,t){for(let s=0;s<e.length;s++){const i=e[s];delete this._poolKey[i.uid],delete this._poolStyle[i.uid],t&&i.destroy(!0)}}clear(e){for(const t of this._buckets.values())this._dropTextures(t,e!==!1);this._buckets.clear()}}const Te=new $u;as.register(Te);class ri{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new L,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 xi,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 s=0;s<t.length;s++){const i=t[s];i._updateFlags=15,this.addChild(i)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Te.returnTexture(this.texture),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 s=0;s<t.length;s++)this.addChild(t[s])}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 s=0;s<t.length;s++)this.removeChild(t[s])}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.indexOf(e)===-1&&this._onRenderContainers.push(e)}removeOnRender(e){const t=this._onRenderContainers.indexOf(e);t!==-1&&this._onRenderContainers.splice(t,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?.destroy(),this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let i=0;i<s.length;i++)this._getChildren(s[i],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new L),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new L),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 L),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 Vu(r,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(r[s]=e[s])}const on=new Ce(null),Er=new Ce(null),an=new Ce(null,1,1),kr=new Ce(null),cr=1,bi=2,ws=4;class _e extends Re{constructor(e={}){super(),this.uid=ne("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 L,this.relativeGroupTransform=new L,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Ce(this,0,0),this._scale=an,this._pivot=Er,this._origin=kr,this._skew=on,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=[],Vu(this,e,{children:!0,parent:!0,effects:!0}),e.children?.forEach(t=>this.addChild(t)),e.parent?.addChild(this)}static mixin(e){O("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),q.mixin(_e,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||O(ue,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let i=0;i<e.length;i++)this.addChild(e[i]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.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,s&&s.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 i=0;i<e.length;i++)this.removeChild(e[i]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,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,s),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?.removeChild(this),this.renderGroup=Se.get(ri,this),this.groupTransform=L.IDENTITY,e?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),Se.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new L),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*mu}set angle(e){this.rotation=e*gu}get pivot(){return this._pivot===Er&&(this._pivot=new Ce(this,0,0)),this._pivot}set pivot(e){this._pivot===Er&&(this._pivot=new Ce(this,0,0),this._origin!==kr&&N("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===on&&(this._skew=new Ce(this,0,0)),this._skew}set skew(e){this._skew===on&&(this._skew=new Ce(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===an&&(this._scale=new Ce(this,1,1)),this._scale}set scale(e){this._scale===an&&(this._scale=new Ce(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===kr&&(this._origin=new Ce(this,0,0)),this._origin}set origin(e){this._origin===kr&&(this._origin=new Ce(this,0,0),this._pivot!==Er&&N("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 s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.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:this.scale.x,typeof e.scaleY=="number"?e.scaleY: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,s=this._scale,i=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,h=i._x,c=i._y,u=-n._x,d=-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-(h*t.a+c*t.c)+(u*t.a+d*t.c)-u,t.ty=o._y-(h*t.b+c*t.d)+(u*t.b+d*t.d)-d}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=cr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=oe.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=cr,this._onUpdate())}get tint(){return Zt(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=bi,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|=ws,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|=ws,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|=ws,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){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?.children)&&t)for(let i=0;i<t.length;++i)t[i].destroy(e);this.renderGroup?.destroy(),this.renderGroup=null}}q.mixin(_e,Ru,Fu,Wu,Hu,Nu,Gu,Du,zu,Eu,Au,Ou,Bu);class vi extends _e{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 ke(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:s,y:i}=e;return s>=t.minX&&s<=t.maxX&&i>=t.minY&&i<=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(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,s){const{renderPipes:i}=t;i.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=i[this.renderPipeId];o?.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let h=0;h<l;h++)a[h].collectRenderables(e,t,s);i.blendMode.popBlendMode(e)}}class ss extends vi{constructor(e=H.EMPTY){e instanceof H&&(e={texture:e});const{texture:t=H.EMPTY,anchor:s,roundPixels:i,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 Ce({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=i??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof H?new ss(e):new ss(H.from(e,t))}set texture(e){e||(e=H.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 Lo(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return O("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:i,height:n}=t.orig;s.minX=-e._x*i,s.maxX=s.minX+i,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._texture.destroy(s)}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 h_=new ke;function Ho(r,e,t){const s=h_;r.measurable=!0,gi(r,t,s),e.addBoundsMask(s),r.measurable=!1}function zo(r,e,t){const s=ct.get();r.measurable=!0;const i=Ae.get().identity(),n=Xu(r,t,i);yi(r,s,n),r.measurable=!1,e.addBoundsMask(s),Ae.return(i),ct.return(s)}function Xu(r,e,t){return r?(r!==e&&(Xu(r.parent,e,t),r.updateLocalTransform(),t.append(r.localTransform)),t):(N("Mask bounds, renderable is not inside the root container"),t)}class Wo{constructor(e){this.priority=0,this.inverse=!1,this.channel="red",this.pipe="alphaMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof ss),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||Ho(this.mask,e,t)}addLocalBounds(e,t){zo(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof ss}}Wo.extension=C.MaskEffect;class $o{constructor(e){this.priority=0,this.pipe="colorMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}$o.extension=C.MaskEffect;class Vo{constructor(e){this.priority=0,this.pipe="stencilMask",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){Ho(this.mask,e,t)}addLocalBounds(e,t){zo(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof _e}}Vo.extension=C.MaskEffect;const ju={createCanvas:(r,e)=>{const t=document.createElement("canvas");return t.width=r,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(r,e)=>fetch(r,e),parseXML:r=>new DOMParser().parseFromString(r,"text/xml")};let Rh=ju;const J={get(){return Rh},set(r){Rh=r}};class Ve extends de{constructor(e){e.resource||(e.resource=J.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,s=this._resolution){const i=super.resize(e,t,s);return i&&this.resizeCanvas(),i}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"))}}Ve.extension=C.TextureSource;class ur 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}}ur.extension=C.TextureSource;var rs=(r=>(r[r.INTERACTION=50]="INTERACTION",r[r.HIGH=25]="HIGH",r[r.NORMAL=0]="NORMAL",r[r.LOW=-25]="LOW",r[r.UTILITY=-50]="UTILITY",r))(rs||{});class Xr{constructor(e,t=null,s=0,i=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=i}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 qu=class Ne{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/Ne.targetFPMS,this.elapsedMS=1/Ne.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,s=rs.NORMAL){return this._addListener(new Xr(e,t,s))}addOnce(e,t,s=rs.NORMAL){return this._addListener(new Xr(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.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*Ne.targetFPMS;const s=this._head;let i=s.next;for(;i;)i=i.emit(this);s.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,Ne.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(!Ne._shared){const e=Ne._shared=new Ne;e.autoStart=!0,e._protected=!0}return Ne._shared}static get system(){if(!Ne._system){const e=Ne._system=new Ne;e.autoStart=!0,e._protected=!0}return Ne._system}};qu.targetFPMS=.06;let We=qu,ln;async function Yu(){return ln??(ln=(async()=>{const e=J.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(o=>{const a=document.createElement("video");a.onloadeddata=()=>o(a),a.onerror=()=>o(null),a.autoplay=!1,a.crossOrigin="anonymous",a.preload="auto",a.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",a.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,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(i),e.deleteTexture(s),e.getExtension("WEBGL_lose_context")?.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),ln}const wi=class Ku extends de{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Ku.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),this._onLoadedMetadata=this._onLoadedMetadata.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=We.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.isValid||e.addEventListener("loadedmetadata",this._onLoadedMetadata),this.alphaMode=await Yu(),this._load=new Promise((s,i)=>{this.isValid?s(this):(this._resolve=s,this._reject=i,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._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onLoadedMetadata(){this.isValid&&this._mediaReady()}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlayThrough),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.isValid&&(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("loadedmetadata",this._onLoadedMetadata),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&&(We.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||(We.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(We.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};wi.extension=C.TextureSource;wi.defaultOptions={...de.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};wi.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Zu=wi;const jt=(r,e,t=!1)=>(Array.isArray(r)||(r=[r]),e?r.map(s=>typeof s=="string"||t?e(s):s):r);class c_{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||N(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=jt(e);let i;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.test(t)){i=h.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(i||{}));i||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const h=i?i[l]:t;this._cache.has(l)&&this._cache.get(l)!==h&&N("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){N(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(i=>{this._cache.delete(i)}),t.keys.forEach(i=>{this._cacheMap.delete(i)})}get parsers(){return this._parsers}}const qt=new c_,Nn=[];q.handleByList(C.TextureSource,Nn);function Qu(r={}){const e=r&&r.resource,t=e?r.resource:r,s=e?r:{resource:r};for(let i=0;i<Nn.length;i++){const n=Nn[i];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function Ju(r={},e=!1){const t=r&&r.resource,s=t?r.resource:r,i=t?r:{resource:r};if(!e&&qt.has(s))return qt.get(s);const n=new H({source:Qu(i)});return n.on("destroy",()=>{qt.has(s)&&qt.remove(s)}),e||qt.set(s,n),n}function ed(r,e=!1){return typeof r=="string"?qt.get(r):r instanceof de?new H({source:r}):Ju(r,e)}H.from=ed;de.from=Qu;q.add(Wo,$o,Vo,Zu,ur,Ve,mi);var Xo=(r=>(r[r.Low=0]="Low",r[r.Normal=1]="Normal",r[r.High=2]="High",r))(Xo||{});function et(r){if(typeof r!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(r)}`)}function Os(r){return r.split("?")[0].split("#")[0]}function u_(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d_(r,e,t){return r.replace(new RegExp(u_(e),"g"),t)}function f_(r,e){let t="",s=0,i=-1,n=0,o=-1;for(let a=0;a<=r.length;++a){if(a<r.length)o=r.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(i===a-1||n===1))if(i!==a-1&&n===2){if(t.length<2||s!==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="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),i=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,i=a,n=0;continue}}}else t.length>0?t+=`/${r.slice(i+1,a)}`:t=r.slice(i+1,a),s=a-i-1;i=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Cs={toPosix(r){return d_(r,"\\","/")},isUrl(r){return/^https?:/.test(this.toPosix(r))},isDataUrl(r){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(r)},isBlobUrl(r){return r.startsWith("blob:")},hasProtocol(r){return/^[^/:]+:/.test(this.toPosix(r))},getProtocol(r){et(r),r=this.toPosix(r);const e=/^file:\/\/\//.exec(r);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(r);return t?t[0]:""},toAbsolute(r,e,t){if(et(r),this.isDataUrl(r)||this.isBlobUrl(r))return r;const s=Os(this.toPosix(e??J.get().getBaseUrl())),i=Os(this.toPosix(t??this.rootname(s)));return r=this.toPosix(r),r.startsWith("/")?Cs.join(i,r.slice(1)):this.isAbsolute(r)?r:this.join(s,r)},normalize(r){if(et(r),r.length===0)return".";if(this.isDataUrl(r)||this.isBlobUrl(r))return r;r=this.toPosix(r);let e="";const t=r.startsWith("/");this.hasProtocol(r)&&(e=this.rootname(r),r=r.slice(e.length));const s=r.endsWith("/");return r=f_(r),r.length>0&&s&&(r+="/"),t?`/${r}`:e+r},isAbsolute(r){return et(r),r=this.toPosix(r),this.hasProtocol(r)?!0:r.startsWith("/")},join(...r){if(r.length===0)return".";let e;for(let t=0;t<r.length;++t){const s=r[t];if(et(s),s.length>0)if(e===void 0)e=s;else{const i=r[t-1]??"";this.joinExtensions.includes(this.extname(i).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(r){if(et(r),r.length===0)return".";r=this.toPosix(r);let e=r.charCodeAt(0);const t=e===47;let s=-1,i=!0;const n=this.getProtocol(r),o=r;r=r.slice(n.length);for(let a=r.length-1;a>=1;--a)if(e=r.charCodeAt(a),e===47){if(!i){s=a;break}}else i=!1;return s===-1?t?"/":this.isUrl(o)?n+r:n:t&&s===1?"//":n+r.slice(0,s)},rootname(r){et(r),r=this.toPosix(r);let e="";if(r.startsWith("/")?e="/":e=this.getProtocol(r),this.isUrl(r)){const t=r.indexOf("/",e.length);t!==-1?e=r.slice(0,t):e=r,e.endsWith("/")||(e+="/")}return e},basename(r,e){et(r),e&&et(e),r=Os(this.toPosix(r));let t=0,s=-1,i=!0,n;if(e!==void 0&&e.length>0&&e.length<=r.length){if(e.length===r.length&&e===r)return"";let o=e.length-1,a=-1;for(n=r.length-1;n>=0;--n){const l=r.charCodeAt(n);if(l===47){if(!i){t=n+1;break}}else a===-1&&(i=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=r.length),r.slice(t,s)}for(n=r.length-1;n>=0;--n)if(r.charCodeAt(n)===47){if(!i){t=n+1;break}}else s===-1&&(i=!1,s=n+1);return s===-1?"":r.slice(t,s)},extname(r){et(r),r=Os(this.toPosix(r));let e=-1,t=0,s=-1,i=!0,n=0;for(let o=r.length-1;o>=0;--o){const a=r.charCodeAt(o);if(a===47){if(!i){t=o+1;break}continue}s===-1&&(i=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":r.slice(e,s)},parse(r){et(r);const e={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return e;r=Os(this.toPosix(r));let t=r.charCodeAt(0);const s=this.isAbsolute(r);let i;e.root=this.rootname(r),s||this.hasProtocol(r)?i=1:i=0;let n=-1,o=0,a=-1,l=!0,h=r.length-1,c=0;for(;h>=i;--h){if(t=r.charCodeAt(h),t===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),t===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&&s?e.base=e.name=r.slice(1,a):e.base=e.name=r.slice(o,a)):(o===0&&s?(e.name=r.slice(1,n),e.base=r.slice(1,a)):(e.name=r.slice(o,n),e.base=r.slice(o,a)),e.ext=r.slice(n,a)),e.dir=this.dirname(r),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function td(r,e,t,s,i){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?td(r.replace(s[t],a),e,t+1,s,i):i.push(r.replace(s[t],a))}}function sd(r){const e=/\{(.*?)\}/g,t=r.match(e),s=[];if(t){const i=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");i.push(o)}),td(r,i,0,t,s)}else s.push(r);return s}const Hn=r=>!Array.isArray(r);class jo{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(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return jt(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>o?.src??o):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&&N("[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 s=[];let i=t;Array.isArray(t)||(i=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),i.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const h=this._createBundleAssetId(e,a);s.push(h),l=[a,h]}else{const h=a.map(c=>this._createBundleAssetId(e,c));s.push(...h),l=[...a,...h]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&N(`[Resolver] already has key: ${n} overwriting`)},jt(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:h,parser:c}=n;const u=jt(o).map(m=>typeof m=="string"?sd(m):Array.isArray(m)?m:[m]),d=this.getAlias(n);Array.isArray(d)?d.forEach(s):s(d);const f=[],p=m=>{const g=this._parsers.find(_=>_.test(m));return{src:m,...g?.parse(m)}};u.forEach(m=>{m.forEach(g=>{let _={};if(typeof g!="object"?_=p(g):(a=g.data??a,l=g.format??l,(g.loadParser||g.parser)&&(h=g.loadParser??h,c=g.parser??c),_={...p(g.src),...g}),!d)throw new Error(`[Resolver] alias is undefined for this asset: ${_.src}`);_=this._buildResolvedAsset(_,{aliases:d,data:a,format:l,loadParser:h,parser:c,progressSize:n.progressSize}),f.push(_)})}),d.forEach(m=>{this._assetMap[m]=f})})}resolveBundle(e){const t=Hn(e);e=jt(e);const s={};return e.forEach(i=>{const n=this._bundles[i];if(n){const o=this.resolve(n),a={};for(const l in o){const h=o[l];a[this._extractAssetIdFromBundle(i,l)]=h}s[i]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const i in t)s[i]=t[i].src;return s}return t.src}resolve(e){const t=Hn(e);e=jt(e);const s={};return e.forEach(i=>{if(!this._resolverHash[i])if(this._assetMap[i]){let n=this._assetMap[i];const o=this._getPreferredOrder(n);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[i]=n[0]}else this._resolverHash[i]=this._buildResolvedAsset({alias:[i],src:i},{});s[i]=this._resolverHash[i]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],i=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(i)return i}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:s,data:i,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Cs.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...i||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??rd(e.src),l!==void 0&&(e.progressSize=l),e}}jo.RETINA_PREFIX=/@([0-9\.]+)x/;function rd(r){return r.split(".").pop().split("?").shift().split("#").shift()}const zn=(r,e)=>{const t=e.split("?")[1];return t&&(r+=`?${t}`),r},id=class Zs{constructor(e,t){this.linkedSheets=[];let s=e;e?.source instanceof de&&(s={texture:e,data:t});const{texture:i,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=i instanceof H?i:null,this.textureSource=i.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,i.source.resolution=this.resolution):this.resolution=i.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<=Zs.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 s=e;const i=t?1/0:Zs.BATCH_SIZE;for(;s-e<i&&s<this._frameKeys.length;){const n=this._frameKeys[s],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 ee(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?l=new ee(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 ee(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 ee(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 H({source:this.textureSource,frame:l,orig:u,trim:h,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}s++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const i=e[t][s];this.animations[t].push(this.textures[i])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Zs.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Zs.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(const t in this.textures)this.textures[t].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};id.BATCH_SIZE=1e3;let Wn=id;const p_=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function nd(r,e,t){const s={};if(r.forEach(i=>{s[i]=e}),Object.keys(e.textures).forEach(i=>{s[`${e.cachePrefix}${i}`]=e.textures[i]}),!t){const i=Cs.dirname(r[0]);e.linkedSheets.forEach((n,o)=>{const a=nd([`${i}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const od={extension:C.Asset,cache:{test:r=>r instanceof Wn,getCacheableAssets:(r,e)=>nd(r,e,!1)},resolver:{extension:{type:C.ResolveParser,name:"resolveSpritesheet"},test:r=>{const t=r.split("?")[0].split("."),s=t.pop(),i=t.pop();return s==="json"&&p_.includes(i)},parse:r=>{const e=r.split(".");return{resolution:parseFloat(jo.RETINA_PREFIX.exec(r)?.[1]??"1"),format:e[e.length-2],src:r}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:C.LoadParser,priority:Xo.Normal,name:"spritesheetLoader"},async testParse(r,e){return Cs.extname(e.src).toLowerCase()===".json"&&!!r.frames},async parse(r,e,t){const{texture:s,imageFilename:i,textureOptions:n,cachePrefix:o}=e?.data??{};let a=Cs.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof H)l=s;else{const u=zn(a+(i??r.meta.image),e.src);l=(await t.load([{src:u,data:n}]))[u]}const h=new Wn({texture:l.source,data:r,cachePrefix:o});await h.parse();const c=r?.meta?.related_multi_packs;if(Array.isArray(c)){const u=[];for(const f of c){if(typeof f!="string")continue;let p=a+f;e.data?.ignoreMultiPack||(p=zn(p,e.src),u.push(t.load({src:p,data:{textureOptions:n,ignoreMultiPack:!0}})))}const d=await Promise.all(u);h.linkedSheets=d,d.forEach(f=>{f.linkedSheets=[h].concat(h.linkedSheets.filter(p=>p!==f))})}return h},async unload(r,e,t){await t.unload(r.textureSource._sourceOrigin),r.destroy(!1)}}};q.add(od);class qo{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,i=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/i*this._renderer.resolution,a=t.left,l=t.top,h=`translate(${a}px, ${l}px) scale(${n}, ${o})`;h!==this._lastTransform&&(this._domElement.style.transform=h,this._lastTransform=h)},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 s=this.canvas.width,i=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/i*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||We.shared.add(this.updateTranslation,this,rs.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&We.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 Bs{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Bs.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new he,this.page=new he,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,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,i,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 hn=/iPhone/i,Bh=/iPod/i,Ih=/iPad/i,Gh=/\biOS-universal(?:.+)Mac\b/i,cn=/\bAndroid(?:.+)Mobile\b/i,Dh=/Android/i,cs=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Pr=/Silk/i,_t=/Windows Phone/i,Fh=/\bWindows(?:.+)ARM\b/i,Lh=/BlackBerry/i,Oh=/BB10/i,Uh=/Opera Mini/i,Nh=/\b(CriOS|Chrome)(?:.+)Mobile/i,Hh=/Mobile(?:.+)Firefox\b/i,zh=function(r){return typeof r<"u"&&r.platform==="MacIntel"&&typeof r.maxTouchPoints=="number"&&r.maxTouchPoints>1&&typeof MSStream>"u"};function m_(r){return function(e){return e.test(r)}}function Wh(r){var e={userAgent:"",platform:"",maxTouchPoints:0};!r&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof r=="string"?e.userAgent=r:r&&r.userAgent&&(e={userAgent:r.userAgent,platform:r.platform,maxTouchPoints:r.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var i=m_(t),n={apple:{phone:i(hn)&&!i(_t),ipod:i(Bh),tablet:!i(hn)&&(i(Ih)||zh(e))&&!i(_t),universal:i(Gh),device:(i(hn)||i(Bh)||i(Ih)||i(Gh)||zh(e))&&!i(_t)},amazon:{phone:i(cs),tablet:!i(cs)&&i(Pr),device:i(cs)||i(Pr)},android:{phone:!i(_t)&&i(cs)||!i(_t)&&i(cn),tablet:!i(_t)&&!i(cs)&&!i(cn)&&(i(Pr)||i(Dh)),device:!i(_t)&&(i(cs)||i(Pr)||i(cn)||i(Dh))||i(/\bokhttp\b/i)},windows:{phone:i(_t),tablet:i(Fh),device:i(_t)||i(Fh)},other:{blackberry:i(Lh),blackberry10:i(Oh),opera:i(Uh),firefox:i(Hh),chrome:i(Nh),device:i(Lh)||i(Oh)||i(Uh)||i(Hh)||i(Nh)},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 g_=Wh.default??Wh,ad=g_(globalThis.navigator),__=9,$h=100,y_=0,x_=0,Vh=2,Xh=1,b_=-1e3,v_=-1e3,w_=2,Yo=class ld{constructor(e,t=ad){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=`${Xh}px`,e.style.height=`${Xh}px`,e.style.position="absolute",e.style.top=`${b_}px`,e.style.left=`${v_}px`,e.style.zIndex=w_.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=`${y_}px`,this._div.style.left=`${x_}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Vh.toString(),this._canvasObserver=new qo({domElement:this._div,renderer:this._renderer})),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(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._renderer.runners.postrender.remove(this);for(const e of this._children)e._accessibleDiv?.parentNode&&(e._accessibleDiv.parentNode.removeChild(e._accessibleDiv),e._accessibleDiv=null),e._accessibleActive=!1;for(const e in this._pools)this._pools[e].forEach(s=>{s.parentNode&&s.parentNode.removeChild(s)}),delete this._pools[e];this._div?.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 s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...ld.defaultOptions,...e?.accessibilityOptions||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),s.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 s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const i=this._children[s];t.has(s)||(i._accessibleDiv&&i._accessibleDiv.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),this._getPool(i.accessibleType).push(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1,Oo(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const i=this._children[s];if(!i._accessibleActive||!i._accessibleDiv)continue;const n=i._accessibleDiv,o=i.hitArea||i.getBounds().rectangle;if(i.hitArea){const a=i.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:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?(s=document.createElement("button"),this.debug||(s.style.color="transparent")):(s=document.createElement(e.accessibleType),s.style.cssText=`
5
+ `),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",i),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",i),console.warn(s))),_h.add(e)});Object.defineProperties(O,{quiet:{get:()=>vs.quiet,set:r=>{vs.quiet=r},enumerable:!0,configurable:!1},noColor:{get:()=>vs.noColor,set:r=>{vs.noColor=r},enumerable:!0,configurable:!1}});const Go=()=>{};function ti(r){return r.endsWith("int")}function es(r){return r+=r===0?1:0,--r,r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r+1}function ts(r){return!(r&r-1)&&!!r}function Do(r){const e={};for(const t in r)r[t]!==void 0&&(e[t]=r[t]);return e}const yh=Object.create(null);function zg(r){const e=yh[r];return e===void 0&&(yh[r]=ne("resource")),e}const bu=class vu extends Re{constructor(e={}){super(),this._resourceType="textureSampler",this._maxAnisotropy=1,this.destroyed=!1,e={...vu.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){O(ue,"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=zg(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};bu.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Dt=bu;const wu=class Tu extends Re{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=ne("textureSource"),this._resourceType="textureSource",this._resourceId=ne("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.depth=1,this._ownsStyle=!1,this.antialias=!1,this.transient=!1,this.storage=!1,this._batchTick=-1,this._textureBindLocation=-1;const t=e;e={...Tu.defaultOptions,...e};const s=Wg(e),i=s==="3d"||s==="1d"?s:"2d";$g(t,s,i),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=i,this.viewDimension=s,this.arrayLayerCount=e.arrayLayerCount,this.depth=i==="3d"?e.depth??1:1,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=i==="3d"?!1:e.antialias,this.transient=e.transient??!1,this.storage=e.storage??!1,this.alphaMode=e.alphaMode,this.style=new Dt(Do(e)),this._ownsStyle=!0,this.destroyed=!1,this._refreshPOT()}get depthOrArrayLayers(){return this.dimension==="3d"?this.depth:this.arrayLayerCount||1}get source(){return this}get style(){return this._style}set style(e){this.style!==e&&(this._ownsStyle=!1,this._style?.off("change",this._onStyleChange,this),this._style=e,this._style?.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._ownsStyle&&this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=ne("resource"),this.emit("change",this),this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy?.();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,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const i=Math.round(e*s),n=Math.round(t*s);return this.width=i/s,this.height=n/s,this._resolution=s,this.pixelWidth===i&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=i,this.pixelHeight=n,this.emit("resize",this),this._resourceId=ne("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=ts(this.pixelWidth)&&ts(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};wu.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let de=wu;function Wg(r){return r.viewDimension?r.viewDimension:r.depth?"3d":r.arrayLayerCount>1?"2d-array":"2d"}function $g(r,e,t){if(r.depth!==void 0&&typeof r.depth!="number")throw new Error(`[TextureSource] depth is a 3D texture's depth in texels, but got ${r.depth}. For a depth buffer, use the depth option of a RenderTarget or the renderer.`);if(r.depth&&r.arrayLayerCount>1)throw new Error("[TextureSource] depth and arrayLayerCount can't be combined: use depth for a 3D texture or arrayLayerCount for a 2D array.");if(r.depth&&e!=="3d")throw new Error(`[TextureSource] depth makes a 3D texture, but viewDimension is '${e}'. Use arrayLayerCount for layered textures.`);if(e==="3d"&&r.arrayLayerCount>1)throw new Error("[TextureSource] a 3D texture takes depth, not arrayLayerCount.");if(r.dimensions&&r.dimensions!==t)throw new Error(`[TextureSource] dimensions '${r.dimensions}' doesn't match viewDimension '${e}'. Leave dimensions out; it is derived from the view.`);if(r.dimensions&&O(xu,"TextureSource dimensions is derived from viewDimension and depth; leave it out."),t==="3d"&&r.antialias)throw new Error("[TextureSource] a 3D texture can't be antialiased: WebGPU has no multisampled 3D textures.")}class mi extends de{constructor(e){const t=e.depth??e.arrayLayerCount??1,s=e.resource||new Float32Array(e.width*e.height*t*4);let i=e.format;i||(s instanceof Float32Array?i="rgba32float":s instanceof Int32Array||s instanceof Uint32Array?i="rgba32uint":s instanceof Int16Array||s instanceof Uint16Array?i="rgba16uint":(s instanceof Int8Array,i="bgra8unorm"));const n=ti(i)||t>1;super({...n&&{alphaMode:"no-premultiply-alpha"},...e,resource:s,format:i}),this.uploadMethodId="buffer",this._updateStart=0,this._updateEnd=1/0}update(e=0,t=1/0){if((e>0||t<1/0)&&this.depthOrArrayLayers>1)throw new Error("[BufferImageSource] a 3D texture or 2D array uploads whole: call update() with no range.");this._updateStart=e,this._updateEnd=t,super.update(),this._updateStart=0,this._updateEnd=1/0}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}}mi.extension=S.TextureSource;const xh=new L;class Fo{constructor(e,t){this.mapCoord=new L,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),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){this._texture!==e&&(this._texture?.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this)),this.update()}destroy(){this._texture?.removeListener("update",this.update,this),this._texture=null}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let i=0;i<e.length;i+=2){const n=e[i],o=e[i+1];t[i]=n*s.a+o*s.c+s.tx,t[i+1]=n*s.b+o*s.d+s.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 s=e.orig,i=e.trim;i&&(xh.set(s.width/i.width,0,0,s.height/i.height,-i.x/i.width,-i.y/i.height),this.mapCoord.append(xh));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 H extends Re{constructor({source:e,label:t,frame:s,orig:i,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:h}={}){if(super(),this.uid=ne("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new ee,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=e?.source??new de,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:c,height:u}=this._source;this.frame.width=c,this.frame.height=u}this.orig=i||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(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 Fo(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:i}=this._source,n=t.x/s,o=t.y/i,a=t.width/s,l=t.height/i;let h=this.rotate;if(h){const c=a/2,u=l/2,d=n+c,f=o+u;h=Z.add(h,Z.NW),e.x0=d+c*Z.uX(h),e.y0=f+u*Z.uY(h),h=Z.add(h,2),e.x1=d+c*Z.uX(h),e.y1=f+u*Z.uY(h),h=Z.add(h,2),e.x2=d+c*Z.uX(h),e.y2=f+u*Z.uY(h),h=Z.add(h,2),e.x3=d+c*Z.uX(h),e.y3=f+u*Z.uY(h)}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 O(ue,"Texture.baseTexture is now Texture.source"),this._source}}H.EMPTY=new H({label:"EMPTY",source:new de({label:"EMPTY"})});H.EMPTY.destroy=Go;H.WHITE=new H({source:new mi({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});H.WHITE.destroy=Go;function Lo(r,e,t){const{width:s,height:i}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;r.minX=n.x-e._x*s,r.maxX=r.minX+o,r.minY=n.y-e._y*i,r.maxY=r.minY+a}else r.minX=-e._x*s,r.maxX=r.minX+s,r.minY=-e._y*i,r.maxY=r.minY+i}const bh=new L;class ke{constructor(e=1/0,t=1/0,s=-1/0,i=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=bh,this.minX=e,this.minY=t,this.maxX=s,this.maxY=i}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new ee);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=bh,this}set(e,t,s,i){this.minX=e,this.minY=t,this.maxX=s,this.maxY=i}addFrame(e,t,s,i,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 d=this.minX,f=this.minY,p=this.maxX,m=this.maxY,g=o*e+l*t+c,_=a*e+h*t+u;g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*s+l*t+c,_=a*s+h*t+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*e+l*i+c,_=a*e+h*i+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),g=o*s+l*i+c,_=a*s+h*i+u,g<d&&(d=g),_<f&&(f=_),g>p&&(p=g),_>m&&(m=_),this.minX=d,this.minY=f,this.maxX=p,this.maxY=m}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,s=this.minY,i=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:h,tx:c,ty:u}=e;let d=o*t+l*s+c,f=a*t+h*s+u;this.minX=d,this.minY=f,this.maxX=d,this.maxY=f,d=o*i+l*s+c,f=a*i+h*s+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*t+l*n+c,f=a*t+h*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*i+l*n+c,f=a*i+h*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f: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,s,i){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>i&&(this.maxY=i),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 ke(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,s,i){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;i||(i=this.matrix);const h=i.a,c=i.b,u=i.c,d=i.d,f=i.tx,p=i.ty;for(let m=t;m<s;m+=2){const g=e[m],_=e[m+1],x=h*g+u*_+f,y=c*g+d*_+p;n=x<n?x:n,o=y<o?y:o,a=x>a?x:a,l=y>l?y: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 Vg={grad:.9,turn:360,rad:360/(2*Math.PI)},gt=function(r){return typeof r=="string"?r.length>0:typeof r=="number"},Me=function(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*r)/t+0},Ye=function(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),r>t?t:r>e?r:e},Su=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},vh=function(r){return{r:Ye(r.r,0,255),g:Ye(r.g,0,255),b:Ye(r.b,0,255),a:Ye(r.a)}},en=function(r){return{r:Me(r.r),g:Me(r.g),b:Me(r.b),a:Me(r.a,3)}},Xg=/^#([0-9a-f]{3,8})$/i,Mr=function(r){var e=r.toString(16);return e.length<2?"0"+e:e},Cu=function(r){var e=r.r,t=r.g,s=r.b,i=r.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-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:i}},Mu=function(r){var e=r.h,t=r.s,s=r.v,i=r.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:i}},wh=function(r){return{h:Su(r.h),s:Ye(r.s,0,100),l:Ye(r.l,0,100),a:Ye(r.a)}},Th=function(r){return{h:Me(r.h),s:Me(r.s),l:Me(r.l),a:Me(r.a,3)}},Sh=function(r){return Mu((t=(e=r).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},Js=function(r){return{h:(e=Cu(r)).h,s:(i=(200-(t=e.s))*(s=e.v)/100)>0&&i<200?t*s/100/(i<=100?i:200-i)*100:0,l:i/2,a:e.a};var e,t,s,i},jg=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,qg=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Yg=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kg=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,On={string:[[function(r){var e=Xg.exec(r);return e?(r=e[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:r.length===4?Me(parseInt(r[3]+r[3],16)/255,2):1}:r.length===6||r.length===8?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:r.length===8?Me(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var e=Yg.exec(r)||Kg.exec(r);return e?e[2]!==e[4]||e[4]!==e[6]?null:vh({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(r){var e=jg.exec(r)||qg.exec(r);if(!e)return null;var t,s,i=wh({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(Vg[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return Sh(i)},"hsl"]],object:[[function(r){var e=r.r,t=r.g,s=r.b,i=r.a,n=i===void 0?1:i;return gt(e)&&gt(t)&&gt(s)?vh({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(r){var e=r.h,t=r.s,s=r.l,i=r.a,n=i===void 0?1:i;if(!gt(e)||!gt(t)||!gt(s))return null;var o=wh({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return Sh(o)},"hsl"],[function(r){var e=r.h,t=r.s,s=r.v,i=r.a,n=i===void 0?1:i;if(!gt(e)||!gt(t)||!gt(s))return null;var o=(function(a){return{h:Su(a.h),s:Ye(a.s,0,100),v:Ye(a.v,0,100),a:Ye(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Mu(o)},"hsv"]]},Ch=function(r,e){for(var t=0;t<e.length;t++){var s=e[t][0](r);if(s)return[s,e[t][1]]}return[null,void 0]},Zg=function(r){return typeof r=="string"?Ch(r.trim(),On.string):typeof r=="object"&&r!==null?Ch(r,On.object):[null,void 0]},tn=function(r,e){var t=Js(r);return{h:t.h,s:Ye(t.s+100*e,0,100),l:t.l,a:t.a}},sn=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},Mh=function(r,e){var t=Js(r);return{h:t.h,s:t.s,l:Ye(t.l+100*e,0,100),a:t.a}},Un=(function(){function r(e){this.parsed=Zg(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return this.parsed!==null},r.prototype.brightness=function(){return Me(sn(this.rgba),2)},r.prototype.isDark=function(){return sn(this.rgba)<.5},r.prototype.isLight=function(){return sn(this.rgba)>=.5},r.prototype.toHex=function(){return e=en(this.rgba),t=e.r,s=e.g,i=e.b,o=(n=e.a)<1?Mr(Me(255*n)):"","#"+Mr(t)+Mr(s)+Mr(i)+o;var e,t,s,i,n,o},r.prototype.toRgb=function(){return en(this.rgba)},r.prototype.toRgbString=function(){return e=en(this.rgba),t=e.r,s=e.g,i=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+i+", "+n+")":"rgb("+t+", "+s+", "+i+")";var e,t,s,i,n},r.prototype.toHsl=function(){return Th(Js(this.rgba))},r.prototype.toHslString=function(){return e=Th(Js(this.rgba)),t=e.h,s=e.s,i=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+i+"%, "+n+")":"hsl("+t+", "+s+"%, "+i+"%)";var e,t,s,i,n},r.prototype.toHsv=function(){return e=Cu(this.rgba),{h:Me(e.h),s:Me(e.s),v:Me(e.v),a:Me(e.a,3)};var e},r.prototype.invert=function(){return nt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},r.prototype.saturate=function(e){return e===void 0&&(e=.1),nt(tn(this.rgba,e))},r.prototype.desaturate=function(e){return e===void 0&&(e=.1),nt(tn(this.rgba,-e))},r.prototype.grayscale=function(){return nt(tn(this.rgba,-1))},r.prototype.lighten=function(e){return e===void 0&&(e=.1),nt(Mh(this.rgba,e))},r.prototype.darken=function(e){return e===void 0&&(e=.1),nt(Mh(this.rgba,-e))},r.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},r.prototype.alpha=function(e){return typeof e=="number"?nt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Me(this.rgba.a,3);var t},r.prototype.hue=function(e){var t=Js(this.rgba);return typeof e=="number"?nt({h:e,s:t.s,l:t.l,a:t.a}):Me(t.h)},r.prototype.isEqual=function(e){return this.toHex()===nt(e).toHex()},r})(),nt=function(r){return r instanceof Un?r:new Un(r)},Eh=[],Qg=function(r){r.forEach(function(e){Eh.indexOf(e)<0&&(e(Un,On),Eh.push(e))})};function Jg(r,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"},s={};for(var i in t)s[t[i]]=i;var n={};r.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,h=s[this.toHex()];if(h)return h;if(o?.closest){var c=this.toRgb(),u=1/0,d="black";if(!n.length)for(var f in t)n[f]=new r(t[f]).toRgb();for(var p in t){var m=(a=c,l=n[p],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));m<u&&(u=m,d=p)}return d}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new r(l).toRgb():null},"name"])}Qg([Jg]);const Ss=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 s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="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,s,i]=this._components;return{r:e,g:t,b:s,a:i}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,i]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(i*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,i,n]=this._components;return e[0]=t,e[1]=s,e[2]=i,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,i]=this._components;return e[0]=t,e[1]=s,e[2]=i,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,i,n]=Ks._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=i,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 s=this._int>>16&255,i=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,i=i*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(i<<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,s,i,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,i=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,i,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,i,n=255]=e,t/=255,s/=255,i/=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=nt(e);o.isValid()&&({r:t,g:s,b:i,a:n}=o.rgba,t/=255,s/=255,i/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=i,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((i,n)=>{e[n]=Math.min(Math.max(i,t),s)}),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}};Ss.shared=new Ss;Ss._temp=new Ss;Ss.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let oe=Ss;const Eu={cullArea:null,cullable:!1,cullableChildren:!0};let rn=0;const kh=500;function N(...r){rn!==kh&&(rn++,rn===kh?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...r))}const as={_registeredResources:new Set,register(r){this._registeredResources.add(r)},unregister(r){this._registeredResources.delete(r)},release(){this._registeredResources.forEach(r=>r.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(r){return this._registeredResources.has(r)},reset(){this._registeredResources.clear()}};class ku{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){let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),t.init?.(e),t}return(e){e.reset?.(),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 Pu{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 ku(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Se=new Pu;as.register(Se);const Au={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(r){typeof r=="boolean"&&r===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(r===!0?{}:r))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(r){O("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(r)}};function Oo(r,e,t){const s=r.length;let i;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(i=e;i<n;++i)r[i]=r[i+t];r.length=n}const Ru={allowChildren:!0,removeChildren(r=0,e){const t=e??this.children.length,s=t-r,i=[];if(s>0&&s<=t){for(let o=t-1;o>=r;o--){const a=this.children[o];a&&(i.push(a),a.parent=null)}Oo(this.children,r,t);const n=this.renderGroup||this.parentRenderGroup;n&&n.removeChildren(i);for(let o=0;o<i.length;++o){const a=i[o];a.parentRenderLayer?.detach(a),this.emit("childRemoved",a,this,o),i[o].emit("removed",this)}return i.length>0&&this._didViewChangeTick++,i}else if(s===0&&this.children.length===0)return i;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(r){const e=this.getChildAt(r);return this.removeChild(e)},getChildAt(r){if(r<0||r>=this.children.length)throw new Error(`getChildAt: Index (${r}) does not exist.`);return this.children[r]},setChildIndex(r,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(r),this.addChildAt(r,e)},getChildIndex(r){const e=this.children.indexOf(r);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(r,e){this.allowChildren||O(ue,"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(`${r}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const s=r.parent===this;if(r.parent){const n=r.parent.children.indexOf(r);if(s){if(n===e)return r;r.parent.children.splice(n,1)}else r.removeFromParent()}e===t.length?t.push(r):t.splice(e,0,r);const i=this.renderGroup||this.parentRenderGroup;return this.sortableChildren&&(this.sortDirty=!0),s?(i&&(i.structureDidChange=!0),r):(r.parent=this,r.didChange=!0,r._updateFlags=15,i&&i.addChild(r),this.emit("childAdded",r,this,e),r.emit("added",this),r)},swapChildren(r,e){if(r===e)return;const t=this.getChildIndex(r),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=r;const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...r){return r.length===1?this.reparentChildAt(r[0],this.children.length):(r.forEach(e=>this.reparentChildAt(e,this.children.length)),r[0])},reparentChildAt(r,e){if(r.parent===this)return this.setChildIndex(r,e),r;const t=r.worldTransform.clone();r.removeFromParent(),this.addChildAt(r,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),r.setFromMatrix(t),r},replaceChild(r,e){r.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(r)),e.setFromMatrix(r.localTransform),e.updateLocalTransform(),this.removeChild(r)}},Bu={collectRenderables(r,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(r,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,r):this.collectRenderablesWithEffects(r,e,t))},collectRenderablesSimple(r,e,t){const s=this.children,i=s.length;for(let n=0;n<i;n++)s[n].collectRenderables(r,e,t)},collectRenderablesWithEffects(r,e,t){const{renderPipes:s}=e;for(let i=0;i<this.effects.length;i++){const n=this.effects[i];s[n.pipe].push(n,this,r)}this.collectRenderablesSimple(r,e,t);for(let i=this.effects.length-1;i>=0;i--){const n=this.effects[i];s[n.pipe].pop(n,this,r)}}};class lr{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 Iu{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 s=this._tests[t];if(s.test(e))return Se.get(s.maskClass,e)}return e}returnMaskEffect(e){Se.return(e)}}const si=new Iu;q.handleByList(S.MaskEffect,si._effectClasses);const Gu={_maskEffect:null,_maskOptions:{inverse:!1,channel:"red"},_filterEffect:null,effects:[],_markStructureAsChanged(){const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0)},addEffect(r){this.effects.indexOf(r)===-1&&(this.effects.push(r),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(r){const e=this.effects.indexOf(r);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(r){const e=this._maskEffect;e?.mask!==r&&(e&&(this.removeEffect(e),si.returnMaskEffect(e),this._maskEffect=null),r!=null&&(this._maskEffect=si.getMaskEffect(r),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(r){this._maskOptions={...this._maskOptions,...r},r.mask&&(this.mask=r.mask),this._markStructureAsChanged()},set filters(r){!Array.isArray(r)&&r&&(r=[r]);const e=this._filterEffect||(this._filterEffect=new lr);r=r;const t=r?.length>0,s=e.filters?.length>0,i=t!==s;r=Array.isArray(r)?r.slice(0):r,e.filters=Object.freeze(r),i&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=r??null))},get filters(){return this._filterEffect?.filters},set filterArea(r){this._filterEffect||(this._filterEffect=new lr),this._filterEffect.filterArea=r},get filterArea(){return this._filterEffect?.filterArea}},Du={label:null,get name(){return O(ue,"Container.name property has been removed, use Container.label instead"),this.label},set name(r){O(ue,"Container.name property has been removed, use Container.label instead"),this.label=r},getChildByName(r,e=!1){return this.getChildByLabel(r,e)},getChildByLabel(r,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const i=t[s];if(i.label===r||r instanceof RegExp&&r.test(i.label))return i}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(r,!0);if(n)return n}return null},getChildrenByLabel(r,e=!1,t=[]){const s=this.children;for(let i=0;i<s.length;i++){const n=s[i];(n.label===r||r instanceof RegExp&&r.test(n.label))&&t.push(n)}if(e)for(let i=0;i<s.length;i++)s[i].getChildrenByLabel(r,!0,t);return t}},Ae=Se.getPool(L),ct=Se.getPool(ke),e_=new L,Fu={getFastGlobalBounds(r,e){e||(e=new ke),e.clear(),this._getGlobalBoundsRecursive(!!r,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(r,e,t){let s=e;if(r&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const i=!!this.effects.length;if((this.renderGroup||i)&&(s=ct.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.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(r,s,t)}if(i){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,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(e_).invert()),e.addBounds(s),ct.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),ct.return(s))}};function gi(r,e,t){t.clear();let s,i;return r.parent?e?s=r.parent.worldTransform:(i=Ae.get().identity(),s=_i(r,i)):s=L.IDENTITY,Lu(r,t,s,e),i&&Ae.return(i),t.isValid||t.set(0,0,0,0),t}function Lu(r,e,t,s){if(!r.visible||!r.measurable)return;let i;s?i=r.worldTransform:(r.updateLocalTransform(),i=Ae.get(),i.appendFrom(r.localTransform,t));const n=e,o=!!r.effects.length;if(o&&(e=ct.get().clear()),r.boundsArea)e.addRect(r.boundsArea,i);else{const a=r.bounds;a&&!a.isEmpty()&&(e.matrix=i,e.addBounds(a));for(let l=0;l<r.children.length;l++)Lu(r.children[l],e,i,s)}if(o){for(let a=0;a<r.effects.length;a++)r.effects[a].addBounds?.(e);n.addBounds(e,L.IDENTITY),ct.return(e)}s||Ae.return(i)}function _i(r,e){const t=r.parent;return t&&(_i(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function Kt(r,e){if(r===16777215||!e)return e;if(e===16777215||!r)return r;const t=r>>16&255,s=r>>8&255,i=r&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,h=s*o/255|0,c=i*a/255|0;return(l<<16)+(h<<8)+c}const Ph=16777215;function hr(r,e){return r===Ph?e:e===Ph?r:Kt(r,e)}function Zt(r){return((r&255)<<16)+(r&65280)+(r>>16&255)}const Ou={getGlobalAlpha(r){if(r)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(r=new L,e){if(e)return r.copyFrom(this.worldTransform);this.updateLocalTransform();const t=_i(this,Ae.get().identity());return r.appendFrom(this.localTransform,t),Ae.return(t),r},getGlobalTint(r){if(r)return this.renderGroup?Zt(this.renderGroup.worldColor):this.parentRenderGroup?Zt(hr(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=hr(e,t.localColor),t=t.parent;return Zt(e)}};function yi(r,e,t){return e.clear(),t||(t=L.IDENTITY),Uu(r,e,t,r,!0),e.isValid||e.set(0,0,0,0),e}function Uu(r,e,t,s,i){let n;if(i)n=Ae.get(),n=t.copyTo(n);else{if(!r.visible||!r.measurable)return;r.updateLocalTransform();const l=r.localTransform;n=Ae.get(),n.appendFrom(l,t)}const o=e,a=!!r.effects.length;if(a&&(e=ct.get().clear()),r.boundsArea)e.addRect(r.boundsArea,n);else{r.renderPipeId&&(e.matrix=n,e.addBounds(r.bounds));const l=r.children;for(let h=0;h<l.length;h++)Uu(l[h],e,n,s,!1)}if(a){for(let l=0;l<r.effects.length;l++)r.effects[l].addLocalBounds?.(e,s);o.addBounds(e,L.IDENTITY),ct.return(e)}Ae.return(n)}function Uo(r,e){const t=r.children;for(let s=0;s<t.length;s++){const i=t[s],n=i.uid,o=(i._didViewChangeTick&65535)<<16|i._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,i.children.length&&Uo(i,e)}return e.didChange}const t_=new L,Nu={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(r,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=r/e*t:this.scale.x=t},_setHeight(r,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=r/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new ke});const r=this._localBoundsCacheData;return r.index=1,r.didChange=!1,r.data[0]!==this._didViewChangeTick&&(r.didChange=!0,r.data[0]=this._didViewChangeTick),Uo(this,r),r.didChange&&yi(this,r.localBounds,t_),r.localBounds},getBounds(r,e){return gi(this,r,e||new ke)}},Hu={_onRender:null,set onRender(r){const e=this.renderGroup||this.parentRenderGroup;if(!r){this._onRender&&e?.removeOnRender(this),this._onRender=null;return}this._onRender||e?.addOnRender(this),this._onRender=r},get onRender(){return this._onRender}},zu={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(r){this._zIndex!==r&&(this._zIndex=r,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(s_))}};function s_(r,e){return r._zIndex-e._zIndex}const Wu={getGlobalPosition(r=new he,e=!1){return this.parent?this.parent.toGlobal(this._position,r,e):(r.x=this._position.x,r.y=this._position.y),r},toGlobal(r,e,t=!1){const s=this.getGlobalTransform(Ae.get(),t);return e=s.apply(r,e),Ae.return(s),e},toLocal(r,e,t,s){e&&(r=e.toGlobal(r,t,s));const i=this.getGlobalTransform(Ae.get(),s);return t=i.applyInverse(r,t),Ae.return(i),t}};class xi{constructor(){this.uid=ne("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){if(this.renderPipes)for(const e in this.renderPipes)this.renderPipes[e].destroyInstructionSet?.(this);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"])}}class No{constructor(){this._screenSizes=new Map,this._widths=[],this._heights=[]}get size(){return this._screenSizes.size}set(e,t,s){const i=this._screenSizes.get(e);return i&&i.pixelWidth===t&&i.pixelHeight===s?!1:(this._screenSizes.set(e,{pixelWidth:t,pixelHeight:s}),this._update(),!0)}remove(e){return this._screenSizes.delete(e)?(this._update(),!0):!1}getFittingWidth(e){return this._getFittingAxis(e,this._widths)}getFittingHeight(e){return this._getFittingAxis(e,this._heights)}hasWidth(e){return this._widths.includes(e)}hasHeight(e){return this._heights.includes(e)}_getFittingAxis(e,t){for(let s=0;s<t.length;s++){const i=t[s];if(i>=e)return i}}_update(){this._widths=[...this._screenSizes.values()].map(e=>e.pixelWidth).filter((e,t,s)=>s.indexOf(e)===t).sort((e,t)=>e-t),this._heights=[...this._screenSizes.values()].map(e=>e.pixelHeight).filter((e,t,s)=>s.indexOf(e)===t).sort((e,t)=>e-t)}}let r_=0;const nn=32767,i_=4294967296,n_=8589934592,Ah=Object.create(null);let o_=0;function a_(r){const e=Ah[r];return e!==void 0?e:Ah[r]=o_++}function l_(r,e,t,s,i,n){return(r<<17)+(e<<2)+((s?1:0)<<1)+(t?1:0)+(n==="nearest"?1:0)*i_+a_(i)*n_}class $u{constructor(e){this._buckets=new Map,this._poolKey=Object.create(null),this._poolStyle=Object.create(null),this._screens=new No,this._enableFullScreen=!1,this.textureOptions=e||{}}get textureStyle(){return O(lt,"TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead."),this._textureStyle||(this._textureStyle=new Dt(this.textureOptions)),this._textureStyle}set textureStyle(e){O(lt,"TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead."),this._textureStyle=e}get enableFullScreen(){return O(lt,"TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize."),this._enableFullScreen}set enableFullScreen(e){O(lt,"TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize."),this._enableFullScreen=e}createTexture(...e){let t=e[0];typeof t=="number"&&(O(lt,"TexturePool.createTexture params are now an options object. See params: { width, height, antialias, autoGenerateMipmaps }"),t={width:t,height:e[1],antialias:e[2]??!1,autoGenerateMipmaps:e[3]??!1});const s=t.format??this.textureOptions.format??de.defaultOptions.format,i=t.scaleMode??this.textureOptions.scaleMode??Dt.defaultOptions.scaleMode,n=new de({...this.textureOptions,width:t.width,height:t.height,resolution:1,antialias:t.antialias??!1,autoGarbageCollect:!1,autoGenerateMipmaps:t.autoGenerateMipmaps??!1,format:s,scaleMode:i});return new H({source:n,label:`texturePool_${r_++}`})}getOptimalTexture(...e){let t=e[0];typeof t=="number"&&(O(lt,"TexturePool.getOptimalTexture params are now an options object. See params: { width, height, resolution, antialias, autoGenerateMipmaps }"),t={width:t,height:e[1],resolution:e[2]??1,antialias:e[3]??!1,autoGenerateMipmaps:e[4]??!1});const s=t.width,i=t.height,n=t.resolution??1,o=t.antialias??!1,a=t.autoGenerateMipmaps??!1,l=t.format??this.textureOptions.format??de.defaultOptions.format,h=t.scaleMode??this.textureOptions.scaleMode??Dt.defaultOptions.scaleMode,{width:c,height:u}=this.getOptimalSize(s,i,n);(c>nn||u>nn)&&N(`TexturePool: ${c}x${u} is larger than the ${nn}px pool key limit, textures of this size may be pooled together`);const d=l_(c,u,o,a,l,h);let f=this._buckets.get(d);f||(f=[],this._buckets.set(d,f));let p=f.pop();return p||(p=this.createTexture({width:c,height:u,antialias:o,autoGenerateMipmaps:a,format:l,scaleMode:h}),this._poolStyle[p.uid]=p.source.style),p.source._resolution=n,p.source.width=c/n,p.source.height=u/n,p.source.pixelWidth=c,p.source.pixelHeight=u,p.frame.x=0,p.frame.y=0,p.frame.width=s,p.frame.height=i,p.updateUvs(),this._poolKey[p.uid]=d,p}getOptimalSize(e,t,s=1){const i=Math.ceil(e*s-1e-6),n=Math.ceil(t*s-1e-6),o=es(i),a=this._screens.getFittingWidth(i),l=es(n),h=this._screens.getFittingHeight(n);return{width:a!==void 0?Math.min(a,o):o,height:h!==void 0?Math.min(h,l):l}}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture({width:e.width,height:e.height,resolution:s._resolution,antialias:t})}returnTexture(e,t=!1){const s=e.uid,i=this._poolKey[s];if(i===void 0){N("TexturePool: returnTexture was passed a texture that did not come from this pool, ignoring it");return}const n=this._poolStyle[s];t&&e.source.style!==n&&(e.source.style=n);const o=this._buckets.get(i);if(!o){delete this._poolKey[s],delete this._poolStyle[s],e.destroy(!0);return}o.push(e)}setScreenSize(e,t,s){this._screens.set(e,t,s)&&this._pruneScreenTextures()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenTextures()}_pruneScreenTextures(){for(const[e,t]of this._buckets){const s=e>>>0,i=s>>>17,n=s>>>2&32767;(ts(i)||this._screens.hasWidth(i))&&(ts(n)||this._screens.hasHeight(n))||(this._dropTextures(t,!0),this._buckets.delete(e))}}_dropTextures(e,t){for(let s=0;s<e.length;s++){const i=e[s];delete this._poolKey[i.uid],delete this._poolStyle[i.uid],t&&i.destroy(!0)}}clear(e){for(const t of this._buckets.values())this._dropTextures(t,e!==!1);this._buckets.clear()}}const Te=new $u;as.register(Te);class ri{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new L,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 xi,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 s=0;s<t.length;s++){const i=t[s];i._updateFlags=15,this.addChild(i)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Te.returnTexture(this.texture),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 s=0;s<t.length;s++)this.addChild(t[s])}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 s=0;s<t.length;s++)this.removeChild(t[s])}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.indexOf(e)===-1&&this._onRenderContainers.push(e)}removeOnRender(e){const t=this._onRenderContainers.indexOf(e);t!==-1&&this._onRenderContainers.splice(t,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?.destroy(),this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let i=0;i<s.length;i++)this._getChildren(s[i],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new L),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new L),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 L),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 Vu(r,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(r[s]=e[s])}const on=new Ce(null),Er=new Ce(null),an=new Ce(null,1,1),kr=new Ce(null),cr=1,bi=2,ws=4;class _e extends Re{constructor(e={}){super(),this.uid=ne("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 L,this.relativeGroupTransform=new L,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Ce(this,0,0),this._scale=an,this._pivot=Er,this._origin=kr,this._skew=on,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=[],Vu(this,e,{children:!0,parent:!0,effects:!0}),e.children?.forEach(t=>this.addChild(t)),e.parent?.addChild(this)}static mixin(e){O("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),q.mixin(_e,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||O(ue,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let i=0;i<e.length;i++)this.addChild(e[i]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.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,s&&s.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 i=0;i<e.length;i++)this.removeChild(e[i]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,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,s),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?.removeChild(this),this.renderGroup=Se.get(ri,this),this.groupTransform=L.IDENTITY,e?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),Se.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new L),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*mu}set angle(e){this.rotation=e*gu}get pivot(){return this._pivot===Er&&(this._pivot=new Ce(this,0,0)),this._pivot}set pivot(e){this._pivot===Er&&(this._pivot=new Ce(this,0,0),this._origin!==kr&&N("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===on&&(this._skew=new Ce(this,0,0)),this._skew}set skew(e){this._skew===on&&(this._skew=new Ce(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===an&&(this._scale=new Ce(this,1,1)),this._scale}set scale(e){this._scale===an&&(this._scale=new Ce(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===kr&&(this._origin=new Ce(this,0,0)),this._origin}set origin(e){this._origin===kr&&(this._origin=new Ce(this,0,0),this._pivot!==Er&&N("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 s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.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:this.scale.x,typeof e.scaleY=="number"?e.scaleY: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,s=this._scale,i=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,h=i._x,c=i._y,u=-n._x,d=-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-(h*t.a+c*t.c)+(u*t.a+d*t.c)-u,t.ty=o._y-(h*t.b+c*t.d)+(u*t.b+d*t.d)-d}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=cr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=oe.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=cr,this._onUpdate())}get tint(){return Zt(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=bi,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|=ws,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|=ws,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|=ws,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){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?.children)&&t)for(let i=0;i<t.length;++i)t[i].destroy(e);this.renderGroup?.destroy(),this.renderGroup=null}}q.mixin(_e,Ru,Fu,Wu,Hu,Nu,Gu,Du,zu,Eu,Au,Ou,Bu);class vi extends _e{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 ke(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:s,y:i}=e;return s>=t.minX&&s<=t.maxX&&i>=t.minY&&i<=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(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,s){const{renderPipes:i}=t;i.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=i[this.renderPipeId];o?.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let h=0;h<l;h++)a[h].collectRenderables(e,t,s);i.blendMode.popBlendMode(e)}}class ss extends vi{constructor(e=H.EMPTY){e instanceof H&&(e={texture:e});const{texture:t=H.EMPTY,anchor:s,roundPixels:i,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 Ce({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=i??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof H?new ss(e):new ss(H.from(e,t))}set texture(e){e||(e=H.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 Lo(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return O("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:i,height:n}=t.orig;s.minX=-e._x*i,s.maxX=s.minX+i,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._texture.destroy(s)}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 h_=new ke;function Ho(r,e,t){const s=h_;r.measurable=!0,gi(r,t,s),e.addBoundsMask(s),r.measurable=!1}function zo(r,e,t){const s=ct.get();r.measurable=!0;const i=Ae.get().identity(),n=Xu(r,t,i);yi(r,s,n),r.measurable=!1,e.addBoundsMask(s),Ae.return(i),ct.return(s)}function Xu(r,e,t){return r?(r!==e&&(Xu(r.parent,e,t),r.updateLocalTransform(),t.append(r.localTransform)),t):(N("Mask bounds, renderable is not inside the root container"),t)}class Wo{constructor(e){this.priority=0,this.inverse=!1,this.channel="red",this.pipe="alphaMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof ss),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||Ho(this.mask,e,t)}addLocalBounds(e,t){zo(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof ss}}Wo.extension=S.MaskEffect;class $o{constructor(e){this.priority=0,this.pipe="colorMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}$o.extension=S.MaskEffect;class Vo{constructor(e){this.priority=0,this.pipe="stencilMask",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){Ho(this.mask,e,t)}addLocalBounds(e,t){zo(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof _e}}Vo.extension=S.MaskEffect;const ju={createCanvas:(r,e)=>{const t=document.createElement("canvas");return t.width=r,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(r,e)=>fetch(r,e),parseXML:r=>new DOMParser().parseFromString(r,"text/xml")};let Rh=ju;const J={get(){return Rh},set(r){Rh=r}};class Ve extends de{constructor(e){e.resource||(e.resource=J.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,s=this._resolution){const i=super.resize(e,t,s);return i&&this.resizeCanvas(),i}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"))}}Ve.extension=S.TextureSource;class ur 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}}ur.extension=S.TextureSource;var rs=(r=>(r[r.INTERACTION=50]="INTERACTION",r[r.HIGH=25]="HIGH",r[r.NORMAL=0]="NORMAL",r[r.LOW=-25]="LOW",r[r.UTILITY=-50]="UTILITY",r))(rs||{});class Xr{constructor(e,t=null,s=0,i=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=i}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 qu=class Ne{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/Ne.targetFPMS,this.elapsedMS=1/Ne.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,s=rs.NORMAL){return this._addListener(new Xr(e,t,s))}addOnce(e,t,s=rs.NORMAL){return this._addListener(new Xr(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.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*Ne.targetFPMS;const s=this._head;let i=s.next;for(;i;)i=i.emit(this);s.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,Ne.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(!Ne._shared){const e=Ne._shared=new Ne;e.autoStart=!0,e._protected=!0}return Ne._shared}static get system(){if(!Ne._system){const e=Ne._system=new Ne;e.autoStart=!0,e._protected=!0}return Ne._system}};qu.targetFPMS=.06;let We=qu,ln;async function Yu(){return ln??(ln=(async()=>{const e=J.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(o=>{const a=document.createElement("video");a.onloadeddata=()=>o(a),a.onerror=()=>o(null),a.autoplay=!1,a.crossOrigin="anonymous",a.preload="auto",a.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",a.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,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(i),e.deleteTexture(s),e.getExtension("WEBGL_lose_context")?.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),ln}const wi=class Ku extends de{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Ku.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),this._onLoadedMetadata=this._onLoadedMetadata.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=We.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.isValid||e.addEventListener("loadedmetadata",this._onLoadedMetadata),this.alphaMode=await Yu(),this._load=new Promise((s,i)=>{this.isValid?s(this):(this._resolve=s,this._reject=i,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._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onLoadedMetadata(){this.isValid&&this._mediaReady()}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlayThrough),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.isValid&&(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("loadedmetadata",this._onLoadedMetadata),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&&(We.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||(We.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(We.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};wi.extension=S.TextureSource;wi.defaultOptions={...de.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};wi.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Zu=wi;const jt=(r,e,t=!1)=>(Array.isArray(r)||(r=[r]),e?r.map(s=>typeof s=="string"||t?e(s):s):r);class c_{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||N(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=jt(e);let i;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.test(t)){i=h.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(i||{}));i||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const h=i?i[l]:t;this._cache.has(l)&&this._cache.get(l)!==h&&N("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){N(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(i=>{this._cache.delete(i)}),t.keys.forEach(i=>{this._cacheMap.delete(i)})}get parsers(){return this._parsers}}const qt=new c_,Nn=[];q.handleByList(S.TextureSource,Nn);function Qu(r={}){const e=r&&r.resource,t=e?r.resource:r,s=e?r:{resource:r};for(let i=0;i<Nn.length;i++){const n=Nn[i];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function Ju(r={},e=!1){const t=r&&r.resource,s=t?r.resource:r,i=t?r:{resource:r};if(!e&&qt.has(s))return qt.get(s);const n=new H({source:Qu(i)});return n.on("destroy",()=>{qt.has(s)&&qt.remove(s)}),e||qt.set(s,n),n}function ed(r,e=!1){return typeof r=="string"?qt.get(r):r instanceof de?new H({source:r}):Ju(r,e)}H.from=ed;de.from=Qu;q.add(Wo,$o,Vo,Zu,ur,Ve,mi);var Xo=(r=>(r[r.Low=0]="Low",r[r.Normal=1]="Normal",r[r.High=2]="High",r))(Xo||{});function et(r){if(typeof r!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(r)}`)}function Os(r){return r.split("?")[0].split("#")[0]}function u_(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d_(r,e,t){return r.replace(new RegExp(u_(e),"g"),t)}function f_(r,e){let t="",s=0,i=-1,n=0,o=-1;for(let a=0;a<=r.length;++a){if(a<r.length)o=r.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(i===a-1||n===1))if(i!==a-1&&n===2){if(t.length<2||s!==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="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),i=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,i=a,n=0;continue}}}else t.length>0?t+=`/${r.slice(i+1,a)}`:t=r.slice(i+1,a),s=a-i-1;i=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Cs={toPosix(r){return d_(r,"\\","/")},isUrl(r){return/^https?:/.test(this.toPosix(r))},isDataUrl(r){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(r)},isBlobUrl(r){return r.startsWith("blob:")},hasProtocol(r){return/^[^/:]+:/.test(this.toPosix(r))},getProtocol(r){et(r),r=this.toPosix(r);const e=/^file:\/\/\//.exec(r);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(r);return t?t[0]:""},toAbsolute(r,e,t){if(et(r),this.isDataUrl(r)||this.isBlobUrl(r))return r;const s=Os(this.toPosix(e??J.get().getBaseUrl())),i=Os(this.toPosix(t??this.rootname(s)));return r=this.toPosix(r),r.startsWith("/")?Cs.join(i,r.slice(1)):this.isAbsolute(r)?r:this.join(s,r)},normalize(r){if(et(r),r.length===0)return".";if(this.isDataUrl(r)||this.isBlobUrl(r))return r;r=this.toPosix(r);let e="";const t=r.startsWith("/");this.hasProtocol(r)&&(e=this.rootname(r),r=r.slice(e.length));const s=r.endsWith("/");return r=f_(r),r.length>0&&s&&(r+="/"),t?`/${r}`:e+r},isAbsolute(r){return et(r),r=this.toPosix(r),this.hasProtocol(r)?!0:r.startsWith("/")},join(...r){if(r.length===0)return".";let e;for(let t=0;t<r.length;++t){const s=r[t];if(et(s),s.length>0)if(e===void 0)e=s;else{const i=r[t-1]??"";this.joinExtensions.includes(this.extname(i).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(r){if(et(r),r.length===0)return".";r=this.toPosix(r);let e=r.charCodeAt(0);const t=e===47;let s=-1,i=!0;const n=this.getProtocol(r),o=r;r=r.slice(n.length);for(let a=r.length-1;a>=1;--a)if(e=r.charCodeAt(a),e===47){if(!i){s=a;break}}else i=!1;return s===-1?t?"/":this.isUrl(o)?n+r:n:t&&s===1?"//":n+r.slice(0,s)},rootname(r){et(r),r=this.toPosix(r);let e="";if(r.startsWith("/")?e="/":e=this.getProtocol(r),this.isUrl(r)){const t=r.indexOf("/",e.length);t!==-1?e=r.slice(0,t):e=r,e.endsWith("/")||(e+="/")}return e},basename(r,e){et(r),e&&et(e),r=Os(this.toPosix(r));let t=0,s=-1,i=!0,n;if(e!==void 0&&e.length>0&&e.length<=r.length){if(e.length===r.length&&e===r)return"";let o=e.length-1,a=-1;for(n=r.length-1;n>=0;--n){const l=r.charCodeAt(n);if(l===47){if(!i){t=n+1;break}}else a===-1&&(i=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=r.length),r.slice(t,s)}for(n=r.length-1;n>=0;--n)if(r.charCodeAt(n)===47){if(!i){t=n+1;break}}else s===-1&&(i=!1,s=n+1);return s===-1?"":r.slice(t,s)},extname(r){et(r),r=Os(this.toPosix(r));let e=-1,t=0,s=-1,i=!0,n=0;for(let o=r.length-1;o>=0;--o){const a=r.charCodeAt(o);if(a===47){if(!i){t=o+1;break}continue}s===-1&&(i=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":r.slice(e,s)},parse(r){et(r);const e={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return e;r=Os(this.toPosix(r));let t=r.charCodeAt(0);const s=this.isAbsolute(r);let i;e.root=this.rootname(r),s||this.hasProtocol(r)?i=1:i=0;let n=-1,o=0,a=-1,l=!0,h=r.length-1,c=0;for(;h>=i;--h){if(t=r.charCodeAt(h),t===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),t===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&&s?e.base=e.name=r.slice(1,a):e.base=e.name=r.slice(o,a)):(o===0&&s?(e.name=r.slice(1,n),e.base=r.slice(1,a)):(e.name=r.slice(o,n),e.base=r.slice(o,a)),e.ext=r.slice(n,a)),e.dir=this.dirname(r),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function td(r,e,t,s,i){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?td(r.replace(s[t],a),e,t+1,s,i):i.push(r.replace(s[t],a))}}function sd(r){const e=/\{(.*?)\}/g,t=r.match(e),s=[];if(t){const i=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");i.push(o)}),td(r,i,0,t,s)}else s.push(r);return s}const Hn=r=>!Array.isArray(r);class jo{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(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return jt(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>o?.src??o):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&&N("[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 s=[];let i=t;Array.isArray(t)||(i=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),i.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const h=this._createBundleAssetId(e,a);s.push(h),l=[a,h]}else{const h=a.map(c=>this._createBundleAssetId(e,c));s.push(...h),l=[...a,...h]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&N(`[Resolver] already has key: ${n} overwriting`)},jt(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:h,parser:c}=n;const u=jt(o).map(m=>typeof m=="string"?sd(m):Array.isArray(m)?m:[m]),d=this.getAlias(n);Array.isArray(d)?d.forEach(s):s(d);const f=[],p=m=>{const g=this._parsers.find(_=>_.test(m));return{src:m,...g?.parse(m)}};u.forEach(m=>{m.forEach(g=>{let _={};if(typeof g!="object"?_=p(g):(a=g.data??a,l=g.format??l,(g.loadParser||g.parser)&&(h=g.loadParser??h,c=g.parser??c),_={...p(g.src),...g}),!d)throw new Error(`[Resolver] alias is undefined for this asset: ${_.src}`);_=this._buildResolvedAsset(_,{aliases:d,data:a,format:l,loadParser:h,parser:c,progressSize:n.progressSize}),f.push(_)})}),d.forEach(m=>{this._assetMap[m]=f})})}resolveBundle(e){const t=Hn(e);e=jt(e);const s={};return e.forEach(i=>{const n=this._bundles[i];if(n){const o=this.resolve(n),a={};for(const l in o){const h=o[l];a[this._extractAssetIdFromBundle(i,l)]=h}s[i]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const i in t)s[i]=t[i].src;return s}return t.src}resolve(e){const t=Hn(e);e=jt(e);const s={};return e.forEach(i=>{if(!this._resolverHash[i])if(this._assetMap[i]){let n=this._assetMap[i];const o=this._getPreferredOrder(n);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[i]=n[0]}else this._resolverHash[i]=this._buildResolvedAsset({alias:[i],src:i},{});s[i]=this._resolverHash[i]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],i=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(i)return i}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:s,data:i,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Cs.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...i||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??rd(e.src),l!==void 0&&(e.progressSize=l),e}}jo.RETINA_PREFIX=/@([0-9\.]+)x/;function rd(r){return r.split(".").pop().split("?").shift().split("#").shift()}const zn=(r,e)=>{const t=e.split("?")[1];return t&&(r+=`?${t}`),r},id=class Zs{constructor(e,t){this.linkedSheets=[];let s=e;e?.source instanceof de&&(s={texture:e,data:t});const{texture:i,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=i instanceof H?i:null,this.textureSource=i.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,i.source.resolution=this.resolution):this.resolution=i.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<=Zs.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 s=e;const i=t?1/0:Zs.BATCH_SIZE;for(;s-e<i&&s<this._frameKeys.length;){const n=this._frameKeys[s],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 ee(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?l=new ee(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 ee(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 ee(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 H({source:this.textureSource,frame:l,orig:u,trim:h,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}s++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const i=e[t][s];this.animations[t].push(this.textures[i])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Zs.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Zs.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(const t in this.textures)this.textures[t].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};id.BATCH_SIZE=1e3;let Wn=id;const p_=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function nd(r,e,t){const s={};if(r.forEach(i=>{s[i]=e}),Object.keys(e.textures).forEach(i=>{s[`${e.cachePrefix}${i}`]=e.textures[i]}),!t){const i=Cs.dirname(r[0]);e.linkedSheets.forEach((n,o)=>{const a=nd([`${i}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const od={extension:S.Asset,cache:{test:r=>r instanceof Wn,getCacheableAssets:(r,e)=>nd(r,e,!1)},resolver:{extension:{type:S.ResolveParser,name:"resolveSpritesheet"},test:r=>{const t=r.split("?")[0].split("."),s=t.pop(),i=t.pop();return s==="json"&&p_.includes(i)},parse:r=>{const e=r.split(".");return{resolution:parseFloat(jo.RETINA_PREFIX.exec(r)?.[1]??"1"),format:e[e.length-2],src:r}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:S.LoadParser,priority:Xo.Normal,name:"spritesheetLoader"},async testParse(r,e){return Cs.extname(e.src).toLowerCase()===".json"&&!!r.frames},async parse(r,e,t){const{texture:s,imageFilename:i,textureOptions:n,cachePrefix:o}=e?.data??{};let a=Cs.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof H)l=s;else{const u=zn(a+(i??r.meta.image),e.src);l=(await t.load([{src:u,data:n}]))[u]}const h=new Wn({texture:l.source,data:r,cachePrefix:o});await h.parse();const c=r?.meta?.related_multi_packs;if(Array.isArray(c)){const u=[];for(const f of c){if(typeof f!="string")continue;let p=a+f;e.data?.ignoreMultiPack||(p=zn(p,e.src),u.push(t.load({src:p,data:{textureOptions:n,ignoreMultiPack:!0}})))}const d=await Promise.all(u);h.linkedSheets=d,d.forEach(f=>{f.linkedSheets=[h].concat(h.linkedSheets.filter(p=>p!==f))})}return h},async unload(r,e,t){await t.unload(r.textureSource._sourceOrigin),r.destroy(!1)}}};q.add(od);class qo{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,i=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/i*this._renderer.resolution,a=t.left,l=t.top,h=`translate(${a}px, ${l}px) scale(${n}, ${o})`;h!==this._lastTransform&&(this._domElement.style.transform=h,this._lastTransform=h)},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 s=this.canvas.width,i=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/i*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||We.shared.add(this.updateTranslation,this,rs.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&We.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 Bs{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Bs.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new he,this.page=new he,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,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,i,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 hn=/iPhone/i,Bh=/iPod/i,Ih=/iPad/i,Gh=/\biOS-universal(?:.+)Mac\b/i,cn=/\bAndroid(?:.+)Mobile\b/i,Dh=/Android/i,cs=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Pr=/Silk/i,_t=/Windows Phone/i,Fh=/\bWindows(?:.+)ARM\b/i,Lh=/BlackBerry/i,Oh=/BB10/i,Uh=/Opera Mini/i,Nh=/\b(CriOS|Chrome)(?:.+)Mobile/i,Hh=/Mobile(?:.+)Firefox\b/i,zh=function(r){return typeof r<"u"&&r.platform==="MacIntel"&&typeof r.maxTouchPoints=="number"&&r.maxTouchPoints>1&&typeof MSStream>"u"};function m_(r){return function(e){return e.test(r)}}function Wh(r){var e={userAgent:"",platform:"",maxTouchPoints:0};!r&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof r=="string"?e.userAgent=r:r&&r.userAgent&&(e={userAgent:r.userAgent,platform:r.platform,maxTouchPoints:r.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var i=m_(t),n={apple:{phone:i(hn)&&!i(_t),ipod:i(Bh),tablet:!i(hn)&&(i(Ih)||zh(e))&&!i(_t),universal:i(Gh),device:(i(hn)||i(Bh)||i(Ih)||i(Gh)||zh(e))&&!i(_t)},amazon:{phone:i(cs),tablet:!i(cs)&&i(Pr),device:i(cs)||i(Pr)},android:{phone:!i(_t)&&i(cs)||!i(_t)&&i(cn),tablet:!i(_t)&&!i(cs)&&!i(cn)&&(i(Pr)||i(Dh)),device:!i(_t)&&(i(cs)||i(Pr)||i(cn)||i(Dh))||i(/\bokhttp\b/i)},windows:{phone:i(_t),tablet:i(Fh),device:i(_t)||i(Fh)},other:{blackberry:i(Lh),blackberry10:i(Oh),opera:i(Uh),firefox:i(Hh),chrome:i(Nh),device:i(Lh)||i(Oh)||i(Uh)||i(Hh)||i(Nh)},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 g_=Wh.default??Wh,ad=g_(globalThis.navigator),__=9,$h=100,y_=0,x_=0,Vh=2,Xh=1,b_=-1e3,v_=-1e3,w_=2,Yo=class ld{constructor(e,t=ad){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=`${Xh}px`,e.style.height=`${Xh}px`,e.style.position="absolute",e.style.top=`${b_}px`,e.style.left=`${v_}px`,e.style.zIndex=w_.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=`${y_}px`,this._div.style.left=`${x_}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Vh.toString(),this._canvasObserver=new qo({domElement:this._div,renderer:this._renderer})),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(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._renderer.runners.postrender.remove(this);for(const e of this._children)e._accessibleDiv?.parentNode&&(e._accessibleDiv.parentNode.removeChild(e._accessibleDiv),e._accessibleDiv=null),e._accessibleActive=!1;for(const e in this._pools)this._pools[e].forEach(s=>{s.parentNode&&s.parentNode.removeChild(s)}),delete this._pools[e];this._div?.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 s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...ld.defaultOptions,...e?.accessibilityOptions||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),s.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 s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const i=this._children[s];t.has(s)||(i._accessibleDiv&&i._accessibleDiv.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),this._getPool(i.accessibleType).push(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1,Oo(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const i=this._children[s];if(!i._accessibleActive||!i._accessibleDiv)continue;const n=i._accessibleDiv,o=i.hitArea||i.getBounds().rectangle;if(i.hitArea){const a=i.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:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?(s=document.createElement("button"),this.debug||(s.style.color="transparent")):(s=document.createElement(e.accessibleType),s.style.cssText=`
6
6
  color: transparent;
7
7
  pointer-events: none;
8
8
  padding: 0;
@@ -15,7 +15,7 @@ Deprecated since v${r}`,n=typeof console.groupCollapsed=="function"&&!vs.noColor
15
15
  -webkit-user-select: none;
16
16
  -moz-user-select: none;
17
17
  -ms-user-select: none;
18
- `),s.style.width=`${$h}px`,s.style.height=`${$h}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=Vh.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleText&&(s.innerText=e.accessibleText),e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,i=this._renderer.events.rootBoundary,n=Object.assign(new Bs(i),{target:s});i.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>i.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!==__||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._canvasObserver?.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]}};Yo.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"accessibility"};Yo.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let T_=Yo;const S_={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},un=Object.create(null),jh=Object.create(null);function is(r,e){let t=jh[r];return t===void 0&&(un[e]===void 0&&(un[e]=1),jh[r]=t=un[e]++),t}let Ar;function Ko(){return(!Ar||Ar?.isContextLost())&&(Ar=J.get().createCanvas().getContext("webgl",{})),Ar}let Rr;function hd(){if(!Rr){Rr="mediump";const r=Ko();r&&r.getShaderPrecisionFormat&&(Rr=r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision?"highp":"mediump")}return Rr}function cd(r,e,t){return e?r:t?(r=r.replace("out vec4 finalColor;",""),`
18
+ `),s.style.width=`${$h}px`,s.style.height=`${$h}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=Vh.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleText&&(s.innerText=e.accessibleText),e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,i=this._renderer.events.rootBoundary,n=Object.assign(new Bs(i),{target:s});i.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>i.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!==__||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._canvasObserver?.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]}};Yo.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"accessibility"};Yo.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let T_=Yo;const S_={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},un=Object.create(null),jh=Object.create(null);function is(r,e){let t=jh[r];return t===void 0&&(un[e]===void 0&&(un[e]=1),jh[r]=t=un[e]++),t}let Ar;function Ko(){return(!Ar||Ar?.isContextLost())&&(Ar=J.get().createCanvas().getContext("webgl",{})),Ar}let Rr;function hd(){if(!Rr){Rr="mediump";const r=Ko();r&&r.getShaderPrecisionFormat&&(Rr=r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision?"highp":"mediump")}return Rr}function cd(r,e,t){return e?r:t?(r=r.replace("out vec4 finalColor;",""),`
19
19
 
20
20
  #ifdef GL_ES // This checks if it is WebGL1
21
21
  #define in varying
@@ -34,7 +34,7 @@ Deprecated since v${r}`,n=typeof console.groupCollapsed=="function"&&!vs.noColor
34
34
  ${r}`}else s!=="highp"&&r.substring(0,15)==="precision highp"&&(r=r.replace("precision highp","precision mediump"));const i=e.maxSupportedFragmentPrecision==="highp"?"highp":"mediump";return k_(r,i)}function k_(r,e){const t=new Set;let s="";for(const[,i]of r.matchAll(M_))t.add(i);for(const[,i]of r.matchAll(C_))t.has(i)||(t.add(i),s+=`precision ${E_[i]??e} ${i};
35
35
  `);return s+r}function dd(r,e){return e?`#version 300 es
36
36
  ${r}`:r}const P_={},A_={};function fd(r,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const s=t?P_:A_;return s[e]?(s[e]++,e+=`-${s[e]}`):s[e]=1,r.indexOf("#define SHADER_NAME")!==-1?r:`${`#define SHADER_NAME ${e}`}
37
- ${r}`}function pd(r,e){return e?r.replace("#version 300 es",""):r}const dn={stripVersion:pd,ensurePrecision:ud,addProgramDefines:cd,setProgramName:fd,insertVersion:dd},Us=Object.create(null),md=class $n{constructor(e){e={...$n.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:hd()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let i=e.fragment,n=e.vertex;Object.keys(dn).forEach(o=>{const a=s[o];i=dn[o](i,a,!0),n=dn[o](n,a,!1)}),this.fragment=i,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=is(`${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,Us[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return Us[t]||(Us[t]=new $n(e),Us[t]._cacheKey=t),Us[t]}};md.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let ls=md;const qh={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 Ms(r){return qh[r]??qh.float32}const R_={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"},Yh=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Kh(r,e){let t;for(;(t=Yh.exec(r))!==null;){const s=R_[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:s,stride:Ms(s).stride,offset:0,instance:!1,start:0}}Yh.lastIndex=0}function B_(r){return r.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function gd({source:r,entryPoint:e}){const t={},s=B_(r),i=s.indexOf(`fn ${e}(`);if(i===-1)return t;const n=s.indexOf("->",i);if(n===-1)return t;const o=s.substring(i,n);if(Kh(o,t),Object.keys(t).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=s.match(h);c&&Kh(c[1],t)}}return t}function jr(r){const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,i=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=r.match(e)?.map(u=>{const d=u.match(i),f=d?.[1]??"";let p;return f==="<uniform>"?p="uniform":f.startsWith("<storage")&&(p="storage"),{group:parseInt(u.match(t)[1],10),binding:parseInt(u.match(s)[1],10),name:d[2],accessMode:p,type:u.match(n)[1]}});if(!h)return{groups:[],structs:[]};const c=r.match(o)?.map(u=>{const d=u.match(l)[1],f=u.match(a).reduce((p,m)=>{const[g,_]=m.split(":");return p[g.trim()]=_.trim(),p},{});return f?{name:d,members:f}:null}).filter(({name:u})=>h.some(d=>d.type===u||d.type.includes(`<${u}>`)))??[];return{groups:h,structs:c}}var fe=(r=>(r[r.VERTEX=1]="VERTEX",r[r.FRAGMENT=2]="FRAGMENT",r[r.COMPUTE=4]="COMPUTE",r))(fe||{});function Br(r){return r.endsWith("<u32>")?"uint":r.endsWith("<i32>")?"sint":"float"}function _d({groups:r}){const e=[];for(let t=0;t<r.length;t++){const s=r[t];e[s.group]||(e[s.group]=[]),s.accessMode==="uniform"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,buffer:{type:"uniform"}}):s.accessMode==="storage"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,buffer:{type:"read-only-storage"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,sampler:{type:"filtering"}}):s.type==="sampler_comparison"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,sampler:{type:"comparison"}}):s.type==="texture_2d"||s.type.startsWith("texture_2d<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"2d",multisampled:!1}}):s.type==="texture_depth_2d"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d",multisampled:!1}}):s.type==="texture_depth_2d_array"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array",multisampled:!1}}):s.type==="texture_2d_array"||s.type.startsWith("texture_2d_array<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"2d-array",multisampled:!1}}):s.type==="texture_3d"||s.type.startsWith("texture_3d<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"3d",multisampled:!1}}):(s.type==="texture_cube"||s.type.startsWith("texture_cube<"))&&e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function yd({groups:r}){const e=[];for(let t=0;t<r.length;t++){const s=r[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function xd(r,e){const t=new Set,s=new Set,i=[...r.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...r.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:i,groups:n}}const Ns=Object.create(null);class Ft{constructor(e){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:i,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const a=jr(t.source);this.structsAndGroups=a}else{const a=jr(s.source),l=jr(t.source);this.structsAndGroups=xd(a,l)}this.layout=i??yd(this.structsAndGroups),this.gpuLayout=n??_d(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=is(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=gd(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Ns[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Ns[t]||(Ns[t]=new Ft(e),Ns[t]._cacheKey=t),Ns[t]}}const Zo=["f32","i32","u32","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>","vec2<u32>","vec3<u32>","vec4<u32>"],bd=Zo.reduce((r,e)=>(r[e]=!0,r),{});function vd(r,e){switch(r){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 wd=class Td extends Re{constructor(e,t){super(),this.uid=ne("uniform"),this._resourceType="uniformGroup",this._resourceId=ne("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Td.defaultOptions,...t},this.uniformStructures=e;const s={};for(const i in e){const n=e[i];if(n.name=i,n.size=n.size??1,!bd[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: ${Zo.join(", ")}`)}n.value??(n.value=vd(n.type,n.size)),s[i]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=is(Object.keys(s).map(i=>`${i}-${e[i].type}`).join("-"),"uniform-group")}get buffer(){return this._buffer}set buffer(e){this._buffer!==e&&(this._buffer?.off("change",this.onBufferChange,this),this._buffer=e,e?.on("change",this.onBufferChange,this))}get _gcLastUsed(){return this._buffer?._gcLastUsed??-1}set _gcLastUsed(e){this._buffer&&(this._buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=ne("resource"),this.emit("change",this)}update(){this._dirtyId++}};wd.defaultOptions={ubo:!1,isStatic:!1};let rt=wd;class St{constructor(e){this.resources=Object.create(null),this._resourceKeysValue=null,this._dirty=!0;let t=0;for(const s in e){const i=e[s];this.setResource(i,t++)}}get _resourceKeys(){return this._resourceKeysValue??(this._resourceKeysValue=Object.keys(this.resources).map(Number)),this._resourceKeysValue}get _key(){if(this._dirty){this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]?this.resources[s]._resourceId:-1;this._keyValue=e.join("|")}return this._keyValue}setResource(e,t){const s=this.resources[t];e!==s&&(s&&s.off?.("change",this.onResourceChange,this),e.on?.("change",this.onResourceChange,this),s===void 0&&(this._resourceKeysValue=null),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e){const t=this.resources,s=this._resourceKeys;for(let i=0;i<s.length;i++){const n=t[s[i]];n&&(n._gcLastUsed=e)}}destroy(){const e=this.resources;for(const t in e)e[t]?.off?.("change",this.onResourceChange,this);this.resources=null,this._resourceKeysValue=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const s in t)t[s]===e&&(t[s]=null);N(`[BindGroup] a '${e._resourceType}' was destroyed while still bound to a shader. Remove it from the shader before destroying it.`)}}}var Ke=(r=>(r[r.WEBGL=1]="WEBGL",r[r.WEBGPU=2]="WEBGPU",r[r.CANVAS=4]="CANVAS",r[r.BOTH=3]="BOTH",r))(Ke||{});class Es{constructor(e){this.data={...e};const t=Object.keys(e).sort().map(s=>`${s}:${e[s]}`).join("|");this.id=is(t,"shader-overrides")}static from(e){return e instanceof Es?e:new Es(e)}}class dt extends Re{constructor(e){super(),this.uid=ne("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:i,resources:n,compatibleRenderers:o,groupMap:a,overrides:l}=e;this._overrides=l?Es.from(l):null,this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=Ke.WEBGPU),s&&(o|=Ke.WEBGL)),this.compatibleRenderers=o;const h={};if(a)for(const c in a)for(const u in a[c]){const d=a[c][u];h[d]={group:c,binding:u,name:d}}if(!n&&!i&&(n={}),n&&i)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&i&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(t&&i&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,h[u.name]=u})}else if(n){i={},a||(a={}),t&&t.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,h[d.name]=d});let c=0;for(const u in n)h[u]||(t&&!s&&N(`[Shader] the resource '${u}' matches no binding in the WGSL source — is the name correct?`),i[99]||(i[99]=new St,this._ownedBindGroups.push(i[99])),h[u]={group:99,binding:c,name:u},a[99]=a[99]||{},a[99][c]=u,c++);for(const u in n){const d=u;let f=n[u];!f.source&&!f._resourceType&&(f=new rt(f));const p=h[d];p&&(i[p.group]||(i[p.group]=new St,this._ownedBindGroups.push(i[p.group])),i[p.group].setResource(f,p.binding))}}this.groups=i,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(i,h)}addResource(e,t,s){var i,n;(i=this._uniformBindMap)[t]||(i[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new St,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const i in t){const n=t[i];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(t=>{t.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null,this._overrides=null)}static from(e){const{gpu:t,gl:s,...i}=e;let n,o;return t&&(n=Ft.from(t)),s&&(o=ls.from(s)),new dt({gpuProgram:n,glProgram:o,...i})}}const I_={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},Qo={BLEND:0,OFFSET:1,CULLING:2,DEPTH_TEST:3,WINDING:4,DEPTH_MASK:5},{BLEND:fn,OFFSET:pn,CULLING:mn,DEPTH_TEST:gn,WINDING:_n,DEPTH_MASK:yn}=Qo,Vn=class Sd{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<fn)}set blend(e){!!(this.data&1<<fn)!==e&&(this.data^=1<<fn)}get offsets(){return!!(this.data&1<<pn)}set offsets(e){!!(this.data&1<<pn)!==e&&(this.data^=1<<pn)}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<<mn)}set culling(e){!!(this.data&1<<mn)!==e&&(this.data^=1<<mn)}get depthTest(){return!!(this.data&1<<gn)}set depthTest(e){!!(this.data&1<<gn)!==e&&(this.data^=1<<gn)}get depthMask(){return!!(this.data&1<<yn)}set depthMask(e){!!(this.data&1<<yn)!==e&&(this.data^=1<<yn)}get clockwiseFrontFace(){return!!(this.data&1<<_n)}set clockwiseFrontFace(e){!!(this.data&1<<_n)!==e&&(this.data^=1<<_n)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=I_[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 Sd;return e.depthTest=!1,e.depthMask=!1,e.blend=!0,e}};Vn.default2d=Vn.for2d();let ft=Vn;const Cd=class Xn extends dt{constructor(e){e={...Xn.defaultOptions,...e},super(e),this.enabled=!0,this._state=ft.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,s,i){e.applyFilter(this,t,s,i)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...i}=e;let n,o;return t&&(n=Ft.from(t)),s&&(o=ls.from(s)),new Xn({gpuProgram:n,glProgram:o,...i})}};Cd.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Jo=Cd;const jn=[];q.handleByNamedList(C.Environment,jn);async function Md(r){if(!r)for(let e=0;e<jn.length;e++){const t=jn[e];if(t.value.test()){await t.value.load();return}}}let Hs;function ea(){if(typeof Hs=="boolean")return Hs;try{Hs=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Hs=!1}return Hs}const dr=new Set;let qn=!1;function Zh(r,e,t=2){const s=e&&e.length,i=s?e[0]*t:r.length;dr.size&&dr.clear();let n=Ed(r,0,i,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a=0,l=0,h=0;if(s&&(n=O_(r,e,n,t)),r.length>80*t){a=r[0],l=r[1];let c=a,u=l;for(let d=t;d<i;d+=t){const f=r[d],p=r[d+1];f<a&&(a=f),p<l&&(l=p),f>c&&(c=f),p>u&&(u=p)}h=Math.max(c-a,u-l),h=h!==0?32767/h:0}return Yn(n,o,a,l,h),o}function Ed(r,e,t,s,i){let n=null;if(i===Z_(r,e,t,s)>0)for(let o=e;o<t;o+=s)n=ec(o/s|0,r[o],r[o+1],n);else for(let o=t-s;o>=e;o-=s)n=ec(o/s|0,r[o],r[o+1],n);return n&&fr(n,n.next)&&(mr(n),n=n.next),n}function ns(r,e=r){const t=e===r;let s=r,i;do i=!1,s!==s.next&&(dr.size===0||!dr.has(s))&&(fr(s,s.next)||xe(s.prev,s,s.next)===0)?((t||s===e)&&(e=s.prev),qn=!0,mr(s),s=s.prev,i=!0):(t||s!==e)&&(s=s.next,i=!t);while(i||s!==e);return e}function Yn(r,e,t,s,i){i&&V_(r,t,s,i);let n=r,o=!1;for(;r.prev!==r.next;){const a=r.prev,l=r.next;if(xe(a,r,l)<0&&(i?D_(r,t,s,i):G_(r))){e.push(a.i,r.i,l.i),mr(r),r=l,n=l;continue}if(r=l,r===n){if(qn=!1,r=ns(r),qn){n=r;continue}if(!o){r=F_(r,e),n=r,o=!0;continue}L_(r,e,t,s,i);break}}}function G_(r){const e=r.prev,t=r,s=r.next,i=e.x,n=t.x,o=s.x,a=e.y,l=t.y,h=s.y,c=Math.min(i,n,o),u=Math.min(a,l,h),d=Math.max(i,n,o),f=Math.max(a,l,h);let p=s.next;for(;p!==e;){if(p.x>=c&&p.x<=d&&p.y>=u&&p.y<=f&&!(i===p.x&&a===p.y)&&ni(i,a,n,l,o,h,p.x,p.y)&&xe(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function D_(r,e,t,s){const i=r.prev,n=r,o=r.next,a=i.x,l=n.x,h=o.x,c=i.y,u=n.y,d=o.y,f=Math.min(a,l,h),p=Math.min(c,u,d),m=Math.max(a,l,h),g=Math.max(c,u,d),_=Jn(f,p,e,t,s),x=Jn(m,g,e,t,s);let y=r.prevZ;for(;y&&y.z>=_;){if(y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==o&&!(a===y.x&&c===y.y)&&ni(a,c,l,u,h,d,y.x,y.y)&&xe(y.prev,y,y.next)>=0)return!1;y=y.prevZ}let b=r.nextZ;for(;b&&b.z<=x;){if(b.x>=f&&b.x<=m&&b.y>=p&&b.y<=g&&b!==o&&!(a===b.x&&c===b.y)&&ni(a,c,l,u,h,d,b.x,b.y)&&xe(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function F_(r,e){let t=r,s=!1;do{const i=t.prev,n=t.next.next;Ad(i,t,t.next,n,!1)&&pr(i,n)&&pr(n,i)&&(e.push(i.i,t.i,n.i),mr(t),mr(t.next),t=r=n,s=!0),t=t.next}while(t!==r);return s?ns(t):t}function L_(r,e,t,s,i){let n=r;do{let o=n.next.next;for(;o!==n.prev;){if(n.i!==o.i&&q_(n,o)){let a=Rd(n,o);n=ns(n,n.next),a=ns(a,a.next),Yn(n,e,t,s,i),Yn(a,e,t,s,i);return}o=o.next}n=n.next}while(n!==r)}let Kn=!1;function O_(r,e,t,s){const i=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:r.length,h=Ed(r,a,l,s,!1);h===h.next&&dr.add(h),i.push(j_(h))}i.sort(U_),H_(r.length/s,e.length),Pd(t,t),Kn=!0;for(let n=0;n<i.length;n++)t=N_(i[n],t);return Kn=!1,ns(t)}function U_(r,e){return r.x-e.x||r.y-e.y||(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)}function N_(r,e){const t=W_(r,e);if(!t)return e;const s=Rd(t,r),i=s.next;return Pd(t,i.next),ns(s,s.next),ns(t,t.next)}const kd=16;let pe=new Float64Array(0),ii=0;const Zn=[],Qn=[];function H_(r,e){const t=Math.ceil((r+2*e)/kd)+e+2;pe.length<t*4&&(pe=new Float64Array(t*4)),ii=0}function Pd(r,e){let t=r;do{const s=ii++;Zn[s]=t;let i=t.x,n=t.y,o=t.x,a=t.y,l=0;do{const c=t.next;t.z=s,c.x<i&&(i=c.x),c.x>o&&(o=c.x),c.y<n&&(n=c.y),c.y>a&&(a=c.y),t=c}while(++l<kd&&t!==e);Qn[s]=t;const h=s*4;pe[h]=i,pe[h+1]=n,pe[h+2]=o,pe[h+3]=a}while(t!==e)}function z_(r,e){const t=r.z*4;e.x<pe[t]&&(pe[t]=e.x),e.y<pe[t+1]&&(pe[t+1]=e.y),e.x>pe[t+2]&&(pe[t+2]=e.x),e.y>pe[t+3]&&(pe[t+3]=e.y)}function Qh(r){let e=Qn[r];for(;e.prev.next!==e;)e=e.next;return Qn[r]=e,e}function Jh(r){let e=Zn[r];for(;e.prev.next!==e;)e=e.next;return Zn[r]=e,e}function W_(r,e){let t=e;const s=r.x,i=r.y;let n=-1/0,o;if(fr(r,t))return t;for(let d=0,f=0;d<ii;d++,f+=4){if(i<pe[f+1]||i>pe[f+3]||pe[f]>s||pe[f+2]<=n)continue;const p=Qh(d);t=Jh(d);do{if(t.prev.next===t){if(fr(r,t.next))return t.next;if(i<=t.y&&i>=t.next.y&&t.next.y!==t.y){const m=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(m<=s&&m>n&&(n=m,o=t.x<t.next.x?t:t.next,m===s))return o}}t=t.next}while(t!==p)}if(!o)return null;const a=o.x,l=o.y,h=Math.min(i,l),c=Math.max(i,l);let u=1/0;for(let d=0,f=0;d<ii;d++,f+=4){if(pe[f+2]<a||pe[f]>s||pe[f+3]<h||pe[f+1]>c)continue;const p=Qh(d);t=Jh(d);do{if(t.prev.next===t&&s>=t.x&&t.x>=a&&s!==t.x&&ni(i<l?s:n,i,a,l,i<l?n:s,i,t.x,t.y)){const m=Math.abs(i-t.y)/(s-t.x);(pr(t,r)||t.y===i&&t.next.y===i&&t.next.x>s)&&(m<u||m===u&&(t.x>o.x||t.x===o.x&&$_(o,t)))&&(o=t,u=m)}t=t.next}while(t!==p)}return o}function $_(r,e){return xe(r.prev,r,e.prev)<0&&xe(e.next,r,r.next)<0}const He=[];let ys=[],Ot=new Uint32Array(0),zs=new Uint32Array(0);const Ws=new Uint32Array(256);function V_(r,e,t,s){let i=r,n=0;do i.z=Jn(i.x,i.y,e,t,s),He[n++]=i,i=i.next;while(i!==r);X_(n);let o=null;for(let a=0;a<n;a++){const l=He[a];l.prevZ=o,o&&(o.nextZ=l),o=l}o.nextZ=null,He.fill(null,0,n),ys.fill(null,0,n)}function X_(r){if(r<=32){for(let e=1;e<r;e++){const t=He[e],s=t.z;let i=e-1;for(;i>=0&&He[i].z>s;)He[i+1]=He[i],i--;He[i+1]=t}return}Ot.length<r&&(Ot=new Uint32Array(r),zs=new Uint32Array(r),ys=new Array(r));for(let e=0;e<r;e++)Ot[e]=He[e].z;Ir(r,He,Ot,ys,zs,0),Ir(r,ys,zs,He,Ot,8),Ir(r,He,Ot,ys,zs,16),Ir(r,ys,zs,He,Ot,24)}function Ir(r,e,t,s,i,n){Ws.fill(0);for(let a=0;a<r;a++)Ws[t[a]>>>n&255]++;let o=0;for(let a=0;a<256;a++){const l=Ws[a];Ws[a]=o,o+=l}for(let a=0;a<r;a++){const l=t[a],h=Ws[l>>>n&255]++;s[h]=e[a],i[h]=l}}function Jn(r,e,t,s,i){return r=(r-t)*i|0,e=(e-s)*i|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function j_(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function ni(r,e,t,s,i,n,o,a){return(i-o)*(e-a)>=(r-o)*(n-a)&&(r-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(i-o)*(s-a)}function q_(r,e){const t=fr(r,e)&&xe(r.prev,r,r.next)>0&&xe(e.prev,e,e.next)>0;return r.next.i!==e.i&&(t||pr(r,e)&&pr(e,r)&&(xe(r.prev,r,e.prev)!==0||xe(r,e.prev,e)!==0))&&!Y_(r,e)&&(t||K_(r,e))}function xe(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function fr(r,e){return r.x===e.x&&r.y===e.y}function Ad(r,e,t,s,i=!0){const n=xe(r,e,t),o=xe(r,e,s),a=xe(t,s,r),l=xe(t,s,e);return(n>0&&o<0||n<0&&o>0)&&(a>0&&l<0||a<0&&l>0)?!0:i?!!(n===0&&Gr(r,t,e)||o===0&&Gr(r,s,e)||a===0&&Gr(t,r,s)||l===0&&Gr(t,e,s)):!1}function Gr(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Y_(r,e){const t=Math.min(r.x,e.x),s=Math.max(r.x,e.x),i=Math.min(r.y,e.y),n=Math.max(r.y,e.y);let o=r;do{const a=o.next;if(o.x>s&&a.x>s||o.x<t&&a.x<t||o.y>n&&a.y>n||o.y<i&&a.y<i){o=a;continue}if(o.i!==r.i&&a.i!==r.i&&o.i!==e.i&&a.i!==e.i&&Ad(o,a,r,e))return!0;o=a}while(o!==r);return!1}function pr(r,e){return xe(r.prev,r,r.next)<0?xe(r,e,r.next)>=0&&xe(r,r.prev,e)>=0:xe(r,e,r.prev)<0||xe(r,r.next,e)<0}function K_(r,e){let t=r,s=!1;const i=(r.x+e.x)/2,n=(r.y+e.y)/2;do{const o=t.next;t.y>n!=o.y>n&&i<(o.x-t.x)*(n-t.y)/(o.y-t.y)+t.x&&(s=!s),t=o}while(t!==r);return s}function Rd(r,e){const t=eo(r.i,r.x,r.y),s=eo(e.i,e.x,e.y),i=r.next,n=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function ec(r,e,t,s){const i=eo(r,e,t);return s?(i.next=s.next,i.prev=s,s.next.prev=i,s.next=i):(i.prev=i,i.next=i),i}function mr(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ),Kn&&z_(r.prev,r.next)}function eo(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null}}function Z_(r,e,t,s){let i=0;for(let n=e,o=t-s;n<t;n+=s)i+=(r[o]-r[n])*(r[n+1]+r[o+1]),o=n;return i}const Bd=Zh.default||Zh;var ye=(r=>(r[r.NONE=0]="NONE",r[r.COLOR=16384]="COLOR",r[r.STENCIL=1024]="STENCIL",r[r.DEPTH=256]="DEPTH",r[r.COLOR_DEPTH=16640]="COLOR_DEPTH",r[r.COLOR_STENCIL=17408]="COLOR_STENCIL",r[r.DEPTH_STENCIL=1280]="DEPTH_STENCIL",r[r.ALL=17664]="ALL",r))(ye||{});class ta{constructor(e){this.items=[],this._name=e}emit(e,t,s,i,n,o,a,l){const{name:h,items:c}=this;for(let u=0,d=c.length;u<d;u++)c[u][h](e,t,s,i,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 Q_=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Id=class Gd extends Re{constructor(e){super(),this.tick=0,this.uid=ne("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=[...Q_,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await Md(t),!t&&this.config.loaders&&await Promise.all(this.config.loaders.map(s=>s.value.load())),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...Gd.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){this.tick++;let s=e;if(s instanceof _e&&(s={container:s},t&&(O(ue,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const i=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=i?s.clearColor:oe.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const i=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==i&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=ye.ALL);const{clear:s,clearColor:i,target:n,mipLevel:o,layer:a}=e;oe.shared.setValue(i??this.background.colorRgba),t.renderTarget.clear(n,s,oe.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 ta(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const i in this.runners)this.runners[i].add(s);return this}_addPipes(e,t){const s=t.reduce((i,n)=>(i[n.name]=n.value,i),{});e.forEach(i=>{const n=i.value,o=i.name,a=s[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)&&as.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(!ea())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()}};Id.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let Is=Id,Dr;function Dd(r){return Dr!==void 0||(Dr=(()=>{const e={stencil:!0,failIfMajorPerformanceCaveat:r??Is.defaultOptions.failIfMajorPerformanceCaveat};try{if(!J.get().getWebGLRenderingContext())return!1;let s=J.get().createCanvas().getContext("webgl",e);const i=!!s?.getContextAttributes()?.stencil;if(s){const n=s.getExtension("WEBGL_lose_context");n&&n.loseContext()}return s=null,i}catch{return!1}})()),Dr}let Fr;async function Fd(r={}){return Fr!==void 0||(Fr=await(async()=>{const e=J.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Fr}const tc=["webgl","webgpu","canvas"];async function Ld(r){let e=[];r.preference?Array.isArray(r.preference)?e=r.preference.slice():(e.push(r.preference),tc.forEach(n=>{n!==r.preference&&e.push(n)})):e=tc.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await Fd()){const{WebGPURenderer:a}=await wt(async()=>{const{WebGPURenderer:l}=await Promise.resolve().then(()=>xx);return{WebGPURenderer:l}},void 0);t=a,s={...r,...r.webgpu};break}else if(o==="webgl"&&Dd(r.failIfMajorPerformanceCaveat??Is.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await wt(async()=>{const{WebGLRenderer:l}=await Promise.resolve().then(()=>rx);return{WebGLRenderer:l}},void 0);t=a,s={...r,...r.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await wt(async()=>{const{CanvasRenderer:l}=await Promise.resolve().then(()=>Uy);return{CanvasRenderer:l}},void 0);t=a,s={...r,...r.canvasOptions};break}}if(delete s.webgpu,delete s.webgl,delete s.canvasOptions,!t)throw new Error("No available renderer for the current environment");const i=new t;return await i.init(s),i}const gr="8.22.0";class sa{static init(){globalThis.__PIXI_APP_INIT__?.(this,gr)}static destroy(){}}sa.extension=C.Application;class ra{constructor(e){this._renderer=e}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,gr)}destroy(){this._renderer=null}}ra.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"initHook",priority:-10};class ia{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,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:i,clientHeight:n}=this._resizeTo;t=i,s=n}this.renderer.resize(t,s),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}}ia.extension=C.Application;class na{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,rs.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?We.shared:new We,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}na.extension=C.Application;q.add(ia);q.add(na);const Od=class to{constructor(...e){this.stage=new _e,e[0]!==void 0&&O(ue,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new _e),this.renderer=await Ld(e),to._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return O(ue,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}get domContainerRoot(){return this.renderer.renderPipes.dom?._domElement}destroy(e=!1,t=!1){const s=to._plugins.slice(0);s.reverse(),s.forEach(i=>{i.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};Od._plugins=[];let oa=Od;q.handleByList(C.Application,oa._plugins);q.add(sa);const xn={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},J_=/([astvzqmhlc])([^astvzqmhlc]*)/gi,e0=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;function t0(r){const e=[];return r.replace(J_,(t,s,i)=>{let n=s.toLowerCase(),o=s;const a=s0(i);for(n==="m"&&a.length>2&&(e.push([o,...a.splice(0,2)]),n="l",o=o==="m"?"l":"L");;){if(a.length===xn[n])return e.push([o,...a]),"";if(a.length<xn[n])throw new Error("malformed path data");e.push([o,...a.splice(0,xn[n])])}}),e}function s0(r){const e=r.match(e0);return e?e.map(Number):[]}function Ud(r,e){const t=t0(r),s=[];let i=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],h=l[0],c=l;switch(h){case"M":n=c[1],o=c[2],e.moveTo(n,o);break;case"m":n+=c[1],o+=c[2],e.moveTo(n,o);break;case"H":n=c[1],e.lineTo(n,o);break;case"h":n+=c[1],e.lineTo(n,o);break;case"V":o=c[1],e.lineTo(n,o);break;case"v":o+=c[1],e.lineTo(n,o);break;case"L":n=c[1],o=c[2],e.lineTo(n,o);break;case"l":n+=c[1],o+=c[2],e.lineTo(n,o);break;case"C":n=c[5],o=c[6],e.bezierCurveTo(c[1],c[2],c[3],c[4],n,o);break;case"c":e.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],e.bezierCurveToShort(c[1],c[2],n,o);break;case"s":e.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],e.quadraticCurveTo(c[1],c[2],n,o);break;case"q":e.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],e.quadraticCurveToShort(n,o);break;case"t":n+=c[1],o+=c[2],e.quadraticCurveToShort(n,o);break;case"A":n=c[6],o=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"a":n+=c[6],o+=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(i=s.pop(),i?(n=i.startX,o=i.startY):(n=0,o=0)),i=null;break;default:N(`Unknown SVG path command: ${h}`)}h!=="Z"&&h!=="z"&&i===null&&(i={startX:n,startY:o},s.push(i))}return e}class Ti{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new Ti(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let i=this.x-e,n=this.y-t;return i*=i,n*=n,i+n<=s}strokeContains(e,t,s,i=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-i)*s,h=Math.sqrt(n*n+o*o);return h<=a+l&&h>a-(s-l)}getBounds(e){return e||(e=new ee),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 Si{constructor(e=0,t=0,s=0,i=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=i}clone(){return new Si(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,i=(t-this.y)/this.halfHeight;return s*=s,i*=i,s+i<=1}strokeContains(e,t,s,i=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-i),l=s-a,h=n-l,c=o-l,u=n+a,d=o+a,f=e-this.x,p=t-this.y;return f*f/(u*u)+p*p/(d*d)>1?!1:h<=0||c<=0?!0:f*f/(h*h)+p*p/(c*c)>1}getBounds(e){return e||(e=new ee),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 aa(r){const e=r.length;if(e<6)return 1;let t=0;for(let s=0,i=r[e-2],n=r[e-1];s<e;s+=2){const o=r[s],a=r[s+1];t+=(o-i)*(a+n),i=o,n=a}return t<0?-1:1}function Nd(r,e,t,s,i,n){const o=r-t,a=e-s,l=i-t,h=n-s,c=o*l+a*h,u=l*l+h*h;let d=-1;u!==0&&(d=c/u);let f,p;d<0?(f=t,p=s):d>1?(f=i,p=n):(f=t+d*l,p=s+d*h);const m=r-f,g=e-p;return m*m+g*g}let r0,i0;class Ts{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let i=0,n=t.length;i<n;i++)s.push(t[i].x,t[i].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let i=0;i<s;i+=2){const n=t[i],o=t[i+1],a=t[(i+2)%s],l=t[(i+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(r0),s=e.getBounds(i0);if(!t.containsRect(s))return!1;const i=e.points;for(let n=0;n<i.length;n+=2){const o=i[n],a=i[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new Ts(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const i=this.points.length/2;for(let n=0,o=i-1;n<i;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>t!=c>t&&e<(h-a)*((t-l)/(c-l))+a&&(s=!s)}return s}strokeContains(e,t,s,i=.5){const{points:n}=this,o=i===.5?i:(i-.5)*aa(n)+.5,a=s*o,l=s-a,h=a*a,c=l*l,u=n.length-(this.closePath?0:2);for(let d=0;d<u;d+=2){const f=n[d],p=n[d+1],m=n[(d+2)%n.length],g=n[(d+3)%n.length],_=Nd(e,t,f,p,m,g),x=Math.sign((m-f)*(t-p)-(g-p)*(e-f));if(_<=(x<0?h:c))return!0}return!1}getBounds(e){e||(e=new ee);const t=this.points;let s=1/0,i=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const h=t[a],c=t[a+1];s=h<s?h:s,i=h>i?h:i,n=c<n?c:n,o=c>o?c:o}return e.x=s,e.width=i-s,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 O("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return O("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 Lr=(r,e,t,s,i,n,o)=>{const a=r-t,l=e-s,h=Math.sqrt(a*a+l*l);return h>=i-n&&h<=i+o};class Ci{constructor(e=0,t=0,s=0,i=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=i,this.radius=n}getBounds(e){return e||(e=new ee),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Ci(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.radius=e.radius,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 s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let i=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(i*i+n*n<=o||(i=e-(this.x+this.width-s),i*i+n*n<=o)||(n=t-(this.y+this.height-s),i*i+n*n<=o)||(i=e-(this.x+s),i*i+n*n<=o))return!0}return!1}strokeContains(e,t,s,i=.5){const{x:n,y:o,width:a,height:l,radius:h}=this,c=s*(1-i),u=s-c,d=n+h,f=o+h,p=a-h*2,m=l-h*2,g=n+a,_=o+l;return(e>=n-c&&e<=n+u||e>=g-u&&e<=g+c)&&t>=f&&t<=f+m||(t>=o-c&&t<=o+u||t>=_-u&&t<=_+c)&&e>=d&&e<=d+p?!0:e<d&&t<f&&Lr(e,t,d,f,h,u,c)||e>g-h&&t<f&&Lr(e,t,g-h,f,h,u,c)||e>g-h&&t>_-h&&Lr(e,t,g-h,_-h,h,u,c)||e<d&&t>_-h&&Lr(e,t,d,_-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 Hd={};function Mi(r,e,t){let s=2166136261;for(let i=0;i<e;i++)s^=r[i].uid,s=Math.imul(s,16777619),s>>>=0;return Hd[s]||n0(r,e,s,t)}function n0(r,e,t,s){const i={};let n=0;for(let a=0;a<s;a++){const l=a<e?r[a]:H.EMPTY.source;i[n++]=l.source,i[n++]=l.style}const o=new St(i);return Hd[t]=o,o}class so{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 oi(r,e,t,s){if(t??(t=0),s??(s=Math.min(r.byteLength-t,e.byteLength)),!(t&7)&&!(s&7)){const i=s/8;new Float64Array(e,0,i).set(new Float64Array(r,t,i))}else if(!(t&3)&&!(s&3)){const i=s/4;new Float32Array(e,0,i).set(new Float32Array(r,t,i))}else new Uint8Array(e).set(new Uint8Array(r,t,s))}const zd={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var me=(r=>(r[r.DISABLED=0]="DISABLED",r[r.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",r[r.MASK_ACTIVE=2]="MASK_ACTIVE",r[r.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",r[r.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",r[r.NONE=5]="NONE",r))(me||{});function ro(r,e){return e.alphaMode==="no-premultiply-alpha"&&zd[r]||r}const o0=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
37
+ ${r}`}function pd(r,e){return e?r.replace("#version 300 es",""):r}const dn={stripVersion:pd,ensurePrecision:ud,addProgramDefines:cd,setProgramName:fd,insertVersion:dd},Us=Object.create(null),md=class $n{constructor(e){e={...$n.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:hd()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let i=e.fragment,n=e.vertex;Object.keys(dn).forEach(o=>{const a=s[o];i=dn[o](i,a,!0),n=dn[o](n,a,!1)}),this.fragment=i,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=is(`${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,Us[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return Us[t]||(Us[t]=new $n(e),Us[t]._cacheKey=t),Us[t]}};md.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let ls=md;const qh={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 Ms(r){return qh[r]??qh.float32}const R_={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"},Yh=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Kh(r,e){let t;for(;(t=Yh.exec(r))!==null;){const s=R_[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:s,stride:Ms(s).stride,offset:0,instance:!1,start:0}}Yh.lastIndex=0}function B_(r){return r.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function gd({source:r,entryPoint:e}){const t={},s=B_(r),i=s.indexOf(`fn ${e}(`);if(i===-1)return t;const n=s.indexOf("->",i);if(n===-1)return t;const o=s.substring(i,n);if(Kh(o,t),Object.keys(t).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=s.match(h);c&&Kh(c[1],t)}}return t}function jr(r){const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,i=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=r.match(e)?.map(u=>{const d=u.match(i),f=d?.[1]??"";let p;return f==="<uniform>"?p="uniform":f.startsWith("<storage")&&(p="storage"),{group:parseInt(u.match(t)[1],10),binding:parseInt(u.match(s)[1],10),name:d[2],accessMode:p,type:u.match(n)[1]}});if(!h)return{groups:[],structs:[]};const c=r.match(o)?.map(u=>{const d=u.match(l)[1],f=u.match(a).reduce((p,m)=>{const[g,_]=m.split(":");return p[g.trim()]=_.trim(),p},{});return f?{name:d,members:f}:null}).filter(({name:u})=>h.some(d=>d.type===u||d.type.includes(`<${u}>`)))??[];return{groups:h,structs:c}}var fe=(r=>(r[r.VERTEX=1]="VERTEX",r[r.FRAGMENT=2]="FRAGMENT",r[r.COMPUTE=4]="COMPUTE",r))(fe||{});function Br(r){return r.endsWith("<u32>")?"uint":r.endsWith("<i32>")?"sint":"float"}function _d({groups:r}){const e=[];for(let t=0;t<r.length;t++){const s=r[t];e[s.group]||(e[s.group]=[]),s.accessMode==="uniform"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,buffer:{type:"uniform"}}):s.accessMode==="storage"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,buffer:{type:"read-only-storage"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,sampler:{type:"filtering"}}):s.type==="sampler_comparison"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,sampler:{type:"comparison"}}):s.type==="texture_2d"||s.type.startsWith("texture_2d<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"2d",multisampled:!1}}):s.type==="texture_depth_2d"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d",multisampled:!1}}):s.type==="texture_depth_2d_array"?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array",multisampled:!1}}):s.type==="texture_2d_array"||s.type.startsWith("texture_2d_array<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"2d-array",multisampled:!1}}):s.type==="texture_3d"||s.type.startsWith("texture_3d<")?e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"3d",multisampled:!1}}):(s.type==="texture_cube"||s.type.startsWith("texture_cube<"))&&e[s.group].push({binding:s.binding,visibility:fe.VERTEX|fe.FRAGMENT,texture:{sampleType:Br(s.type),viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function yd({groups:r}){const e=[];for(let t=0;t<r.length;t++){const s=r[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function xd(r,e){const t=new Set,s=new Set,i=[...r.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...r.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:i,groups:n}}const Ns=Object.create(null);class Ft{constructor(e){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:i,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const a=jr(t.source);this.structsAndGroups=a}else{const a=jr(s.source),l=jr(t.source);this.structsAndGroups=xd(a,l)}this.layout=i??yd(this.structsAndGroups),this.gpuLayout=n??_d(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=is(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=gd(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Ns[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Ns[t]||(Ns[t]=new Ft(e),Ns[t]._cacheKey=t),Ns[t]}}const Zo=["f32","i32","u32","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>","vec2<u32>","vec3<u32>","vec4<u32>"],bd=Zo.reduce((r,e)=>(r[e]=!0,r),{});function vd(r,e){switch(r){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 wd=class Td extends Re{constructor(e,t){super(),this.uid=ne("uniform"),this._resourceType="uniformGroup",this._resourceId=ne("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Td.defaultOptions,...t},this.uniformStructures=e;const s={};for(const i in e){const n=e[i];if(n.name=i,n.size=n.size??1,!bd[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: ${Zo.join(", ")}`)}n.value??(n.value=vd(n.type,n.size)),s[i]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=is(Object.keys(s).map(i=>`${i}-${e[i].type}`).join("-"),"uniform-group")}get buffer(){return this._buffer}set buffer(e){this._buffer!==e&&(this._buffer?.off("change",this.onBufferChange,this),this._buffer=e,e?.on("change",this.onBufferChange,this))}get _gcLastUsed(){return this._buffer?._gcLastUsed??-1}set _gcLastUsed(e){this._buffer&&(this._buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=ne("resource"),this.emit("change",this)}update(){this._dirtyId++}};wd.defaultOptions={ubo:!1,isStatic:!1};let rt=wd;class St{constructor(e){this.resources=Object.create(null),this._resourceKeysValue=null,this._dirty=!0;let t=0;for(const s in e){const i=e[s];this.setResource(i,t++)}}get _resourceKeys(){return this._resourceKeysValue??(this._resourceKeysValue=Object.keys(this.resources).map(Number)),this._resourceKeysValue}get _key(){if(this._dirty){this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]?this.resources[s]._resourceId:-1;this._keyValue=e.join("|")}return this._keyValue}setResource(e,t){const s=this.resources[t];e!==s&&(s&&s.off?.("change",this.onResourceChange,this),e.on?.("change",this.onResourceChange,this),s===void 0&&(this._resourceKeysValue=null),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e){const t=this.resources,s=this._resourceKeys;for(let i=0;i<s.length;i++){const n=t[s[i]];n&&(n._gcLastUsed=e)}}destroy(){const e=this.resources;for(const t in e)e[t]?.off?.("change",this.onResourceChange,this);this.resources=null,this._resourceKeysValue=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const s in t)t[s]===e&&(t[s]=null);N(`[BindGroup] a '${e._resourceType}' was destroyed while still bound to a shader. Remove it from the shader before destroying it.`)}}}var Ke=(r=>(r[r.WEBGL=1]="WEBGL",r[r.WEBGPU=2]="WEBGPU",r[r.CANVAS=4]="CANVAS",r[r.BOTH=3]="BOTH",r))(Ke||{});class Es{constructor(e){this.data={...e};const t=Object.keys(e).sort().map(s=>`${s}:${e[s]}`).join("|");this.id=is(t,"shader-overrides")}static from(e){return e instanceof Es?e:new Es(e)}}class dt extends Re{constructor(e){super(),this.uid=ne("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:i,resources:n,compatibleRenderers:o,groupMap:a,overrides:l}=e;this._overrides=l?Es.from(l):null,this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=Ke.WEBGPU),s&&(o|=Ke.WEBGL)),this.compatibleRenderers=o;const h={};if(a)for(const c in a)for(const u in a[c]){const d=a[c][u];h[d]={group:c,binding:u,name:d}}if(!n&&!i&&(n={}),n&&i)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&i&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(t&&i&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,h[u.name]=u})}else if(n){i={},a||(a={}),t&&t.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,h[d.name]=d});let c=0;for(const u in n)h[u]||(t&&!s&&N(`[Shader] the resource '${u}' matches no binding in the WGSL source — is the name correct?`),i[99]||(i[99]=new St,this._ownedBindGroups.push(i[99])),h[u]={group:99,binding:c,name:u},a[99]=a[99]||{},a[99][c]=u,c++);for(const u in n){const d=u;let f=n[u];!f.source&&!f._resourceType&&(f=new rt(f));const p=h[d];p&&(i[p.group]||(i[p.group]=new St,this._ownedBindGroups.push(i[p.group])),i[p.group].setResource(f,p.binding))}}this.groups=i,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(i,h)}addResource(e,t,s){var i,n;(i=this._uniformBindMap)[t]||(i[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new St,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const i in t){const n=t[i];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(t=>{t.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null,this._overrides=null)}static from(e){const{gpu:t,gl:s,...i}=e;let n,o;return t&&(n=Ft.from(t)),s&&(o=ls.from(s)),new dt({gpuProgram:n,glProgram:o,...i})}}const I_={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},Qo={BLEND:0,OFFSET:1,CULLING:2,DEPTH_TEST:3,WINDING:4,DEPTH_MASK:5},{BLEND:fn,OFFSET:pn,CULLING:mn,DEPTH_TEST:gn,WINDING:_n,DEPTH_MASK:yn}=Qo,Vn=class Sd{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<fn)}set blend(e){!!(this.data&1<<fn)!==e&&(this.data^=1<<fn)}get offsets(){return!!(this.data&1<<pn)}set offsets(e){!!(this.data&1<<pn)!==e&&(this.data^=1<<pn)}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<<mn)}set culling(e){!!(this.data&1<<mn)!==e&&(this.data^=1<<mn)}get depthTest(){return!!(this.data&1<<gn)}set depthTest(e){!!(this.data&1<<gn)!==e&&(this.data^=1<<gn)}get depthMask(){return!!(this.data&1<<yn)}set depthMask(e){!!(this.data&1<<yn)!==e&&(this.data^=1<<yn)}get clockwiseFrontFace(){return!!(this.data&1<<_n)}set clockwiseFrontFace(e){!!(this.data&1<<_n)!==e&&(this.data^=1<<_n)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=I_[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 Sd;return e.depthTest=!1,e.depthMask=!1,e.blend=!0,e}};Vn.default2d=Vn.for2d();let ft=Vn;const Cd=class Xn extends dt{constructor(e){e={...Xn.defaultOptions,...e},super(e),this.enabled=!0,this._state=ft.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,s,i){e.applyFilter(this,t,s,i)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...i}=e;let n,o;return t&&(n=Ft.from(t)),s&&(o=ls.from(s)),new Xn({gpuProgram:n,glProgram:o,...i})}};Cd.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Jo=Cd;const jn=[];q.handleByNamedList(S.Environment,jn);async function Md(r){if(!r)for(let e=0;e<jn.length;e++){const t=jn[e];if(t.value.test()){await t.value.load();return}}}let Hs;function ea(){if(typeof Hs=="boolean")return Hs;try{Hs=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Hs=!1}return Hs}const dr=new Set;let qn=!1;function Zh(r,e,t=2){const s=e&&e.length,i=s?e[0]*t:r.length;dr.size&&dr.clear();let n=Ed(r,0,i,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a=0,l=0,h=0;if(s&&(n=O_(r,e,n,t)),r.length>80*t){a=r[0],l=r[1];let c=a,u=l;for(let d=t;d<i;d+=t){const f=r[d],p=r[d+1];f<a&&(a=f),p<l&&(l=p),f>c&&(c=f),p>u&&(u=p)}h=Math.max(c-a,u-l),h=h!==0?32767/h:0}return Yn(n,o,a,l,h),o}function Ed(r,e,t,s,i){let n=null;if(i===Z_(r,e,t,s)>0)for(let o=e;o<t;o+=s)n=ec(o/s|0,r[o],r[o+1],n);else for(let o=t-s;o>=e;o-=s)n=ec(o/s|0,r[o],r[o+1],n);return n&&fr(n,n.next)&&(mr(n),n=n.next),n}function ns(r,e=r){const t=e===r;let s=r,i;do i=!1,s!==s.next&&(dr.size===0||!dr.has(s))&&(fr(s,s.next)||xe(s.prev,s,s.next)===0)?((t||s===e)&&(e=s.prev),qn=!0,mr(s),s=s.prev,i=!0):(t||s!==e)&&(s=s.next,i=!t);while(i||s!==e);return e}function Yn(r,e,t,s,i){i&&V_(r,t,s,i);let n=r,o=!1;for(;r.prev!==r.next;){const a=r.prev,l=r.next;if(xe(a,r,l)<0&&(i?D_(r,t,s,i):G_(r))){e.push(a.i,r.i,l.i),mr(r),r=l,n=l;continue}if(r=l,r===n){if(qn=!1,r=ns(r),qn){n=r;continue}if(!o){r=F_(r,e),n=r,o=!0;continue}L_(r,e,t,s,i);break}}}function G_(r){const e=r.prev,t=r,s=r.next,i=e.x,n=t.x,o=s.x,a=e.y,l=t.y,h=s.y,c=Math.min(i,n,o),u=Math.min(a,l,h),d=Math.max(i,n,o),f=Math.max(a,l,h);let p=s.next;for(;p!==e;){if(p.x>=c&&p.x<=d&&p.y>=u&&p.y<=f&&!(i===p.x&&a===p.y)&&ni(i,a,n,l,o,h,p.x,p.y)&&xe(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function D_(r,e,t,s){const i=r.prev,n=r,o=r.next,a=i.x,l=n.x,h=o.x,c=i.y,u=n.y,d=o.y,f=Math.min(a,l,h),p=Math.min(c,u,d),m=Math.max(a,l,h),g=Math.max(c,u,d),_=Jn(f,p,e,t,s),x=Jn(m,g,e,t,s);let y=r.prevZ;for(;y&&y.z>=_;){if(y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==o&&!(a===y.x&&c===y.y)&&ni(a,c,l,u,h,d,y.x,y.y)&&xe(y.prev,y,y.next)>=0)return!1;y=y.prevZ}let b=r.nextZ;for(;b&&b.z<=x;){if(b.x>=f&&b.x<=m&&b.y>=p&&b.y<=g&&b!==o&&!(a===b.x&&c===b.y)&&ni(a,c,l,u,h,d,b.x,b.y)&&xe(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function F_(r,e){let t=r,s=!1;do{const i=t.prev,n=t.next.next;Ad(i,t,t.next,n,!1)&&pr(i,n)&&pr(n,i)&&(e.push(i.i,t.i,n.i),mr(t),mr(t.next),t=r=n,s=!0),t=t.next}while(t!==r);return s?ns(t):t}function L_(r,e,t,s,i){let n=r;do{let o=n.next.next;for(;o!==n.prev;){if(n.i!==o.i&&q_(n,o)){let a=Rd(n,o);n=ns(n,n.next),a=ns(a,a.next),Yn(n,e,t,s,i),Yn(a,e,t,s,i);return}o=o.next}n=n.next}while(n!==r)}let Kn=!1;function O_(r,e,t,s){const i=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:r.length,h=Ed(r,a,l,s,!1);h===h.next&&dr.add(h),i.push(j_(h))}i.sort(U_),H_(r.length/s,e.length),Pd(t,t),Kn=!0;for(let n=0;n<i.length;n++)t=N_(i[n],t);return Kn=!1,ns(t)}function U_(r,e){return r.x-e.x||r.y-e.y||(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)}function N_(r,e){const t=W_(r,e);if(!t)return e;const s=Rd(t,r),i=s.next;return Pd(t,i.next),ns(s,s.next),ns(t,t.next)}const kd=16;let pe=new Float64Array(0),ii=0;const Zn=[],Qn=[];function H_(r,e){const t=Math.ceil((r+2*e)/kd)+e+2;pe.length<t*4&&(pe=new Float64Array(t*4)),ii=0}function Pd(r,e){let t=r;do{const s=ii++;Zn[s]=t;let i=t.x,n=t.y,o=t.x,a=t.y,l=0;do{const c=t.next;t.z=s,c.x<i&&(i=c.x),c.x>o&&(o=c.x),c.y<n&&(n=c.y),c.y>a&&(a=c.y),t=c}while(++l<kd&&t!==e);Qn[s]=t;const h=s*4;pe[h]=i,pe[h+1]=n,pe[h+2]=o,pe[h+3]=a}while(t!==e)}function z_(r,e){const t=r.z*4;e.x<pe[t]&&(pe[t]=e.x),e.y<pe[t+1]&&(pe[t+1]=e.y),e.x>pe[t+2]&&(pe[t+2]=e.x),e.y>pe[t+3]&&(pe[t+3]=e.y)}function Qh(r){let e=Qn[r];for(;e.prev.next!==e;)e=e.next;return Qn[r]=e,e}function Jh(r){let e=Zn[r];for(;e.prev.next!==e;)e=e.next;return Zn[r]=e,e}function W_(r,e){let t=e;const s=r.x,i=r.y;let n=-1/0,o;if(fr(r,t))return t;for(let d=0,f=0;d<ii;d++,f+=4){if(i<pe[f+1]||i>pe[f+3]||pe[f]>s||pe[f+2]<=n)continue;const p=Qh(d);t=Jh(d);do{if(t.prev.next===t){if(fr(r,t.next))return t.next;if(i<=t.y&&i>=t.next.y&&t.next.y!==t.y){const m=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(m<=s&&m>n&&(n=m,o=t.x<t.next.x?t:t.next,m===s))return o}}t=t.next}while(t!==p)}if(!o)return null;const a=o.x,l=o.y,h=Math.min(i,l),c=Math.max(i,l);let u=1/0;for(let d=0,f=0;d<ii;d++,f+=4){if(pe[f+2]<a||pe[f]>s||pe[f+3]<h||pe[f+1]>c)continue;const p=Qh(d);t=Jh(d);do{if(t.prev.next===t&&s>=t.x&&t.x>=a&&s!==t.x&&ni(i<l?s:n,i,a,l,i<l?n:s,i,t.x,t.y)){const m=Math.abs(i-t.y)/(s-t.x);(pr(t,r)||t.y===i&&t.next.y===i&&t.next.x>s)&&(m<u||m===u&&(t.x>o.x||t.x===o.x&&$_(o,t)))&&(o=t,u=m)}t=t.next}while(t!==p)}return o}function $_(r,e){return xe(r.prev,r,e.prev)<0&&xe(e.next,r,r.next)<0}const He=[];let ys=[],Ot=new Uint32Array(0),zs=new Uint32Array(0);const Ws=new Uint32Array(256);function V_(r,e,t,s){let i=r,n=0;do i.z=Jn(i.x,i.y,e,t,s),He[n++]=i,i=i.next;while(i!==r);X_(n);let o=null;for(let a=0;a<n;a++){const l=He[a];l.prevZ=o,o&&(o.nextZ=l),o=l}o.nextZ=null,He.fill(null,0,n),ys.fill(null,0,n)}function X_(r){if(r<=32){for(let e=1;e<r;e++){const t=He[e],s=t.z;let i=e-1;for(;i>=0&&He[i].z>s;)He[i+1]=He[i],i--;He[i+1]=t}return}Ot.length<r&&(Ot=new Uint32Array(r),zs=new Uint32Array(r),ys=new Array(r));for(let e=0;e<r;e++)Ot[e]=He[e].z;Ir(r,He,Ot,ys,zs,0),Ir(r,ys,zs,He,Ot,8),Ir(r,He,Ot,ys,zs,16),Ir(r,ys,zs,He,Ot,24)}function Ir(r,e,t,s,i,n){Ws.fill(0);for(let a=0;a<r;a++)Ws[t[a]>>>n&255]++;let o=0;for(let a=0;a<256;a++){const l=Ws[a];Ws[a]=o,o+=l}for(let a=0;a<r;a++){const l=t[a],h=Ws[l>>>n&255]++;s[h]=e[a],i[h]=l}}function Jn(r,e,t,s,i){return r=(r-t)*i|0,e=(e-s)*i|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function j_(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function ni(r,e,t,s,i,n,o,a){return(i-o)*(e-a)>=(r-o)*(n-a)&&(r-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(i-o)*(s-a)}function q_(r,e){const t=fr(r,e)&&xe(r.prev,r,r.next)>0&&xe(e.prev,e,e.next)>0;return r.next.i!==e.i&&(t||pr(r,e)&&pr(e,r)&&(xe(r.prev,r,e.prev)!==0||xe(r,e.prev,e)!==0))&&!Y_(r,e)&&(t||K_(r,e))}function xe(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function fr(r,e){return r.x===e.x&&r.y===e.y}function Ad(r,e,t,s,i=!0){const n=xe(r,e,t),o=xe(r,e,s),a=xe(t,s,r),l=xe(t,s,e);return(n>0&&o<0||n<0&&o>0)&&(a>0&&l<0||a<0&&l>0)?!0:i?!!(n===0&&Gr(r,t,e)||o===0&&Gr(r,s,e)||a===0&&Gr(t,r,s)||l===0&&Gr(t,e,s)):!1}function Gr(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Y_(r,e){const t=Math.min(r.x,e.x),s=Math.max(r.x,e.x),i=Math.min(r.y,e.y),n=Math.max(r.y,e.y);let o=r;do{const a=o.next;if(o.x>s&&a.x>s||o.x<t&&a.x<t||o.y>n&&a.y>n||o.y<i&&a.y<i){o=a;continue}if(o.i!==r.i&&a.i!==r.i&&o.i!==e.i&&a.i!==e.i&&Ad(o,a,r,e))return!0;o=a}while(o!==r);return!1}function pr(r,e){return xe(r.prev,r,r.next)<0?xe(r,e,r.next)>=0&&xe(r,r.prev,e)>=0:xe(r,e,r.prev)<0||xe(r,r.next,e)<0}function K_(r,e){let t=r,s=!1;const i=(r.x+e.x)/2,n=(r.y+e.y)/2;do{const o=t.next;t.y>n!=o.y>n&&i<(o.x-t.x)*(n-t.y)/(o.y-t.y)+t.x&&(s=!s),t=o}while(t!==r);return s}function Rd(r,e){const t=eo(r.i,r.x,r.y),s=eo(e.i,e.x,e.y),i=r.next,n=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function ec(r,e,t,s){const i=eo(r,e,t);return s?(i.next=s.next,i.prev=s,s.next.prev=i,s.next=i):(i.prev=i,i.next=i),i}function mr(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ),Kn&&z_(r.prev,r.next)}function eo(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null}}function Z_(r,e,t,s){let i=0;for(let n=e,o=t-s;n<t;n+=s)i+=(r[o]-r[n])*(r[n+1]+r[o+1]),o=n;return i}const Bd=Zh.default||Zh;var ye=(r=>(r[r.NONE=0]="NONE",r[r.COLOR=16384]="COLOR",r[r.STENCIL=1024]="STENCIL",r[r.DEPTH=256]="DEPTH",r[r.COLOR_DEPTH=16640]="COLOR_DEPTH",r[r.COLOR_STENCIL=17408]="COLOR_STENCIL",r[r.DEPTH_STENCIL=1280]="DEPTH_STENCIL",r[r.ALL=17664]="ALL",r))(ye||{});class ta{constructor(e){this.items=[],this._name=e}emit(e,t,s,i,n,o,a,l){const{name:h,items:c}=this;for(let u=0,d=c.length;u<d;u++)c[u][h](e,t,s,i,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 Q_=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Id=class Gd extends Re{constructor(e){super(),this.tick=0,this.uid=ne("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=[...Q_,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await Md(t),!t&&this.config.loaders&&await Promise.all(this.config.loaders.map(s=>s.value.load())),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...Gd.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){this.tick++;let s=e;if(s instanceof _e&&(s={container:s},t&&(O(ue,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const i=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=i?s.clearColor:oe.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const i=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==i&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=ye.ALL);const{clear:s,clearColor:i,target:n,mipLevel:o,layer:a}=e;oe.shared.setValue(i??this.background.colorRgba),t.renderTarget.clear(n,s,oe.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 ta(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const i in this.runners)this.runners[i].add(s);return this}_addPipes(e,t){const s=t.reduce((i,n)=>(i[n.name]=n.value,i),{});e.forEach(i=>{const n=i.value,o=i.name,a=s[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)&&as.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(!ea())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()}};Id.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let Is=Id,Dr;function Dd(r){return Dr!==void 0||(Dr=(()=>{const e={stencil:!0,failIfMajorPerformanceCaveat:r??Is.defaultOptions.failIfMajorPerformanceCaveat};try{if(!J.get().getWebGLRenderingContext())return!1;let s=J.get().createCanvas().getContext("webgl",e);const i=!!s?.getContextAttributes()?.stencil;if(s){const n=s.getExtension("WEBGL_lose_context");n&&n.loseContext()}return s=null,i}catch{return!1}})()),Dr}let Fr;async function Fd(r={}){return Fr!==void 0||(Fr=await(async()=>{const e=J.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Fr}const tc=["webgl","webgpu","canvas"];async function Ld(r){let e=[];r.preference?Array.isArray(r.preference)?e=r.preference.slice():(e.push(r.preference),tc.forEach(n=>{n!==r.preference&&e.push(n)})):e=tc.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await Fd()){const{WebGPURenderer:a}=await wt(async()=>{const{WebGPURenderer:l}=await Promise.resolve().then(()=>xx);return{WebGPURenderer:l}},void 0);t=a,s={...r,...r.webgpu};break}else if(o==="webgl"&&Dd(r.failIfMajorPerformanceCaveat??Is.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await wt(async()=>{const{WebGLRenderer:l}=await Promise.resolve().then(()=>rx);return{WebGLRenderer:l}},void 0);t=a,s={...r,...r.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await wt(async()=>{const{CanvasRenderer:l}=await Promise.resolve().then(()=>Uy);return{CanvasRenderer:l}},void 0);t=a,s={...r,...r.canvasOptions};break}}if(delete s.webgpu,delete s.webgl,delete s.canvasOptions,!t)throw new Error("No available renderer for the current environment");const i=new t;return await i.init(s),i}const gr="8.22.0";class sa{static init(){globalThis.__PIXI_APP_INIT__?.(this,gr)}static destroy(){}}sa.extension=S.Application;class ra{constructor(e){this._renderer=e}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,gr)}destroy(){this._renderer=null}}ra.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"initHook",priority:-10};class ia{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,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:i,clientHeight:n}=this._resizeTo;t=i,s=n}this.renderer.resize(t,s),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}}ia.extension=S.Application;class na{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,rs.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?We.shared:new We,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}na.extension=S.Application;q.add(ia);q.add(na);const Od=class to{constructor(...e){this.stage=new _e,e[0]!==void 0&&O(ue,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new _e),this.renderer=await Ld(e),to._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return O(ue,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}get domContainerRoot(){return this.renderer.renderPipes.dom?._domElement}destroy(e=!1,t=!1){const s=to._plugins.slice(0);s.reverse(),s.forEach(i=>{i.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};Od._plugins=[];let oa=Od;q.handleByList(S.Application,oa._plugins);q.add(sa);const xn={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},J_=/([astvzqmhlc])([^astvzqmhlc]*)/gi,e0=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;function t0(r){const e=[];return r.replace(J_,(t,s,i)=>{let n=s.toLowerCase(),o=s;const a=s0(i);for(n==="m"&&a.length>2&&(e.push([o,...a.splice(0,2)]),n="l",o=o==="m"?"l":"L");;){if(a.length===xn[n])return e.push([o,...a]),"";if(a.length<xn[n])throw new Error("malformed path data");e.push([o,...a.splice(0,xn[n])])}}),e}function s0(r){const e=r.match(e0);return e?e.map(Number):[]}function Ud(r,e){const t=t0(r),s=[];let i=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],h=l[0],c=l;switch(h){case"M":n=c[1],o=c[2],e.moveTo(n,o);break;case"m":n+=c[1],o+=c[2],e.moveTo(n,o);break;case"H":n=c[1],e.lineTo(n,o);break;case"h":n+=c[1],e.lineTo(n,o);break;case"V":o=c[1],e.lineTo(n,o);break;case"v":o+=c[1],e.lineTo(n,o);break;case"L":n=c[1],o=c[2],e.lineTo(n,o);break;case"l":n+=c[1],o+=c[2],e.lineTo(n,o);break;case"C":n=c[5],o=c[6],e.bezierCurveTo(c[1],c[2],c[3],c[4],n,o);break;case"c":e.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],e.bezierCurveToShort(c[1],c[2],n,o);break;case"s":e.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],e.quadraticCurveTo(c[1],c[2],n,o);break;case"q":e.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],e.quadraticCurveToShort(n,o);break;case"t":n+=c[1],o+=c[2],e.quadraticCurveToShort(n,o);break;case"A":n=c[6],o=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"a":n+=c[6],o+=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(i=s.pop(),i?(n=i.startX,o=i.startY):(n=0,o=0)),i=null;break;default:N(`Unknown SVG path command: ${h}`)}h!=="Z"&&h!=="z"&&i===null&&(i={startX:n,startY:o},s.push(i))}return e}class Ti{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new Ti(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let i=this.x-e,n=this.y-t;return i*=i,n*=n,i+n<=s}strokeContains(e,t,s,i=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-i)*s,h=Math.sqrt(n*n+o*o);return h<=a+l&&h>a-(s-l)}getBounds(e){return e||(e=new ee),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 Si{constructor(e=0,t=0,s=0,i=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=i}clone(){return new Si(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,i=(t-this.y)/this.halfHeight;return s*=s,i*=i,s+i<=1}strokeContains(e,t,s,i=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-i),l=s-a,h=n-l,c=o-l,u=n+a,d=o+a,f=e-this.x,p=t-this.y;return f*f/(u*u)+p*p/(d*d)>1?!1:h<=0||c<=0?!0:f*f/(h*h)+p*p/(c*c)>1}getBounds(e){return e||(e=new ee),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 aa(r){const e=r.length;if(e<6)return 1;let t=0;for(let s=0,i=r[e-2],n=r[e-1];s<e;s+=2){const o=r[s],a=r[s+1];t+=(o-i)*(a+n),i=o,n=a}return t<0?-1:1}function Nd(r,e,t,s,i,n){const o=r-t,a=e-s,l=i-t,h=n-s,c=o*l+a*h,u=l*l+h*h;let d=-1;u!==0&&(d=c/u);let f,p;d<0?(f=t,p=s):d>1?(f=i,p=n):(f=t+d*l,p=s+d*h);const m=r-f,g=e-p;return m*m+g*g}let r0,i0;class Ts{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let i=0,n=t.length;i<n;i++)s.push(t[i].x,t[i].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let i=0;i<s;i+=2){const n=t[i],o=t[i+1],a=t[(i+2)%s],l=t[(i+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(r0),s=e.getBounds(i0);if(!t.containsRect(s))return!1;const i=e.points;for(let n=0;n<i.length;n+=2){const o=i[n],a=i[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new Ts(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const i=this.points.length/2;for(let n=0,o=i-1;n<i;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>t!=c>t&&e<(h-a)*((t-l)/(c-l))+a&&(s=!s)}return s}strokeContains(e,t,s,i=.5){const{points:n}=this,o=i===.5?i:(i-.5)*aa(n)+.5,a=s*o,l=s-a,h=a*a,c=l*l,u=n.length-(this.closePath?0:2);for(let d=0;d<u;d+=2){const f=n[d],p=n[d+1],m=n[(d+2)%n.length],g=n[(d+3)%n.length],_=Nd(e,t,f,p,m,g),x=Math.sign((m-f)*(t-p)-(g-p)*(e-f));if(_<=(x<0?h:c))return!0}return!1}getBounds(e){e||(e=new ee);const t=this.points;let s=1/0,i=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const h=t[a],c=t[a+1];s=h<s?h:s,i=h>i?h:i,n=c<n?c:n,o=c>o?c:o}return e.x=s,e.width=i-s,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 O("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return O("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 Lr=(r,e,t,s,i,n,o)=>{const a=r-t,l=e-s,h=Math.sqrt(a*a+l*l);return h>=i-n&&h<=i+o};class Ci{constructor(e=0,t=0,s=0,i=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=i,this.radius=n}getBounds(e){return e||(e=new ee),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Ci(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.radius=e.radius,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 s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let i=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(i*i+n*n<=o||(i=e-(this.x+this.width-s),i*i+n*n<=o)||(n=t-(this.y+this.height-s),i*i+n*n<=o)||(i=e-(this.x+s),i*i+n*n<=o))return!0}return!1}strokeContains(e,t,s,i=.5){const{x:n,y:o,width:a,height:l,radius:h}=this,c=s*(1-i),u=s-c,d=n+h,f=o+h,p=a-h*2,m=l-h*2,g=n+a,_=o+l;return(e>=n-c&&e<=n+u||e>=g-u&&e<=g+c)&&t>=f&&t<=f+m||(t>=o-c&&t<=o+u||t>=_-u&&t<=_+c)&&e>=d&&e<=d+p?!0:e<d&&t<f&&Lr(e,t,d,f,h,u,c)||e>g-h&&t<f&&Lr(e,t,g-h,f,h,u,c)||e>g-h&&t>_-h&&Lr(e,t,g-h,_-h,h,u,c)||e<d&&t>_-h&&Lr(e,t,d,_-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 Hd={};function Mi(r,e,t){let s=2166136261;for(let i=0;i<e;i++)s^=r[i].uid,s=Math.imul(s,16777619),s>>>=0;return Hd[s]||n0(r,e,s,t)}function n0(r,e,t,s){const i={};let n=0;for(let a=0;a<s;a++){const l=a<e?r[a]:H.EMPTY.source;i[n++]=l.source,i[n++]=l.style}const o=new St(i);return Hd[t]=o,o}class so{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 oi(r,e,t,s){if(t??(t=0),s??(s=Math.min(r.byteLength-t,e.byteLength)),!(t&7)&&!(s&7)){const i=s/8;new Float64Array(e,0,i).set(new Float64Array(r,t,i))}else if(!(t&3)&&!(s&3)){const i=s/4;new Float32Array(e,0,i).set(new Float32Array(r,t,i))}else new Uint8Array(e).set(new Uint8Array(r,t,s))}const zd={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var me=(r=>(r[r.DISABLED=0]="DISABLED",r[r.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",r[r.MASK_ACTIVE=2]="MASK_ACTIVE",r[r.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",r[r.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",r[r.NONE=5]="NONE",r))(me||{});function ro(r,e){return e.alphaMode==="no-premultiply-alpha"&&zd[r]||r}const o0=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
38
38
  `);function a0(r){let e="";for(let t=0;t<r;++t)t>0&&(e+=`
39
39
  else `),t<r-1&&(e+=`if(test == ${t}.0){}`);return e}function la(r,e){if(r===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const s=o0.replace(/%forloop%/gi,a0(r));if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))r=r/2|0;else break}}finally{e.deleteShader(t)}return r}let us=null;function Wd(){if(us)return us;const r=Ko();return us=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),us=la(us,r),r.getExtension("WEBGL_lose_context")?.loseContext(),us}class $d{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 Vd{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new $d,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 er=[];let ai=0;as.register({clear:()=>{if(er.length>0)for(const r of er)r&&r.destroy();er.length=0,ai=0}});function sc(){return ai>0?er[--ai]:new Vd}function rc(r){r.elements=null,er[ai++]=r}let $s=0;const Xd=class jd{constructor(e){this.uid=ne("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...jd.defaultOptions,...e},e.maxTextures||(O("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Wd());const{maxTextures:t,attributesInitialSize:s,indicesInitialSize:i}=e;this.attributeBuffer=new so(s*4),this.indexBuffer=new Uint16Array(i),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)rc(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 s=e._batch.textures.ids[t._source.uid];return!s&&s!==0?!1:(e._textureId=s,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 s=sc(),i=s.textures;i.clear();const n=t[this.elementStart];let o=ro(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,d=this._batchIndexStart,f="startBatch",p=[];const m=this.maxTextures;for(let g=this.elementStart;g<this.elementSize;++g){const _=t[g];t[g]=null;const y=_.texture._source,b=ro(_.blendMode,y),w=o!==b||a!==_.topology;if(y._batchTick===$s&&!w){_._textureId=y._textureBindLocation,u+=_.indexSize,_.packAsQuad?(this.packQuadAttributes(_,l,h,_._attributeStart,_._textureId),this.packQuadIndex(c,_._indexStart,_._attributeStart/this.vertexSize)):(this.packAttributes(_,l,h,_._attributeStart,_._textureId),this.packIndex(_,c,_._indexStart,_._attributeStart/this.vertexSize)),_._batch=s,p.push(_);continue}y._batchTick=$s,(i.count>=m||w)&&(this._finishBatch(s,d,u-d,i,o,a,e,f,p),f="renderBatch",d=u,o=b,a=_.topology,s=sc(),i=s.textures,i.clear(),p=[],++$s),_._textureId=y._textureBindLocation=i.count,i.ids[y.uid]=i.count,i.textures[i.count++]=y,_._batch=s,p.push(_),u+=_.indexSize,_.packAsQuad?(this.packQuadAttributes(_,l,h,_._attributeStart,_._textureId),this.packQuadIndex(c,_._indexStart,_._attributeStart/this.vertexSize)):(this.packAttributes(_,l,h,_._attributeStart,_._textureId),this.packIndex(_,c,_._indexStart,_._attributeStart/this.vertexSize))}i.count>0&&(this._finishBatch(s,d,u-d,i,o,a,e,f,p),d=u,++$s),this.elementStart=this.elementSize,this._batchIndexStart=d,this._batchIndexSize=u}_finishBatch(e,t,s,i,n,o,a,l,h){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=i,e.blendMode=n,e.topology=o,e.start=t,e.size=s,e.elements=h,++$s,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),s=new so(t);oi(this.attributeBuffer.rawBinaryData,s.rawBinaryData),this.attributeBuffer=s}_resizeIndexBuffer(e){const t=this.indexBuffer;let s=Math.max(e,t.length*1.5);s+=s%2;const i=s>65535?new Uint32Array(s):new Uint16Array(s);if(i.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)i[n]=t[n];else oi(t.buffer,i.buffer);this.indexBuffer=i}packQuadIndex(e,t,s){e[t]=s+0,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s+0,e[t+4]=s+2,e[t+5]=s+3}packIndex(e,t,s,i){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let h=0;h<o;h++)t[s++]=i+n[h+a]-l}destroy(e={}){if(this.batches!==null){for(let t=0;t<this.batchIndex;t++)rc(this.batches[t]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&(this.shader?.destroy(),this.shader=null);for(let t=0;t<this._elements.length;t++)this._elements[t]&&(this._elements[t]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Xd.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let qd=Xd;var ce=(r=>(r[r.MAP_READ=1]="MAP_READ",r[r.MAP_WRITE=2]="MAP_WRITE",r[r.COPY_SRC=4]="COPY_SRC",r[r.COPY_DST=8]="COPY_DST",r[r.INDEX=16]="INDEX",r[r.VERTEX=32]="VERTEX",r[r.UNIFORM=64]="UNIFORM",r[r.STORAGE=128]="STORAGE",r[r.INDIRECT=256]="INDIRECT",r[r.QUERY_RESOLVE=512]="QUERY_RESOLVE",r[r.STATIC=1024]="STATIC",r))(ce||{});class Ct extends Re{constructor(e){let{data:t,size:s}=e;const{usage:i,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=ne("buffer"),this._resourceType="buffer",this._resourceId=ne("resource"),this._updateID=1,this._updateOffset=0,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,s??(s=t?.byteLength);const a=!!t;this.descriptor={size:s,usage:i,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&ce.STATIC)}set static(e){e?this.descriptor.usage|=ce.STATIC:this.descriptor.usage&=~ce.STATIC}setDataWithSize(e,t,s){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._updateOffset=0,this._data===e){s&&this.emit("update",this);return}const i=this._data;if(this._data=e,this._dataInt32=null,!i||i.length!==e.length){!this.shrinkToFit&&i&&e.byteLength<i.byteLength?s&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=ne("resource"),this.emit("change",this));return}s&&this.emit("update",this)}update(e,t){this._updateSize=e??this._updateSize,this._updateOffset=t||0,this._updateID++,this.emit("update",this)}unload(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null),this.destroyed||(this._resourceId=ne("resource"),this.emit("change",this))}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function ha(r,e){if(!(r instanceof Ct)){let t=e?ce.INDEX:ce.VERTEX;r instanceof Array&&(e?(r=new Uint32Array(r),t=ce.INDEX|ce.COPY_DST):(r=new Float32Array(r),t=ce.VERTEX|ce.COPY_DST)),r=new Ct({data:r,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return r}function Yd(r,e,t){const s=r.getAttribute(e);if(!s)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const i=s.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const h=i.BYTES_PER_ELEMENT,c=(s.offset||0)/h,u=(s.stride||8)/h;for(let d=c;d<i.length;d+=u){const f=i[d],p=i[d+1];f>a&&(a=f),p>l&&(l=p),f<n&&(n=f),p<o&&(o=p)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function l0(r){return(r instanceof Ct||Array.isArray(r)||r.BYTES_PER_ELEMENT)&&(r={buffer:r}),r.buffer=ha(r.buffer,!1),r}class Ei extends Re{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ne("geometry"),this._layoutKey=0,this.instanceCount=1,this.indexCount=0,this._bounds=new ke,this._boundsDirty=!0,this._vertexCount=0,this._vertexCountDirty=!0;const{attributes:t,indexBuffer:s,topology:i}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,this.indexCount=e.indexCount??0,s&&this.addIndex(s),this.topology=i||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this._vertexCountDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}get vertexCount(){if(!this._vertexCountDirty)return this._vertexCount;this._vertexCountDirty=!1;const e=this.attributes;for(const t in e){const s=e[t];if(s.instance)continue;const i=s.buffer;return this._vertexCount=i.data.length/(s.stride/4||s.size),this._vertexCount}return this._vertexCount=0,0}getSize(){return O("8.20.0","Geometry.getSize is deprecated, please use Geometry.vertexCount instead."),this.vertexCount}addAttribute(e,t){const s=l0(t);this.buffers.indexOf(s.buffer)===-1&&(this.buffers.push(s.buffer),s.buffer.on("update",this.onBufferUpdate,this),s.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=s,this._vertexCountDirty=!0}addIndex(e){this.indexBuffer=ha(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Yd(this,"aPosition",this._bounds)):this._bounds}unload(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null)}destroy(e=!1){this.emit("destroy",this);for(const t of this.buffers)t.off("update",this.onBufferUpdate,this),t.off("change",this.onBufferUpdate,this),e&&t.destroy();this.unload(),this.removeAllListeners(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const h0=new Float32Array(1),c0=new Uint32Array(1);class Kd extends Ei{constructor(){const t=new Ct({data:h0,label:"attribute-batch-buffer",usage:ce.VERTEX|ce.COPY_DST,shrinkToFit:!1}),s=new Ct({data:c0,label:"index-batch-buffer",usage:ce.INDEX|ce.COPY_DST,shrinkToFit:!1}),i=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:i,offset:0},aUV:{buffer:t,format:"float32x2",stride:i,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:i,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:i,offset:20}},indexBuffer:s})}}function io(r,e,t){if(r)for(const s in r){const i=s.toLocaleLowerCase(),n=e[i];if(n){let o=r[s];s==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else N(`${s} placement hook does not exist in shader`)}}const u0=/\{\{(.*?)\}\}/g;function no(r){const e={};return(r.match(u0)?.map(s=>s.replace(/[{()}]/g,""))??[]).forEach(s=>{e[s]=[]}),e}function ic(r,e){let t;const s=/@in\s+([^;]+);/g;for(;(t=s.exec(r))!==null;)e.push(t[1])}function oo(r,e,t=!1){const s=[];ic(e,s),r.forEach(a=>{a.header&&ic(a.header,s)});const i=s;t&&i.sort();const n=i.map((a,l)=>` @location(${l}) ${a},`).join(`
40
40
  `);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
@@ -250,7 +250,7 @@ ${i.join(`
250
250
  {
251
251
  return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
252
252
  }
253
- `}},oc={};function pa(r){let e=oc[r];if(e)return e;const t=new Int32Array(r);for(let s=0;s<r;s++)t[s]=s;return e=oc[r]=new rt({uTextures:{value:t,type:"i32",size:r}},{isStatic:!0}),e}class lo extends dt{constructor(e){const t=Pi({name:"batch",bits:[ua,fa(e),Ri]}),s=ki({name:"batch",bits:[ca,da(e),Ai]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:pa(e)}}),this.maxTextures=e}}let Vs=null;const hf=class cf extends qd{constructor(e){super(e),this.geometry=new Kd,this.name=cf.extension.name,this.vertexSize=6,Vs??(Vs=new lo(e.maxTextures)),this.shader=Vs}packAttributes(e,t,s,i,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,h=a.b,c=a.c,u=a.d,d=a.tx,f=a.ty,{positions:p,uvs:m}=e,g=e.color,_=e.attributeOffset,x=_+e.attributeSize;for(let y=_;y<x;y++){const b=y*2,w=p[b],v=p[b+1];t[i++]=l*w+c*v+d,t[i++]=u*v+h*w+f,t[i++]=m[b],t[i++]=m[b+1],s[i++]=g,s[i++]=o}}packQuadAttributes(e,t,s,i,n){const o=e.texture,a=e.transform,l=a.a,h=a.b,c=a.c,u=a.d,d=a.tx,f=a.ty,p=e.bounds,m=p.maxX,g=p.minX,_=p.maxY,x=p.minY,y=o.uvs,b=e.color,w=n<<16|e.roundPixels&65535;t[i+0]=l*g+c*x+d,t[i+1]=u*x+h*g+f,t[i+2]=y.x0,t[i+3]=y.y0,s[i+4]=b,s[i+5]=w,t[i+6]=l*m+c*x+d,t[i+7]=u*x+h*m+f,t[i+8]=y.x1,t[i+9]=y.y1,s[i+10]=b,s[i+11]=w,t[i+12]=l*m+c*_+d,t[i+13]=u*_+h*m+f,t[i+14]=y.x2,t[i+15]=y.y2,s[i+16]=b,s[i+17]=w,t[i+18]=l*g+c*_+d,t[i+19]=u*_+h*g+f,t[i+20]=y.x3,t[i+21]=y.y3,s[i+22]=b,s[i+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Vs=new lo(e),this.shader=Vs)}destroy(){this.shader=null,super.destroy()}};hf.extension={type:[C.Batcher],name:"default"};let Bi=hf;class it{constructor(e){this.items=Object.create(null);const{renderer:t,type:s,onUnload:i,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",s,n??0),this._onUnload=i,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){if(!this.items[e.uid])return;const s=e._gpuData[this._renderer.uid];s&&(this._onUnload?.(e,...t),e.off("unload",this.remove,this),s.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 uf(r,e,t,s,i,n,o,a=null){let l=0;t*=e,i*=n;const h=a.a,c=a.b,u=a.c,d=a.d,f=a.tx,p=a.ty;for(;l<o;){const m=r[t],g=r[t+1];s[i]=h*m+u*g+f,s[i+1]=c*m+d*g+p,i+=n,t+=e,l++}}function df(r,e,t,s){let i=0;for(e*=t;i<s;)r[e]=0,r[e+1]=0,e+=t,i++}function ma(r,e,t,s,i){const n=e.a,o=e.b,a=e.c,l=e.d,h=e.tx,c=e.ty;t||(t=0),s||(s=2),i||(i=r.length/s-t);let u=t*s;for(let d=0;d<i;d++){const f=r[u],p=r[u+1];r[u]=n*f+a*p+h,r[u+1]=o*f+l*p+c,u+=s}}const x0=new L;class Ii{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,s=this.renderable;return s?Kt(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||x0}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 ks={extension:{type:C.ShapeBuilder,name:"circle"},build(r,e){let t,s,i,n,o,a;if(r.type==="circle"){const b=r;if(o=a=b.radius,o<=0)return!1;t=b.x,s=b.y,i=n=0}else if(r.type==="ellipse"){const b=r;if(o=b.halfWidth,a=b.halfHeight,o<=0||a<=0)return!1;t=b.x,s=b.y,i=n=0}else{const b=r,w=b.width/2,v=b.height/2;t=b.x+w,s=b.y+v,o=a=Math.max(0,Math.min(b.radius,Math.min(w,v))),i=w-o,n=v-a}if(i<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),h=l*8+(i?4:0)+(n?4:0);if(h===0)return!1;if(l===0)return e[0]=e[6]=t+i,e[1]=e[3]=s+n,e[2]=e[4]=t-i,e[5]=e[7]=s-n,!0;let c=0,u=l*4+(i?2:0)+2,d=u,f=h,p=i+o,m=n,g=t+p,_=t-p,x=s+m;if(e[c++]=g,e[c++]=x,e[--u]=x,e[--u]=_,n){const b=s-m;e[d++]=_,e[d++]=b,e[--f]=b,e[--f]=g}for(let b=1;b<l;b++){const w=Math.PI/2*(b/l),v=i+Math.cos(w)*o,S=n+Math.sin(w)*a,E=t+v,k=t-v,P=s+S,T=s-S;e[c++]=E,e[c++]=P,e[--u]=P,e[--u]=k,e[d++]=k,e[d++]=T,e[--f]=T,e[--f]=E}p=i,m=n+a,g=t+p,_=t-p,x=s+m;const y=s-m;return e[c++]=g,e[c++]=x,e[--f]=y,e[--f]=g,i&&(e[c++]=_,e[c++]=x,e[--f]=y,e[--f]=_),!0},triangulate(r,e,t,s,i,n){if(r.length===0)return;let o=0,a=0;for(let c=0;c<r.length;c+=2)o+=r[c],a+=r[c+1];o/=r.length/2,a/=r.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const h=l++;for(let c=0;c<r.length;c+=2)e[l*t]=r[c],e[l*t+1]=r[c+1],c>0&&(i[n++]=l,i[n++]=h,i[n++]=l-1),l++;i[n++]=h+1,i[n++]=h,i[n++]=l-1}},ff={...ks,extension:{...ks.extension,name:"ellipse"}},pf={...ks,extension:{...ks.extension,name:"roundedRectangle"}},ga=1e-4,ho=1e-4;function ac(r,e,t,s,i,n,o,a){const l=r-t*i,h=e-s*i,c=r+t*n,u=e+s*n;let d,f;o?(d=s,f=-t):(d=-s,f=t);const p=l+d,m=h+f,g=c+d,_=u+f;return a.push(p,m),a.push(g,_),2}function Ut(r,e,t,s,i,n,o,a){const l=t-r,h=s-e;let c=Math.atan2(l,h),u=Math.atan2(i-r,n-e);a&&c<u?c+=Math.PI*2:!a&&c>u&&(u+=Math.PI*2);let d=c;const f=u-c,p=Math.abs(f),m=Math.sqrt(l*l+h*h),g=(15*p*Math.sqrt(m)/Math.PI>>0)+1,_=f/g;if(d+=_,a){o.push(r,e),o.push(t,s);for(let x=1,y=d;x<g;x++,y+=_)o.push(r,e),o.push(r+Math.sin(y)*m,e+Math.cos(y)*m);o.push(r,e),o.push(i,n)}else{o.push(t,s),o.push(r,e);for(let x=1,y=d;x<g;x++,y+=_)o.push(r+Math.sin(y)*m,e+Math.cos(y)*m),o.push(r,e);o.push(i,n),o.push(r,e)}return g*2}function Gi(r,e,t,s,i,n){const o=ga;if(r.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let B=aa(r);l=(l-.5)*B+.5}const h=new he(r[0],r[1]),c=new he(r[r.length-2],r[r.length-1]),u=s,d=Math.abs(h.x-c.x)<o&&Math.abs(h.y-c.y)<o;if(u){r=r.slice(),d&&(r.pop(),r.pop(),c.set(r[r.length-2],r[r.length-1]));const B=(h.x+c.x)*.5,U=(c.y+h.y)*.5;r.unshift(B,U),r.push(B,U)}const f=i,p=r.length/2;let m=r.length;const g=f.length/2,_=a.width/2,x=_*_,y=a.miterLimit*a.miterLimit;let b=r[0],w=r[1],v=r[2],S=r[3],E=0,k=0,P=-(w-S),T=b-v,A=0,I=0,F=Math.sqrt(P*P+T*T);P/=F,T/=F,P*=_,T*=_;const X=l,R=(1-X)*2,M=X*2;u||(a.cap==="round"?m+=Ut(b-P*(R-M)*.5,w-T*(R-M)*.5,b-P*R,w-T*R,b+P*M,w+T*M,f,!0)+2:a.cap==="square"&&(m+=ac(b,w,P,T,R,M,!0,f))),f.push(b-P*R,w-T*R),f.push(b+P*M,w+T*M);for(let B=1;B<p-1;++B){b=r[(B-1)*2],w=r[(B-1)*2+1],v=r[B*2],S=r[B*2+1],E=r[(B+1)*2],k=r[(B+1)*2+1],P=-(w-S),T=b-v,F=Math.sqrt(P*P+T*T),P/=F,T/=F,P*=_,T*=_,A=-(S-k),I=v-E,F=Math.sqrt(A*A+I*I),A/=F,I/=F,A*=_,I*=_;const U=v-b,W=w-S,se=v-E,te=k-S,ie=U*se+W*te,$=W*se-te*U,Ze=$<0;if(Math.abs($)<.001*Math.abs(ie)){f.push(v-P*R,S-T*R),f.push(v+P*M,S+T*M),ie>=0&&(a.join==="round"?m+=Ut(v,S,v-P*R,S-T*R,v-A*R,S-I*R,f,!1)+4:m+=2,f.push(v-A*M,S-I*M),f.push(v+A*R,S+I*R));continue}const Tr=(-P+b)*(-T+S)-(-P+v)*(-T+w),Ds=(-A+E)*(-I+S)-(-A+v)*(-I+k),Fs=(U*Ds-se*Tr)/$,pt=(te*Tr-W*Ds)/$,Lt=(Fs-v)*(Fs-v)+(pt-S)*(pt-S),Qe=v+(Fs-v)*R,Le=S+(pt-S)*R,Oe=v-(Fs-v)*M,Je=S-(pt-S)*M,Pt=Math.min(U*U+W*W,se*se+te*te),mt=Ze?R:M,Ls=Pt+mt*mt*x;Lt<=Ls?a.join==="bevel"||Lt/x>y?(Ze?(f.push(Qe,Le),f.push(v+P*M,S+T*M),f.push(Qe,Le),f.push(v+A*M,S+I*M)):(f.push(v-P*R,S-T*R),f.push(Oe,Je),f.push(v-A*R,S-I*R),f.push(Oe,Je)),m+=2):a.join==="round"?Ze?(f.push(Qe,Le),f.push(v+P*M,S+T*M),m+=Ut(v,S,v+P*M,S+T*M,v+A*M,S+I*M,f,!0)+4,f.push(Qe,Le),f.push(v+A*M,S+I*M)):(f.push(v-P*R,S-T*R),f.push(Oe,Je),m+=Ut(v,S,v-P*R,S-T*R,v-A*R,S-I*R,f,!1)+4,f.push(v-A*R,S-I*R),f.push(Oe,Je)):(f.push(Qe,Le),f.push(Oe,Je)):(f.push(v-P*R,S-T*R),f.push(v+P*M,S+T*M),a.join==="round"?Ze?m+=Ut(v,S,v+P*M,S+T*M,v+A*M,S+I*M,f,!0)+2:m+=Ut(v,S,v-P*R,S-T*R,v-A*R,S-I*R,f,!1)+2:a.join==="miter"&&Lt/x<=y&&(Ze?(f.push(Oe,Je),f.push(Oe,Je)):(f.push(Qe,Le),f.push(Qe,Le)),m+=2),f.push(v-A*R,S-I*R),f.push(v+A*M,S+I*M),m+=2)}b=r[(p-2)*2],w=r[(p-2)*2+1],v=r[(p-1)*2],S=r[(p-1)*2+1],P=-(w-S),T=b-v,F=Math.sqrt(P*P+T*T),P/=F,T/=F,P*=_,T*=_,f.push(v-P*R,S-T*R),f.push(v+P*M,S+T*M),u||(a.cap==="round"?m+=Ut(v-P*(R-M)*.5,S-T*(R-M)*.5,v-P*R,S-T*R,v+P*M,S+T*M,f,!1)+2:a.cap==="square"&&(m+=ac(v,S,P,T,R,M,!1,f)));const G=ho*ho;for(let B=g;B<m+g-2;++B)b=f[B*2],w=f[B*2+1],v=f[(B+1)*2],S=f[(B+1)*2+1],E=f[(B+2)*2],k=f[(B+2)*2+1],!(Math.abs(b*(S-k)+v*(k-w)+E*(w-S))<G)&&n.push(B,B+1,B+2)}function mf(r,e,t,s){const i=ga;if(r.length===0)return;const n=r[0],o=r[1],a=r[r.length-2],l=r[r.length-1],h=e||Math.abs(n-a)<i&&Math.abs(o-l)<i,c=t,u=r.length/2,d=c.length/2;for(let f=0;f<u;f++)c.push(r[f*2]),c.push(r[f*2+1]);for(let f=0;f<u-1;f++)s.push(d+f,d+f+1);h&&s.push(d+u-1,d)}function _a(r,e,t,s,i,n,o){const a=Bd(r,e,2);if(!a)return;for(let h=0;h<a.length;h+=3)n[o++]=a[h]+i,n[o++]=a[h+1]+i,n[o++]=a[h+2]+i;let l=i*s;for(let h=0;h<r.length;h+=2)t[l]=r[h],t[l+1]=r[h+1],l+=s}const b0=[],gf={extension:{type:C.ShapeBuilder,name:"polygon"},build(r,e){for(let t=0;t<r.points.length;t++)e[t]=r.points[t];return!0},triangulate(r,e,t,s,i,n){_a(r,b0,e,t,s,i,n)}},_f={extension:{type:C.ShapeBuilder,name:"rectangle"},build(r,e){const t=r,s=t.x,i=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=i,e[2]=s+n,e[3]=i,e[4]=s+n,e[5]=i+o,e[6]=s,e[7]=i+o,!0):!1},triangulate(r,e,t,s,i,n){let o=0;s*=t,e[s+o]=r[0],e[s+o+1]=r[1],o+=t,e[s+o]=r[2],e[s+o+1]=r[3],o+=t,e[s+o]=r[6],e[s+o+1]=r[7],o+=t,e[s+o]=r[4],e[s+o+1]=r[5],o+=t;const a=s/t;i[n++]=a,i[n++]=a+1,i[n++]=a+2,i[n++]=a+1,i[n++]=a+3,i[n++]=a+2}},yf={extension:{type:C.ShapeBuilder,name:"triangle"},build(r,e){return e[0]=r.x,e[1]=r.y,e[2]=r.x2,e[3]=r.y2,e[4]=r.x3,e[5]=r.y3,!0},triangulate(r,e,t,s,i,n){let o=0;s*=t,e[s+o]=r[0],e[s+o+1]=r[1],o+=t,e[s+o]=r[2],e[s+o+1]=r[3],o+=t,e[s+o]=r[4],e[s+o+1]=r[5];const a=s/t;i[n++]=a,i[n++]=a+1,i[n++]=a+2}},lc=[{offset:0,color:"white"},{offset:1,color:"black"}],ya=class co{constructor(...e){this.uid=ne("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=v0(e);t={...t.type==="radial"?co.defaultRadialOptions:co.defaultLinearOptions,...Do(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(i=>{this.addColorStop(i.offset,i.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:oe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:i}=this.end,n=s-e,o=i-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const g=e;e=s,s=g,n*=-1}if(o<0){const g=t;t=i,i=g,o*=-1}}const l=this.colorStops.length?this.colorStops:lc,h=this._textureSize,{canvas:c,context:u}=cc(h,1),d=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);hc(d,l),u.fillStyle=d,u.fillRect(0,0,h,1),this.texture=new H({source:new ur({resource:c,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),p=Math.atan2(o,n),m=new L;m.scale(f/h,1),m.rotate(p),m.translate(e,t),this.textureSpace==="local"&&m.scale(h,h),this.transform=m}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:lc,t=this._textureSize,{canvas:s,context:i}=cc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,h=this.innerRadius,c=this.outerRadius,u=a-c,d=l-c,f=t/(c*2),p=(n-u)*f,m=(o-d)*f,g=i.createRadialGradient(p,m,h*f,(a-u)*f,(l-d)*f,c*f);hc(g,e),i.fillStyle=e[e.length-1].color,i.fillRect(0,0,t,t),i.fillStyle=g,i.translate(p,m),i.rotate(this.rotation),i.scale(1,this.scale),i.translate(-p,-m),i.fillRect(0,0,t,t),this.texture=new H({source:new ur({resource:s,addressMode:this._wrapMode})});const _=new L;this.textureSpace==="local"?_.scale(2*c,2*c):_.scale(1/f,1/f),_.translate(u,d),this.transform=_}destroy(){this.texture?.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}`}};ya.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"};ya.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,rotation:0,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Xe=ya;function hc(r,e){for(let t=0;t<e.length;t++){const s=e[t];r.addColorStop(s.offset,s.color)}}function cc(r,e){const t=J.get().createCanvas(r,e),s=t.getContext("2d");return{canvas:t,context:s}}function v0(r){let e=r[0]??{};return(typeof e=="number"||r[1])&&(O("8.5.2","use options object instead"),e={type:"linear",start:{x:r[0],y:r[1]},end:{x:r[2],y:r[3]},textureSpace:r[4],textureSize:r[5]??Xe.defaultLinearOptions.textureSize}),e}const w0=new L,T0=new ee,S0=new L;function xa(r,e,t,s){const i=e.matrix?r.copyFrom(e.matrix).invert():r.identity();if(e.textureSpace==="local"){const o=t.getBounds(T0);e.width&&o.pad(e.width);const{x:a,y:l}=o,h=1/o.width,c=1/o.height,u=-a*h,d=-l*c,f=i.a,p=i.b,m=i.c,g=i.d;i.a*=h,i.b*=h,i.c*=c,i.d*=c,i.tx=u*f+d*m+i.tx,i.ty=u*p+d*g+i.ty}else if(e.texture.rotate){const{uvs:o,orig:a}=e.texture;i.scale(1/a.width,1/a.height),i.prepend(S0.set(o.x1-o.x0,o.y1-o.y0,o.x3-o.x0,o.y3-o.y0,o.x0,o.y0))}else i.translate(e.texture.frame.x,e.texture.frame.y),i.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof Xe)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&i.append(w0.copyFrom(s).invert()),i}const hs={};q.handleByMap(C.ShapeBuilder,hs);q.add(_f,gf,yf,ks,ff,pf);const C0=new ee,M0=new L;function xf(r,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let i=0;i<r.instructions.length;i++){const n=r.instructions[i];if(n.action==="texture")E0(n.data,s,t);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&&uc(h.shapePath,l,!0,s,t),h&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=h.shapePath.shapePrimitives),uc(a,l,o,s,t)}}}function E0(r,e,t){const s=[],i=hs.rectangle,n=C0;n.x=r.dx,n.y=r.dy,n.width=r.dw,n.height=r.dh;const o=r.transform;if(!i.build(n,s))return;const{vertices:a,uvs:l,indices:h}=t,c=h.length,u=a.length/2;o&&ma(s,o),i.triangulate(s,a,2,u,h,c);const d=r.image,f=d.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const p=Se.get(Ii);p.indexOffset=c,p.indexSize=h.length-c,p.attributeOffset=u,p.attributeSize=a.length/2-u,p.baseColor=r.style,p.alpha=r.alpha,p.texture=d,p.geometryData=t,e.push(p)}function uc(r,e,t,s,i){const{vertices:n,uvs:o,indices:a}=i;r.shapePrimitives.forEach(({shape:l,transform:h,holes:c})=>{const u=[],d=hs[l.type];if(!d.build(l,u))return;const f=a.length,p=n.length/2;let m="triangle-list";if(h&&ma(u,h),t){const y=l.closePath??!0,b=e;b.pixelLine?(mf(u,y,n,a),m="line-list"):Gi(u,b,!1,y,n,a)}else if(c){const y=[],b=u.slice();k0(c).forEach(v=>{y.push(b.length/2),b.push(...v)}),_a(b,y,n,2,p,a,f)}else d.triangulate(u,n,2,p,a,f);const g=o.length/2,_=e.texture;if(_!==H.WHITE){const y=xa(M0,e,l,h);uf(n,2,p,o,g,2,n.length/2-p,y)}else df(o,g,2,n.length/2-p);const x=Se.get(Ii);x.indexOffset=f,x.indexSize=a.length-f,x.attributeOffset=p,x.attributeSize=n.length/2-p,x.baseColor=e.color,x.alpha=e.alpha,x.texture=_,x.geometryData=i,x.topology=m,s.push(x)})}function k0(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t].shape,i=[];hs[s.type].build(s,i)&&e.push(i)}return e}class bf{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Se.return(e)}),this.graphicsData&&Se.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 vf{constructor(){this.instructions=new xi}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Bi({maxTextures:t}),this.instructions.reset()}get geometry(){return O(yu,"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 ba=class uo{constructor(e){this._renderer=e,this._managedContexts=new it({renderer:e,type:"resource",name:"graphicsContext"})}init(e){uo.defaultOptions.bezierSmoothness=e?.bezierSmoothness??uo.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],s=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&s.reset(),xf(e,s);const i=e.batchMode;e.customShader||i==="no-batch"?s.isBatchable=!1:i==="auto"?s.isBatchable=s.geometryData.vertices.length<400:s.isBatchable=!0,e.dirty=!1}return s}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Se.get(vf,{maxTextures:this._renderer.limits.maxBatchableTextures}),s=e._gpuData[this._renderer.uid],{batches:i,geometryData:n}=s;s.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<i.length;u++)i[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<i.length;u++){const d=i[u];l.add(d)}l.finish(t.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<l.batchIndex;u++){const d=c[u];d.bindGroup=Mi(d.textures.textures,d.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new bf;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};ba.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"graphicsContext"};ba.defaultOptions={bezierSmoothness:.5};let Di=ba;const P0=8,Or=11920929e-14,A0=1;function va(r,e,t,s,i,n,o,a,l,h){const u=Math.min(.99,Math.max(0,h??Di.defaultOptions.bezierSmoothness));let d=(A0-u)/1;return d*=d,R0(e,t,s,i,n,o,a,l,r,d),r}function R0(r,e,t,s,i,n,o,a,l,h){fo(r,e,t,s,i,n,o,a,l,h,0),l.push(o,a)}function fo(r,e,t,s,i,n,o,a,l,h,c){if(c>P0)return;const u=(r+t)/2,d=(e+s)/2,f=(t+i)/2,p=(s+n)/2,m=(i+o)/2,g=(n+a)/2,_=(u+f)/2,x=(d+p)/2,y=(f+m)/2,b=(p+g)/2,w=(_+y)/2,v=(x+b)/2;if(c>0){let S=o-r,E=a-e;const k=Math.abs((t-o)*E-(s-a)*S),P=Math.abs((i-o)*E-(n-a)*S);if(k>Or&&P>Or){if((k+P)*(k+P)<=h*(S*S+E*E)){l.push(w,v);return}}else if(k>Or){if(k*k<=h*(S*S+E*E)){l.push(w,v);return}}else if(P>Or){if(P*P<=h*(S*S+E*E)){l.push(w,v);return}}else if(S=w-(r+o)/2,E=v-(e+a)/2,S*S+E*E<=h){l.push(w,v);return}}fo(r,e,u,d,_,x,w,v,l,h,c+1),fo(w,v,y,b,m,g,o,a,l,h,c+1)}const B0=8,I0=11920929e-14,G0=1;function wf(r,e,t,s,i,n,o,a){const h=Math.min(.99,Math.max(0,a??Di.defaultOptions.bezierSmoothness));let c=(G0-h)/1;return c*=c,D0(e,t,s,i,n,o,r,c),r}function D0(r,e,t,s,i,n,o,a){po(o,r,e,t,s,i,n,a,0),o.push(i,n)}function po(r,e,t,s,i,n,o,a,l){if(l>B0)return;const h=(e+s)/2,c=(t+i)/2,u=(s+n)/2,d=(i+o)/2,f=(h+u)/2,p=(c+d)/2;let m=n-e,g=o-t;const _=Math.abs((s-n)*g-(i-o)*m);if(_>I0){if(_*_<=a*(m*m+g*g)){r.push(f,p);return}}else if(m=f-(e+n)/2,g=p-(t+o)/2,m*m+g*g<=a){r.push(f,p);return}po(r,e,t,h,c,f,p,a,l+1),po(r,f,p,u,d,n,o,a,l+1)}function wa(r,e,t,s,i,n,o,a){let l=Math.abs(i-n);(!o&&i>n||o&&n>i)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let h=l/a,c=i;h*=o?-1:1;for(let u=0;u<a+1;u++){const d=Math.cos(c),f=Math.sin(c),p=e+d*s,m=t+f*s;r.push(p,m),c+=h}}function Tf(r,e,t,s,i,n){const o=r[r.length-2],l=r[r.length-1]-t,h=o-e,c=i-t,u=s-e,d=Math.abs(l*u-h*c);if(d<1e-8||n===0){(r[r.length-2]!==e||r[r.length-1]!==t)&&r.push(e,t);return}const f=l*l+h*h,p=c*c+u*u,m=l*c+h*u,g=n*Math.sqrt(f)/d,_=n*Math.sqrt(p)/d,x=g*m/f,y=_*m/p,b=g*u+_*h,w=g*c+_*l,v=h*(_+x),S=l*(_+x),E=u*(g+y),k=c*(g+y),P=Math.atan2(S-w,v-b),T=Math.atan2(k-w,E-b);wa(r,b+e,w+t,n,P,T,h*c>u*l)}const tr=Math.PI*2,Tn={centerX:0,centerY:0,ang1:0,ang2:0},Sn=({x:r,y:e},t,s,i,n,o,a,l)=>{r*=t,e*=s;const h=i*r-n*e,c=n*r+i*e;return l.x=h+o,l.y=c+a,l};function F0(r,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,i=Math.cos(r),n=Math.sin(r),o=Math.cos(r+e),a=Math.sin(r+e);return[{x:i-n*s,y:n+i*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const dc=(r,e,t,s)=>{const i=r*s-e*t<0?-1:1;let n=r*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),i*Math.acos(n)},L0=(r,e,t,s,i,n,o,a,l,h,c,u,d)=>{const f=Math.pow(i,2),p=Math.pow(n,2),m=Math.pow(c,2),g=Math.pow(u,2);let _=f*p-f*g-p*m;_<0&&(_=0),_/=f*g+p*m,_=Math.sqrt(_)*(o===a?-1:1);const x=_*i/n*u,y=_*-n/i*c,b=h*x-l*y+(r+t)/2,w=l*x+h*y+(e+s)/2,v=(c-x)/i,S=(u-y)/n,E=(-c-x)/i,k=(-u-y)/n,P=dc(1,0,v,S);let T=dc(v,S,E,k);a===0&&T>0&&(T-=tr),a===1&&T<0&&(T+=tr),d.centerX=b,d.centerY=w,d.ang1=P,d.ang2=T};function Sf(r,e,t,s,i,n,o,a=0,l=0,h=0){if(n===0||o===0)return;const c=Math.sin(a*tr/360),u=Math.cos(a*tr/360),d=u*(e-s)/2+c*(t-i)/2,f=-c*(e-s)/2+u*(t-i)/2;if(d===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const p=Math.pow(d,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);p>1&&(n*=Math.sqrt(p),o*=Math.sqrt(p)),L0(e,t,s,i,n,o,l,h,c,u,d,f,Tn);let{ang1:m,ang2:g}=Tn;const{centerX:_,centerY:x}=Tn;let y=Math.abs(g)/(tr/4);Math.abs(1-y)<1e-7&&(y=1);const b=Math.max(Math.ceil(y),1);g/=b;let w=r[r.length-2],v=r[r.length-1];const S={x:0,y:0};for(let E=0;E<b;E++){const k=F0(m,g),{x:P,y:T}=Sn(k[0],n,o,u,c,_,x,S),{x:A,y:I}=Sn(k[1],n,o,u,c,_,x,S),{x:F,y:X}=Sn(k[2],n,o,u,c,_,x,S);va(r,w,v,P,T,A,I,F,X),w=F,v=X,m+=g}}function Cf(r,e,t){const s=(o,a)=>{const l=a.x-o.x,h=a.y-o.y,c=Math.sqrt(l*l+h*h),u=l/c,d=h/c;return{len:c,nx:u,ny:d}},i=(o,a)=>{o===0?r.moveTo(a.x,a.y):r.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){i(o,a),n=a;continue}const h=e[(o+1)%e.length],c=s(a,n),u=s(a,h);if(c.len<1e-4||u.len<1e-4){i(o,a),n=a;continue}let d=Math.asin(c.nx*u.ny-c.ny*u.nx),f=1,p=!1;c.nx*u.nx-c.ny*-u.ny<0?d<0?d=Math.PI+d:(d=Math.PI-d,f=-1,p=!0):d>0&&(f=-1,p=!0);const m=d/2;let g,_=Math.abs(Math.cos(m)*l/Math.sin(m));_>Math.min(c.len/2,u.len/2)?(_=Math.min(c.len/2,u.len/2),g=Math.abs(_*Math.sin(m)/Math.cos(m))):g=l;const x=a.x+u.nx*_+-u.ny*g*f,y=a.y+u.ny*_+u.nx*g*f,b=Math.atan2(c.ny,c.nx)+Math.PI/2*f,w=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&r.moveTo(x+Math.cos(b)*g,y+Math.sin(b)*g),r.arc(x,y,g,b,w,p),n=a}}function Mf(r,e,t,s){const i=(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=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],h=l.radius??t;if(h<=0){a===0?r.moveTo(l.x,l.y):r.lineTo(l.x,l.y);continue}const c=e[a],u=e[(a+2)%o],d=i(c,l);let f;if(d<1e-4)f=l;else{const g=Math.min(d/2,h);f=n(l,c,g/d)}const p=i(u,l);let m;if(p<1e-4)m=l;else{const g=Math.min(p/2,h);m=n(l,u,g/p)}a===0?r.moveTo(f.x,f.y):r.lineTo(f.x,f.y),r.quadraticCurveTo(l.x,l.y,m.x,m.y,s)}}const O0=new ee;class Ef{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new ke,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,i=s[s.length-2],n=s[s.length-1];return(i!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,i,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return wa(a,e,t,s,i,n,o),this}arcTo(e,t,s,i,n){this._ensurePoly();const o=this._currentPoly.points;return Tf(o,e,t,s,i,n),this}arcToSvg(e,t,s,i,n,o,a){const l=this._currentPoly.points;return Sf(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,i,n),this}bezierCurveTo(e,t,s,i,n,o,a){this._ensurePoly();const l=this._currentPoly;return va(this._currentPoly.points,l.lastX,l.lastY,e,t,s,i,n,o,a),this}quadraticCurveTo(e,t,s,i,n){this._ensurePoly();const o=this._currentPoly;return wf(this._currentPoly.points,o.lastX,o.lastY,e,t,s,i,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,i=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-i>1){let n=null;for(let o=i;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,h=n?.shape;h&&h.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,i,n){return this.drawShape(new ee(e,t,s,i),n),this}circle(e,t,s,i){return this.drawShape(new Ti(e,t,s),i),this}poly(e,t,s){const i=new Ts(e);return i.closePath=t,this.drawShape(i,s),this}regularPoly(e,t,s,i,n=0,o){i=Math.max(i|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/i,h=[];for(let c=0;c<i;c++){const u=a-c*l;h.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(h,!0,o),this}roundPoly(e,t,s,i,n,o=0,a){if(i=Math.max(i|0,3),n<=0)return this.regularPoly(e,t,s,i,o);const l=s*Math.sin(Math.PI/i)-.001;n=Math.min(n,l);const h=-1*Math.PI/2+o,c=Math.PI*2/i,u=(i-2)*Math.PI/i/2;for(let d=0;d<i;d++){const f=d*c+h,p=e+s*Math.cos(f),m=t+s*Math.sin(f),g=f+Math.PI+u,_=f-Math.PI-u,x=p+n*Math.cos(g),y=m+n*Math.sin(g),b=p+n*Math.cos(_),w=m+n*Math.sin(_);d===0?this.moveTo(x,y):this.lineTo(x,y),this.quadraticCurveTo(p,m,b,w,a)}return this.closePath()}roundShape(e,t,s=!1,i){return e.length<3?this:(s?Mf(this,e,t,i):Cf(this,e,t),this.closePath())}filletRect(e,t,s,i,n){if(n===0)return this.rect(e,t,s,i);const o=Math.min(s,i)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,h=t+i,c=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+c,t+c,e+u,t,u).lineTo(l-u,t).arcTo(l-c,t+c,l,t+u,u).lineTo(l,h-u).arcTo(l-c,h-c,e+s-u,h,u).lineTo(e+u,h).arcTo(e+c,h-c,e,h-u,u).closePath()}chamferRect(e,t,s,i,n,o){if(n<=0)return this.rect(e,t,s,i);const a=Math.min(n,Math.min(s,i)/2),l=e+s,h=t+i,c=[e+a,t,l-a,t,l,t+a,l,h-a,l-a,h,e+a,h,e,h-a,e,t+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(e,t,s,i,n){return this.drawShape(new Si(e,t,s,i),n),this}roundRect(e,t,s,i,n,o){return this.drawShape(new Ci(e,t,s,i,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new Ts,s.points.push(e,t),this._currentPoly=s,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 Ts,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,i=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*i+n.tx,i=n.b*o+n.d*i+n.ty}this._currentPoly.points.push(s,i)}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 s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const i=t[s],n=i.shape.getBounds(O0);i.transform?e.addRect(n,i.transform):e.addRect(n)}return e}}class ut{constructor(e,t=!1){this.instructions=[],this.uid=ne("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Ud(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new Ef(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,s,i,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(he.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,e,t,s,i,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,s){const i=this.instructions[this.instructions.length-1],n=this.getLastPoint(he.shared);let o=0,a=0;if(!i||i.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=i.data[0],a=i.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,e,t,s]}),this._dirty=!0,this}rect(e,t,s,i,n){return this.instructions.push({action:"rect",data:[e,t,s,i,n]}),this._dirty=!0,this}circle(e,t,s,i){return this.instructions.push({action:"circle",data:[e,t,s,i]}),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,s,i,n,o,a){n||(n=i/2);const l=-1*Math.PI/2+o,h=s*2,c=Math.PI*2/h,u=[];for(let d=0;d<h;d++){const f=d%2?n:i,p=d*c+l;u.push(e+f*Math.cos(p),t+f*Math.sin(p))}return this.poly(u,!0,a),this}clone(e=!1){const t=new ut;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const i=this.instructions[s];t.instructions.push({action:i.action,data:i.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,s=e.b,i=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,h=0,c=0,u=0,d=0,f=0,p=0,m=0;for(let g=0;g<this.instructions.length;g++){const _=this.instructions[g],x=_.data;switch(_.action){case"moveTo":case"lineTo":l=x[0],h=x[1],x[0]=t*l+i*h+o,x[1]=s*l+n*h+a;break;case"bezierCurveTo":c=x[0],u=x[1],d=x[2],f=x[3],l=x[4],h=x[5],x[0]=t*c+i*u+o,x[1]=s*c+n*u+a,x[2]=t*d+i*f+o,x[3]=s*d+n*f+a,x[4]=t*l+i*h+o,x[5]=s*l+n*h+a;break;case"quadraticCurveTo":c=x[0],u=x[1],l=x[2],h=x[3],x[0]=t*c+i*u+o,x[1]=s*c+n*u+a,x[2]=t*l+i*h+o,x[3]=s*l+n*h+a;break;case"arcToSvg":l=x[5],h=x[6],p=x[0],m=x[1],x[0]=t*p+i*m,x[1]=s*p+n*m,x[5]=t*l+i*h+o,x[6]=s*l+n*h+a;break;case"circle":x[4]=ds(x[3],e);break;case"rect":x[4]=ds(x[4],e);break;case"ellipse":x[8]=ds(x[8],e);break;case"roundRect":x[5]=ds(x[5],e);break;case"addPath":x[0].transform(e);break;case"poly":x[2]=ds(x[2],e);break;case"regularPoly":case"chamferRect":x[5]=ds(x[5],e);break;case"closePath":break;default:N("unknown transform action",_.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function ds(r,e){return r?r.prepend(e):e.clone()}function ve(r,e,t){const s=r.getAttribute(e);return s?Number(s):t}function kf(r,e){const t=r.querySelectorAll("defs");for(let s=0;s<t.length;s++){const i=t[s];for(let n=0;n<i.children.length;n++){const o=i.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=U0(o);break;case"radialgradient":e.defs[o.id]=N0(o);break}}}}function st(r,e,t){const s=r.getAttribute(e);if(s?.trim().endsWith("%")){const i=Number(s.trim().slice(0,-1));return Number.isNaN(i)?t:i/100}return ve(r,e,t)}function Pf(r){return(r.getAttribute("gradientUnits")||"objectBoundingBox")==="objectBoundingBox"?"local":"global"}function Af(r){const e=[];for(let t=0;t<r.children.length;t++){const s=r.children[t],i=st(s,"offset",0),n=oe.shared.setValue(s.getAttribute("stop-color")).toNumber();e.push({offset:i,color:n})}return e}function U0(r){const e=st(r,"x1",0),t=st(r,"y1",0),s=st(r,"x2",1),i=st(r,"y2",0);return new Xe({type:"linear",start:{x:e,y:t},end:{x:s,y:i},textureSpace:Pf(r),colorStops:Af(r)})}function N0(r){const e=st(r,"cx",.5),t=st(r,"cy",.5),s=st(r,"r",.5),i=st(r,"fx",e),n=st(r,"fy",t),o=st(r,"fr",0);return new Xe({type:"radial",center:{x:i,y:n},innerRadius:o,outerCenter:{x:e,y:t},outerRadius:s,textureSpace:Pf(r),colorStops:Af(r)})}function mo(r){const e=r.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const go={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 Ta(r,e){const t=r.getAttribute("style"),s={},i={},n={strokeStyle:s,fillStyle:i,useFill:!1,useStroke:!1};for(const o in go){const a=r.getAttribute(o);a&&fc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[h,c]=l.split(":");go[h]&&fc(e,n,h,c.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?i:null,useFill:n.useFill,useStroke:n.useStroke}}function fc(r,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const i=mo(s);e.strokeStyle.fill=r.defs[i]}else e.strokeStyle.color=oe.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const i=mo(s);e.fillStyle.fill=r.defs[i]}else e.fillStyle.color=oe.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function Rf(r){if(r.length<=2)return!0;const e=r.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,i=e[e.length-1],n=t/s,o=s/i;return!(n>3&&o<2)}function Bf(r){return r.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function If(r){const e=r.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],i=[];for(let c=0;c<t.length;c+=2)c+1<t.length&&(s.push(t[c]),i.push(t[c+1]));if(s.length===0||i.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...i),l=Math.max(...i);return(o-n)*(l-a)}function _o(r,e){const t=new ut(r,!1);for(const s of t.instructions)e.instructions.push(s)}function Gf(r,e){if(typeof r=="string"){const o=document.createElement("div");o.innerHTML=r.trim(),r=o.querySelector("svg")}const t={context:e,defs:{},path:new ut};kf(r,t);const s=r.children,{fillStyle:i,strokeStyle:n}=Ta(r,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&Df(a,t,i,n)}return e}function Df(r,e,t,s){const i=r.children,{fillStyle:n,strokeStyle:o}=Ta(r,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,h,c,u,d,f,p,m,g,_,x,y,b,w,v,S,E;switch(r.nodeName.toLowerCase()){case"path":{w=r.getAttribute("d");const k=r.getAttribute("fill-rule"),P=Bf(w),T=k==="evenodd",A=P.length>1;if(T&&A){const F=P.map(R=>({path:R,area:If(R)}));if(F.sort((R,M)=>M.area-R.area),P.length>3||!Rf(F))for(let R=0;R<F.length;R++){const M=F[R],G=R===0;e.context.beginPath();const B=new ut(void 0,!0);_o(M.path,B),e.context.path(B),G?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let R=0;R<F.length;R++){const M=F[R],G=R%2===1;e.context.beginPath();const B=new ut(void 0,!0);_o(M.path,B),e.context.path(B),G?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const F=k?k==="evenodd":!0;v=new ut(w,F),e.context.path(v),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":p=ve(r,"cx",0),m=ve(r,"cy",0),g=ve(r,"r",0),e.context.ellipse(p,m,g,g),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=ve(r,"x",0),h=ve(r,"y",0),S=ve(r,"width",0),E=ve(r,"height",0),_=ve(r,"rx",0),x=ve(r,"ry",0),_||x?e.context.roundRect(l,h,S,E,_||x):e.context.rect(l,h,S,E),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":p=ve(r,"cx",0),m=ve(r,"cy",0),_=ve(r,"rx",0),x=ve(r,"ry",0),e.context.beginPath(),e.context.ellipse(p,m,_,x),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":c=ve(r,"x1",0),u=ve(r,"y1",0),d=ve(r,"x2",0),f=ve(r,"y2",0),e.context.beginPath(),e.context.moveTo(c,u),e.context.lineTo(d,f),s&&e.context.stroke(s);break;case"polygon":b=r.getAttribute("points"),y=b.match(/-?\d+/g).map(k=>parseInt(k,10)),e.context.poly(y,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":b=r.getAttribute("points"),y=b.match(/-?\d+/g).map(k=>parseInt(k,10)),e.context.poly(y,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{N(`[SVG parser] <${r.nodeName}> elements unsupported`);break}}a&&(t=null);for(let k=0;k<i.length;k++)Df(i[k],e,t,s)}function H0(r){return r.texture!==void 0}const pc={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 Gs{constructor(e,t){this.uid=ne("fillPattern"),this._tick=0,this.transform=new L;const s=H0(e)?e:{texture:e,repetition:t};this.texture=s.texture,this.textureSpace=s.textureSpace??"global";const i=s.repetition;i&&(this.texture.source.style.addressModeU=pc[i].addressModeU,this.texture.source.style.addressModeV=pc[i].addressModeV)}setTransform(e){if(e){if(this.transform.equals(e))return;this.transform.copyFrom(e)}else{if(this.transform.isIdentity())return;this.transform.identity()}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 z0(r){return oe.isColorLike(r)}function mc(r){return r instanceof Gs}function gc(r){return r instanceof Xe}function W0(r){return r instanceof H}function $0(r,e,t){const s=oe.shared.setValue(e??0);return r.color=s.toNumber(),r.alpha=s.alpha===1?t.alpha:s.alpha,r.texture=H.WHITE,{...t,...r}}function V0(r,e,t){return r.texture=e,{...t,...r}}function _c(r,e,t){return r.fill=e,r.color=16777215,r.texture=e.texture,r.matrix=e.transform,r.textureSpace=e.textureSpace,{...t,...r}}function yc(r,e,t){return e.buildGradient(),r.fill=e,r.color=16777215,r.texture=e.texture,r.matrix=e.transform,r.textureSpace=e.textureSpace,{...t,...r}}function X0(r,e){const t={...e,...r},s=oe.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function Gt(r,e){if(r==null)return null;const t={},s=r;return z0(r)?$0(t,r,e):W0(r)?V0(t,r,e):mc(r)?_c(t,r,e):gc(r)?yc(t,r,e):s.fill&&mc(s.fill)?_c(s,s.fill,e):s.fill&&gc(s.fill)?yc(s,s.fill,e):X0(s,e)}function _r(r,e){const{width:t,alignment:s,miterLimit:i,cap:n,join:o,pixelLine:a,...l}=e,h=Gt(r,l);return h?{width:t,alignment:s,miterLimit:i,cap:n,join:o,pixelLine:a,...h}:null}function Ff(r,e){let t=1;const s=r.shapePath.shapePrimitives;for(let i=0;i<s.length;i++){const n=s[i].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,d=o[c],f=o[c+1],p=o[h],m=o[h+1],g=o[u],_=o[u+1],x=d-p,y=f-m,b=g-p,w=_-m,v=x*x+y*y,S=b*b+w*w;if(v<1e-12||S<1e-12)continue;let P=(x*b+y*w)/Math.sqrt(v*S);P<-1?P=-1:P>1&&(P=1);const T=Math.sqrt((1-P)*.5);if(T<1e-6)continue;const A=Math.min(1/T,e);A>t&&(t=A)}}return t}const j0=new he,xc=new L,Sa=class ot extends Re{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ne("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new ut,this._transform=new L,this._fillStyle={...ot.defaultFillStyle},this._strokeStyle={...ot.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new ke,this._boundsDirty=!0}clone(){const e=new ot;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=Gt(e,ot.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=_r(e,ot.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=Gt(e,ot.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=Gt(e,ot.defaultStrokeStyle),this}texture(e,t,s,i,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:i||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?oe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new ut,this}fill(e,t){let s;const i=this.instructions[this.instructions.length-1];return this._tick===0&&i?.action==="stroke"?s=i.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(O(ue,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=Gt(e,ot.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(he.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&s?.action==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=_r(e,ot.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],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,i,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,s,i,n,o),this}arcTo(e,t,s,i,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*s+o.c*i+o.tx,o.b*s+o.d*i+o.ty,n),this}arcToSvg(e,t,s,i,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,i,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,i,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*s+l.c*i+l.tx,l.b*s+l.d*i+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,s,i){return this._tick++,this._activePath.ellipse(e,t,s,i,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,i=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return i.length===1&&i[0].action==="moveTo"?(i[0].data[0]=n,i[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,i,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*s+o.c*i+o.tx,o.b*s+o.d*i+o.ty,n),this}rect(e,t,s,i){return this._tick++,this._activePath.rect(e,t,s,i,this._transform.clone()),this}roundRect(e,t,s,i,n){return this._tick++,this._activePath.roundRect(e,t,s,i,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,i,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,i,n,o),this}roundPoly(e,t,s,i,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,i,n,o),this}roundShape(e,t,s,i){return this._tick++,this._activePath.roundShape(e,t,s,i),this}filletRect(e,t,s,i,n){return this._tick++,this._activePath.filletRect(e,t,s,i,n),this}chamferRect(e,t,s,i,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,i,n,o),this}star(e,t,s,i,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,i,n,o,this._transform.clone()),this}svg(e){return this._tick++,Gf(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,s,i,n,o){return e instanceof L?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,i,n,o),this)}transform(e,t,s,i,n,o){return e instanceof L?(this._transform.append(e),this):(xc.set(e,t,s,i,n,o),this._transform.append(xc),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 s=this.instructions[t],i=s.action;if(i==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(i==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(i==="stroke"){const n=s.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=Ff(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){if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let i=0;i<t.length;i++){const n=t[i],o=n.data,a=o.path;if(!n.action||!a)continue;const l=o.style,h=a.shapePath.shapePrimitives;for(let c=0;c<h.length;c++){const u=h[c].shape;if(!l||!u)continue;const d=h[c].transform,f=d?d.applyInverse(e,j0):e;if(n.action==="fill")s=u.contains(f.x,f.y);else{const m=l;s=u.strokeContains(f.x,f.y,m.width,m.alignment)}const p=o.hole;if(p){const m=p.shapePath?.shapePrimitives;if(m)for(let g=0;g<m.length;g++)m[g].shape.contains(f.x,f.y)&&(s=!1)}if(s)return!0}}return s}unload(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[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?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};Sa.defaultFillStyle={color:16777215,alpha:1,texture:H.WHITE,matrix:null,fill:null,textureSpace:"local"};Sa.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:H.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let qe=Sa;class Lf{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 qo({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 s=e[t],i=s.element;if(!s.parent||s.globalDisplayStatus<7)i?.remove(),e.splice(t,1),t--;else{this._domElement.contains(i)||(i.style.position="absolute",i.style.pointerEvents="auto",this._domElement.appendChild(i));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;i.style.transformOrigin=`${a}px ${l}px`,i.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,i.style.opacity=s.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)this._attachedDomElements[e].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Lf.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"dom"};class q0{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||(We.system.add(this._tickerUpdate,this,rs.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(We.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 ht=new q0;class yr extends Bs{constructor(){super(...arguments),this.client=new he,this.movement=new he,this.offset=new he,this.global=new he,this.screen=new he}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,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,i,n,o,a,l,h,c,u,d,f,p,m){throw new Error("Method not implemented.")}}class Fe extends yr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1,this.persistentDeviceId=0}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class os extends yr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}os.DOM_DELTA_PIXEL=0;os.DOM_DELTA_LINE=1;os.DOM_DELTA_PAGE=2;const Y0=2048,K0=new he,Xs=new he;class Of{constructor(e){this.dispatch=new Re,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.mapContextMenu=this.mapContextMenu.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),this.addEventMapping("contextmenu",this.mapContextMenu)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,i)=>s.priority-i.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 s=0,i=t.length;s<i;s++)t[s].fn(e);else N(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){ht.pauseUpdate=!0;const i=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[i](this.rootTarget,this.rootTarget.eventMode,K0.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let i=0,n=s.length-1;i<n;i++)if(e.currentTarget=s[i],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 i=s.length-2;i>=0;i--)if(e.currentTarget=s[i],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const i=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)i.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<Y0&&e!==this.rootTarget&&e.parent;s++){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,s,i,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(ht.pauseUpdate=!1),e.interactiveChildren&&e.children){const c=e.children;for(let u=c.length-1;u>=0;u--){const d=c[u],f=this.hitTestMoveRecursive(d,this._isInteractive(t)?t:d.eventMode,s,i,n,o||n(e,s));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const p=e.isInteractive();(f.length>0||p)&&(p&&this._allInteractiveElements.push(e),f.push(e)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(t),h=e.isInteractive();return h&&h&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&i(e,s)?h?[e]:[]:null}hitTestRecursive(e,t,s,i,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(ht.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,h=s;for(let c=l.length-1;c>=0;c--){const u=l[c],d=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,h,i,n);if(d){if(d.length>0&&!d[d.length-1].parent)continue;const f=e.isInteractive();return(d.length>0||f)&&d.push(e),d}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&i(e,s)?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 s=0;s<e.effects.length;s++){const i=e.effects[s];if(i.containsPoint&&!i.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e?.containsPoint?(e.worldTransform.applyInverse(t,Xs),e.containsPoint(Xs)):!1}notifyTarget(e,t){if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;e.currentTarget[s]?.(e);const i=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,i),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof Fe)){N("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 i=t.button===2;this.dispatchEvent(t,i?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){if(!(e instanceof Fe)){N("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 s=t.pointerType==="mouse"||t.pointerType==="pen",i=this.trackingData(e.pointerId),n=this.findMountedTarget(i.overTargets);if(i.overTargets?.length>0&&n!==t.target){const l=e.type==="mousemove"?"mouseout":"pointerout",h=this.createPointerEvent(e,l,n);if(this.dispatchEvent(h,"pointerout"),s&&this.dispatchEvent(h,"mouseout"),!t.composedPath().includes(n)){const c=this.createPointerEvent(e,"pointerleave",n);for(c.eventPhase=c.AT_TARGET;c.target&&!t.composedPath().includes(c.target);)c.currentTarget=c.target,this.notifyTarget(c),s&&this.notifyTarget(c,"mouseleave"),c.target=c.target.parent;this.freeEvent(c)}this.freeEvent(h)}if(n!==t.target){const l=e.type==="mousemove"?"mouseover":"pointerover",h=this.clonePointerEvent(t,l);this.dispatchEvent(h,"pointerover"),s&&this.dispatchEvent(h,"mouseover");let c=n?.parent;for(;c&&c!==this.rootTarget.parent&&c!==t.target;)c=c.parent;if(!c||c===this.rootTarget.parent){const d=this.clonePointerEvent(t,"pointerenter");for(d.eventPhase=d.AT_TARGET;d.target&&d.target!==n&&d.target!==this.rootTarget.parent;)d.currentTarget=d.target,this.notifyTarget(d),s&&this.notifyTarget(d,"mouseenter"),d.target=d.target.parent;this.freeEvent(d)}this.freeEvent(h)}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")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=t.target?.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,i.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),i=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),i&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=s.target?.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",i=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",i);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",i);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&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 Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const i=this.trackingData(e.pointerId),n=this.findMountedTarget(i.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete i.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,i.clicksByButton[e.button]||(i.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=i.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 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(s)}mapPointerUpOutside(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),i=this.createPointerEvent(e);if(s){let n=s;for(;n;)i.currentTarget=n,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch"?this.notifyTarget(i,"touchendoutside"):(i.pointerType==="mouse"||i.pointerType==="pen")&&this.notifyTarget(i,i.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(i)}mapWheel(e){if(!(e instanceof os)){N("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}mapContextMenu(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);this.dispatchEvent(t,"contextmenu"),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const i=this.allocateEvent(Fe);return this.copyPointerData(e,i),this.copyMouseData(e,i),this.copyData(e,i),i.nativeEvent=e.nativeEvent,i.originalEvent=e,i.target=s??this.hitTest(i.global.x,i.global.y)??this._hitElements[0],typeof t=="string"&&(i.type=t),i}createWheelEvent(e){const t=this.allocateEvent(os);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 s=this.allocateEvent(Fe);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof Fe&&t instanceof Fe&&(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,t.persistentDeviceId=e.persistentDeviceId)}copyMouseData(e,t){e instanceof yr&&t instanceof yr&&(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 s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let i=0,n=s.length;i<n&&!e.propagationImmediatelyStopped;i++)s[i].once&&e.currentTarget.removeListener(t,s[i].fn,void 0,!0),s[i].fn.call(s[i].context,e)}}const Z0=1,Q0={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Ca=class yo{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new Of(null),ht.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new Fe(null),this._rootWheelEvent=new os(null),this._rootContextMenuEvent=new Fe(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...yo.defaultEventFeatures},{set:(t,s,i)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=i),t[s]=i,!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._onContextMenu=this._onContextMenu.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,yo._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){ht.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 s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);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 s=0,i=t.length;s<i;s++){const n=t[s],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,ht.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);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 s=t!==this.domElement?"outside":"",i=this._normalizeToPointerData(e);for(let n=0,o=i.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,i[n]);a.type+=s,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 s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onContextMenu(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootContextMenuEvent,t[s]);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,ht.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;ht.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.domElement.addEventListener("contextmenu",this._onContextMenu,!0),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;ht.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.removeEventListener("contextmenu",this._onContextMenu,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const i=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-i.left)*(this.domElement.width/i.width)*n,e.y=(s-i.top)*(this.domElement.height/i.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,i=e.changedTouches.length;s<i;s++){const n=e.changedTouches[s];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 s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=Z0),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}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=Q0[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}};Ca.extension={name:"events",type:[C.WebGLSystem,C.CanvasSystem,C.WebGPUSystem],priority:-1};Ca.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Uf=Ca;const J0={onclick:null,oncontextmenu: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(r){this.eventMode=r?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Uf.defaultEventMode},set eventMode(r){this._internalEventMode=r},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(r,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,i=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;r=s?`${r}capture`:r;const a=typeof e=="function"?e:e.handleEvent,l=this;i&&i.addEventListener("abort",()=>{l.off(r,a,o)}),n?l.once(r,a,o):l.on(r,a,o)},removeEventListener(r,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,i=typeof e=="function"?void 0:e;r=s?`${r}capture`:r,e=typeof e=="function"?e:e.handleEvent,this.off(r,e,i)},dispatchEvent(r){if(!(r instanceof Bs))throw new Error("Container cannot propagate events outside of the Federated Events API");return r.defaultPrevented=!1,r.path=null,r.target=this,r.manager.dispatchEvent(r),!r.defaultPrevented}};let fs;function bc(r){const e=J.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=r,t.fillRect(0,0,6,1),e}function Ma(){if(fs!==void 0)return fs;try{const r=bc("#ff00ff"),e=bc("#ffff00"),s=J.get().createCanvas(6,1).getContext("2d");s.globalCompositeOperation="multiply",s.drawImage(r,0,0),s.drawImage(e,2,0);const i=s.getImageData(2,0,1,1);if(!i)fs=!1;else{const n=i.data;fs=n[0]===255&&n[1]===0&&n[2]===0}}catch{fs=!1}return fs}const Y={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:Ma(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:r=>{const e=r.source,t=e?.resource;if(!t)return null;const s=e.alphaMode==="premultiplied-alpha",i=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=i!==e.pixelWidth||n!==e.pixelHeight;if(s){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=Y._unpremultipliedCache.get(e);if(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=Y._canvasSourceCache.get(e);if(a?.resourceId===e._resourceId)return a.canvas;const l=J.get().createCanvas(e.pixelWidth,e.pixelHeight),h=l.getContext("2d"),c=h.createImageData(e.pixelWidth,e.pixelHeight),u=c.data,d=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let f=0;f<u.length&&f+3<d.length;f+=4)u[f]=d[f+2],u[f+1]=d[f+1],u[f+2]=d[f],u[f+3]=d[f+3];else u.set(d.subarray(0,u.length));return h.putImageData(c,0,0),Y._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(s){const a=J.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 h=l.getImageData(0,0,a.width,a.height),c=h.data;for(let u=0;u<c.length;u+=4){const d=c[u+3];if(d>0){const f=255/d;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),Y._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=Y._canvasSourceCache.get(e);if(a?.resourceId===e._resourceId)return a.canvas;const l=J.get().createCanvas(e.pixelWidth,e.pixelHeight),h=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,h.drawImage(t,0,0),Y._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(r,e)=>{const t=r.texture,s=oe.shared.setValue(e).toHex(),i=t.tintCache||(t.tintCache={}),n=i[s],o=t.source._resourceId;if(n?.tintId===o)return n;const a=n&&"getContext"in n?n:J.get().createCanvas();return Y.tintMethod(t,e,a),a.tintId=o,i[s]=a,i[s]},getTintedPattern:(r,e)=>{const t=oe.shared.setValue(e).toHex(),s=r.patternCache||(r.patternCache={}),i=r.source._resourceId;let n=s[t];return n?.tintId===i||(Y.canvas||(Y.canvas=J.get().createCanvas()),Y.tintMethod(r,e,Y.canvas),n=Y.canvas.getContext("2d").createPattern(Y.canvas,"repeat"),n.tintId=i,s[t]=n),n},applyPatternTransform:(r,e,t=!0)=>{if(!e)return;const s=r;if(!s.setTransform)return;const i=globalThis.DOMMatrix;if(!i)return;const n=new i([e.a,e.b,e.c,e.d,e.tx,e.ty]);s.setTransform(t?n.inverse():n)},tintWithMultiply:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),e!==16777215&&(s.fillStyle=oe.shared.setValue(e).toHex(),s.fillRect(0,0,l,h),s.globalCompositeOperation="multiply");const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),e!==16777215&&(s.globalCompositeOperation="destination-atop",s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height)),s.restore()},tintWithOverlay:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),s.globalCompositeOperation="copy",s.fillStyle=oe.shared.setValue(e).toHex(),s.fillRect(0,0,l,h),s.globalCompositeOperation="destination-atop";const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),s.restore()},tintWithPerPixel:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),s.globalCompositeOperation="copy";const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),s.restore();const u=e>>16&255,d=e>>8&255,f=e&255,p=s.getImageData(0,0,l,h),m=p.data;for(let g=0;g<m.length;g+=4)m[g]=m[g]*u/255,m[g+1]=m[g+1]*d/255,m[g+2]=m[g+2]*f/255;s.putImageData(p,0,0)},_applyInverseRotation:(r,e,t,s)=>{const i=Z.inv(e),n=Z.uX(i),o=Z.uY(i),a=Z.vX(i),l=Z.vY(i),h=-Math.min(0,n*t,a*s,n*t+a*s),c=-Math.min(0,o*t,l*s,o*t+l*s);r.transform(n,o,a,l,h,c)}};Y.tintMethod=Y.canUseMultiply?Y.tintWithMultiply:Y.tintWithPerPixel;const Cn=32767;function vc(r,e){return(r<<17)+(e<<2)}class Nf{constructor(e){this._buckets=new Map,this._screens=new No,this._enableFullScreen=!1,this.canvasOptions=e||{}}get enableFullScreen(){return O(lt,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen}set enableFullScreen(e){O(lt,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen=e}_createCanvasAndContext(e,t){const s=J.get().createCanvas();s.width=e,s.height=t;const i=s.getContext("2d");return{canvas:s,context:i}}getOptimalCanvasAndContext(e,t,s=1){const{width:i,height:n}=this.getOptimalSize(e,t,s);(i>Cn||n>Cn)&&N(`CanvasPool: ${i}x${n} is larger than the ${Cn}px pool key limit, canvases of this size may be pooled together`);const o=vc(i,n);let a=this._buckets.get(o);a||(a=[],this._buckets.set(o,a));let l=a.pop();return l||(l=this._createCanvasAndContext(i,n)),l}getOptimalSize(e,t,s=1){const i=Math.ceil(e*s-1e-6),n=Math.ceil(t*s-1e-6),o=es(i),a=this._screens.getFittingWidth(i),l=es(n),h=this._screens.getFittingHeight(n);return{width:a!==void 0?Math.min(a,o):o,height:h!==void 0?Math.min(h,l):l}}returnCanvasAndContext(e){const t=e.canvas,{width:s,height:i}=t,n=this._buckets.get(vc(s,i));n&&(e.context.resetTransform(),e.context.clearRect(0,0,s,i),n.push(e))}setScreenSize(e,t,s){this._screens.set(e,t,s)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(const[e]of this._buckets){const t=e>>>17,s=e>>>2&32767;(ts(t)||this._screens.hasWidth(t))&&(ts(s)||this._screens.hasHeight(s))||this._buckets.delete(e)}}}const Mt=new Nf;as.register(Mt);const wc=new L;function Ea(r,e){e.clear();const t=e.matrix;for(let s=0;s<r.length;s++){const i=r[s];if(i.globalDisplayStatus<7)continue;const n=i.renderGroup??i.parentRenderGroup;n?.isCachedAsTexture?e.matrix=wc.copyFrom(n.textureOffsetInverseTransform).append(i.worldTransform):n?._parentCacheAsTextureRenderGroup?e.matrix=wc.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(i.groupTransform):e.matrix=i.worldTransform,e.addBounds(i.bounds)}return e.matrix=t,e}const ey=new ke;function ka(r,e,t,s,i=!1,n){const o=ey;o.minX=0,o.minY=0,o.maxX=r.width/s|0,o.maxY=r.height/s|0;const a=Te.getOptimalTexture({width:o.width,height:o.height,resolution:s,autoGenerateMipmaps:i,scaleMode:n});return a.source.uploadMethodId="image",a.source.resource=r,a.source.alphaMode="premultiply-alpha-on-upload",a.frame.width=e/s,a.frame.height=t/s,a.source.emit("update",a.source),a.updateUvs(),a}function xo(r){return typeof r.getCanvasFilterString=="function"}class ty{constructor(){this.skip=!1,this.useClip=!1,this.filters=null,this.container=null,this.bounds=new ke,this.cssFilterString=""}}class Hf{constructor(e){this._filterStack=[],this._filterStackIndex=0,this._savedStates=[],this._alphaMultiplier=1,this._warnedFilterTypes=new Set,this.renderer=e}push(e){const t=this._pushFilterFrame(),s=e.filterEffect.filters;if(t.skip=!1,t.useClip=!1,t.filters=s,t.container=e.container,t.cssFilterString="",s.every(l=>!l.enabled)){t.skip=!0;return}const i=[],n=1;for(const l of s){if(!l.enabled)continue;if(!xo(l)){this._warnUnsupportedFilter(l);continue}const h=l.getCanvasFilterString();if(h===null){this._warnUnsupportedFilter(l);continue}h&&i.push(h)}if(i.length===0&&n===1){t.skip=!0;return}t.cssFilterString=i.join(" "),this._calculateFilterArea(e,t.bounds),t.useClip=!!e.filterEffect.filterArea;const o=this.renderer.canvasContext.activeContext,a=o.filter||"none";if(this._savedStates.push({filter:a,alphaMultiplier:this._alphaMultiplier}),t.useClip&&Number.isFinite(t.bounds.width)&&Number.isFinite(t.bounds.height)&&t.bounds.width>0&&t.bounds.height>0){const l=this.renderer.canvasContext.activeResolution||1;o.save(),o.setTransform(1,0,0,1,0,0),o.beginPath(),o.rect(t.bounds.x*l,t.bounds.y*l,t.bounds.width*l,t.bounds.height*l),o.clip()}else t.useClip=!1;t.cssFilterString&&(o.filter=a!=="none"?`${a} ${t.cssFilterString}`:t.cssFilterString)}pop(){const e=this._popFilterFrame();if(e.skip)return;const t=this._savedStates.pop();if(!t)return;const s=this.renderer.canvasContext.activeContext;e.useClip?s.restore():s.filter=t.filter,this._alphaMultiplier=t.alphaMultiplier}generateFilteredTexture({texture:e,filters:t}){if(!t?.length||t.every(_=>!_.enabled))return e;const s=[],i=1;for(const _ of t){if(!_.enabled)continue;if(!xo(_)){this._warnUnsupportedFilter(_);continue}const x=_.getCanvasFilterString();if(x===null){this._warnUnsupportedFilter(_);continue}x&&s.push(x)}if(s.length===0&&i===1)return e;const n=Y.getCanvasSource(e);if(!n)return e;const o=e.frame,a=e.source._resolution??e.source.resolution??1,l=o.width,h=o.height,c=Mt.getOptimalCanvasAndContext(l,h,a),{canvas:u,context:d}=c;d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,u.width,u.height),s.length&&(d.filter=s.join(" "));const f=o.x*a,p=o.y*a,m=l*a,g=h*a;return d.drawImage(n,f,p,m,g,0,0,m,g),d.filter="none",d.globalAlpha=1,ka(u,l,h,a)}_calculateFilterArea(e,t){if(e.renderables?Ea(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 i=(e.container.renderGroup||e.container.parentRenderGroup)?.cacheToLocalTransform;i&&t.applyMatrix(i)}}_warnUnsupportedFilter(e){const t=e?.constructor?.name||"Filter";this._warnedFilterTypes.has(t)||(this._warnedFilterTypes.add(t),console.warn(`CanvasRenderer: filter "${t}" is not supported in Canvas2D and will be skipped.`))}get alphaMultiplier(){return this._alphaMultiplier}_pushFilterFrame(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new ty),this._filterStackIndex++,e}_popFilterFrame(){return this._filterStackIndex<=0?this._filterStack[0]:(this._filterStackIndex--,this._filterStack[this._filterStackIndex])}destroy(){this._filterStack=null,this._savedStates=null,this._warnedFilterTypes=null,this._alphaMultiplier=1}}Hf.extension={type:[C.CanvasSystem],name:"filter"};var zf=`in vec2 aPosition;
253
+ `}},oc={};function pa(r){let e=oc[r];if(e)return e;const t=new Int32Array(r);for(let s=0;s<r;s++)t[s]=s;return e=oc[r]=new rt({uTextures:{value:t,type:"i32",size:r}},{isStatic:!0}),e}class lo extends dt{constructor(e){const t=Pi({name:"batch",bits:[ua,fa(e),Ri]}),s=ki({name:"batch",bits:[ca,da(e),Ai]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:pa(e)}}),this.maxTextures=e}}let Vs=null;const hf=class cf extends qd{constructor(e){super(e),this.geometry=new Kd,this.name=cf.extension.name,this.vertexSize=6,Vs??(Vs=new lo(e.maxTextures)),this.shader=Vs}packAttributes(e,t,s,i,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,h=a.b,c=a.c,u=a.d,d=a.tx,f=a.ty,{positions:p,uvs:m}=e,g=e.color,_=e.attributeOffset,x=_+e.attributeSize;for(let y=_;y<x;y++){const b=y*2,w=p[b],v=p[b+1];t[i++]=l*w+c*v+d,t[i++]=u*v+h*w+f,t[i++]=m[b],t[i++]=m[b+1],s[i++]=g,s[i++]=o}}packQuadAttributes(e,t,s,i,n){const o=e.texture,a=e.transform,l=a.a,h=a.b,c=a.c,u=a.d,d=a.tx,f=a.ty,p=e.bounds,m=p.maxX,g=p.minX,_=p.maxY,x=p.minY,y=o.uvs,b=e.color,w=n<<16|e.roundPixels&65535;t[i+0]=l*g+c*x+d,t[i+1]=u*x+h*g+f,t[i+2]=y.x0,t[i+3]=y.y0,s[i+4]=b,s[i+5]=w,t[i+6]=l*m+c*x+d,t[i+7]=u*x+h*m+f,t[i+8]=y.x1,t[i+9]=y.y1,s[i+10]=b,s[i+11]=w,t[i+12]=l*m+c*_+d,t[i+13]=u*_+h*m+f,t[i+14]=y.x2,t[i+15]=y.y2,s[i+16]=b,s[i+17]=w,t[i+18]=l*g+c*_+d,t[i+19]=u*_+h*g+f,t[i+20]=y.x3,t[i+21]=y.y3,s[i+22]=b,s[i+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Vs=new lo(e),this.shader=Vs)}destroy(){this.shader=null,super.destroy()}};hf.extension={type:[S.Batcher],name:"default"};let Bi=hf;class it{constructor(e){this.items=Object.create(null);const{renderer:t,type:s,onUnload:i,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",s,n??0),this._onUnload=i,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){if(!this.items[e.uid])return;const s=e._gpuData[this._renderer.uid];s&&(this._onUnload?.(e,...t),e.off("unload",this.remove,this),s.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 uf(r,e,t,s,i,n,o,a=null){let l=0;t*=e,i*=n;const h=a.a,c=a.b,u=a.c,d=a.d,f=a.tx,p=a.ty;for(;l<o;){const m=r[t],g=r[t+1];s[i]=h*m+u*g+f,s[i+1]=c*m+d*g+p,i+=n,t+=e,l++}}function df(r,e,t,s){let i=0;for(e*=t;i<s;)r[e]=0,r[e+1]=0,e+=t,i++}function ma(r,e,t,s,i){const n=e.a,o=e.b,a=e.c,l=e.d,h=e.tx,c=e.ty;t||(t=0),s||(s=2),i||(i=r.length/s-t);let u=t*s;for(let d=0;d<i;d++){const f=r[u],p=r[u+1];r[u]=n*f+a*p+h,r[u+1]=o*f+l*p+c,u+=s}}const x0=new L;class Ii{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,s=this.renderable;return s?Kt(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||x0}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 ks={extension:{type:S.ShapeBuilder,name:"circle"},build(r,e){let t,s,i,n,o,a;if(r.type==="circle"){const b=r;if(o=a=b.radius,o<=0)return!1;t=b.x,s=b.y,i=n=0}else if(r.type==="ellipse"){const b=r;if(o=b.halfWidth,a=b.halfHeight,o<=0||a<=0)return!1;t=b.x,s=b.y,i=n=0}else{const b=r,w=b.width/2,v=b.height/2;t=b.x+w,s=b.y+v,o=a=Math.max(0,Math.min(b.radius,Math.min(w,v))),i=w-o,n=v-a}if(i<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),h=l*8+(i?4:0)+(n?4:0);if(h===0)return!1;if(l===0)return e[0]=e[6]=t+i,e[1]=e[3]=s+n,e[2]=e[4]=t-i,e[5]=e[7]=s-n,!0;let c=0,u=l*4+(i?2:0)+2,d=u,f=h,p=i+o,m=n,g=t+p,_=t-p,x=s+m;if(e[c++]=g,e[c++]=x,e[--u]=x,e[--u]=_,n){const b=s-m;e[d++]=_,e[d++]=b,e[--f]=b,e[--f]=g}for(let b=1;b<l;b++){const w=Math.PI/2*(b/l),v=i+Math.cos(w)*o,T=n+Math.sin(w)*a,k=t+v,P=t-v,A=s+T,C=s-T;e[c++]=k,e[c++]=A,e[--u]=A,e[--u]=P,e[d++]=P,e[d++]=C,e[--f]=C,e[--f]=k}p=i,m=n+a,g=t+p,_=t-p,x=s+m;const y=s-m;return e[c++]=g,e[c++]=x,e[--f]=y,e[--f]=g,i&&(e[c++]=_,e[c++]=x,e[--f]=y,e[--f]=_),!0},triangulate(r,e,t,s,i,n){if(r.length===0)return;let o=0,a=0;for(let c=0;c<r.length;c+=2)o+=r[c],a+=r[c+1];o/=r.length/2,a/=r.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const h=l++;for(let c=0;c<r.length;c+=2)e[l*t]=r[c],e[l*t+1]=r[c+1],c>0&&(i[n++]=l,i[n++]=h,i[n++]=l-1),l++;i[n++]=h+1,i[n++]=h,i[n++]=l-1}},ff={...ks,extension:{...ks.extension,name:"ellipse"}},pf={...ks,extension:{...ks.extension,name:"roundedRectangle"}},ga=1e-4,ho=1e-4;function ac(r,e,t,s,i,n,o,a){const l=r-t*i,h=e-s*i,c=r+t*n,u=e+s*n;let d,f;o?(d=s,f=-t):(d=-s,f=t);const p=l+d,m=h+f,g=c+d,_=u+f;return a.push(p,m),a.push(g,_),2}function Ut(r,e,t,s,i,n,o,a){const l=t-r,h=s-e;let c=Math.atan2(l,h),u=Math.atan2(i-r,n-e);a&&c<u?c+=Math.PI*2:!a&&c>u&&(u+=Math.PI*2);let d=c;const f=u-c,p=Math.abs(f),m=Math.sqrt(l*l+h*h),g=(15*p*Math.sqrt(m)/Math.PI>>0)+1,_=f/g;if(d+=_,a){o.push(r,e),o.push(t,s);for(let x=1,y=d;x<g;x++,y+=_)o.push(r,e),o.push(r+Math.sin(y)*m,e+Math.cos(y)*m);o.push(r,e),o.push(i,n)}else{o.push(t,s),o.push(r,e);for(let x=1,y=d;x<g;x++,y+=_)o.push(r+Math.sin(y)*m,e+Math.cos(y)*m),o.push(r,e);o.push(i,n),o.push(r,e)}return g*2}function Gi(r,e,t,s,i,n){const o=ga;if(r.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let R=aa(r);l=(l-.5)*R+.5}const h=new he(r[0],r[1]),c=new he(r[r.length-2],r[r.length-1]),u=s,d=Math.abs(h.x-c.x)<o&&Math.abs(h.y-c.y)<o;if(u){r=r.slice(),d&&(r.pop(),r.pop(),c.set(r[r.length-2],r[r.length-1]));const R=(h.x+c.x)*.5,U=(c.y+h.y)*.5;r.unshift(R,U),r.push(R,U)}const f=i,p=r.length/2;let m=r.length;const g=f.length/2,_=a.width/2,x=_*_,y=a.miterLimit*a.miterLimit;let b=r[0],w=r[1],v=r[2],T=r[3],k=0,P=0,A=-(w-T),C=b-v,E=0,B=0,G=Math.sqrt(A*A+C*C);A/=G,C/=G,A*=_,C*=_;const V=l,I=(1-V)*2,M=V*2;u||(a.cap==="round"?m+=Ut(b-A*(I-M)*.5,w-C*(I-M)*.5,b-A*I,w-C*I,b+A*M,w+C*M,f,!0)+2:a.cap==="square"&&(m+=ac(b,w,A,C,I,M,!0,f))),f.push(b-A*I,w-C*I),f.push(b+A*M,w+C*M);for(let R=1;R<p-1;++R){b=r[(R-1)*2],w=r[(R-1)*2+1],v=r[R*2],T=r[R*2+1],k=r[(R+1)*2],P=r[(R+1)*2+1],A=-(w-T),C=b-v,G=Math.sqrt(A*A+C*C),A/=G,C/=G,A*=_,C*=_,E=-(T-P),B=v-k,G=Math.sqrt(E*E+B*B),E/=G,B/=G,E*=_,B*=_;const U=v-b,W=w-T,se=v-k,te=P-T,ie=U*se+W*te,$=W*se-te*U,Ze=$<0;if(Math.abs($)<.001*Math.abs(ie)){f.push(v-A*I,T-C*I),f.push(v+A*M,T+C*M),ie>=0&&(a.join==="round"?m+=Ut(v,T,v-A*I,T-C*I,v-E*I,T-B*I,f,!1)+4:m+=2,f.push(v-E*M,T-B*M),f.push(v+E*I,T+B*I));continue}const Tr=(-A+b)*(-C+T)-(-A+v)*(-C+w),Ds=(-E+k)*(-B+T)-(-E+v)*(-B+P),Fs=(U*Ds-se*Tr)/$,pt=(te*Tr-W*Ds)/$,Lt=(Fs-v)*(Fs-v)+(pt-T)*(pt-T),Qe=v+(Fs-v)*I,Le=T+(pt-T)*I,Oe=v-(Fs-v)*M,Je=T-(pt-T)*M,Pt=Math.min(U*U+W*W,se*se+te*te),mt=Ze?I:M,Ls=Pt+mt*mt*x;Lt<=Ls?a.join==="bevel"||Lt/x>y?(Ze?(f.push(Qe,Le),f.push(v+A*M,T+C*M),f.push(Qe,Le),f.push(v+E*M,T+B*M)):(f.push(v-A*I,T-C*I),f.push(Oe,Je),f.push(v-E*I,T-B*I),f.push(Oe,Je)),m+=2):a.join==="round"?Ze?(f.push(Qe,Le),f.push(v+A*M,T+C*M),m+=Ut(v,T,v+A*M,T+C*M,v+E*M,T+B*M,f,!0)+4,f.push(Qe,Le),f.push(v+E*M,T+B*M)):(f.push(v-A*I,T-C*I),f.push(Oe,Je),m+=Ut(v,T,v-A*I,T-C*I,v-E*I,T-B*I,f,!1)+4,f.push(v-E*I,T-B*I),f.push(Oe,Je)):(f.push(Qe,Le),f.push(Oe,Je)):(f.push(v-A*I,T-C*I),f.push(v+A*M,T+C*M),a.join==="round"?Ze?m+=Ut(v,T,v+A*M,T+C*M,v+E*M,T+B*M,f,!0)+2:m+=Ut(v,T,v-A*I,T-C*I,v-E*I,T-B*I,f,!1)+2:a.join==="miter"&&Lt/x<=y&&(Ze?(f.push(Oe,Je),f.push(Oe,Je)):(f.push(Qe,Le),f.push(Qe,Le)),m+=2),f.push(v-E*I,T-B*I),f.push(v+E*M,T+B*M),m+=2)}b=r[(p-2)*2],w=r[(p-2)*2+1],v=r[(p-1)*2],T=r[(p-1)*2+1],A=-(w-T),C=b-v,G=Math.sqrt(A*A+C*C),A/=G,C/=G,A*=_,C*=_,f.push(v-A*I,T-C*I),f.push(v+A*M,T+C*M),u||(a.cap==="round"?m+=Ut(v-A*(I-M)*.5,T-C*(I-M)*.5,v-A*I,T-C*I,v+A*M,T+C*M,f,!1)+2:a.cap==="square"&&(m+=ac(v,T,A,C,I,M,!1,f)));const D=ho*ho;for(let R=g;R<m+g-2;++R)b=f[R*2],w=f[R*2+1],v=f[(R+1)*2],T=f[(R+1)*2+1],k=f[(R+2)*2],P=f[(R+2)*2+1],!(Math.abs(b*(T-P)+v*(P-w)+k*(w-T))<D)&&n.push(R,R+1,R+2)}function mf(r,e,t,s){const i=ga;if(r.length===0)return;const n=r[0],o=r[1],a=r[r.length-2],l=r[r.length-1],h=e||Math.abs(n-a)<i&&Math.abs(o-l)<i,c=t,u=r.length/2,d=c.length/2;for(let f=0;f<u;f++)c.push(r[f*2]),c.push(r[f*2+1]);for(let f=0;f<u-1;f++)s.push(d+f,d+f+1);h&&s.push(d+u-1,d)}function _a(r,e,t,s,i,n,o){const a=Bd(r,e,2);if(!a)return;for(let h=0;h<a.length;h+=3)n[o++]=a[h]+i,n[o++]=a[h+1]+i,n[o++]=a[h+2]+i;let l=i*s;for(let h=0;h<r.length;h+=2)t[l]=r[h],t[l+1]=r[h+1],l+=s}const b0=[],gf={extension:{type:S.ShapeBuilder,name:"polygon"},build(r,e){for(let t=0;t<r.points.length;t++)e[t]=r.points[t];return!0},triangulate(r,e,t,s,i,n){_a(r,b0,e,t,s,i,n)}},_f={extension:{type:S.ShapeBuilder,name:"rectangle"},build(r,e){const t=r,s=t.x,i=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=i,e[2]=s+n,e[3]=i,e[4]=s+n,e[5]=i+o,e[6]=s,e[7]=i+o,!0):!1},triangulate(r,e,t,s,i,n){let o=0;s*=t,e[s+o]=r[0],e[s+o+1]=r[1],o+=t,e[s+o]=r[2],e[s+o+1]=r[3],o+=t,e[s+o]=r[6],e[s+o+1]=r[7],o+=t,e[s+o]=r[4],e[s+o+1]=r[5],o+=t;const a=s/t;i[n++]=a,i[n++]=a+1,i[n++]=a+2,i[n++]=a+1,i[n++]=a+3,i[n++]=a+2}},yf={extension:{type:S.ShapeBuilder,name:"triangle"},build(r,e){return e[0]=r.x,e[1]=r.y,e[2]=r.x2,e[3]=r.y2,e[4]=r.x3,e[5]=r.y3,!0},triangulate(r,e,t,s,i,n){let o=0;s*=t,e[s+o]=r[0],e[s+o+1]=r[1],o+=t,e[s+o]=r[2],e[s+o+1]=r[3],o+=t,e[s+o]=r[4],e[s+o+1]=r[5];const a=s/t;i[n++]=a,i[n++]=a+1,i[n++]=a+2}},lc=[{offset:0,color:"white"},{offset:1,color:"black"}],ya=class co{constructor(...e){this.uid=ne("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=v0(e);t={...t.type==="radial"?co.defaultRadialOptions:co.defaultLinearOptions,...Do(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(i=>{this.addColorStop(i.offset,i.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:oe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:i}=this.end,n=s-e,o=i-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const g=e;e=s,s=g,n*=-1}if(o<0){const g=t;t=i,i=g,o*=-1}}const l=this.colorStops.length?this.colorStops:lc,h=this._textureSize,{canvas:c,context:u}=cc(h,1),d=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);hc(d,l),u.fillStyle=d,u.fillRect(0,0,h,1),this.texture=new H({source:new ur({resource:c,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),p=Math.atan2(o,n),m=new L;m.scale(f/h,1),m.rotate(p),m.translate(e,t),this.textureSpace==="local"&&m.scale(h,h),this.transform=m}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:lc,t=this._textureSize,{canvas:s,context:i}=cc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,h=this.innerRadius,c=this.outerRadius,u=a-c,d=l-c,f=t/(c*2),p=(n-u)*f,m=(o-d)*f,g=i.createRadialGradient(p,m,h*f,(a-u)*f,(l-d)*f,c*f);hc(g,e),i.fillStyle=e[e.length-1].color,i.fillRect(0,0,t,t),i.fillStyle=g,i.translate(p,m),i.rotate(this.rotation),i.scale(1,this.scale),i.translate(-p,-m),i.fillRect(0,0,t,t),this.texture=new H({source:new ur({resource:s,addressMode:this._wrapMode})});const _=new L;this.textureSpace==="local"?_.scale(2*c,2*c):_.scale(1/f,1/f),_.translate(u,d),this.transform=_}destroy(){this.texture?.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}`}};ya.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"};ya.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,rotation:0,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Xe=ya;function hc(r,e){for(let t=0;t<e.length;t++){const s=e[t];r.addColorStop(s.offset,s.color)}}function cc(r,e){const t=J.get().createCanvas(r,e),s=t.getContext("2d");return{canvas:t,context:s}}function v0(r){let e=r[0]??{};return(typeof e=="number"||r[1])&&(O("8.5.2","use options object instead"),e={type:"linear",start:{x:r[0],y:r[1]},end:{x:r[2],y:r[3]},textureSpace:r[4],textureSize:r[5]??Xe.defaultLinearOptions.textureSize}),e}const w0=new L,T0=new ee,S0=new L;function xa(r,e,t,s){const i=e.matrix?r.copyFrom(e.matrix).invert():r.identity();if(e.textureSpace==="local"){const o=t.getBounds(T0);e.width&&o.pad(e.width);const{x:a,y:l}=o,h=1/o.width,c=1/o.height,u=-a*h,d=-l*c,f=i.a,p=i.b,m=i.c,g=i.d;i.a*=h,i.b*=h,i.c*=c,i.d*=c,i.tx=u*f+d*m+i.tx,i.ty=u*p+d*g+i.ty}else if(e.texture.rotate){const{uvs:o,orig:a}=e.texture;i.scale(1/a.width,1/a.height),i.prepend(S0.set(o.x1-o.x0,o.y1-o.y0,o.x3-o.x0,o.y3-o.y0,o.x0,o.y0))}else i.translate(e.texture.frame.x,e.texture.frame.y),i.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof Xe)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&i.append(w0.copyFrom(s).invert()),i}const hs={};q.handleByMap(S.ShapeBuilder,hs);q.add(_f,gf,yf,ks,ff,pf);const C0=new ee,M0=new L;function xf(r,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let i=0;i<r.instructions.length;i++){const n=r.instructions[i];if(n.action==="texture")E0(n.data,s,t);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&&uc(h.shapePath,l,!0,s,t),h&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=h.shapePath.shapePrimitives),uc(a,l,o,s,t)}}}function E0(r,e,t){const s=[],i=hs.rectangle,n=C0;n.x=r.dx,n.y=r.dy,n.width=r.dw,n.height=r.dh;const o=r.transform;if(!i.build(n,s))return;const{vertices:a,uvs:l,indices:h}=t,c=h.length,u=a.length/2;o&&ma(s,o),i.triangulate(s,a,2,u,h,c);const d=r.image,f=d.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const p=Se.get(Ii);p.indexOffset=c,p.indexSize=h.length-c,p.attributeOffset=u,p.attributeSize=a.length/2-u,p.baseColor=r.style,p.alpha=r.alpha,p.texture=d,p.geometryData=t,e.push(p)}function uc(r,e,t,s,i){const{vertices:n,uvs:o,indices:a}=i;r.shapePrimitives.forEach(({shape:l,transform:h,holes:c})=>{const u=[],d=hs[l.type];if(!d.build(l,u))return;const f=a.length,p=n.length/2;let m="triangle-list";if(h&&ma(u,h),t){const y=l.closePath??!0,b=e;b.pixelLine?(mf(u,y,n,a),m="line-list"):Gi(u,b,!1,y,n,a)}else if(c){const y=[],b=u.slice();k0(c).forEach(v=>{y.push(b.length/2),b.push(...v)}),_a(b,y,n,2,p,a,f)}else d.triangulate(u,n,2,p,a,f);const g=o.length/2,_=e.texture;if(_!==H.WHITE){const y=xa(M0,e,l,h);uf(n,2,p,o,g,2,n.length/2-p,y)}else df(o,g,2,n.length/2-p);const x=Se.get(Ii);x.indexOffset=f,x.indexSize=a.length-f,x.attributeOffset=p,x.attributeSize=n.length/2-p,x.baseColor=e.color,x.alpha=e.alpha,x.texture=_,x.geometryData=i,x.topology=m,s.push(x)})}function k0(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t].shape,i=[];hs[s.type].build(s,i)&&e.push(i)}return e}class bf{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Se.return(e)}),this.graphicsData&&Se.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 vf{constructor(){this.instructions=new xi}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Bi({maxTextures:t}),this.instructions.reset()}get geometry(){return O(yu,"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 ba=class uo{constructor(e){this._renderer=e,this._managedContexts=new it({renderer:e,type:"resource",name:"graphicsContext"})}init(e){uo.defaultOptions.bezierSmoothness=e?.bezierSmoothness??uo.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],s=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&s.reset(),xf(e,s);const i=e.batchMode;e.customShader||i==="no-batch"?s.isBatchable=!1:i==="auto"?s.isBatchable=s.geometryData.vertices.length<400:s.isBatchable=!0,e.dirty=!1}return s}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Se.get(vf,{maxTextures:this._renderer.limits.maxBatchableTextures}),s=e._gpuData[this._renderer.uid],{batches:i,geometryData:n}=s;s.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<i.length;u++)i[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<i.length;u++){const d=i[u];l.add(d)}l.finish(t.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<l.batchIndex;u++){const d=c[u];d.bindGroup=Mi(d.textures.textures,d.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new bf;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};ba.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"graphicsContext"};ba.defaultOptions={bezierSmoothness:.5};let Di=ba;const P0=8,Or=11920929e-14,A0=1;function va(r,e,t,s,i,n,o,a,l,h){const u=Math.min(.99,Math.max(0,h??Di.defaultOptions.bezierSmoothness));let d=(A0-u)/1;return d*=d,R0(e,t,s,i,n,o,a,l,r,d),r}function R0(r,e,t,s,i,n,o,a,l,h){fo(r,e,t,s,i,n,o,a,l,h,0),l.push(o,a)}function fo(r,e,t,s,i,n,o,a,l,h,c){if(c>P0)return;const u=(r+t)/2,d=(e+s)/2,f=(t+i)/2,p=(s+n)/2,m=(i+o)/2,g=(n+a)/2,_=(u+f)/2,x=(d+p)/2,y=(f+m)/2,b=(p+g)/2,w=(_+y)/2,v=(x+b)/2;if(c>0){let T=o-r,k=a-e;const P=Math.abs((t-o)*k-(s-a)*T),A=Math.abs((i-o)*k-(n-a)*T);if(P>Or&&A>Or){if((P+A)*(P+A)<=h*(T*T+k*k)){l.push(w,v);return}}else if(P>Or){if(P*P<=h*(T*T+k*k)){l.push(w,v);return}}else if(A>Or){if(A*A<=h*(T*T+k*k)){l.push(w,v);return}}else if(T=w-(r+o)/2,k=v-(e+a)/2,T*T+k*k<=h){l.push(w,v);return}}fo(r,e,u,d,_,x,w,v,l,h,c+1),fo(w,v,y,b,m,g,o,a,l,h,c+1)}const B0=8,I0=11920929e-14,G0=1;function wf(r,e,t,s,i,n,o,a){const h=Math.min(.99,Math.max(0,a??Di.defaultOptions.bezierSmoothness));let c=(G0-h)/1;return c*=c,D0(e,t,s,i,n,o,r,c),r}function D0(r,e,t,s,i,n,o,a){po(o,r,e,t,s,i,n,a,0),o.push(i,n)}function po(r,e,t,s,i,n,o,a,l){if(l>B0)return;const h=(e+s)/2,c=(t+i)/2,u=(s+n)/2,d=(i+o)/2,f=(h+u)/2,p=(c+d)/2;let m=n-e,g=o-t;const _=Math.abs((s-n)*g-(i-o)*m);if(_>I0){if(_*_<=a*(m*m+g*g)){r.push(f,p);return}}else if(m=f-(e+n)/2,g=p-(t+o)/2,m*m+g*g<=a){r.push(f,p);return}po(r,e,t,h,c,f,p,a,l+1),po(r,f,p,u,d,n,o,a,l+1)}function wa(r,e,t,s,i,n,o,a){let l=Math.abs(i-n);(!o&&i>n||o&&n>i)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let h=l/a,c=i;h*=o?-1:1;for(let u=0;u<a+1;u++){const d=Math.cos(c),f=Math.sin(c),p=e+d*s,m=t+f*s;r.push(p,m),c+=h}}function Tf(r,e,t,s,i,n){const o=r[r.length-2],l=r[r.length-1]-t,h=o-e,c=i-t,u=s-e,d=Math.abs(l*u-h*c);if(d<1e-8||n===0){(r[r.length-2]!==e||r[r.length-1]!==t)&&r.push(e,t);return}const f=l*l+h*h,p=c*c+u*u,m=l*c+h*u,g=n*Math.sqrt(f)/d,_=n*Math.sqrt(p)/d,x=g*m/f,y=_*m/p,b=g*u+_*h,w=g*c+_*l,v=h*(_+x),T=l*(_+x),k=u*(g+y),P=c*(g+y),A=Math.atan2(T-w,v-b),C=Math.atan2(P-w,k-b);wa(r,b+e,w+t,n,A,C,h*c>u*l)}const tr=Math.PI*2,Tn={centerX:0,centerY:0,ang1:0,ang2:0},Sn=({x:r,y:e},t,s,i,n,o,a,l)=>{r*=t,e*=s;const h=i*r-n*e,c=n*r+i*e;return l.x=h+o,l.y=c+a,l};function F0(r,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,i=Math.cos(r),n=Math.sin(r),o=Math.cos(r+e),a=Math.sin(r+e);return[{x:i-n*s,y:n+i*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const dc=(r,e,t,s)=>{const i=r*s-e*t<0?-1:1;let n=r*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),i*Math.acos(n)},L0=(r,e,t,s,i,n,o,a,l,h,c,u,d)=>{const f=Math.pow(i,2),p=Math.pow(n,2),m=Math.pow(c,2),g=Math.pow(u,2);let _=f*p-f*g-p*m;_<0&&(_=0),_/=f*g+p*m,_=Math.sqrt(_)*(o===a?-1:1);const x=_*i/n*u,y=_*-n/i*c,b=h*x-l*y+(r+t)/2,w=l*x+h*y+(e+s)/2,v=(c-x)/i,T=(u-y)/n,k=(-c-x)/i,P=(-u-y)/n,A=dc(1,0,v,T);let C=dc(v,T,k,P);a===0&&C>0&&(C-=tr),a===1&&C<0&&(C+=tr),d.centerX=b,d.centerY=w,d.ang1=A,d.ang2=C};function Sf(r,e,t,s,i,n,o,a=0,l=0,h=0){if(n===0||o===0)return;const c=Math.sin(a*tr/360),u=Math.cos(a*tr/360),d=u*(e-s)/2+c*(t-i)/2,f=-c*(e-s)/2+u*(t-i)/2;if(d===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const p=Math.pow(d,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);p>1&&(n*=Math.sqrt(p),o*=Math.sqrt(p)),L0(e,t,s,i,n,o,l,h,c,u,d,f,Tn);let{ang1:m,ang2:g}=Tn;const{centerX:_,centerY:x}=Tn;let y=Math.abs(g)/(tr/4);Math.abs(1-y)<1e-7&&(y=1);const b=Math.max(Math.ceil(y),1);g/=b;let w=r[r.length-2],v=r[r.length-1];const T={x:0,y:0};for(let k=0;k<b;k++){const P=F0(m,g),{x:A,y:C}=Sn(P[0],n,o,u,c,_,x,T),{x:E,y:B}=Sn(P[1],n,o,u,c,_,x,T),{x:G,y:V}=Sn(P[2],n,o,u,c,_,x,T);va(r,w,v,A,C,E,B,G,V),w=G,v=V,m+=g}}function Cf(r,e,t){const s=(o,a)=>{const l=a.x-o.x,h=a.y-o.y,c=Math.sqrt(l*l+h*h),u=l/c,d=h/c;return{len:c,nx:u,ny:d}},i=(o,a)=>{o===0?r.moveTo(a.x,a.y):r.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){i(o,a),n=a;continue}const h=e[(o+1)%e.length],c=s(a,n),u=s(a,h);if(c.len<1e-4||u.len<1e-4){i(o,a),n=a;continue}let d=Math.asin(c.nx*u.ny-c.ny*u.nx),f=1,p=!1;c.nx*u.nx-c.ny*-u.ny<0?d<0?d=Math.PI+d:(d=Math.PI-d,f=-1,p=!0):d>0&&(f=-1,p=!0);const m=d/2;let g,_=Math.abs(Math.cos(m)*l/Math.sin(m));_>Math.min(c.len/2,u.len/2)?(_=Math.min(c.len/2,u.len/2),g=Math.abs(_*Math.sin(m)/Math.cos(m))):g=l;const x=a.x+u.nx*_+-u.ny*g*f,y=a.y+u.ny*_+u.nx*g*f,b=Math.atan2(c.ny,c.nx)+Math.PI/2*f,w=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&r.moveTo(x+Math.cos(b)*g,y+Math.sin(b)*g),r.arc(x,y,g,b,w,p),n=a}}function Mf(r,e,t,s){const i=(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=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],h=l.radius??t;if(h<=0){a===0?r.moveTo(l.x,l.y):r.lineTo(l.x,l.y);continue}const c=e[a],u=e[(a+2)%o],d=i(c,l);let f;if(d<1e-4)f=l;else{const g=Math.min(d/2,h);f=n(l,c,g/d)}const p=i(u,l);let m;if(p<1e-4)m=l;else{const g=Math.min(p/2,h);m=n(l,u,g/p)}a===0?r.moveTo(f.x,f.y):r.lineTo(f.x,f.y),r.quadraticCurveTo(l.x,l.y,m.x,m.y,s)}}const O0=new ee;class Ef{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new ke,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,i=s[s.length-2],n=s[s.length-1];return(i!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,i,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return wa(a,e,t,s,i,n,o),this}arcTo(e,t,s,i,n){this._ensurePoly();const o=this._currentPoly.points;return Tf(o,e,t,s,i,n),this}arcToSvg(e,t,s,i,n,o,a){const l=this._currentPoly.points;return Sf(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,i,n),this}bezierCurveTo(e,t,s,i,n,o,a){this._ensurePoly();const l=this._currentPoly;return va(this._currentPoly.points,l.lastX,l.lastY,e,t,s,i,n,o,a),this}quadraticCurveTo(e,t,s,i,n){this._ensurePoly();const o=this._currentPoly;return wf(this._currentPoly.points,o.lastX,o.lastY,e,t,s,i,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,i=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-i>1){let n=null;for(let o=i;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,h=n?.shape;h&&h.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,i,n){return this.drawShape(new ee(e,t,s,i),n),this}circle(e,t,s,i){return this.drawShape(new Ti(e,t,s),i),this}poly(e,t,s){const i=new Ts(e);return i.closePath=t,this.drawShape(i,s),this}regularPoly(e,t,s,i,n=0,o){i=Math.max(i|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/i,h=[];for(let c=0;c<i;c++){const u=a-c*l;h.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(h,!0,o),this}roundPoly(e,t,s,i,n,o=0,a){if(i=Math.max(i|0,3),n<=0)return this.regularPoly(e,t,s,i,o);const l=s*Math.sin(Math.PI/i)-.001;n=Math.min(n,l);const h=-1*Math.PI/2+o,c=Math.PI*2/i,u=(i-2)*Math.PI/i/2;for(let d=0;d<i;d++){const f=d*c+h,p=e+s*Math.cos(f),m=t+s*Math.sin(f),g=f+Math.PI+u,_=f-Math.PI-u,x=p+n*Math.cos(g),y=m+n*Math.sin(g),b=p+n*Math.cos(_),w=m+n*Math.sin(_);d===0?this.moveTo(x,y):this.lineTo(x,y),this.quadraticCurveTo(p,m,b,w,a)}return this.closePath()}roundShape(e,t,s=!1,i){return e.length<3?this:(s?Mf(this,e,t,i):Cf(this,e,t),this.closePath())}filletRect(e,t,s,i,n){if(n===0)return this.rect(e,t,s,i);const o=Math.min(s,i)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,h=t+i,c=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+c,t+c,e+u,t,u).lineTo(l-u,t).arcTo(l-c,t+c,l,t+u,u).lineTo(l,h-u).arcTo(l-c,h-c,e+s-u,h,u).lineTo(e+u,h).arcTo(e+c,h-c,e,h-u,u).closePath()}chamferRect(e,t,s,i,n,o){if(n<=0)return this.rect(e,t,s,i);const a=Math.min(n,Math.min(s,i)/2),l=e+s,h=t+i,c=[e+a,t,l-a,t,l,t+a,l,h-a,l-a,h,e+a,h,e,h-a,e,t+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(e,t,s,i,n){return this.drawShape(new Si(e,t,s,i),n),this}roundRect(e,t,s,i,n,o){return this.drawShape(new Ci(e,t,s,i,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new Ts,s.points.push(e,t),this._currentPoly=s,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 Ts,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,i=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*i+n.tx,i=n.b*o+n.d*i+n.ty}this._currentPoly.points.push(s,i)}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 s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const i=t[s],n=i.shape.getBounds(O0);i.transform?e.addRect(n,i.transform):e.addRect(n)}return e}}class ut{constructor(e,t=!1){this.instructions=[],this.uid=ne("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Ud(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new Ef(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,s,i,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(he.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,e,t,s,i,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,s){const i=this.instructions[this.instructions.length-1],n=this.getLastPoint(he.shared);let o=0,a=0;if(!i||i.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=i.data[0],a=i.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,e,t,s]}),this._dirty=!0,this}rect(e,t,s,i,n){return this.instructions.push({action:"rect",data:[e,t,s,i,n]}),this._dirty=!0,this}circle(e,t,s,i){return this.instructions.push({action:"circle",data:[e,t,s,i]}),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,s,i,n,o,a){n||(n=i/2);const l=-1*Math.PI/2+o,h=s*2,c=Math.PI*2/h,u=[];for(let d=0;d<h;d++){const f=d%2?n:i,p=d*c+l;u.push(e+f*Math.cos(p),t+f*Math.sin(p))}return this.poly(u,!0,a),this}clone(e=!1){const t=new ut;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const i=this.instructions[s];t.instructions.push({action:i.action,data:i.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,s=e.b,i=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,h=0,c=0,u=0,d=0,f=0,p=0,m=0;for(let g=0;g<this.instructions.length;g++){const _=this.instructions[g],x=_.data;switch(_.action){case"moveTo":case"lineTo":l=x[0],h=x[1],x[0]=t*l+i*h+o,x[1]=s*l+n*h+a;break;case"bezierCurveTo":c=x[0],u=x[1],d=x[2],f=x[3],l=x[4],h=x[5],x[0]=t*c+i*u+o,x[1]=s*c+n*u+a,x[2]=t*d+i*f+o,x[3]=s*d+n*f+a,x[4]=t*l+i*h+o,x[5]=s*l+n*h+a;break;case"quadraticCurveTo":c=x[0],u=x[1],l=x[2],h=x[3],x[0]=t*c+i*u+o,x[1]=s*c+n*u+a,x[2]=t*l+i*h+o,x[3]=s*l+n*h+a;break;case"arcToSvg":l=x[5],h=x[6],p=x[0],m=x[1],x[0]=t*p+i*m,x[1]=s*p+n*m,x[5]=t*l+i*h+o,x[6]=s*l+n*h+a;break;case"circle":x[4]=ds(x[3],e);break;case"rect":x[4]=ds(x[4],e);break;case"ellipse":x[8]=ds(x[8],e);break;case"roundRect":x[5]=ds(x[5],e);break;case"addPath":x[0].transform(e);break;case"poly":x[2]=ds(x[2],e);break;case"regularPoly":case"chamferRect":x[5]=ds(x[5],e);break;case"closePath":break;default:N("unknown transform action",_.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function ds(r,e){return r?r.prepend(e):e.clone()}function ve(r,e,t){const s=r.getAttribute(e);return s?Number(s):t}function kf(r,e){const t=r.querySelectorAll("defs");for(let s=0;s<t.length;s++){const i=t[s];for(let n=0;n<i.children.length;n++){const o=i.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=U0(o);break;case"radialgradient":e.defs[o.id]=N0(o);break}}}}function st(r,e,t){const s=r.getAttribute(e);if(s?.trim().endsWith("%")){const i=Number(s.trim().slice(0,-1));return Number.isNaN(i)?t:i/100}return ve(r,e,t)}function Pf(r){return(r.getAttribute("gradientUnits")||"objectBoundingBox")==="objectBoundingBox"?"local":"global"}function Af(r){const e=[];for(let t=0;t<r.children.length;t++){const s=r.children[t],i=st(s,"offset",0),n=oe.shared.setValue(s.getAttribute("stop-color")).toNumber();e.push({offset:i,color:n})}return e}function U0(r){const e=st(r,"x1",0),t=st(r,"y1",0),s=st(r,"x2",1),i=st(r,"y2",0);return new Xe({type:"linear",start:{x:e,y:t},end:{x:s,y:i},textureSpace:Pf(r),colorStops:Af(r)})}function N0(r){const e=st(r,"cx",.5),t=st(r,"cy",.5),s=st(r,"r",.5),i=st(r,"fx",e),n=st(r,"fy",t),o=st(r,"fr",0);return new Xe({type:"radial",center:{x:i,y:n},innerRadius:o,outerCenter:{x:e,y:t},outerRadius:s,textureSpace:Pf(r),colorStops:Af(r)})}function mo(r){const e=r.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const go={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 Ta(r,e){const t=r.getAttribute("style"),s={},i={},n={strokeStyle:s,fillStyle:i,useFill:!1,useStroke:!1};for(const o in go){const a=r.getAttribute(o);a&&fc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[h,c]=l.split(":");go[h]&&fc(e,n,h,c.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?i:null,useFill:n.useFill,useStroke:n.useStroke}}function fc(r,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const i=mo(s);e.strokeStyle.fill=r.defs[i]}else e.strokeStyle.color=oe.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const i=mo(s);e.fillStyle.fill=r.defs[i]}else e.fillStyle.color=oe.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function Rf(r){if(r.length<=2)return!0;const e=r.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,i=e[e.length-1],n=t/s,o=s/i;return!(n>3&&o<2)}function Bf(r){return r.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function If(r){const e=r.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],i=[];for(let c=0;c<t.length;c+=2)c+1<t.length&&(s.push(t[c]),i.push(t[c+1]));if(s.length===0||i.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...i),l=Math.max(...i);return(o-n)*(l-a)}function _o(r,e){const t=new ut(r,!1);for(const s of t.instructions)e.instructions.push(s)}function Gf(r,e){if(typeof r=="string"){const o=document.createElement("div");o.innerHTML=r.trim(),r=o.querySelector("svg")}const t={context:e,defs:{},path:new ut};kf(r,t);const s=r.children,{fillStyle:i,strokeStyle:n}=Ta(r,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&Df(a,t,i,n)}return e}function Df(r,e,t,s){const i=r.children,{fillStyle:n,strokeStyle:o}=Ta(r,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,h,c,u,d,f,p,m,g,_,x,y,b,w,v,T,k;switch(r.nodeName.toLowerCase()){case"path":{w=r.getAttribute("d");const P=r.getAttribute("fill-rule"),A=Bf(w),C=P==="evenodd",E=A.length>1;if(C&&E){const G=A.map(I=>({path:I,area:If(I)}));if(G.sort((I,M)=>M.area-I.area),A.length>3||!Rf(G))for(let I=0;I<G.length;I++){const M=G[I],D=I===0;e.context.beginPath();const R=new ut(void 0,!0);_o(M.path,R),e.context.path(R),D?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let I=0;I<G.length;I++){const M=G[I],D=I%2===1;e.context.beginPath();const R=new ut(void 0,!0);_o(M.path,R),e.context.path(R),D?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const G=P?P==="evenodd":!0;v=new ut(w,G),e.context.path(v),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":p=ve(r,"cx",0),m=ve(r,"cy",0),g=ve(r,"r",0),e.context.ellipse(p,m,g,g),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=ve(r,"x",0),h=ve(r,"y",0),T=ve(r,"width",0),k=ve(r,"height",0),_=ve(r,"rx",0),x=ve(r,"ry",0),_||x?e.context.roundRect(l,h,T,k,_||x):e.context.rect(l,h,T,k),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":p=ve(r,"cx",0),m=ve(r,"cy",0),_=ve(r,"rx",0),x=ve(r,"ry",0),e.context.beginPath(),e.context.ellipse(p,m,_,x),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":c=ve(r,"x1",0),u=ve(r,"y1",0),d=ve(r,"x2",0),f=ve(r,"y2",0),e.context.beginPath(),e.context.moveTo(c,u),e.context.lineTo(d,f),s&&e.context.stroke(s);break;case"polygon":b=r.getAttribute("points"),y=b.match(/-?\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":b=r.getAttribute("points"),y=b.match(/-?\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{N(`[SVG parser] <${r.nodeName}> elements unsupported`);break}}a&&(t=null);for(let P=0;P<i.length;P++)Df(i[P],e,t,s)}function H0(r){return r.texture!==void 0}const pc={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 Gs{constructor(e,t){this.uid=ne("fillPattern"),this._tick=0,this.transform=new L;const s=H0(e)?e:{texture:e,repetition:t};this.texture=s.texture,this.textureSpace=s.textureSpace??"global";const i=s.repetition;i&&(this.texture.source.style.addressModeU=pc[i].addressModeU,this.texture.source.style.addressModeV=pc[i].addressModeV)}setTransform(e){if(e){if(this.transform.equals(e))return;this.transform.copyFrom(e)}else{if(this.transform.isIdentity())return;this.transform.identity()}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 z0(r){return oe.isColorLike(r)}function mc(r){return r instanceof Gs}function gc(r){return r instanceof Xe}function W0(r){return r instanceof H}function $0(r,e,t){const s=oe.shared.setValue(e??0);return r.color=s.toNumber(),r.alpha=s.alpha===1?t.alpha:s.alpha,r.texture=H.WHITE,{...t,...r}}function V0(r,e,t){return r.texture=e,{...t,...r}}function _c(r,e,t){return r.fill=e,r.color=16777215,r.texture=e.texture,r.matrix=e.transform,r.textureSpace=e.textureSpace,{...t,...r}}function yc(r,e,t){return e.buildGradient(),r.fill=e,r.color=16777215,r.texture=e.texture,r.matrix=e.transform,r.textureSpace=e.textureSpace,{...t,...r}}function X0(r,e){const t={...e,...r},s=oe.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function Gt(r,e){if(r==null)return null;const t={},s=r;return z0(r)?$0(t,r,e):W0(r)?V0(t,r,e):mc(r)?_c(t,r,e):gc(r)?yc(t,r,e):s.fill&&mc(s.fill)?_c(s,s.fill,e):s.fill&&gc(s.fill)?yc(s,s.fill,e):X0(s,e)}function _r(r,e){const{width:t,alignment:s,miterLimit:i,cap:n,join:o,pixelLine:a,...l}=e,h=Gt(r,l);return h?{width:t,alignment:s,miterLimit:i,cap:n,join:o,pixelLine:a,...h}:null}function Ff(r,e){let t=1;const s=r.shapePath.shapePrimitives;for(let i=0;i<s.length;i++){const n=s[i].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,d=o[c],f=o[c+1],p=o[h],m=o[h+1],g=o[u],_=o[u+1],x=d-p,y=f-m,b=g-p,w=_-m,v=x*x+y*y,T=b*b+w*w;if(v<1e-12||T<1e-12)continue;let A=(x*b+y*w)/Math.sqrt(v*T);A<-1?A=-1:A>1&&(A=1);const C=Math.sqrt((1-A)*.5);if(C<1e-6)continue;const E=Math.min(1/C,e);E>t&&(t=E)}}return t}const j0=new he,xc=new L,Sa=class ot extends Re{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ne("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new ut,this._transform=new L,this._fillStyle={...ot.defaultFillStyle},this._strokeStyle={...ot.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new ke,this._boundsDirty=!0}clone(){const e=new ot;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=Gt(e,ot.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=_r(e,ot.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=Gt(e,ot.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=Gt(e,ot.defaultStrokeStyle),this}texture(e,t,s,i,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:i||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?oe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new ut,this}fill(e,t){let s;const i=this.instructions[this.instructions.length-1];return this._tick===0&&i?.action==="stroke"?s=i.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(O(ue,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=Gt(e,ot.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(he.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&s?.action==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=_r(e,ot.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],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,i,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,s,i,n,o),this}arcTo(e,t,s,i,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*s+o.c*i+o.tx,o.b*s+o.d*i+o.ty,n),this}arcToSvg(e,t,s,i,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,i,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,i,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*s+l.c*i+l.tx,l.b*s+l.d*i+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,s,i){return this._tick++,this._activePath.ellipse(e,t,s,i,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,i=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return i.length===1&&i[0].action==="moveTo"?(i[0].data[0]=n,i[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,i,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*s+o.c*i+o.tx,o.b*s+o.d*i+o.ty,n),this}rect(e,t,s,i){return this._tick++,this._activePath.rect(e,t,s,i,this._transform.clone()),this}roundRect(e,t,s,i,n){return this._tick++,this._activePath.roundRect(e,t,s,i,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,i,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,i,n,o),this}roundPoly(e,t,s,i,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,i,n,o),this}roundShape(e,t,s,i){return this._tick++,this._activePath.roundShape(e,t,s,i),this}filletRect(e,t,s,i,n){return this._tick++,this._activePath.filletRect(e,t,s,i,n),this}chamferRect(e,t,s,i,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,i,n,o),this}star(e,t,s,i,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,i,n,o,this._transform.clone()),this}svg(e){return this._tick++,Gf(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,s,i,n,o){return e instanceof L?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,i,n,o),this)}transform(e,t,s,i,n,o){return e instanceof L?(this._transform.append(e),this):(xc.set(e,t,s,i,n,o),this._transform.append(xc),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 s=this.instructions[t],i=s.action;if(i==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(i==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(i==="stroke"){const n=s.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=Ff(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){if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let i=0;i<t.length;i++){const n=t[i],o=n.data,a=o.path;if(!n.action||!a)continue;const l=o.style,h=a.shapePath.shapePrimitives;for(let c=0;c<h.length;c++){const u=h[c].shape;if(!l||!u)continue;const d=h[c].transform,f=d?d.applyInverse(e,j0):e;if(n.action==="fill")s=u.contains(f.x,f.y);else{const m=l;s=u.strokeContains(f.x,f.y,m.width,m.alignment)}const p=o.hole;if(p){const m=p.shapePath?.shapePrimitives;if(m)for(let g=0;g<m.length;g++)m[g].shape.contains(f.x,f.y)&&(s=!1)}if(s)return!0}}return s}unload(){this.emit("unload",this);for(const e in this._gpuData)this._gpuData[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?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};Sa.defaultFillStyle={color:16777215,alpha:1,texture:H.WHITE,matrix:null,fill:null,textureSpace:"local"};Sa.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:H.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let qe=Sa;class Lf{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 qo({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 s=e[t],i=s.element;if(!s.parent||s.globalDisplayStatus<7)i?.remove(),e.splice(t,1),t--;else{this._domElement.contains(i)||(i.style.position="absolute",i.style.pointerEvents="auto",this._domElement.appendChild(i));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;i.style.transformOrigin=`${a}px ${l}px`,i.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,i.style.opacity=s.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)this._attachedDomElements[e].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Lf.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"dom"};class q0{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||(We.system.add(this._tickerUpdate,this,rs.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(We.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 ht=new q0;class yr extends Bs{constructor(){super(...arguments),this.client=new he,this.movement=new he,this.offset=new he,this.global=new he,this.screen=new he}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,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,i,n,o,a,l,h,c,u,d,f,p,m){throw new Error("Method not implemented.")}}class Fe extends yr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1,this.persistentDeviceId=0}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class os extends yr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}os.DOM_DELTA_PIXEL=0;os.DOM_DELTA_LINE=1;os.DOM_DELTA_PAGE=2;const Y0=2048,K0=new he,Xs=new he;class Of{constructor(e){this.dispatch=new Re,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.mapContextMenu=this.mapContextMenu.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),this.addEventMapping("contextmenu",this.mapContextMenu)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,i)=>s.priority-i.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 s=0,i=t.length;s<i;s++)t[s].fn(e);else N(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){ht.pauseUpdate=!0;const i=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[i](this.rootTarget,this.rootTarget.eventMode,K0.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let i=0,n=s.length-1;i<n;i++)if(e.currentTarget=s[i],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 i=s.length-2;i>=0;i--)if(e.currentTarget=s[i],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const i=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)i.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<Y0&&e!==this.rootTarget&&e.parent;s++){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,s,i,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(ht.pauseUpdate=!1),e.interactiveChildren&&e.children){const c=e.children;for(let u=c.length-1;u>=0;u--){const d=c[u],f=this.hitTestMoveRecursive(d,this._isInteractive(t)?t:d.eventMode,s,i,n,o||n(e,s));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const p=e.isInteractive();(f.length>0||p)&&(p&&this._allInteractiveElements.push(e),f.push(e)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(t),h=e.isInteractive();return h&&h&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&i(e,s)?h?[e]:[]:null}hitTestRecursive(e,t,s,i,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(ht.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,h=s;for(let c=l.length-1;c>=0;c--){const u=l[c],d=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,h,i,n);if(d){if(d.length>0&&!d[d.length-1].parent)continue;const f=e.isInteractive();return(d.length>0||f)&&d.push(e),d}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&i(e,s)?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 s=0;s<e.effects.length;s++){const i=e.effects[s];if(i.containsPoint&&!i.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e?.containsPoint?(e.worldTransform.applyInverse(t,Xs),e.containsPoint(Xs)):!1}notifyTarget(e,t){if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;e.currentTarget[s]?.(e);const i=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,i),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof Fe)){N("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 i=t.button===2;this.dispatchEvent(t,i?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){if(!(e instanceof Fe)){N("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 s=t.pointerType==="mouse"||t.pointerType==="pen",i=this.trackingData(e.pointerId),n=this.findMountedTarget(i.overTargets);if(i.overTargets?.length>0&&n!==t.target){const l=e.type==="mousemove"?"mouseout":"pointerout",h=this.createPointerEvent(e,l,n);if(this.dispatchEvent(h,"pointerout"),s&&this.dispatchEvent(h,"mouseout"),!t.composedPath().includes(n)){const c=this.createPointerEvent(e,"pointerleave",n);for(c.eventPhase=c.AT_TARGET;c.target&&!t.composedPath().includes(c.target);)c.currentTarget=c.target,this.notifyTarget(c),s&&this.notifyTarget(c,"mouseleave"),c.target=c.target.parent;this.freeEvent(c)}this.freeEvent(h)}if(n!==t.target){const l=e.type==="mousemove"?"mouseover":"pointerover",h=this.clonePointerEvent(t,l);this.dispatchEvent(h,"pointerover"),s&&this.dispatchEvent(h,"mouseover");let c=n?.parent;for(;c&&c!==this.rootTarget.parent&&c!==t.target;)c=c.parent;if(!c||c===this.rootTarget.parent){const d=this.clonePointerEvent(t,"pointerenter");for(d.eventPhase=d.AT_TARGET;d.target&&d.target!==n&&d.target!==this.rootTarget.parent;)d.currentTarget=d.target,this.notifyTarget(d),s&&this.notifyTarget(d,"mouseenter"),d.target=d.target.parent;this.freeEvent(d)}this.freeEvent(h)}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")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=t.target?.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,i.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),i=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),i&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=s.target?.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",i=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",i);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",i);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&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 Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const i=this.trackingData(e.pointerId),n=this.findMountedTarget(i.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete i.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,i.clicksByButton[e.button]||(i.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=i.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 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(s)}mapPointerUpOutside(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),i=this.createPointerEvent(e);if(s){let n=s;for(;n;)i.currentTarget=n,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch"?this.notifyTarget(i,"touchendoutside"):(i.pointerType==="mouse"||i.pointerType==="pen")&&this.notifyTarget(i,i.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(i)}mapWheel(e){if(!(e instanceof os)){N("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}mapContextMenu(e){if(!(e instanceof Fe)){N("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);this.dispatchEvent(t,"contextmenu"),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const i=this.allocateEvent(Fe);return this.copyPointerData(e,i),this.copyMouseData(e,i),this.copyData(e,i),i.nativeEvent=e.nativeEvent,i.originalEvent=e,i.target=s??this.hitTest(i.global.x,i.global.y)??this._hitElements[0],typeof t=="string"&&(i.type=t),i}createWheelEvent(e){const t=this.allocateEvent(os);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 s=this.allocateEvent(Fe);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof Fe&&t instanceof Fe&&(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,t.persistentDeviceId=e.persistentDeviceId)}copyMouseData(e,t){e instanceof yr&&t instanceof yr&&(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 s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let i=0,n=s.length;i<n&&!e.propagationImmediatelyStopped;i++)s[i].once&&e.currentTarget.removeListener(t,s[i].fn,void 0,!0),s[i].fn.call(s[i].context,e)}}const Z0=1,Q0={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Ca=class yo{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new Of(null),ht.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new Fe(null),this._rootWheelEvent=new os(null),this._rootContextMenuEvent=new Fe(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...yo.defaultEventFeatures},{set:(t,s,i)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=i),t[s]=i,!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._onContextMenu=this._onContextMenu.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,yo._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){ht.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 s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);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 s=0,i=t.length;s<i;s++){const n=t[s],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,ht.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);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 s=t!==this.domElement?"outside":"",i=this._normalizeToPointerData(e);for(let n=0,o=i.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,i[n]);a.type+=s,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 s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onContextMenu(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,i=t.length;s<i;s++){const n=this._bootstrapEvent(this._rootContextMenuEvent,t[s]);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,ht.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;ht.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.domElement.addEventListener("contextmenu",this._onContextMenu,!0),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;ht.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.removeEventListener("contextmenu",this._onContextMenu,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const i=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-i.left)*(this.domElement.width/i.width)*n,e.y=(s-i.top)*(this.domElement.height/i.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,i=e.changedTouches.length;s<i;s++){const n=e.changedTouches[s];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 s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=Z0),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}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=Q0[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}};Ca.extension={name:"events",type:[S.WebGLSystem,S.CanvasSystem,S.WebGPUSystem],priority:-1};Ca.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Uf=Ca;const J0={onclick:null,oncontextmenu: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(r){this.eventMode=r?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Uf.defaultEventMode},set eventMode(r){this._internalEventMode=r},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(r,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,i=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;r=s?`${r}capture`:r;const a=typeof e=="function"?e:e.handleEvent,l=this;i&&i.addEventListener("abort",()=>{l.off(r,a,o)}),n?l.once(r,a,o):l.on(r,a,o)},removeEventListener(r,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,i=typeof e=="function"?void 0:e;r=s?`${r}capture`:r,e=typeof e=="function"?e:e.handleEvent,this.off(r,e,i)},dispatchEvent(r){if(!(r instanceof Bs))throw new Error("Container cannot propagate events outside of the Federated Events API");return r.defaultPrevented=!1,r.path=null,r.target=this,r.manager.dispatchEvent(r),!r.defaultPrevented}};let fs;function bc(r){const e=J.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=r,t.fillRect(0,0,6,1),e}function Ma(){if(fs!==void 0)return fs;try{const r=bc("#ff00ff"),e=bc("#ffff00"),s=J.get().createCanvas(6,1).getContext("2d");s.globalCompositeOperation="multiply",s.drawImage(r,0,0),s.drawImage(e,2,0);const i=s.getImageData(2,0,1,1);if(!i)fs=!1;else{const n=i.data;fs=n[0]===255&&n[1]===0&&n[2]===0}}catch{fs=!1}return fs}const Y={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:Ma(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:r=>{const e=r.source,t=e?.resource;if(!t)return null;const s=e.alphaMode==="premultiplied-alpha",i=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=i!==e.pixelWidth||n!==e.pixelHeight;if(s){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=Y._unpremultipliedCache.get(e);if(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=Y._canvasSourceCache.get(e);if(a?.resourceId===e._resourceId)return a.canvas;const l=J.get().createCanvas(e.pixelWidth,e.pixelHeight),h=l.getContext("2d"),c=h.createImageData(e.pixelWidth,e.pixelHeight),u=c.data,d=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let f=0;f<u.length&&f+3<d.length;f+=4)u[f]=d[f+2],u[f+1]=d[f+1],u[f+2]=d[f],u[f+3]=d[f+3];else u.set(d.subarray(0,u.length));return h.putImageData(c,0,0),Y._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(s){const a=J.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 h=l.getImageData(0,0,a.width,a.height),c=h.data;for(let u=0;u<c.length;u+=4){const d=c[u+3];if(d>0){const f=255/d;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),Y._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=Y._canvasSourceCache.get(e);if(a?.resourceId===e._resourceId)return a.canvas;const l=J.get().createCanvas(e.pixelWidth,e.pixelHeight),h=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,h.drawImage(t,0,0),Y._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(r,e)=>{const t=r.texture,s=oe.shared.setValue(e).toHex(),i=t.tintCache||(t.tintCache={}),n=i[s],o=t.source._resourceId;if(n?.tintId===o)return n;const a=n&&"getContext"in n?n:J.get().createCanvas();return Y.tintMethod(t,e,a),a.tintId=o,i[s]=a,i[s]},getTintedPattern:(r,e)=>{const t=oe.shared.setValue(e).toHex(),s=r.patternCache||(r.patternCache={}),i=r.source._resourceId;let n=s[t];return n?.tintId===i||(Y.canvas||(Y.canvas=J.get().createCanvas()),Y.tintMethod(r,e,Y.canvas),n=Y.canvas.getContext("2d").createPattern(Y.canvas,"repeat"),n.tintId=i,s[t]=n),n},applyPatternTransform:(r,e,t=!0)=>{if(!e)return;const s=r;if(!s.setTransform)return;const i=globalThis.DOMMatrix;if(!i)return;const n=new i([e.a,e.b,e.c,e.d,e.tx,e.ty]);s.setTransform(t?n.inverse():n)},tintWithMultiply:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),e!==16777215&&(s.fillStyle=oe.shared.setValue(e).toHex(),s.fillRect(0,0,l,h),s.globalCompositeOperation="multiply");const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),e!==16777215&&(s.globalCompositeOperation="destination-atop",s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height)),s.restore()},tintWithOverlay:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),s.globalCompositeOperation="copy",s.fillStyle=oe.shared.setValue(e).toHex(),s.fillRect(0,0,l,h),s.globalCompositeOperation="destination-atop";const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),s.restore()},tintWithPerPixel:(r,e,t)=>{const s=t.getContext("2d"),i=r.frame.clone(),n=r.source._resolution??r.source.resolution??1,o=r.rotate;i.x*=n,i.y*=n,i.width*=n,i.height*=n;const a=Z.isVertical(o),l=a?i.height:i.width,h=a?i.width:i.height;t.width=Math.ceil(l),t.height=Math.ceil(h),s.save(),s.globalCompositeOperation="copy";const c=Y.getCanvasSource(r);if(!c){s.restore();return}o&&Y._applyInverseRotation(s,o,i.width,i.height),s.drawImage(c,i.x,i.y,i.width,i.height,0,0,i.width,i.height),s.restore();const u=e>>16&255,d=e>>8&255,f=e&255,p=s.getImageData(0,0,l,h),m=p.data;for(let g=0;g<m.length;g+=4)m[g]=m[g]*u/255,m[g+1]=m[g+1]*d/255,m[g+2]=m[g+2]*f/255;s.putImageData(p,0,0)},_applyInverseRotation:(r,e,t,s)=>{const i=Z.inv(e),n=Z.uX(i),o=Z.uY(i),a=Z.vX(i),l=Z.vY(i),h=-Math.min(0,n*t,a*s,n*t+a*s),c=-Math.min(0,o*t,l*s,o*t+l*s);r.transform(n,o,a,l,h,c)}};Y.tintMethod=Y.canUseMultiply?Y.tintWithMultiply:Y.tintWithPerPixel;const Cn=32767;function vc(r,e){return(r<<17)+(e<<2)}class Nf{constructor(e){this._buckets=new Map,this._screens=new No,this._enableFullScreen=!1,this.canvasOptions=e||{}}get enableFullScreen(){return O(lt,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen}set enableFullScreen(e){O(lt,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen=e}_createCanvasAndContext(e,t){const s=J.get().createCanvas();s.width=e,s.height=t;const i=s.getContext("2d");return{canvas:s,context:i}}getOptimalCanvasAndContext(e,t,s=1){const{width:i,height:n}=this.getOptimalSize(e,t,s);(i>Cn||n>Cn)&&N(`CanvasPool: ${i}x${n} is larger than the ${Cn}px pool key limit, canvases of this size may be pooled together`);const o=vc(i,n);let a=this._buckets.get(o);a||(a=[],this._buckets.set(o,a));let l=a.pop();return l||(l=this._createCanvasAndContext(i,n)),l}getOptimalSize(e,t,s=1){const i=Math.ceil(e*s-1e-6),n=Math.ceil(t*s-1e-6),o=es(i),a=this._screens.getFittingWidth(i),l=es(n),h=this._screens.getFittingHeight(n);return{width:a!==void 0?Math.min(a,o):o,height:h!==void 0?Math.min(h,l):l}}returnCanvasAndContext(e){const t=e.canvas,{width:s,height:i}=t,n=this._buckets.get(vc(s,i));n&&(e.context.resetTransform(),e.context.clearRect(0,0,s,i),n.push(e))}setScreenSize(e,t,s){this._screens.set(e,t,s)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(const[e]of this._buckets){const t=e>>>17,s=e>>>2&32767;(ts(t)||this._screens.hasWidth(t))&&(ts(s)||this._screens.hasHeight(s))||this._buckets.delete(e)}}}const Mt=new Nf;as.register(Mt);const wc=new L;function Ea(r,e){e.clear();const t=e.matrix;for(let s=0;s<r.length;s++){const i=r[s];if(i.globalDisplayStatus<7)continue;const n=i.renderGroup??i.parentRenderGroup;n?.isCachedAsTexture?e.matrix=wc.copyFrom(n.textureOffsetInverseTransform).append(i.worldTransform):n?._parentCacheAsTextureRenderGroup?e.matrix=wc.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(i.groupTransform):e.matrix=i.worldTransform,e.addBounds(i.bounds)}return e.matrix=t,e}const ey=new ke;function ka(r,e,t,s,i=!1,n){const o=ey;o.minX=0,o.minY=0,o.maxX=r.width/s|0,o.maxY=r.height/s|0;const a=Te.getOptimalTexture({width:o.width,height:o.height,resolution:s,autoGenerateMipmaps:i,scaleMode:n});return a.source.uploadMethodId="image",a.source.resource=r,a.source.alphaMode="premultiply-alpha-on-upload",a.frame.width=e/s,a.frame.height=t/s,a.source.emit("update",a.source),a.updateUvs(),a}function xo(r){return typeof r.getCanvasFilterString=="function"}class ty{constructor(){this.skip=!1,this.useClip=!1,this.filters=null,this.container=null,this.bounds=new ke,this.cssFilterString=""}}class Hf{constructor(e){this._filterStack=[],this._filterStackIndex=0,this._savedStates=[],this._alphaMultiplier=1,this._warnedFilterTypes=new Set,this.renderer=e}push(e){const t=this._pushFilterFrame(),s=e.filterEffect.filters;if(t.skip=!1,t.useClip=!1,t.filters=s,t.container=e.container,t.cssFilterString="",s.every(l=>!l.enabled)){t.skip=!0;return}const i=[],n=1;for(const l of s){if(!l.enabled)continue;if(!xo(l)){this._warnUnsupportedFilter(l);continue}const h=l.getCanvasFilterString();if(h===null){this._warnUnsupportedFilter(l);continue}h&&i.push(h)}if(i.length===0&&n===1){t.skip=!0;return}t.cssFilterString=i.join(" "),this._calculateFilterArea(e,t.bounds),t.useClip=!!e.filterEffect.filterArea;const o=this.renderer.canvasContext.activeContext,a=o.filter||"none";if(this._savedStates.push({filter:a,alphaMultiplier:this._alphaMultiplier}),t.useClip&&Number.isFinite(t.bounds.width)&&Number.isFinite(t.bounds.height)&&t.bounds.width>0&&t.bounds.height>0){const l=this.renderer.canvasContext.activeResolution||1;o.save(),o.setTransform(1,0,0,1,0,0),o.beginPath(),o.rect(t.bounds.x*l,t.bounds.y*l,t.bounds.width*l,t.bounds.height*l),o.clip()}else t.useClip=!1;t.cssFilterString&&(o.filter=a!=="none"?`${a} ${t.cssFilterString}`:t.cssFilterString)}pop(){const e=this._popFilterFrame();if(e.skip)return;const t=this._savedStates.pop();if(!t)return;const s=this.renderer.canvasContext.activeContext;e.useClip?s.restore():s.filter=t.filter,this._alphaMultiplier=t.alphaMultiplier}generateFilteredTexture({texture:e,filters:t}){if(!t?.length||t.every(_=>!_.enabled))return e;const s=[],i=1;for(const _ of t){if(!_.enabled)continue;if(!xo(_)){this._warnUnsupportedFilter(_);continue}const x=_.getCanvasFilterString();if(x===null){this._warnUnsupportedFilter(_);continue}x&&s.push(x)}if(s.length===0&&i===1)return e;const n=Y.getCanvasSource(e);if(!n)return e;const o=e.frame,a=e.source._resolution??e.source.resolution??1,l=o.width,h=o.height,c=Mt.getOptimalCanvasAndContext(l,h,a),{canvas:u,context:d}=c;d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,u.width,u.height),s.length&&(d.filter=s.join(" "));const f=o.x*a,p=o.y*a,m=l*a,g=h*a;return d.drawImage(n,f,p,m,g,0,0,m,g),d.filter="none",d.globalAlpha=1,ka(u,l,h,a)}_calculateFilterArea(e,t){if(e.renderables?Ea(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 i=(e.container.renderGroup||e.container.parentRenderGroup)?.cacheToLocalTransform;i&&t.applyMatrix(i)}}_warnUnsupportedFilter(e){const t=e?.constructor?.name||"Filter";this._warnedFilterTypes.has(t)||(this._warnedFilterTypes.add(t),console.warn(`CanvasRenderer: filter "${t}" is not supported in Canvas2D and will be skipped.`))}get alphaMultiplier(){return this._alphaMultiplier}_pushFilterFrame(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new ty),this._filterStackIndex++,e}_popFilterFrame(){return this._filterStackIndex<=0?this._filterStack[0]:(this._filterStackIndex--,this._filterStack[this._filterStackIndex])}destroy(){this._filterStack=null,this._savedStates=null,this._warnedFilterTypes=null,this._alphaMultiplier=1}}Hf.extension={type:[S.CanvasSystem],name:"filter"};var zf=`in vec2 aPosition;
254
254
  out vec2 vTextureCoord;
255
255
 
256
256
  uniform vec4 uInputSize;
@@ -332,7 +332,7 @@ fn mainFragment(
332
332
  ) -> @location(0) vec4<f32> {
333
333
  return textureSample(uTexture, uSampler, uv);
334
334
  }
335
- `;class $f extends Jo{constructor(){const e=Ft.from({vertex:{source:bo,entryPoint:"mainVertex"},fragment:{source:bo,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=ls.from({vertex:zf,fragment:Wf,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class Vf{constructor(e){this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.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}}Vf.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"filter"};const sy=new Ei({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 ry{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new ke,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class Xf{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new rt({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 St({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){const t=this.renderer,s=e.filterEffect.filters,i=this._pushFilterData();i.skip=!1,i.filters=s,i.container=e.container,i.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(s.every(c=>!c.enabled)){i.skip=!0;return}const l=i.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(i,t.renderTarget.rootViewPort,a,o,1),i.skip)return;const h=this._getPreviousFilterData();this._setupFilterTextures(i,l,t,h)}generateFilteredTexture({texture:e,filters:t}){if(t.every(c=>!c.enabled))return e;const s=this._pushFilterData();this._activeFilterData=s,s.skip=!1,s.filters=t;const i=e.source,n=i.resolution,o=i.antialias,a=s.bounds;if(a.clear(),a.addRect(e.frame),this._calculateFilterBounds(s,a.rectangle,o,n,0),s.skip)return this._popFilterData(),e;s.outputRenderSurface=Te.getOptimalTexture({width:a.width,height:a.height,resolution:s.resolution,antialias:s.antialias}),s.backTexture=H.EMPTY,s.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(s,!0);const h=s.outputRenderSurface;return h.source.alphaMode="premultiplied-alpha",this._popFilterData(),h}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&&Te.returnTexture(t.backTexture),Te.returnTexture(t.inputTexture))}getBackTexture(e,t,s){const i=e.colorTexture.source._resolution,n=Te.getOptimalTexture({width:t.width,height:t.height,resolution:i});let o=t.minX,a=t.minY;s&&(o-=s.minX,a-=s.minY),o=Math.floor(o*i),a=Math.floor(a*i);const l=Math.ceil(t.width*i),h=Math.ceil(t.height*i);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:h},{x:0,y:0}),n}applyFilter(e,t,s,i){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===s,h=this._findClosestFilterData(),c=h?h.inputTexture.source._resolution:n.renderTarget.rootRenderTarget.colorTexture.source._resolution;let u=0,d=0;l&&h&&(u=h.bounds.minX,d=h.bounds.minY),this._updateFilterUniforms(t,s,o,u,d,c,l,i);const f=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(f,t,n)}calculateSpriteMatrix(e,t){const s=this._activeFilterData,i=e.set(s.inputTexture._source.width,0,0,s.inputTexture._source.height,s.bounds.minX,s.bounds.minY),n=t.worldTransform.copyTo(L.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),i.prepend(n),i.scale(1/t.texture.orig.width,1/t.texture.orig.height),i.translate(t.anchor.x,t.anchor.y),i}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new $f),this._passthroughFilter}_setupBindGroupsAndRender(e,t,s){if(s.renderPipes.uniformBatch){const i=s.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(i,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,s.encoder.draw({geometry:sy,shader:e,state:e._state,topology:"triangle-list"}),s.type===Ke.WEBGL&&s.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,s,i){if(e.backTexture=H.EMPTY,e.inputTexture=Te.getOptimalTexture({width:t.width,height:t.height,resolution:e.resolution,antialias:e.antialias}),e.blendRequired){s.renderTarget.finishRenderPass();const n=s.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,i?.bounds)}s.renderTarget.bind({target:e.inputTexture,clear:!0}),s.globalUniforms.push({offset:t})}_updateFilterUniforms(e,t,s,i,n,o,a,l){const h=this._filterGlobalUniforms.uniforms,c=h.uOutputFrame,u=h.uInputSize,d=h.uInputPixel,f=h.uInputClamp,p=h.uGlobalFrame,m=h.uOutputTexture;a?(c[0]=s.bounds.minX-i,c[1]=s.bounds.minY-n):(c[0]=0,c[1]=0),c[2]=e.frame.width,c[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],d[0]=e.source.pixelWidth,d[1]=e.source.pixelHeight,d[2]=1/d[0],d[3]=1/d[1],f[0]=.5*d[2],f[1]=.5*d[3],f[2]=e.frame.width*u[2]-.5*d[2],f[3]=e.frame.height*u[3]-.5*d[3];const g=this.renderer.renderTarget.rootRenderTarget.colorTexture;p[0]=i*o,p[1]=n*o,p[2]=g.source.width*o,p[3]=g.source.height*o,t instanceof H&&(t.source.resource=null);const _=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind({target:t,clear:!!l}),t instanceof H?(m[0]=t.frame.width,m[1]=t.frame.height):(m[0]=_.width,m[1]=_.height),m[2]=_.isRoot?-1:1,this._filterGlobalUniforms.update()}_findClosestFilterData(){for(let e=this._filterStackIndex-1;e>=0;e--){const t=this._filterStack[e];if(!t.skip)return t}return null}_calculateFilterArea(e,t){if(e.renderables?Ea(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 i=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;i&&t.applyMatrix(i)}}_applyFiltersToTexture(e,t){const s=e.inputTexture,i=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(s.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,s,e.outputRenderSurface,t);else{let l=e.inputTexture;const h=Te.getOptimalTexture({width:i.width,height:i.height,resolution:l.source._resolution});let c=h;for(let u=o;u<a;u++){const d=n[u];if(!d.enabled)continue;d.apply(this,l,c,!0);const f=l;l=c,c=f}n[a].apply(this,l,e.outputRenderSurface,t),Te.returnTexture(h)}}_calculateFilterBounds(e,t,s,i,n){const o=this.renderer,a=e.bounds,l=e.filters;let h=1/0,c=0,u=!0,d=!1,f=!1,p=!0,m=-1,g=-1;for(let _=0;_<l.length;_++){const x=l[_];if(!x.enabled)continue;if(m===-1&&(m=_),g=_,h=Math.min(h,x.resolution==="inherit"?i:x.resolution),c+=x.padding,x.antialias==="off"?u=!1:x.antialias==="inherit"&&u&&(u=s),x.clipToViewport||(p=!1),!!!(x.compatibleRenderers&o.type)){f=!1;break}if(x.blendRequired&&!(o.backBuffer?.useBackBuffer??!0)){N("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),f=!1;break}f=!0,d||(d=x.blendRequired)}if(!f){e.skip=!0;return}if(p&&a.fitBounds(0,t.width/i,0,t.height/i),a.scale(h).ceil().scale(1/h).pad((c|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=h,e.blendRequired=d,e.firstEnabledIndex=m,e.lastEnabledIndex=g}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){for(let e=this._filterStackIndex-2;e>=0;e--){const t=this._filterStack[e];if(!t.skip)return t}return null}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new ry),this._filterStackIndex++,e}}Xf.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"filter"};var jf=`in vec2 vMaskCoord;
335
+ `;class $f extends Jo{constructor(){const e=Ft.from({vertex:{source:bo,entryPoint:"mainVertex"},fragment:{source:bo,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=ls.from({vertex:zf,fragment:Wf,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class Vf{constructor(e){this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.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}}Vf.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"filter"};const sy=new Ei({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 ry{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new ke,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class Xf{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new rt({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 St({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){const t=this.renderer,s=e.filterEffect.filters,i=this._pushFilterData();i.skip=!1,i.filters=s,i.container=e.container,i.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(s.every(c=>!c.enabled)){i.skip=!0;return}const l=i.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(i,t.renderTarget.rootViewPort,a,o,1),i.skip)return;const h=this._getPreviousFilterData();this._setupFilterTextures(i,l,t,h)}generateFilteredTexture({texture:e,filters:t}){if(t.every(c=>!c.enabled))return e;const s=this._pushFilterData();this._activeFilterData=s,s.skip=!1,s.filters=t;const i=e.source,n=i.resolution,o=i.antialias,a=s.bounds;if(a.clear(),a.addRect(e.frame),this._calculateFilterBounds(s,a.rectangle,o,n,0),s.skip)return this._popFilterData(),e;s.outputRenderSurface=Te.getOptimalTexture({width:a.width,height:a.height,resolution:s.resolution,antialias:s.antialias}),s.backTexture=H.EMPTY,s.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(s,!0);const h=s.outputRenderSurface;return h.source.alphaMode="premultiplied-alpha",this._popFilterData(),h}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&&Te.returnTexture(t.backTexture),Te.returnTexture(t.inputTexture))}getBackTexture(e,t,s){const i=e.colorTexture.source._resolution,n=Te.getOptimalTexture({width:t.width,height:t.height,resolution:i});let o=t.minX,a=t.minY;s&&(o-=s.minX,a-=s.minY),o=Math.floor(o*i),a=Math.floor(a*i);const l=Math.ceil(t.width*i),h=Math.ceil(t.height*i);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:h},{x:0,y:0}),n}applyFilter(e,t,s,i){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===s,h=this._findClosestFilterData(),c=h?h.inputTexture.source._resolution:n.renderTarget.rootRenderTarget.colorTexture.source._resolution;let u=0,d=0;l&&h&&(u=h.bounds.minX,d=h.bounds.minY),this._updateFilterUniforms(t,s,o,u,d,c,l,i);const f=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(f,t,n)}calculateSpriteMatrix(e,t){const s=this._activeFilterData,i=e.set(s.inputTexture._source.width,0,0,s.inputTexture._source.height,s.bounds.minX,s.bounds.minY),n=t.worldTransform.copyTo(L.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),i.prepend(n),i.scale(1/t.texture.orig.width,1/t.texture.orig.height),i.translate(t.anchor.x,t.anchor.y),i}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new $f),this._passthroughFilter}_setupBindGroupsAndRender(e,t,s){if(s.renderPipes.uniformBatch){const i=s.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(i,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,s.encoder.draw({geometry:sy,shader:e,state:e._state,topology:"triangle-list"}),s.type===Ke.WEBGL&&s.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,s,i){if(e.backTexture=H.EMPTY,e.inputTexture=Te.getOptimalTexture({width:t.width,height:t.height,resolution:e.resolution,antialias:e.antialias}),e.blendRequired){s.renderTarget.finishRenderPass();const n=s.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,i?.bounds)}s.renderTarget.bind({target:e.inputTexture,clear:!0}),s.globalUniforms.push({offset:t})}_updateFilterUniforms(e,t,s,i,n,o,a,l){const h=this._filterGlobalUniforms.uniforms,c=h.uOutputFrame,u=h.uInputSize,d=h.uInputPixel,f=h.uInputClamp,p=h.uGlobalFrame,m=h.uOutputTexture;a?(c[0]=s.bounds.minX-i,c[1]=s.bounds.minY-n):(c[0]=0,c[1]=0),c[2]=e.frame.width,c[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],d[0]=e.source.pixelWidth,d[1]=e.source.pixelHeight,d[2]=1/d[0],d[3]=1/d[1],f[0]=.5*d[2],f[1]=.5*d[3],f[2]=e.frame.width*u[2]-.5*d[2],f[3]=e.frame.height*u[3]-.5*d[3];const g=this.renderer.renderTarget.rootRenderTarget.colorTexture;p[0]=i*o,p[1]=n*o,p[2]=g.source.width*o,p[3]=g.source.height*o,t instanceof H&&(t.source.resource=null);const _=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind({target:t,clear:!!l}),t instanceof H?(m[0]=t.frame.width,m[1]=t.frame.height):(m[0]=_.width,m[1]=_.height),m[2]=_.isRoot?-1:1,this._filterGlobalUniforms.update()}_findClosestFilterData(){for(let e=this._filterStackIndex-1;e>=0;e--){const t=this._filterStack[e];if(!t.skip)return t}return null}_calculateFilterArea(e,t){if(e.renderables?Ea(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 i=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;i&&t.applyMatrix(i)}}_applyFiltersToTexture(e,t){const s=e.inputTexture,i=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(s.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,s,e.outputRenderSurface,t);else{let l=e.inputTexture;const h=Te.getOptimalTexture({width:i.width,height:i.height,resolution:l.source._resolution});let c=h;for(let u=o;u<a;u++){const d=n[u];if(!d.enabled)continue;d.apply(this,l,c,!0);const f=l;l=c,c=f}n[a].apply(this,l,e.outputRenderSurface,t),Te.returnTexture(h)}}_calculateFilterBounds(e,t,s,i,n){const o=this.renderer,a=e.bounds,l=e.filters;let h=1/0,c=0,u=!0,d=!1,f=!1,p=!0,m=-1,g=-1;for(let _=0;_<l.length;_++){const x=l[_];if(!x.enabled)continue;if(m===-1&&(m=_),g=_,h=Math.min(h,x.resolution==="inherit"?i:x.resolution),c+=x.padding,x.antialias==="off"?u=!1:x.antialias==="inherit"&&u&&(u=s),x.clipToViewport||(p=!1),!!!(x.compatibleRenderers&o.type)){f=!1;break}if(x.blendRequired&&!(o.backBuffer?.useBackBuffer??!0)){N("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),f=!1;break}f=!0,d||(d=x.blendRequired)}if(!f){e.skip=!0;return}if(p&&a.fitBounds(0,t.width/i,0,t.height/i),a.scale(h).ceil().scale(1/h).pad((c|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=h,e.blendRequired=d,e.firstEnabledIndex=m,e.lastEnabledIndex=g}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){for(let e=this._filterStackIndex-2;e>=0;e--){const t=this._filterStack[e];if(!t.skip)return t}return null}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new ry),this._filterStackIndex++,e}}Xf.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"filter"};var jf=`in vec2 vMaskCoord;
336
336
  in vec2 vTextureCoord;
337
337
 
338
338
  uniform sampler2D uTexture;
@@ -513,7 +513,7 @@ fn mainFragment(
513
513
 
514
514
  return source * a;
515
515
  }
516
- `;class Yf extends Jo{constructor(e){const{sprite:t,...s}=e,i=new Fo(t.texture),n=new rt({uFilterMatrix:{value:new L,type:"mat3x3<f32>"},uMaskClamp:{value:i.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"},uChannel:{value:e.channel==="alpha"?1:0,type:"f32"}}),o=Ft.from({vertex:{source:vo,entryPoint:"mainVertex"},fragment:{source:vo,entryPoint:"mainFragment"}}),a=ls.from({vertex:qf,fragment:jf,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=i}setSprite(e){this.sprite=e;const t=this._getSafeTexture();this._textureMatrix.texture=t,this.resources.uMaskTexture=t.source}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}set channel(e){this.resources.filterUniforms.uniforms.uChannel=e==="alpha"?1:0}get channel(){return this.resources.filterUniforms.uniforms.uChannel===1?"alpha":"red"}apply(e,t,s,i){const n=this._getSafeTexture();this._textureMatrix.texture=n,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=n.source,e.applyFilter(this,t,s,i)}_getSafeTexture(){const e=this.sprite.texture;return e.destroyed||!e.source||e.source.destroyed?(N("[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture."),H.EMPTY):e}destroy(e=!1){this._textureMatrix.destroy(),super.destroy(e)}}class iy{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class ny{constructor(){this.instructions=new xi}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Pa=class wo{constructor(e){this._renderer=e,this._managedContexts=new it({renderer:e,type:"resource",name:"graphicsContext"})}init(e){wo.defaultOptions.bezierSmoothness=e?.bezierSmoothness??wo.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,s=!!t[this._renderer.uid],i=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!s)&&(s&&i.reset(),i.isBatchable=!1,e.dirty=!1),i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new ny,s=this.getGpuContext(e);return s.graphicsData=t,t.init(),t}_initContext(e){const t=new iy;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Pa.extension={type:[C.CanvasSystem],name:"graphicsContext"};Pa.defaultOptions={bezierSmoothness:.5};let Kf=Pa;class Aa{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new it({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}}Aa.extension={type:[C.CanvasPipes],name:"graphics"};function Ra(r,e,t){const s=(r>>24&255)/255;e[t++]=(r&255)/255*s,e[t++]=(r>>8&255)/255*s,e[t++]=(r>>16&255)/255*s,e[t++]=s}class Zf{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Se.return(e)}),this.batches.length=0}}class Ba{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new it({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||s!==n.isBatchable)}addRenderable(e,t){const i=this.renderer.graphicsContext.updateGpuContext(e.context);(e.didViewUpdate||!e._gpuData[this.renderer.uid])&&this._rebuild(e),i.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let i=0;i<s.length;i++){const n=s[i];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.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,Ra(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),i=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),i.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,i=this._getGpuDataForRenderable(e).batches;for(let n=0;n<i.length;n++){const o=i[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new Zf;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const s=e.context,n=this.renderer.graphicsContext.getGpuContext(s),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Se.get(Ii);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}}Ba.extension={type:[C.WebGLPipes,C.WebGPUPipes],name:"graphics"};q.add(Aa);q.add(Ba);q.add(Kf);q.add(Di);class Pe extends vi{constructor(e){e instanceof qe&&(e={context:e});const{context:t,roundPixels:s,...i}=e||{};super({label:"Graphics",...i}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new qe,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!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?.context===!0)&&this._context.destroy(e),this._context?.off("update",this.onViewUpdate,this),this._context?.off("unload",this.unload,this),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 Pe(this._context.clone()):(this._ownedContext=null,new Pe(this._context))}lineStyle(e,t,s){O(ue,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const i={};return e&&(i.width=e),t&&(i.color=t),s&&(i.alpha=s),this.context.strokeStyle=i,this}beginFill(e,t){O(ue,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){O(ue,"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!==qe.defaultStrokeStyle.width||e.color!==qe.defaultStrokeStyle.color||e.alpha!==qe.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return O(ue,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return O(ue,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return O(ue,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return O(ue,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return O(ue,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return O(ue,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const sr={name:"local-uniform-bit",vertex:{header:`
516
+ `;class Yf extends Jo{constructor(e){const{sprite:t,...s}=e,i=new Fo(t.texture),n=new rt({uFilterMatrix:{value:new L,type:"mat3x3<f32>"},uMaskClamp:{value:i.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"},uChannel:{value:e.channel==="alpha"?1:0,type:"f32"}}),o=Ft.from({vertex:{source:vo,entryPoint:"mainVertex"},fragment:{source:vo,entryPoint:"mainFragment"}}),a=ls.from({vertex:qf,fragment:jf,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=i}setSprite(e){this.sprite=e;const t=this._getSafeTexture();this._textureMatrix.texture=t,this.resources.uMaskTexture=t.source}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}set channel(e){this.resources.filterUniforms.uniforms.uChannel=e==="alpha"?1:0}get channel(){return this.resources.filterUniforms.uniforms.uChannel===1?"alpha":"red"}apply(e,t,s,i){const n=this._getSafeTexture();this._textureMatrix.texture=n,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=n.source,e.applyFilter(this,t,s,i)}_getSafeTexture(){const e=this.sprite.texture;return e.destroyed||!e.source||e.source.destroyed?(N("[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture."),H.EMPTY):e}destroy(e=!1){this._textureMatrix.destroy(),super.destroy(e)}}class iy{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class ny{constructor(){this.instructions=new xi}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Pa=class wo{constructor(e){this._renderer=e,this._managedContexts=new it({renderer:e,type:"resource",name:"graphicsContext"})}init(e){wo.defaultOptions.bezierSmoothness=e?.bezierSmoothness??wo.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,s=!!t[this._renderer.uid],i=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!s)&&(s&&i.reset(),i.isBatchable=!1,e.dirty=!1),i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new ny,s=this.getGpuContext(e);return s.graphicsData=t,t.init(),t}_initContext(e){const t=new iy;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Pa.extension={type:[S.CanvasSystem],name:"graphicsContext"};Pa.defaultOptions={bezierSmoothness:.5};let Kf=Pa;class Aa{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new it({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}}Aa.extension={type:[S.CanvasPipes],name:"graphics"};function Ra(r,e,t){const s=(r>>24&255)/255;e[t++]=(r&255)/255*s,e[t++]=(r>>8&255)/255*s,e[t++]=(r>>16&255)/255*s,e[t++]=s}class Zf{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Se.return(e)}),this.batches.length=0}}class Ba{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new it({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||s!==n.isBatchable)}addRenderable(e,t){const i=this.renderer.graphicsContext.updateGpuContext(e.context);(e.didViewUpdate||!e._gpuData[this.renderer.uid])&&this._rebuild(e),i.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let i=0;i<s.length;i++){const n=s[i];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.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,Ra(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),i=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),i.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,i=this._getGpuDataForRenderable(e).batches;for(let n=0;n<i.length;n++){const o=i[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new Zf;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const s=e.context,n=this.renderer.graphicsContext.getGpuContext(s),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Se.get(Ii);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}}Ba.extension={type:[S.WebGLPipes,S.WebGPUPipes],name:"graphics"};q.add(Aa);q.add(Ba);q.add(Kf);q.add(Di);class Pe extends vi{constructor(e){e instanceof qe&&(e={context:e});const{context:t,roundPixels:s,...i}=e||{};super({label:"Graphics",...i}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new qe,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!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?.context===!0)&&this._context.destroy(e),this._context?.off("update",this.onViewUpdate,this),this._context?.off("unload",this.unload,this),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 Pe(this._context.clone()):(this._ownedContext=null,new Pe(this._context))}lineStyle(e,t,s){O(ue,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const i={};return e&&(i.width=e),t&&(i.color=t),s&&(i.alpha=s),this.context.strokeStyle=i,this}beginFill(e,t){O(ue,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){O(ue,"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!==qe.defaultStrokeStyle.width||e.color!==qe.defaultStrokeStyle.color||e.alpha!==qe.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return O(ue,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return O(ue,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return O(ue,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return O(ue,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return O(ue,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return O(ue,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const sr={name:"local-uniform-bit",vertex:{header:`
517
517
 
518
518
  struct LocalUniforms {
519
519
  uTransformMatrix:mat3x3<f32>,
@@ -551,10 +551,10 @@ fn mainFragment(
551
551
  * @version 11.4.7
552
552
  */class ay{constructor(e=0,t=0,s=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=s,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 s=0;s<e.length;s++){const i=e[s];t[s]=[i,this.get(i)]}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,s=0;for(;t!==null;)e[s++]=t.key,t=t.next;return e}setWithEvicted(e,t,s=this.resetTtl){let i=null;if(this.has(e))this.set(e,t,!0,s);else{this.max>0&&this.size===this.max&&(i={...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 i}set(e,t,s=!1,i=this.resetTtl){let n=this.items[e];return s||n!==void 0?(n.value=t,s===!1&&i&&(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 s=0;s<e.length;s++)t[s]=this.get(e[s]);return t}}function ly(r=1e3,e=0,t=!1){if(isNaN(r)||r<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 ay(r,e,t)}function Ga(r){return!!r.tagStyles&&Object.keys(r.tagStyles).length>0}function Da(r){return r.includes("<")}function hy(r,e){return r.clone().assign(e)}function sp(r,e){const t=[],s=e.tagStyles;if(!Ga(e)||!Da(r))return t.push({text:r,style:e}),t;const i=[e],n=[];let o="",a=0;for(;a<r.length;){const l=r[a];if(l==="<"){const h=r.indexOf(">",a);if(h===-1){o+=l,a++;continue}const c=r.indexOf("<",a+1);if(c!==-1&&c<h){o+=l,a++;continue}const u=r.slice(a+1,h);if(u.startsWith("/")){const d=u.slice(1).trim();if(n.length>0&&n[n.length-1]===d){o.length>0&&(t.push({text:o,style:i[i.length-1]}),o=""),i.pop(),n.pop(),a=h+1;continue}else{o+=r.slice(a,h+1),a=h+1;continue}}else{const d=u.trim();if(s[d]){o.length>0&&(t.push({text:o,style:i[i.length-1]}),o="");const f=i[i.length-1],p=hy(f,s[d]);i.push(p),n.push(d),a=h+1;continue}else{o+=r.slice(a,h+1),a=h+1;continue}}}else o+=l,a++}return o.length>0&&t.push({text:o,style:i[i.length-1]}),t}const rp=[10,13],ip=new Set(rp),np=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],op=new Set(np),ap=[9,32];new Set(ap);const lp=[45,8208,8211,8212,173],hp=new Set(lp),cp=/(\r\n|\r|\n)/,up=/(?:\r\n|\r|\n)/;function xr(r){return typeof r!="string"?!1:ip.has(r.charCodeAt(0))}function $e(r,e){return typeof r!="string"?!1:op.has(r.charCodeAt(0))}function dp(r){return typeof r!="string"?!1:hp.has(r.charCodeAt(0))}function Fa(r){return r==="normal"||r==="pre-line"}function La(r){return r==="normal"}function at(r){if(typeof r!="string")return"";let e=r.length-1;for(;e>=0&&$e(r[e]);)e--;return e<r.length-1?r.slice(0,e+1):r}function Oa(r){const e=[],t=[];if(typeof r!="string")return e;for(let s=0;s<r.length;s++){const i=r[s],n=r[s+1];if($e(i)||xr(i)){t.length>0&&(e.push(t.join("")),t.length=0),i==="\r"&&n===`
553
553
  `?(e.push(`\r
554
- `),s++):e.push(i);continue}t.push(i),dp(i)&&n&&!$e(n)&&!xr(n)&&(e.push(t.join("")),t.length=0)}return t.length>0&&e.push(t.join("")),e}function Ua(r,e,t,s){const i=t(r),n=[];for(let o=0;o<i.length;o++){let a=i[o],l=a,h=1;for(;i[o+h];){const c=i[o+h];if(!s(l,c,r,o,e))a+=c,l=c,h++;else break}o+=h-1,n.push(a)}return n}const cy=/\r\n|\r|\n/g;function fp(r,e,t,s,i,n,o,a,l){const h=sp(r,e);if(La(e.whiteSpace))for(let F=0;F<h.length;F++){const X=h[F];h[F]={text:X.text.replace(cy," "),style:X.style}}const u=[];let d=[];for(const F of h){const X=F.text.split(cp);for(let R=0;R<X.length;R++){const M=X[R];M===`\r
554
+ `),s++):e.push(i);continue}t.push(i),dp(i)&&n&&!$e(n)&&!xr(n)&&(e.push(t.join("")),t.length=0)}return t.length>0&&e.push(t.join("")),e}function Ua(r,e,t,s){const i=t(r),n=[];for(let o=0;o<i.length;o++){let a=i[o],l=a,h=1;for(;i[o+h];){const c=i[o+h];if(!s(l,c,r,o,e))a+=c,l=c,h++;else break}o+=h-1,n.push(a)}return n}const cy=/\r\n|\r|\n/g;function fp(r,e,t,s,i,n,o,a,l){const h=sp(r,e);if(La(e.whiteSpace))for(let G=0;G<h.length;G++){const V=h[G];h[G]={text:V.text.replace(cy," "),style:V.style}}const u=[];let d=[];for(const G of h){const V=G.text.split(cp);for(let I=0;I<V.length;I++){const M=V[I];M===`\r
555
555
  `||M==="\r"||M===`
556
- `?(u.push(d),d=[]):M.length>0&&d.push({text:M,style:F.style})}}(d.length>0||u.length===0)&&u.push(d);const f=t?pp(u,e,s,n,a,l):u,p=[],m=[],g=[],_=[],x=[];let y=0;const b=e._fontString,w=o(b);w.fontSize===0&&(w.fontSize=e.fontSize,w.ascent=e.fontSize);let v="",S=!!e.dropShadow,E=e._stroke?.width||0;for(const F of f){let X=0,R=w.ascent,M=w.descent,G="";for(const U of F){const W=U.style._fontString,se=o(W);W!==v&&(s.font=W,v=W);const te=i(U.text,U.style.letterSpacing,s);X+=te,R=Math.max(R,se.ascent),M=Math.max(M,se.descent),G+=U.text;const ie=U.style._stroke?.width||0;ie>E&&(E=ie),!S&&U.style.dropShadow&&(S=!0)}F.length===0&&(R=w.ascent,M=w.descent),p.push(X),m.push(R),g.push(M),x.push(G);const B=e.lineHeight||R+M;_.push(B+e.leading),y=Math.max(y,X)}const k=E,P=y+k+(e.dropShadow?e.dropShadow.distance:0);let T=0;for(let F=0;F<_.length;F++)T+=_[F];T=Math.max(T,_[0]+k);const A=T+(e.dropShadow?e.dropShadow.distance:0),I=e.lineHeight||w.fontSize;return{width:P,height:A,lines:x,lineWidths:p,lineHeight:I+e.leading,maxLineWidth:y,fontProperties:w,runsByLine:f,lineAscents:m,lineDescents:g,lineHeights:_,hasDropShadow:S}}function pp(r,e,t,s,i,n){const{letterSpacing:o,whiteSpace:a,wordWrapWidth:l,breakWords:h}=e,c=Fa(a),u=l+o,d={};let f="";const p=(g,_)=>{const x=`${g}|${_.styleKey}`;let y=d[x];if(y===void 0){const b=_._fontString;b!==f&&(t.font=b,f=b),y=s(g,_.letterSpacing,t)+_.letterSpacing,d[x]=y}return y},m=[];for(const g of r){const _=mp(g),x=m.length,y=T=>{let A=0,I=T;do{const{token:F,style:X}=_[I];A+=p(F,X),I++}while(I<_.length&&_[I].continuesFromPrevious);return A},b=T=>{const A=[];let I=T;do A.push({token:_[I].token,style:_[I].style}),I++;while(I<_.length&&_[I].continuesFromPrevious);return A};let w=[],v=0,S=!c,E=null;const k=()=>{E&&E.text.length>0&&w.push(E),E=null},P=()=>{if(k(),w.length>0){const T=w[w.length-1];T.text=at(T.text),T.text.length===0&&w.pop()}m.push(w),w=[],v=0,S=!1};for(let T=0;T<_.length;T++){const{token:A,style:I,continuesFromPrevious:F}=_[T],X=p(A,I);if(c){const G=$e(A),B=E?.text[E.text.length-1]??w[w.length-1]?.text.slice(-1)??"",U=B?$e(B):!1;if(G&&U)continue}const R=!F,M=R?y(T):X;if(M>u&&R)if(v>0&&P(),h){const G=b(T);for(let B=0;B<G.length;B++){const U=G[B].token,W=G[B].style,se=Ua(U,h,n,i);for(const te of se){const ie=p(te,W);ie+v>u&&P(),!E||E.style!==W?(k(),E={text:te,style:W}):E.text+=te,v+=ie}}T+=G.length-1}else{const G=b(T);k(),m.push(G.map(B=>({text:B.token,style:B.style}))),S=!1,T+=G.length-1}else if(M+v>u&&R){if($e(A)){S=!1;continue}P(),E={text:A,style:I},v=X}else if(F&&!h)!E||E.style!==I?(k(),E={text:A,style:I}):E.text+=A,v+=X;else{const G=$e(A);if(v===0&&G&&!S)continue;!E||E.style!==I?(k(),E={text:A,style:I}):E.text+=A,v+=X}}if(k(),w.length>0){const T=w[w.length-1];T.text=at(T.text),T.text.length===0&&w.pop()}(w.length>0||m.length===x)&&m.push(w)}return m}function mp(r){const e=[];let t=!1;for(const s of r){const i=Oa(s.text);let n=!0;for(const o of i){const a=$e(o)||xr(o),l=n&&t&&!a;e.push({token:o,style:s.style,continuesFromPrevious:l}),t=!a,n=!1}}return e}const uy={willReadFrequently:!0};function Cc(r,e,t,s,i){let n=t[r];return typeof n!="number"&&(n=i(r,e,s)+e,t[r]=n),n}function gp(r,e,t,s,i,n,o){const a=t.getContext("2d",uy);a.font=e._fontString;let l=0,h="";const c=[],u=Object.create(null),{letterSpacing:d,whiteSpace:f}=e,p=Fa(f),m=La(f);let g=!p;const _=e.wordWrapWidth+d,x=Oa(r);for(let b=0;b<x.length;b++){let w=x[b];if(xr(w)){if(!m){c.push(at(h)),g=!p,h="",l=0;continue}w=" "}if(p){const S=$e(w),E=$e(h[h.length-1]);if(S&&E)continue}const v=Cc(w,d,u,a,s);if(v>_)if(h!==""&&(c.push(at(h)),h="",l=0),i(w,e.breakWords)){const S=Ua(w,e.breakWords,o,n);for(const E of S){const k=Cc(E,d,u,a,s);k+l>_&&(c.push(at(h)),g=!1,h="",l=0),h+=E,l+=k}}else h.length>0&&(c.push(at(h)),h="",l=0),c.push(at(w)),g=!1,h="",l=0;else v+l>_&&(g=!1,c.push(at(h)),h="",l=0),(h.length>0||!$e(w)||g)&&(h+=w,l+=v)}const y=at(h);return y.length>0&&c.push(y),c.join(`
557
- `)}const Mc={willReadFrequently:!0},Et=class z{static get experimentalLetterSpacingSupported(){let e=z._experimentalLetterSpacingSupported;if(e===void 0){const t=J.get().getCanvasRenderingContext2D().prototype;e=z._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,s,i,n,o,a,l,h,c){this.text=e,this.style=t,this.width=s,this.height=i,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(e=" ",t,s=z._canvas,i=t.wordWrap){const n=`${e}-${t.styleKey}-wordWrap-${i}`;if(z._measurementCache.has(n))return z._measurementCache.get(n);if(Ga(t)&&Da(e)){const b=fp(e,t,i,z._context,z._measureText,z._measureTextAdvance,z.measureFont,z.canBreakChars,z.wordWrapSplit),w=new z(e,t,b.width,b.height,b.lines,b.lineWidths,b.lineHeight,b.maxLineWidth,b.fontProperties,{runsByLine:b.runsByLine,lineAscents:b.lineAscents,lineDescents:b.lineDescents,lineHeights:b.lineHeights,hasDropShadow:b.hasDropShadow});return z._measurementCache.set(n,w),w}const a=t._fontString,l=z.measureFont(a);l.fontSize===0&&(l.fontSize=t.fontSize,l.ascent=t.fontSize,l.descent=0);const h=z._context;h.font=a;const u=(i?z._wordWrap(e,t,s):e).split(up),d=new Array(u.length);let f=0;for(let b=0;b<u.length;b++){const w=z._measureText(u[b],t.letterSpacing,h);d[b]=w,f=Math.max(f,w)}const p=t._stroke?.width??0,m=t.lineHeight||l.fontSize,g=z._adjustWidthForStyle(f,t),_=Math.max(m,l.fontSize+p)+(u.length-1)*(m+t.leading),x=z._adjustHeightForStyle(_,t),y=new z(e,t,g,x,u,d,m+t.leading,f,l);return z._measurementCache.set(n,y),y}static _adjustWidthForStyle(e,t){const s=t._stroke?.width||0;let i=e+s;return t.dropShadow&&(i+=t.dropShadow.distance),i}static _adjustHeightForStyle(e,t){let s=e;return t.dropShadow&&(s+=t.dropShadow.distance),s}static _measureText(e,t,s){const{metricWidth:i,metrics:n,letterSpacingVal:o}=z._measureTextCore(e,t,s),a=-(n.actualBoundingBoxLeft??0);let h=(n.actualBoundingBoxRight??0)-a;return n.width>0&&(h+=o),Math.max(i,h)}static _measureTextAdvance(e,t,s){return z._measureTextCore(e,t,s).metricWidth}static _measureTextCore(e,t,s){let i=!1;z.experimentalLetterSpacingSupported&&(z.experimentalLetterSpacing?(s.letterSpacing=`${t}px`,s.textLetterSpacing=`${t}px`,i=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));const n=s.measureText(e);let o=n.width,a=0;return o>0&&(i?a=-t:a=(z.graphemeSegmenter(e).length-1)*t,o+=a),{metricWidth:o,metrics:n,letterSpacingVal:a}}static _wordWrap(e,t,s=z._canvas){return gp(e,t,s,z._measureTextAdvance,z.canBreakWords,z.canBreakChars,z.wordWrapSplit)}static isBreakingSpace(e,t){return $e(e)}static canBreakWords(e,t){return t}static canBreakChars(e,t,s,i,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 s=t.measureText(z.METRICS_STRING+z.BASELINE_SYMBOL),i=s.actualBoundingBoxAscent??0,n=s.actualBoundingBoxDescent??0,o={ascent:i,descent:n,fontSize:i+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);if(t.getContext("2d",Mc)?.measureText)return z.__canvas=t,t;e=J.get().createCanvas()}catch{e=J.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",Mc)),z.__context}};Et.METRICS_STRING="|ÉqÅ";Et.BASELINE_SYMBOL="M";Et.BASELINE_MULTIPLIER=1.4;Et.HEIGHT_MULTIPLIER=2;Et.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const r=new Intl.Segmenter;return e=>{const t=r.segment(e),s=[];let i=0;for(const n of t)s[i++]=n.segment;return s}}return r=>[...r]})();Et.experimentalLetterSpacing=!1;Et._fonts={};Et._measurementCache=ly(1e3);let yt=Et;const dy=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function li(r){const e=typeof r.fontSize=="number"?`${r.fontSize}px`:r.fontSize;let t=r.fontFamily;Array.isArray(r.fontFamily)||(t=r.fontFamily.split(","));for(let s=t.length-1;s>=0;s--){let i=t[s].trim();!/([\"\'])[^\'\"]+\1/.test(i)&&!dy.includes(i)&&(i=`"${i}"`),t[s]=i}return`${r.fontStyle} ${r.fontVariant} ${r.fontWeight} ${e} ${t.join(",")}`}const Ec=1e5;function Qs(r,e,t,s=0,i=0,n=0){if(r.texture===H.WHITE&&!r.fill)return oe.shared.setValue(r.color).setAlpha(r.alpha??1).toHexa();if(r.fill){if(r.fill instanceof Gs){const o=r.fill,a=e.createPattern(o.texture.source.resource,"repeat");return Y.applyPatternTransform(a,o.transform,!1),a}else if(r.fill instanceof Xe){const o=r.fill,a=o.type==="linear",l=o.textureSpace==="local";let h=1,c=1;l&&t&&(h=t.width+s,c=t.height+s);let u,d=!1;if(a){const{start:f,end:p}=o;u=e.createLinearGradient(f.x*h+i,f.y*c+n,p.x*h+i,p.y*c+n),d=Math.abs(p.x-f.x)<Math.abs((p.y-f.y)*.1)}else{const{center:f,innerRadius:p,outerCenter:m,outerRadius:g}=o;u=e.createRadialGradient(f.x*h+i,f.y*c+n,p*h,m.x*h+i,m.y*c+n,g*h)}if(d&&l&&t){const f=t.lineHeight/c;for(let p=0;p<t.lines.length;p++){const m=(p*t.lineHeight+s/2)/c;o.colorStops.forEach(g=>{let _=m+g.offset*f;_=Math.max(0,Math.min(1,_)),u.addColorStop(Math.floor(_*Ec)/Ec,oe.shared.setValue(g.color).toHex())})}}else o.colorStops.forEach(f=>{u.addColorStop(f.offset,oe.shared.setValue(f.color).toHex())});return u}}else{const o=e.createPattern(r.texture.source.resource,"repeat"),a=r.matrix.copyTo(L.shared);return a.scale(r.texture.source.pixelWidth,r.texture.source.pixelHeight),o.setTransform(a),o}return N("FillStyle not recognised",r),"red"}const kc=new ee;function ps(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===32&&e++;return e}class fy{getCanvasAndContext(e){const{text:t,style:s,resolution:i=1}=e,n=s._getFinalPadding(),o=yt.measureText(t||" ",s),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*i),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*i),h=Mt.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(s,n,i,h,o);const c=s.trim?tp({canvas:h.canvas,width:a,height:l,resolution:1,output:kc}):kc.set(0,0,a,l);return{canvasAndContext:h,frame:c}}returnCanvasAndContext(e){Mt.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,s,i,n){if(n.runsByLine&&n.runsByLine.length>0){this._renderTaggedTextToCanvas(n,e,t,s,i);return}const{canvas:o,context:a}=i,l=li(e),h=n.lines,c=n.lineHeight,u=n.lineWidths,d=n.maxLineWidth,f=n.fontProperties,p=o.height;if(a.resetTransform(),a.scale(s,s),a.textBaseline=e.textBaseline,e._stroke?.width){const w=e._stroke;a.lineWidth=w.width,a.miterLimit=w.miterLimit,a.lineJoin=w.join,a.lineCap=w.cap}a.font=l;let m,g;const _=e.dropShadow?2:1,y=(e._stroke?.width??0)/2;let b=(c-f.fontSize)/2;c-f.fontSize<0&&(b=0);for(let w=0;w<_;++w){const v=e.dropShadow&&w===0,S=v?Math.ceil(Math.max(1,p)+t*2):0,E=S*s;if(v)this._setupDropShadow(a,e,s,E);else{const k=e._gradientBounds,P=e._gradientOffset;if(k){const T={width:k.width,height:k.height,lineHeight:k.height,lines:n.lines};this._setFillAndStrokeStyles(a,e,T,t,y,P?.x??0,P?.y??0)}else P?this._setFillAndStrokeStyles(a,e,n,t,y,P.x,P.y):this._setFillAndStrokeStyles(a,e,n,t,y);a.shadowColor="rgba(0,0,0,0)"}for(let k=0;k<h.length;k++){m=y,g=y+k*c+f.ascent+b,m+=this._getAlignmentOffset(u[k],d,e.align);let P=0;if(e.align==="justify"&&e.wordWrap&&k<h.length-1){const T=ps(h[k]);T>0&&(P=(d-u[k])/T)}e._stroke?.width&&this._drawLetterSpacing(h[k],e,i,m+t,g+t-S,!0,P),e._fill!==void 0&&this._drawLetterSpacing(h[k],e,i,m+t,g+t-S,!1,P)}}}_renderTaggedTextToCanvas(e,t,s,i,n){const{canvas:o,context:a}=n,{runsByLine:l,lineWidths:h,maxLineWidth:c,lineAscents:u,lineHeights:d,hasDropShadow:f}=e,p=o.height;a.resetTransform(),a.scale(i,i),a.textBaseline=t.textBaseline;const m=f?2:1;let g=t._stroke?.width??0;for(const y of l)for(const b of y){const w=b.style._stroke?.width??0;w>g&&(g=w)}const _=g/2,x=[];for(let y=0;y<l.length;y++){const b=l[y],w=[];for(const v of b){const S=li(v.style);a.font=S,w.push({width:yt._measureText(v.text,v.style.letterSpacing,a),font:S})}x.push(w)}for(let y=0;y<m;++y){const b=f&&y===0,w=b?Math.ceil(Math.max(1,p)+s*2):0,v=w*i;b||(a.shadowColor="rgba(0,0,0,0)");let S=_;for(let E=0;E<l.length;E++){const k=l[E],P=h[E],T=u[E],A=d[E],I=x[E];let F=_;F+=this._getAlignmentOffset(P,c,t.align);let X=0;if(t.align==="justify"&&t.wordWrap&&E<l.length-1){let G=0;for(const B of k)G+=ps(B.text);G>0&&(X=(c-P)/G)}const R=S+T;let M=F+s;for(let G=0;G<k.length;G++){const B=k[G],{width:U,font:W}=I[G];if(a.font=W,a.textBaseline=B.style.textBaseline,B.style._stroke?.width){const te=B.style._stroke;if(a.lineWidth=te.width,a.miterLimit=te.miterLimit,a.lineJoin=te.join,a.lineCap=te.cap,b)if(B.style.dropShadow)this._setupDropShadow(a,B.style,i,v);else{const ie=ps(B.text);M+=U+ie*X;continue}else{const ie=yt.measureFont(W),$=B.style.lineHeight||ie.fontSize,Ze={width:U,height:$,lineHeight:$,lines:[B.text]};a.strokeStyle=Qs(te,a,Ze,s*2,M-s,S)}this._drawLetterSpacing(B.text,B.style,n,M,R+s-w,!0,X)}const se=ps(B.text);M+=U+se*X}M=F+s;for(let G=0;G<k.length;G++){const B=k[G],{width:U,font:W}=I[G];if(a.font=W,a.textBaseline=B.style.textBaseline,B.style._fill!==void 0){if(b)if(B.style.dropShadow)this._setupDropShadow(a,B.style,i,v);else{const te=ps(B.text);M+=U+te*X;continue}else{const te=yt.measureFont(W),ie=B.style.lineHeight||te.fontSize,$={width:U,height:ie,lineHeight:ie,lines:[B.text]};a.fillStyle=Qs(B.style._fill,a,$,s*2,M-s,S)}this._drawLetterSpacing(B.text,B.style,n,M,R+s-w,!1,X)}const se=ps(B.text);M+=U+se*X}S+=A}}}_setFillAndStrokeStyles(e,t,s,i,n,o=0,a=0){if(e.fillStyle=t._fill?Qs(t._fill,e,s,i*2,o,a):null,t._stroke?.width){const l=n+i*2;e.strokeStyle=Qs(t._stroke,e,s,l,o,a)}}_setupDropShadow(e,t,s,i){e.fillStyle="black",e.strokeStyle="black";const n=t.dropShadow,o=n.color,a=n.alpha;e.shadowColor=oe.shared.setValue(o).setAlpha(a).toRgbaString();const l=n.blur*s,h=n.distance*s;e.shadowBlur=l,e.shadowOffsetX=Math.cos(n.angle)*h,e.shadowOffsetY=Math.sin(n.angle)*h+i}_getAlignmentOffset(e,t,s){return s==="right"?t-e:s==="center"?(t-e)/2:0}_drawLetterSpacing(e,t,s,i,n,o=!1,a=0){const{context:l}=s,h=t.letterSpacing;let c=!1;if(yt.experimentalLetterSpacingSupported&&(yt.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(e,i,n):l.fillText(e,i,n);return}if(a!==0&&(h===0||c)){const m=e.split(" ");let g=i;const _=l.measureText(" ").width;for(let x=0;x<m.length;x++)o?l.strokeText(m[x],g,n):l.fillText(m[x],g,n),g+=l.measureText(m[x]).width+_+a;return}let u=i;const d=yt.graphemeSegmenter(e);let f=l.measureText(e).width,p=0;for(let m=0;m<d.length;++m){const g=d[m];o?l.strokeText(g,u,n):l.fillText(g,u,n);let _="";for(let x=m+1;x<d.length;++x)_+=d[x];p=l.measureText(_).width,u+=f-p+h,g===" "&&(u+=a),f=p}}}const Yt=new fy,Na=class Vt extends Re{constructor(e={}){super(),this.uid=ne("textStyle"),this._tick=0,this._cachedFontString=null,py(e),e instanceof Vt&&(e=e._toObject());const i={...Vt.defaultTextStyle,...e};for(const n in i){const o=n;this[o]=i[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({...Vt.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...Vt.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({...qe.defaultFillStyle,...e},()=>{this._fill=Gt({...this._originalFill},qe.defaultFillStyle)})),this._fill=Gt(e===0?"black":e,qe.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...qe.defaultStrokeStyle,...e},()=>{this._stroke=_r({...this._originalStroke},qe.defaultStrokeStyle)})),this._stroke=_r(e,qe.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=Vt.defaultTextStyle;for(const t in e)this[t]=e[t]}assign(e){for(const t in e){const s=t;this[s]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=li(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 Vt(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){if(this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(s),this._originalFill?.texture&&this._originalFill.texture.destroy(s),this._stroke?.texture&&this._stroke.texture.destroy(s),this._originalStroke?.texture&&this._originalStroke.texture.destroy(s)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(s,i,n)=>(s[i]===n||(s[i]=n,t?.(i,n),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(oe.isColorLike(e)||e instanceof Xe||e instanceof Gs)}};Na.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};Na.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 Ps=Na;function py(r){const e=r;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=Ps.defaultDropShadow;r.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){O(ue,"strokeThickness is now a part of stroke");const t=e.stroke;let s={};if(oe.isColorLike(t))s.color=t;else if(t instanceof Xe||t instanceof Gs)s.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))s=t;else throw new Error("Invalid stroke value.");r.stroke={...s,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(O(ue,"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&&N("The number of fill colors must match the number of fill gradient stops.");const t=new Xe({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),s=e.fillGradientStops.slice(),i=e.fill.map(n=>oe.shared.setValue(n).toNumber());s.forEach((n,o)=>{t.addColorStop(n,i[o])}),r.fill={fill:t}}}let Pc=!1;function _p(r){if(Pc)return;const e=new Dt({scaleMode:r.scaleMode});r._resourceId!==e._resourceId&&(Pc=!0,N("Text textureStyle: only scaleMode is applied to a text texture, the other fields are ignored"))}function yp(r,e){const{texture:t,bounds:s}=r,i=e._style._getFinalPadding();Lo(s,e._anchor,t);const n=e._anchor._x*i*2,o=e._anchor._y*i*2;s.minX-=i-n,s.minY-=i-o,s.maxX-=i-n,s.maxY-=i-o}class Fi{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 xp extends Fi{}class Ha{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),e.runners.contextChange.add(this),this._managedTexts=new it({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?._autoResolution&&t.onViewUpdate()}}contextChange(){for(const e in this._managedTexts.items)this._managedTexts.items[e]?.unload()}validateRenderable(e){const t=this._getGpuText(e),s=e.styleKey;return t.currentKey!==s?!0:e._didTextUpdate}addRenderable(e,t){const s=this._getGpuText(e);if(e._didTextUpdate||s.currentKey!==e.styleKey){const i=e._autoResolution?this._renderer.resolution:e.resolution;(s.currentKey!==e.styleKey||e._resolution!==i)&&this._updateGpuText(e),e._didTextUpdate=!1,yp(s,e)}this._renderer.renderPipes.batch.addToBatch(s,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 xp;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:s}=this._renderer;s.getReferenceCount(t.currentKey)>0?s.decreaseReferenceCount(t.currentKey):t.texture&&s.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}Ha.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"text"};class za{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,s,i){typeof e=="string"&&(O("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:s,resolution:t}),e.style instanceof Ps||(e.style=new Ps(e.style)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:n,style:o,textureStyle:a,autoGenerateMipmaps:l}=e,h=e.resolution??this._renderer.resolution,{frame:c,canvasAndContext:u}=Yt.getCanvasAndContext({text:n,style:o,resolution:h}),d=ka(u.canvas,c.width,c.height,h,l,a?.scaleMode);if(o.trim&&(c.pad(o.padding),d.frame.copyFrom(c),d.frame.scale(1/h),d.updateUvs()),o.filters){const f=this._applyFilters(d,o.filters);return this.returnTexture(d),Yt.returnCanvasAndContext(u),f}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||Yt.returnCanvasAndContext(u),d}returnTexture(e){const t=e.source,s=t.resource;if(this._retainCanvasContext&&s?.getContext){const i=s.getContext("2d");i&&Yt.returnCanvasAndContext({canvas:s,context:i})}t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",Te.returnTexture(e)}renderTextToCanvas(){O("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 s=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:s,usageCount:1},s}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const s=this._renderer.renderTarget.renderTarget,i=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind({target:s,clear:!1}),i}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}class Wa extends za{constructor(e){super(e,!0)}}Wa.extension={type:[C.CanvasSystem],name:"canvasText"};class $a extends za{constructor(e){super(e,!1)}}$a.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"canvasText"};q.add(Wa);q.add($a);q.add(Ha);class bp extends Jf{constructor(...e){const t=ep(e,"Text");super(t,Ps),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof Dt?t.textureStyle:new Dt(t.textureStyle),_p(this.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??de.defaultOptions.autoGenerateMipmaps}updateBounds(){const e=this._bounds,t=this._anchor;let s=0,i=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Yt.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Yt.returnCanvasAndContext(o),s=n.width,i=n.height}else{const n=yt.measureText(this._text,this._style);s=n.width,i=n.height}e.minX=-t._x*s,e.maxX=e.minX+s,e.minY=-t._y*i,e.maxY=e.minY+i}}function vp(){const{userAgent:r}=J.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(r)}const Va=class Xt{static _getPatternRepeat(e,t){const s=e&&e!=="clamp-to-edge",i=t&&t!=="clamp-to-edge";return s&&i?"repeat":s?"repeat-x":i?"repeat-y":"no-repeat"}start(e,t,s){}execute(e,t){const s=t.elements;if(!s||!s.length)return;const i=e.renderer,n=i.canvasContext,o=n.activeContext;for(let a=0;a<s.length;a++){const l=s[a];if(!l.packAsQuad)continue;const h=l,c=h.texture,u=c?Y.getCanvasSource(c):null;if(!u)continue;const d=c.source.style,f=n.smoothProperty,p=d.scaleMode!=="nearest";o[f]!==p&&(o[f]=p),n.setBlendMode(t.blendMode);const m=i.globalUniforms.globalUniformData?.worldColor??4294967295,g=h.color,_=(m>>>24&255)/255,x=(g>>>24&255)/255,y=i.filter?.alphaMultiplier??1,b=_*x*y;if(b<=0)continue;o.globalAlpha=b;const w=m&16777215,v=g&16777215,S=Zt(Kt(v,w)),E=c.frame,k=d.addressModeU??d.addressMode,P=d.addressModeV??d.addressMode,T=Xt._getPatternRepeat(k,P),A=c.source._resolution??c.source.resolution??1,I=h.renderable?.renderGroup?.isCachedAsTexture,F=E.x*A,X=E.y*A,R=E.width*A,M=E.height*A,G=h.bounds,B=i.renderTarget.renderTarget.isRoot,U=G.minX,W=G.minY,se=G.maxX-G.minX,te=G.maxY-G.minY,ie=c.rotate,$=c.uvs,Ze=Math.min($.x0,$.x1,$.x2,$.x3,$.y0,$.y1,$.y2,$.y3),Tr=Math.max($.x0,$.x1,$.x2,$.x3,$.y0,$.y1,$.y2,$.y3),Ds=T!=="no-repeat"&&(Ze<0||Tr>1),pt=ie&&!(!Ds&&(S!==16777215||ie));pt?(Xt._tempPatternMatrix.copyFrom(h.transform),Z.matrixAppendRotationInv(Xt._tempPatternMatrix,ie,U,W,se,te),n.setContextTransform(Xt._tempPatternMatrix,h.roundPixels===1,void 0,I&&B)):n.setContextTransform(h.transform,h.roundPixels===1,void 0,I&&B);const Lt=se,Qe=te;let Le=pt?0:U,Oe=pt?0:W;if(!pt&&h.roundPixels===1&&(Le|=0,Oe|=0),Ds){let Je=u;const Pt=S!==16777215&&!ie,mt=E.width<=c.source.width&&E.height<=c.source.height;Pt&&mt&&(Je=Y.getTintedCanvas({texture:c},S));const Ls=o.createPattern(Je,T);if(!Ls)continue;const qi=Lt,lh=Qe;if(qi===0||lh===0)continue;const hh=1/qi,ch=1/lh,uh=($.x1-$.x0)*hh,dh=($.y1-$.y0)*hh,fh=($.x3-$.x0)*ch,ph=($.y3-$.y0)*ch,Bg=$.x0-uh*Le-fh*Oe,Ig=$.y0-dh*Le-ph*Oe,Yi=c.source.pixelWidth,Ki=c.source.pixelHeight;Xt._tempPatternMatrix.set(uh*Yi,dh*Ki,fh*Yi,ph*Ki,Bg*Yi,Ig*Ki),Y.applyPatternTransform(Ls,Xt._tempPatternMatrix),o.fillStyle=Ls,o.fillRect(Le,Oe,Lt,Qe)}else{const Pt=S!==16777215||ie?Y.getTintedCanvas({texture:c},S):u,mt=Pt!==u;o.drawImage(Pt,mt?0:F,mt?0:X,mt?Pt.width:R,mt?Pt.height:M,Le,Oe,Lt,Qe)}}}};Va._tempPatternMatrix=new L;Va.extension={type:[C.CanvasPipesAdaptor],name:"batch"};let wp=Va;class Xa{constructor(){this._tempState=ft.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,s){const i=e.renderer,n=this._didUploadHash[s.uid];i.shader.bind(s,n),n||(this._didUploadHash[s.uid]=!0),i.shader.updateUniformGroup(i.globalUniforms.uniformGroup),i.geometry.bind(t,s.glProgram)}execute(e,t){const s=e.renderer;this._tempState.blendMode=t.blendMode,s.state.set(this._tempState);const i=t.textures.textures;for(let n=0;n<t.textures.count;n++)s.texture.bind(i[n],n);s.texture.unbindIntegerTextures(t.textures.count),s.geometry.draw(t.topology,t.size,t.start)}}Xa.extension={type:[C.WebGLPipesAdaptor],name:"batch"};const Ur=ft.for2d();class ja{start(e,t,s){const i=e.renderer,n=i.encoder,o=s.gpuProgram;this._shader=s,this._geometry=t,n.setGeometry(t,o),Ur.blendMode="normal",i.pipeline.getPipeline(t,o,Ur,void 0,s._overrides);const a=i.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const s=this._shader.gpuProgram,i=e.renderer,n=i.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Mi(l.textures,l.count,i.limits.maxBatchableTextures)}Ur.blendMode=t.blendMode;const o=i.bindGroup.getBindGroup(t.bindGroup,s,1),a=i.pipeline.getPipeline(this._geometry,s,Ur,t.topology,this._shader._overrides);t.bindGroup._touch(i.gc.now),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}ja.extension={type:[C.WebGPUPipesAdaptor],name:"batch"};const qa=class Tp{constructor(e,t){this.state=ft.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e,t){return new this._availableBatchers[e]({maxTextures:t})}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new Bi({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const s in this._activeBatches)this._activeBatches[s].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let s=this._activeBatches[e.batcherName];s||(s=this._activeBatches[e.batcherName]=Tp.getBatcher(e.batcherName,this.renderer.limits.maxBatchableTextures),s.begin()),this._activeBatch=s}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const s in t){const i=t[s],n=i.geometry;n.indexBuffer.setDataWithSize(i.indexBuffer,i.indexSize,!0),n.buffers[0].setDataWithSize(i.attributeBuffer.float32View,i.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const s in t){const i=t[s],n=i.geometry;i.dirty&&(i.dirty=!1,n.buffers[0].update(i.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,s=t.geometry,i=t.shader;this._adaptor.start(this,s,i)}this._adaptor.execute(this,e)}destroyInstructionSet(e){const t=this._batchersByInstructionSet[e.uid];if(t){for(const s in t)t[s].destroy();delete this._batchersByInstructionSet[e.uid],this._activeBatches===t&&(this._activeBatches=Object.create(null),this._activeBatch=null)}}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};qa.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"batch"};qa._availableBatchers=Object.create(null);let Li=qa;q.handleByMap(C.Batcher,Li._availableBatchers);q.add(Bi);const Sp={name:"texture-bit",vertex:{header:`
556
+ `?(u.push(d),d=[]):M.length>0&&d.push({text:M,style:G.style})}}(d.length>0||u.length===0)&&u.push(d);const f=t?pp(u,e,s,n,a,l):u,p=[],m=[],g=[],_=[],x=[];let y=0;const b=e._fontString,w=o(b);w.fontSize===0&&(w.fontSize=e.fontSize,w.ascent=e.fontSize);let v="",T=!!e.dropShadow,k=e._stroke?.width||0;for(const G of f){let V=0,I=w.ascent,M=w.descent,D="";for(const U of G){const W=U.style._fontString,se=o(W);W!==v&&(s.font=W,v=W);const te=i(U.text,U.style.letterSpacing,s);V+=te,I=Math.max(I,se.ascent),M=Math.max(M,se.descent),D+=U.text;const ie=U.style._stroke?.width||0;ie>k&&(k=ie),!T&&U.style.dropShadow&&(T=!0)}G.length===0&&(I=w.ascent,M=w.descent),p.push(V),m.push(I),g.push(M),x.push(D);const R=e.lineHeight||I+M;_.push(R+e.leading),y=Math.max(y,V)}const P=k,A=y+P+(e.dropShadow?e.dropShadow.distance:0);let C=0;for(let G=0;G<_.length;G++)C+=_[G];C=Math.max(C,_[0]+P);const E=C+(e.dropShadow?e.dropShadow.distance:0),B=e.lineHeight||w.fontSize;return{width:A,height:E,lines:x,lineWidths:p,lineHeight:B+e.leading,maxLineWidth:y,fontProperties:w,runsByLine:f,lineAscents:m,lineDescents:g,lineHeights:_,hasDropShadow:T}}function pp(r,e,t,s,i,n){const{letterSpacing:o,whiteSpace:a,wordWrapWidth:l,breakWords:h}=e,c=Fa(a),u=l+o,d={};let f="";const p=(g,_)=>{const x=`${g}|${_.styleKey}`;let y=d[x];if(y===void 0){const b=_._fontString;b!==f&&(t.font=b,f=b),y=s(g,_.letterSpacing,t)+_.letterSpacing,d[x]=y}return y},m=[];for(const g of r){const _=mp(g),x=m.length,y=C=>{let E=0,B=C;do{const{token:G,style:V}=_[B];E+=p(G,V),B++}while(B<_.length&&_[B].continuesFromPrevious);return E},b=C=>{const E=[];let B=C;do E.push({token:_[B].token,style:_[B].style}),B++;while(B<_.length&&_[B].continuesFromPrevious);return E};let w=[],v=0,T=!c,k=null;const P=()=>{k&&k.text.length>0&&w.push(k),k=null},A=()=>{if(P(),w.length>0){const C=w[w.length-1];C.text=at(C.text),C.text.length===0&&w.pop()}m.push(w),w=[],v=0,T=!1};for(let C=0;C<_.length;C++){const{token:E,style:B,continuesFromPrevious:G}=_[C],V=p(E,B);if(c){const D=$e(E),R=k?.text[k.text.length-1]??w[w.length-1]?.text.slice(-1)??"",U=R?$e(R):!1;if(D&&U)continue}const I=!G,M=I?y(C):V;if(M>u&&I)if(v>0&&A(),h){const D=b(C);for(let R=0;R<D.length;R++){const U=D[R].token,W=D[R].style,se=Ua(U,h,n,i);for(const te of se){const ie=p(te,W);ie+v>u&&A(),!k||k.style!==W?(P(),k={text:te,style:W}):k.text+=te,v+=ie}}C+=D.length-1}else{const D=b(C);P(),m.push(D.map(R=>({text:R.token,style:R.style}))),T=!1,C+=D.length-1}else if(M+v>u&&I){if($e(E)){T=!1;continue}A(),k={text:E,style:B},v=V}else if(G&&!h)!k||k.style!==B?(P(),k={text:E,style:B}):k.text+=E,v+=V;else{const D=$e(E);if(v===0&&D&&!T)continue;!k||k.style!==B?(P(),k={text:E,style:B}):k.text+=E,v+=V}}if(P(),w.length>0){const C=w[w.length-1];C.text=at(C.text),C.text.length===0&&w.pop()}(w.length>0||m.length===x)&&m.push(w)}return m}function mp(r){const e=[];let t=!1;for(const s of r){const i=Oa(s.text);let n=!0;for(const o of i){const a=$e(o)||xr(o),l=n&&t&&!a;e.push({token:o,style:s.style,continuesFromPrevious:l}),t=!a,n=!1}}return e}const uy={willReadFrequently:!0};function Cc(r,e,t,s,i){let n=t[r];return typeof n!="number"&&(n=i(r,e,s)+e,t[r]=n),n}function gp(r,e,t,s,i,n,o){const a=t.getContext("2d",uy);a.font=e._fontString;let l=0,h="";const c=[],u=Object.create(null),{letterSpacing:d,whiteSpace:f}=e,p=Fa(f),m=La(f);let g=!p;const _=e.wordWrapWidth+d,x=Oa(r);for(let b=0;b<x.length;b++){let w=x[b];if(xr(w)){if(!m){c.push(at(h)),g=!p,h="",l=0;continue}w=" "}if(p){const T=$e(w),k=$e(h[h.length-1]);if(T&&k)continue}const v=Cc(w,d,u,a,s);if(v>_)if(h!==""&&(c.push(at(h)),h="",l=0),i(w,e.breakWords)){const T=Ua(w,e.breakWords,o,n);for(const k of T){const P=Cc(k,d,u,a,s);P+l>_&&(c.push(at(h)),g=!1,h="",l=0),h+=k,l+=P}}else h.length>0&&(c.push(at(h)),h="",l=0),c.push(at(w)),g=!1,h="",l=0;else v+l>_&&(g=!1,c.push(at(h)),h="",l=0),(h.length>0||!$e(w)||g)&&(h+=w,l+=v)}const y=at(h);return y.length>0&&c.push(y),c.join(`
557
+ `)}const Mc={willReadFrequently:!0},Et=class z{static get experimentalLetterSpacingSupported(){let e=z._experimentalLetterSpacingSupported;if(e===void 0){const t=J.get().getCanvasRenderingContext2D().prototype;e=z._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,s,i,n,o,a,l,h,c){this.text=e,this.style=t,this.width=s,this.height=i,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(e=" ",t,s=z._canvas,i=t.wordWrap){const n=`${e}-${t.styleKey}-wordWrap-${i}`;if(z._measurementCache.has(n))return z._measurementCache.get(n);if(Ga(t)&&Da(e)){const b=fp(e,t,i,z._context,z._measureText,z._measureTextAdvance,z.measureFont,z.canBreakChars,z.wordWrapSplit),w=new z(e,t,b.width,b.height,b.lines,b.lineWidths,b.lineHeight,b.maxLineWidth,b.fontProperties,{runsByLine:b.runsByLine,lineAscents:b.lineAscents,lineDescents:b.lineDescents,lineHeights:b.lineHeights,hasDropShadow:b.hasDropShadow});return z._measurementCache.set(n,w),w}const a=t._fontString,l=z.measureFont(a);l.fontSize===0&&(l.fontSize=t.fontSize,l.ascent=t.fontSize,l.descent=0);const h=z._context;h.font=a;const u=(i?z._wordWrap(e,t,s):e).split(up),d=new Array(u.length);let f=0;for(let b=0;b<u.length;b++){const w=z._measureText(u[b],t.letterSpacing,h);d[b]=w,f=Math.max(f,w)}const p=t._stroke?.width??0,m=t.lineHeight||l.fontSize,g=z._adjustWidthForStyle(f,t),_=Math.max(m,l.fontSize+p)+(u.length-1)*(m+t.leading),x=z._adjustHeightForStyle(_,t),y=new z(e,t,g,x,u,d,m+t.leading,f,l);return z._measurementCache.set(n,y),y}static _adjustWidthForStyle(e,t){const s=t._stroke?.width||0;let i=e+s;return t.dropShadow&&(i+=t.dropShadow.distance),i}static _adjustHeightForStyle(e,t){let s=e;return t.dropShadow&&(s+=t.dropShadow.distance),s}static _measureText(e,t,s){const{metricWidth:i,metrics:n,letterSpacingVal:o}=z._measureTextCore(e,t,s),a=-(n.actualBoundingBoxLeft??0);let h=(n.actualBoundingBoxRight??0)-a;return n.width>0&&(h+=o),Math.max(i,h)}static _measureTextAdvance(e,t,s){return z._measureTextCore(e,t,s).metricWidth}static _measureTextCore(e,t,s){let i=!1;z.experimentalLetterSpacingSupported&&(z.experimentalLetterSpacing?(s.letterSpacing=`${t}px`,s.textLetterSpacing=`${t}px`,i=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));const n=s.measureText(e);let o=n.width,a=0;return o>0&&(i?a=-t:a=(z.graphemeSegmenter(e).length-1)*t,o+=a),{metricWidth:o,metrics:n,letterSpacingVal:a}}static _wordWrap(e,t,s=z._canvas){return gp(e,t,s,z._measureTextAdvance,z.canBreakWords,z.canBreakChars,z.wordWrapSplit)}static isBreakingSpace(e,t){return $e(e)}static canBreakWords(e,t){return t}static canBreakChars(e,t,s,i,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 s=t.measureText(z.METRICS_STRING+z.BASELINE_SYMBOL),i=s.actualBoundingBoxAscent??0,n=s.actualBoundingBoxDescent??0,o={ascent:i,descent:n,fontSize:i+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);if(t.getContext("2d",Mc)?.measureText)return z.__canvas=t,t;e=J.get().createCanvas()}catch{e=J.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",Mc)),z.__context}};Et.METRICS_STRING="|ÉqÅ";Et.BASELINE_SYMBOL="M";Et.BASELINE_MULTIPLIER=1.4;Et.HEIGHT_MULTIPLIER=2;Et.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const r=new Intl.Segmenter;return e=>{const t=r.segment(e),s=[];let i=0;for(const n of t)s[i++]=n.segment;return s}}return r=>[...r]})();Et.experimentalLetterSpacing=!1;Et._fonts={};Et._measurementCache=ly(1e3);let yt=Et;const dy=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function li(r){const e=typeof r.fontSize=="number"?`${r.fontSize}px`:r.fontSize;let t=r.fontFamily;Array.isArray(r.fontFamily)||(t=r.fontFamily.split(","));for(let s=t.length-1;s>=0;s--){let i=t[s].trim();!/([\"\'])[^\'\"]+\1/.test(i)&&!dy.includes(i)&&(i=`"${i}"`),t[s]=i}return`${r.fontStyle} ${r.fontVariant} ${r.fontWeight} ${e} ${t.join(",")}`}const Ec=1e5;function Qs(r,e,t,s=0,i=0,n=0){if(r.texture===H.WHITE&&!r.fill)return oe.shared.setValue(r.color).setAlpha(r.alpha??1).toHexa();if(r.fill){if(r.fill instanceof Gs){const o=r.fill,a=e.createPattern(o.texture.source.resource,"repeat");return Y.applyPatternTransform(a,o.transform,!1),a}else if(r.fill instanceof Xe){const o=r.fill,a=o.type==="linear",l=o.textureSpace==="local";let h=1,c=1;l&&t&&(h=t.width+s,c=t.height+s);let u,d=!1;if(a){const{start:f,end:p}=o;u=e.createLinearGradient(f.x*h+i,f.y*c+n,p.x*h+i,p.y*c+n),d=Math.abs(p.x-f.x)<Math.abs((p.y-f.y)*.1)}else{const{center:f,innerRadius:p,outerCenter:m,outerRadius:g}=o;u=e.createRadialGradient(f.x*h+i,f.y*c+n,p*h,m.x*h+i,m.y*c+n,g*h)}if(d&&l&&t){const f=t.lineHeight/c;for(let p=0;p<t.lines.length;p++){const m=(p*t.lineHeight+s/2)/c;o.colorStops.forEach(g=>{let _=m+g.offset*f;_=Math.max(0,Math.min(1,_)),u.addColorStop(Math.floor(_*Ec)/Ec,oe.shared.setValue(g.color).toHex())})}}else o.colorStops.forEach(f=>{u.addColorStop(f.offset,oe.shared.setValue(f.color).toHex())});return u}}else{const o=e.createPattern(r.texture.source.resource,"repeat"),a=r.matrix.copyTo(L.shared);return a.scale(r.texture.source.pixelWidth,r.texture.source.pixelHeight),o.setTransform(a),o}return N("FillStyle not recognised",r),"red"}const kc=new ee;function ps(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===32&&e++;return e}class fy{getCanvasAndContext(e){const{text:t,style:s,resolution:i=1}=e,n=s._getFinalPadding(),o=yt.measureText(t||" ",s),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*i),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*i),h=Mt.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(s,n,i,h,o);const c=s.trim?tp({canvas:h.canvas,width:a,height:l,resolution:1,output:kc}):kc.set(0,0,a,l);return{canvasAndContext:h,frame:c}}returnCanvasAndContext(e){Mt.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,s,i,n){if(n.runsByLine&&n.runsByLine.length>0){this._renderTaggedTextToCanvas(n,e,t,s,i);return}const{canvas:o,context:a}=i,l=li(e),h=n.lines,c=n.lineHeight,u=n.lineWidths,d=n.maxLineWidth,f=n.fontProperties,p=o.height;if(a.resetTransform(),a.scale(s,s),a.textBaseline=e.textBaseline,e._stroke?.width){const w=e._stroke;a.lineWidth=w.width,a.miterLimit=w.miterLimit,a.lineJoin=w.join,a.lineCap=w.cap}a.font=l;let m,g;const _=e.dropShadow?2:1,y=(e._stroke?.width??0)/2;let b=(c-f.fontSize)/2;c-f.fontSize<0&&(b=0);for(let w=0;w<_;++w){const v=e.dropShadow&&w===0,T=v?Math.ceil(Math.max(1,p)+t*2):0,k=T*s;if(v)this._setupDropShadow(a,e,s,k);else{const P=e._gradientBounds,A=e._gradientOffset;if(P){const C={width:P.width,height:P.height,lineHeight:P.height,lines:n.lines};this._setFillAndStrokeStyles(a,e,C,t,y,A?.x??0,A?.y??0)}else A?this._setFillAndStrokeStyles(a,e,n,t,y,A.x,A.y):this._setFillAndStrokeStyles(a,e,n,t,y);a.shadowColor="rgba(0,0,0,0)"}for(let P=0;P<h.length;P++){m=y,g=y+P*c+f.ascent+b,m+=this._getAlignmentOffset(u[P],d,e.align);let A=0;if(e.align==="justify"&&e.wordWrap&&P<h.length-1){const C=ps(h[P]);C>0&&(A=(d-u[P])/C)}e._stroke?.width&&this._drawLetterSpacing(h[P],e,i,m+t,g+t-T,!0,A),e._fill!==void 0&&this._drawLetterSpacing(h[P],e,i,m+t,g+t-T,!1,A)}}}_renderTaggedTextToCanvas(e,t,s,i,n){const{canvas:o,context:a}=n,{runsByLine:l,lineWidths:h,maxLineWidth:c,lineAscents:u,lineHeights:d,hasDropShadow:f}=e,p=o.height;a.resetTransform(),a.scale(i,i),a.textBaseline=t.textBaseline;const m=f?2:1;let g=t._stroke?.width??0;for(const y of l)for(const b of y){const w=b.style._stroke?.width??0;w>g&&(g=w)}const _=g/2,x=[];for(let y=0;y<l.length;y++){const b=l[y],w=[];for(const v of b){const T=li(v.style);a.font=T,w.push({width:yt._measureText(v.text,v.style.letterSpacing,a),font:T})}x.push(w)}for(let y=0;y<m;++y){const b=f&&y===0,w=b?Math.ceil(Math.max(1,p)+s*2):0,v=w*i;b||(a.shadowColor="rgba(0,0,0,0)");let T=_;for(let k=0;k<l.length;k++){const P=l[k],A=h[k],C=u[k],E=d[k],B=x[k];let G=_;G+=this._getAlignmentOffset(A,c,t.align);let V=0;if(t.align==="justify"&&t.wordWrap&&k<l.length-1){let D=0;for(const R of P)D+=ps(R.text);D>0&&(V=(c-A)/D)}const I=T+C;let M=G+s;for(let D=0;D<P.length;D++){const R=P[D],{width:U,font:W}=B[D];if(a.font=W,a.textBaseline=R.style.textBaseline,R.style._stroke?.width){const te=R.style._stroke;if(a.lineWidth=te.width,a.miterLimit=te.miterLimit,a.lineJoin=te.join,a.lineCap=te.cap,b)if(R.style.dropShadow)this._setupDropShadow(a,R.style,i,v);else{const ie=ps(R.text);M+=U+ie*V;continue}else{const ie=yt.measureFont(W),$=R.style.lineHeight||ie.fontSize,Ze={width:U,height:$,lineHeight:$,lines:[R.text]};a.strokeStyle=Qs(te,a,Ze,s*2,M-s,T)}this._drawLetterSpacing(R.text,R.style,n,M,I+s-w,!0,V)}const se=ps(R.text);M+=U+se*V}M=G+s;for(let D=0;D<P.length;D++){const R=P[D],{width:U,font:W}=B[D];if(a.font=W,a.textBaseline=R.style.textBaseline,R.style._fill!==void 0){if(b)if(R.style.dropShadow)this._setupDropShadow(a,R.style,i,v);else{const te=ps(R.text);M+=U+te*V;continue}else{const te=yt.measureFont(W),ie=R.style.lineHeight||te.fontSize,$={width:U,height:ie,lineHeight:ie,lines:[R.text]};a.fillStyle=Qs(R.style._fill,a,$,s*2,M-s,T)}this._drawLetterSpacing(R.text,R.style,n,M,I+s-w,!1,V)}const se=ps(R.text);M+=U+se*V}T+=E}}}_setFillAndStrokeStyles(e,t,s,i,n,o=0,a=0){if(e.fillStyle=t._fill?Qs(t._fill,e,s,i*2,o,a):null,t._stroke?.width){const l=n+i*2;e.strokeStyle=Qs(t._stroke,e,s,l,o,a)}}_setupDropShadow(e,t,s,i){e.fillStyle="black",e.strokeStyle="black";const n=t.dropShadow,o=n.color,a=n.alpha;e.shadowColor=oe.shared.setValue(o).setAlpha(a).toRgbaString();const l=n.blur*s,h=n.distance*s;e.shadowBlur=l,e.shadowOffsetX=Math.cos(n.angle)*h,e.shadowOffsetY=Math.sin(n.angle)*h+i}_getAlignmentOffset(e,t,s){return s==="right"?t-e:s==="center"?(t-e)/2:0}_drawLetterSpacing(e,t,s,i,n,o=!1,a=0){const{context:l}=s,h=t.letterSpacing;let c=!1;if(yt.experimentalLetterSpacingSupported&&(yt.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(e,i,n):l.fillText(e,i,n);return}if(a!==0&&(h===0||c)){const m=e.split(" ");let g=i;const _=l.measureText(" ").width;for(let x=0;x<m.length;x++)o?l.strokeText(m[x],g,n):l.fillText(m[x],g,n),g+=l.measureText(m[x]).width+_+a;return}let u=i;const d=yt.graphemeSegmenter(e);let f=l.measureText(e).width,p=0;for(let m=0;m<d.length;++m){const g=d[m];o?l.strokeText(g,u,n):l.fillText(g,u,n);let _="";for(let x=m+1;x<d.length;++x)_+=d[x];p=l.measureText(_).width,u+=f-p+h,g===" "&&(u+=a),f=p}}}const Yt=new fy,Na=class Vt extends Re{constructor(e={}){super(),this.uid=ne("textStyle"),this._tick=0,this._cachedFontString=null,py(e),e instanceof Vt&&(e=e._toObject());const i={...Vt.defaultTextStyle,...e};for(const n in i){const o=n;this[o]=i[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({...Vt.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...Vt.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({...qe.defaultFillStyle,...e},()=>{this._fill=Gt({...this._originalFill},qe.defaultFillStyle)})),this._fill=Gt(e===0?"black":e,qe.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...qe.defaultStrokeStyle,...e},()=>{this._stroke=_r({...this._originalStroke},qe.defaultStrokeStyle)})),this._stroke=_r(e,qe.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=Vt.defaultTextStyle;for(const t in e)this[t]=e[t]}assign(e){for(const t in e){const s=t;this[s]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=li(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 Vt(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){if(this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(s),this._originalFill?.texture&&this._originalFill.texture.destroy(s),this._stroke?.texture&&this._stroke.texture.destroy(s),this._originalStroke?.texture&&this._originalStroke.texture.destroy(s)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(s,i,n)=>(s[i]===n||(s[i]=n,t?.(i,n),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(oe.isColorLike(e)||e instanceof Xe||e instanceof Gs)}};Na.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};Na.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 Ps=Na;function py(r){const e=r;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=Ps.defaultDropShadow;r.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){O(ue,"strokeThickness is now a part of stroke");const t=e.stroke;let s={};if(oe.isColorLike(t))s.color=t;else if(t instanceof Xe||t instanceof Gs)s.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))s=t;else throw new Error("Invalid stroke value.");r.stroke={...s,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(O(ue,"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&&N("The number of fill colors must match the number of fill gradient stops.");const t=new Xe({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),s=e.fillGradientStops.slice(),i=e.fill.map(n=>oe.shared.setValue(n).toNumber());s.forEach((n,o)=>{t.addColorStop(n,i[o])}),r.fill={fill:t}}}let Pc=!1;function _p(r){if(Pc)return;const e=new Dt({scaleMode:r.scaleMode});r._resourceId!==e._resourceId&&(Pc=!0,N("Text textureStyle: only scaleMode is applied to a text texture, the other fields are ignored"))}function yp(r,e){const{texture:t,bounds:s}=r,i=e._style._getFinalPadding();Lo(s,e._anchor,t);const n=e._anchor._x*i*2,o=e._anchor._y*i*2;s.minX-=i-n,s.minY-=i-o,s.maxX-=i-n,s.maxY-=i-o}class Fi{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 xp extends Fi{}class Ha{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),e.runners.contextChange.add(this),this._managedTexts=new it({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?._autoResolution&&t.onViewUpdate()}}contextChange(){for(const e in this._managedTexts.items)this._managedTexts.items[e]?.unload()}validateRenderable(e){const t=this._getGpuText(e),s=e.styleKey;return t.currentKey!==s?!0:e._didTextUpdate}addRenderable(e,t){const s=this._getGpuText(e);if(e._didTextUpdate||s.currentKey!==e.styleKey){const i=e._autoResolution?this._renderer.resolution:e.resolution;(s.currentKey!==e.styleKey||e._resolution!==i)&&this._updateGpuText(e),e._didTextUpdate=!1,yp(s,e)}this._renderer.renderPipes.batch.addToBatch(s,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 xp;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:s}=this._renderer;s.getReferenceCount(t.currentKey)>0?s.decreaseReferenceCount(t.currentKey):t.texture&&s.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}Ha.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"text"};class za{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,s,i){typeof e=="string"&&(O("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:s,resolution:t}),e.style instanceof Ps||(e.style=new Ps(e.style)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:n,style:o,textureStyle:a,autoGenerateMipmaps:l}=e,h=e.resolution??this._renderer.resolution,{frame:c,canvasAndContext:u}=Yt.getCanvasAndContext({text:n,style:o,resolution:h}),d=ka(u.canvas,c.width,c.height,h,l,a?.scaleMode);if(o.trim&&(c.pad(o.padding),d.frame.copyFrom(c),d.frame.scale(1/h),d.updateUvs()),o.filters){const f=this._applyFilters(d,o.filters);return this.returnTexture(d),Yt.returnCanvasAndContext(u),f}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||Yt.returnCanvasAndContext(u),d}returnTexture(e){const t=e.source,s=t.resource;if(this._retainCanvasContext&&s?.getContext){const i=s.getContext("2d");i&&Yt.returnCanvasAndContext({canvas:s,context:i})}t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",Te.returnTexture(e)}renderTextToCanvas(){O("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 s=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:s,usageCount:1},s}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const s=this._renderer.renderTarget.renderTarget,i=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind({target:s,clear:!1}),i}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}class Wa extends za{constructor(e){super(e,!0)}}Wa.extension={type:[S.CanvasSystem],name:"canvasText"};class $a extends za{constructor(e){super(e,!1)}}$a.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"canvasText"};q.add(Wa);q.add($a);q.add(Ha);class bp extends Jf{constructor(...e){const t=ep(e,"Text");super(t,Ps),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof Dt?t.textureStyle:new Dt(t.textureStyle),_p(this.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??de.defaultOptions.autoGenerateMipmaps}updateBounds(){const e=this._bounds,t=this._anchor;let s=0,i=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Yt.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Yt.returnCanvasAndContext(o),s=n.width,i=n.height}else{const n=yt.measureText(this._text,this._style);s=n.width,i=n.height}e.minX=-t._x*s,e.maxX=e.minX+s,e.minY=-t._y*i,e.maxY=e.minY+i}}function vp(){const{userAgent:r}=J.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(r)}const Va=class Xt{static _getPatternRepeat(e,t){const s=e&&e!=="clamp-to-edge",i=t&&t!=="clamp-to-edge";return s&&i?"repeat":s?"repeat-x":i?"repeat-y":"no-repeat"}start(e,t,s){}execute(e,t){const s=t.elements;if(!s||!s.length)return;const i=e.renderer,n=i.canvasContext,o=n.activeContext;for(let a=0;a<s.length;a++){const l=s[a];if(!l.packAsQuad)continue;const h=l,c=h.texture,u=c?Y.getCanvasSource(c):null;if(!u)continue;const d=c.source.style,f=n.smoothProperty,p=d.scaleMode!=="nearest";o[f]!==p&&(o[f]=p),n.setBlendMode(t.blendMode);const m=i.globalUniforms.globalUniformData?.worldColor??4294967295,g=h.color,_=(m>>>24&255)/255,x=(g>>>24&255)/255,y=i.filter?.alphaMultiplier??1,b=_*x*y;if(b<=0)continue;o.globalAlpha=b;const w=m&16777215,v=g&16777215,T=Zt(Kt(v,w)),k=c.frame,P=d.addressModeU??d.addressMode,A=d.addressModeV??d.addressMode,C=Xt._getPatternRepeat(P,A),E=c.source._resolution??c.source.resolution??1,B=h.renderable?.renderGroup?.isCachedAsTexture,G=k.x*E,V=k.y*E,I=k.width*E,M=k.height*E,D=h.bounds,R=i.renderTarget.renderTarget.isRoot,U=D.minX,W=D.minY,se=D.maxX-D.minX,te=D.maxY-D.minY,ie=c.rotate,$=c.uvs,Ze=Math.min($.x0,$.x1,$.x2,$.x3,$.y0,$.y1,$.y2,$.y3),Tr=Math.max($.x0,$.x1,$.x2,$.x3,$.y0,$.y1,$.y2,$.y3),Ds=C!=="no-repeat"&&(Ze<0||Tr>1),pt=ie&&!(!Ds&&(T!==16777215||ie));pt?(Xt._tempPatternMatrix.copyFrom(h.transform),Z.matrixAppendRotationInv(Xt._tempPatternMatrix,ie,U,W,se,te),n.setContextTransform(Xt._tempPatternMatrix,h.roundPixels===1,void 0,B&&R)):n.setContextTransform(h.transform,h.roundPixels===1,void 0,B&&R);const Lt=se,Qe=te;let Le=pt?0:U,Oe=pt?0:W;if(!pt&&h.roundPixels===1&&(Le|=0,Oe|=0),Ds){let Je=u;const Pt=T!==16777215&&!ie,mt=k.width<=c.source.width&&k.height<=c.source.height;Pt&&mt&&(Je=Y.getTintedCanvas({texture:c},T));const Ls=o.createPattern(Je,C);if(!Ls)continue;const qi=Lt,lh=Qe;if(qi===0||lh===0)continue;const hh=1/qi,ch=1/lh,uh=($.x1-$.x0)*hh,dh=($.y1-$.y0)*hh,fh=($.x3-$.x0)*ch,ph=($.y3-$.y0)*ch,Bg=$.x0-uh*Le-fh*Oe,Ig=$.y0-dh*Le-ph*Oe,Yi=c.source.pixelWidth,Ki=c.source.pixelHeight;Xt._tempPatternMatrix.set(uh*Yi,dh*Ki,fh*Yi,ph*Ki,Bg*Yi,Ig*Ki),Y.applyPatternTransform(Ls,Xt._tempPatternMatrix),o.fillStyle=Ls,o.fillRect(Le,Oe,Lt,Qe)}else{const Pt=T!==16777215||ie?Y.getTintedCanvas({texture:c},T):u,mt=Pt!==u;o.drawImage(Pt,mt?0:G,mt?0:V,mt?Pt.width:I,mt?Pt.height:M,Le,Oe,Lt,Qe)}}}};Va._tempPatternMatrix=new L;Va.extension={type:[S.CanvasPipesAdaptor],name:"batch"};let wp=Va;class Xa{constructor(){this._tempState=ft.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,s){const i=e.renderer,n=this._didUploadHash[s.uid];i.shader.bind(s,n),n||(this._didUploadHash[s.uid]=!0),i.shader.updateUniformGroup(i.globalUniforms.uniformGroup),i.geometry.bind(t,s.glProgram)}execute(e,t){const s=e.renderer;this._tempState.blendMode=t.blendMode,s.state.set(this._tempState);const i=t.textures.textures;for(let n=0;n<t.textures.count;n++)s.texture.bind(i[n],n);s.texture.unbindIntegerTextures(t.textures.count),s.geometry.draw(t.topology,t.size,t.start)}}Xa.extension={type:[S.WebGLPipesAdaptor],name:"batch"};const Ur=ft.for2d();class ja{start(e,t,s){const i=e.renderer,n=i.encoder,o=s.gpuProgram;this._shader=s,this._geometry=t,n.setGeometry(t,o),Ur.blendMode="normal",i.pipeline.getPipeline(t,o,Ur,void 0,s._overrides);const a=i.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const s=this._shader.gpuProgram,i=e.renderer,n=i.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Mi(l.textures,l.count,i.limits.maxBatchableTextures)}Ur.blendMode=t.blendMode;const o=i.bindGroup.getBindGroup(t.bindGroup,s,1),a=i.pipeline.getPipeline(this._geometry,s,Ur,t.topology,this._shader._overrides);t.bindGroup._touch(i.gc.now),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}ja.extension={type:[S.WebGPUPipesAdaptor],name:"batch"};const qa=class Tp{constructor(e,t){this.state=ft.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e,t){return new this._availableBatchers[e]({maxTextures:t})}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new Bi({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const s in this._activeBatches)this._activeBatches[s].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let s=this._activeBatches[e.batcherName];s||(s=this._activeBatches[e.batcherName]=Tp.getBatcher(e.batcherName,this.renderer.limits.maxBatchableTextures),s.begin()),this._activeBatch=s}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const s in t){const i=t[s],n=i.geometry;n.indexBuffer.setDataWithSize(i.indexBuffer,i.indexSize,!0),n.buffers[0].setDataWithSize(i.attributeBuffer.float32View,i.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const s in t){const i=t[s],n=i.geometry;i.dirty&&(i.dirty=!1,n.buffers[0].update(i.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,s=t.geometry,i=t.shader;this._adaptor.start(this,s,i)}this._adaptor.execute(this,e)}destroyInstructionSet(e){const t=this._batchersByInstructionSet[e.uid];if(t){for(const s in t)t[s].destroy();delete this._batchersByInstructionSet[e.uid],this._activeBatches===t&&(this._activeBatches=Object.create(null),this._activeBatch=null)}}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};qa.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"batch"};qa._availableBatchers=Object.create(null);let Li=qa;q.handleByMap(S.Batcher,Li._availableBatchers);q.add(Bi);const Sp={name:"texture-bit",vertex:{header:`
558
558
 
559
559
  struct TextureUniforms {
560
560
  uTextureMatrix:mat3x3<f32>,
@@ -580,9 +580,9 @@ fn mainFragment(
580
580
 
581
581
  `,main:`
582
582
  outColor = texture(uTexture, vUV);
583
- `}},my=new ke;class gy extends lr{constructor(){super(),this._placeholderSprite=new ss(H.EMPTY),this.filters=[new Yf({sprite:this._placeholderSprite,inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].setSprite(e)}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}get channel(){return this.filters[0].channel}set channel(e){this.filters[0].channel=e}reset(){this._placeholderSprite.texture=H.EMPTY,this.sprite=this._placeholderSprite}}class Oi{constructor(e){this._activeMaskStage=[],this._usedEffects=[],this._renderer=e,e.runners.postrender.add(this)}push(e,t,s){const i=this._renderer;if(i.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.channel=t._maskOptions.channel??"red",e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(s,i,null),n.includeInBuild=!1}i.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,s=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const i=Se.get(gy);if(i.inverse=e.inverse,i.channel=e.mask.channel,s){e.mask.mask.measurable=!0;const n=gi(e.mask.mask,!0,my);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Te.getOptimalTexture({width:n.width,height:n.height,resolution:o._resolution,antialias:o.antialias});t.renderTarget.push({target:a,clear:!0}),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=i.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:i,maskedContainer:e.maskedContainer,filterTexture:a})}else i.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:i,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const i=this._activeMaskStage[this._activeMaskStage.length-1];s&&(t.type===Ke.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:i.maskedContainer,filterEffect:i.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const i=this._activeMaskStage.pop();s&&Te.returnTexture(i.filterTexture),this._usedEffects.push(i.filterEffect)}}postrender(){const e=this._usedEffects;for(let t=0;t<e.length;t++)Se.return(e[t]);e.length=0}destroy(){this.postrender(),this._renderer.runners.postrender.remove(this),this._renderer=null,this._activeMaskStage=null,this._usedEffects=null}}Oi.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"alphaMask"};class Ya{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,s){this._renderer.renderPipes.batch.break(s);const i=this._colorStack;i[this._colorStackIndex]=i[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const i=this._colorStack;this._colorStackIndex--;const n=i[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}Ya.extension={type:[C.CanvasPipes],name:"colorMask"};class Ka{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,s){this._renderer.renderPipes.batch.break(s);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,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}Ka.extension={type:[C.WebGLPipes,C.WebGPUPipes],name:"colorMask"};function _y(r,e,t,s,i,n){n=Math.max(0,Math.min(n,Math.min(s,i)/2)),r.moveTo(e+n,t),r.lineTo(e+s-n,t),r.quadraticCurveTo(e+s,t,e+s,t+n),r.lineTo(e+s,t+i-n),r.quadraticCurveTo(e+s,t+i,e+s-n,t+i),r.lineTo(e+n,t+i),r.quadraticCurveTo(e,t+i,e,t+i-n),r.lineTo(e,t+n),r.quadraticCurveTo(e,t,e+n,t)}function Mp(r,e){switch(e.type){case"rectangle":{const t=e;r.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;_y(r,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;r.moveTo(t.x+t.radius,t.y),r.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;r.ellipse?(r.moveTo(t.x+t.halfWidth,t.y),r.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(r.save(),r.translate(t.x,t.y),r.scale(t.halfWidth,t.halfHeight),r.moveTo(1,0),r.arc(0,0,1,0,Math.PI*2),r.restore());break}case"triangle":{const t=e;r.moveTo(t.x,t.y),r.lineTo(t.x2,t.y2),r.lineTo(t.x3,t.y3),r.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!s?.length)break;r.moveTo(s[0],s[1]);for(let i=2;i<s.length;i+=2)r.lineTo(s[i],s[i+1]);t.closePath&&r.closePath();break}}}function yy(r,e,t){const s=[],i=[],n=[];if(!hs[e.type]?.build(e,s))return!1;const a=e.closePath??!0;Gi(s,t,!1,a,i,n);for(let l=0;l<n.length;l+=3){const h=n[l]*2,c=n[l+1]*2,u=n[l+2]*2;r.moveTo(i[h],i[h+1]),r.lineTo(i[c],i[c+1]),r.lineTo(i[u],i[u+1]),r.closePath()}return!0}function xy(r,e){if(!e?.length)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!s?.shape)continue;const i=s.transform,n=i&&!i.isIdentity();n&&(r.save(),r.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Mp(r,s.shape),n&&r.restore()}return!0}class Za{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,s=t.canvasContext,i=s?.activeContext;if(!i)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&i.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 Pe)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=o.context?.instructions;if(!a?.length){this._canvasMaskStack.push(!1);return}i.save(),s.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),i.beginPath();let l=!1,h=!1;for(let c=0;c<a.length;c++){const u=a[c],d=u.action;if(d!=="fill"&&d!=="stroke")continue;const f=u.data,p=f?.path?.shapePath;if(!p?.shapePrimitives?.length)continue;const m=d==="stroke",g=p.shapePrimitives;for(let _=0;_<g.length;_++){const x=g[_];if(!x?.shape)continue;const y=x.transform,b=y&&!y.isIdentity();b&&(i.save(),i.transform(y.a,y.b,y.c,y.d,y.tx,y.ty)),m&&f.style?l=yy(i,x.shape,f.style)||l:(Mp(i,x.shape),h=xy(i,x.holes)||h,l=!0),b&&i.restore()}}if(!l){i.restore(),this._canvasMaskStack.push(!1);return}h?i.clip("evenodd"):i.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),N(t))}}Za.extension={type:[C.CanvasPipes],name:"stencilMask"};class Qa{constructor(e){this._maskHash=new WeakMap,this._renderer=e}push(e,t,s){const i=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(i.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const o=i.mask;o.includeInBuild=!0,this._maskHash.has(i)||this._maskHash.set(i,{instructionsStart:0,instructionsLength:0});const a=this._maskHash.get(i);a.instructionsStart=s.instructionSize,o.collectRenderables(s,n,null),o.includeInBuild=!1,n.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const l=s.instructionSize-a.instructionsStart-1;a.instructionsLength=l}pop(e,t,s){const i=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(i.mask,"none",s),s.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++)s.instructions[s.instructionSize++]=s.instructions[o.instructionsStart++];s.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){const s=this._renderer,i=s.renderTarget.getGpuRenderTarget(s.renderTarget.renderTarget);let n=i.maskStackIndex;e.action==="pushMaskBegin"?(s.renderTarget.ensureDepthStencil(),s.stencil.setStencilMode(me.RENDERING_MASK_ADD,n),n++,s.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?s.stencil.setStencilMode(me.INVERSE_MASK_ACTIVE,n):s.stencil.setStencilMode(me.MASK_ACTIVE,n),s.colorMask.setMask(15)):e.action==="popMaskBegin"?(s.colorMask.setMask(0),n!==0?s.stencil.setStencilMode(me.RENDERING_MASK_REMOVE,n):(s.renderTarget.clear(null,ye.STENCIL),s.stencil.setStencilMode(me.DISABLED,n)),n--):e.action==="popMaskEnd"&&(e.inverse?s.stencil.setStencilMode(me.INVERSE_MASK_ACTIVE,n):s.stencil.setStencilMode(me.MASK_ACTIVE,n),s.colorMask.setMask(15)),i.maskStackIndex=n}destroy(){this._renderer=null,this._maskHash=null}}Qa.extension={type:[C.WebGLPipes,C.WebGPUPipes],name:"stencilMask"};const ae="source-over";function Ep(){const r=Ma(),e=Object.create(null);return e.inherit=ae,e.none=ae,e.normal="source-over",e.add="lighter",e.multiply=r?"multiply":ae,e.screen=r?"screen":ae,e.overlay=r?"overlay":ae,e.darken=r?"darken":ae,e.lighten=r?"lighten":ae,e["color-dodge"]=r?"color-dodge":ae,e["color-burn"]=r?"color-burn":ae,e["hard-light"]=r?"hard-light":ae,e["soft-light"]=r?"soft-light":ae,e.difference=r?"difference":ae,e.exclusion=r?"exclusion":ae,e.saturation=r?"saturation":ae,e.color=r?"color":ae,e.luminosity=r?"luminosity":ae,e["linear-burn"]=r?"color-burn":ae,e["linear-dodge"]=r?"color-dodge":ae,e["linear-light"]=r?"hard-light":ae,e["pin-light"]=r?"hard-light":ae,e["vivid-light"]=r?"hard-light":ae,e["hard-mix"]=ae,e.negation=r?"difference":ae,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=ae,e.divide=ae,e.min=ae,e.max=ae,e}const by=new L;class Ja{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=Ep(),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,s,i){const n=i?L.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||L.IDENTITY;let o=by;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(s=s||l,a){const h=L.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l,o.ty*l)}clear(e,t){const s=this.activeContext,i=this._renderer;if(s.clearRect(0,0,i.width,i.height),e){const n=oe.shared.setValue(e);s.globalAlpha=t??n.alpha,s.fillStyle=n.toHex(),s.fillRect(0,0,i.width,i.height),s.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()}}Ja.extension={type:[C.CanvasSystem],name:"canvasContext"};class el{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}el.extension={type:[C.CanvasSystem],name:"limits"};class Ui{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}}Ui.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"customRender"};function hi(r,e){const t=r.instructionSet,s=t.instructions;for(let i=0;i<t.instructionSize;i++){const n=s[i];e[n.renderPipeId].execute(n)}}class Ni{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&&(Se.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Se.get(Fi));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new L().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push({target:e.texture,clear:!0,frame:e.texture.frame}),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),hi(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}),hi(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Ni.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"renderGroup"};const vy="#808080",Nr=new L,wy=new L,Ty=new L,Mn=new L,Sy=new L;function Cy(r,e,t){r.beginPath();for(let s=0;s<t.length;s+=3){const i=t[s]*2,n=t[s+1]*2,o=t[s+2]*2;r.moveTo(e[i],e[i+1]),r.lineTo(e[n],e[n+1]),r.lineTo(e[o],e[o+1]),r.closePath()}r.fill()}function My(r){return`#${(r&16777215).toString(16).padStart(6,"0")}`}function Ey(r,e,t,s,i,n){n=Math.max(0,Math.min(n,Math.min(s,i)/2)),r.moveTo(e+n,t),r.lineTo(e+s-n,t),r.quadraticCurveTo(e+s,t,e+s,t+n),r.lineTo(e+s,t+i-n),r.quadraticCurveTo(e+s,t+i,e+s-n,t+i),r.lineTo(e+n,t+i),r.quadraticCurveTo(e,t+i,e,t+i-n),r.lineTo(e,t+n),r.quadraticCurveTo(e,t,e+n,t)}function qr(r,e){switch(e.type){case"rectangle":{const t=e;r.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Ey(r,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;r.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;r.ellipse?r.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(r.save(),r.translate(t.x,t.y),r.scale(t.halfWidth,t.halfHeight),r.arc(0,0,1,0,Math.PI*2),r.restore());break}case"triangle":{const t=e;r.moveTo(t.x,t.y),r.lineTo(t.x2,t.y2),r.lineTo(t.x3,t.y3),r.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!s?.length)break;r.moveTo(s[0],s[1]);for(let i=2;i<s.length;i+=2)r.lineTo(s[i],s[i+1]);t.closePath&&r.closePath();break}}}function ky(r,e){if(!e?.length)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!s?.shape)continue;const i=s.transform,n=i&&!i.isIdentity();n&&(r.save(),r.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),qr(r,s.shape),n&&r.restore()}return!0}function Py(r,e,t,s){const i=r.fill;if(i instanceof Xe){i.buildGradient();const o=i.texture;if(o){const a=Y.getTintedPattern(o,e),l=t?Mn.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):Mn.copyFrom(i.transform);return s&&!r.textureSpace&&l.append(s),Y.applyPatternTransform(a,l),a}}if(i instanceof Gs){const o=Y.getTintedPattern(i.texture,e);return Y.applyPatternTransform(o,i.transform,!1),o}const n=r.texture;if(n&&n!==H.WHITE){if(!n.source.resource)return vy;const o=Y.getTintedPattern(n,e);let a=r.matrix;if(t){const{resolution:l}=n.source;if(a=Mn.copyFrom(t),n.rotate){const{uvs:h,orig:c}=n;a.prepend(Sy.set(h.x1-h.x0,h.y1-h.y0,h.x3-h.x0,h.y3-h.y0,h.x0,h.y0).invert()).scale(c.width*l,c.height*l)}else a.scale(n.source.pixelWidth,n.source.pixelHeight).translate(-n.frame.x*l,-n.frame.y*l)}return Y.applyPatternTransform(o,a),o}return My(e)}class tl{constructor(){this.shader=null}contextChange(e){}execute(e,t){const s=e.renderer,i=s.canvasContext,n=i.activeContext,o=t.groupTransform,a=s.globalUniforms.globalUniformData?.worldColor??4294967295,l=t.groupColorAlpha,h=(a>>>24&255)/255,c=(l>>>24&255)/255,u=s.filter?.alphaMultiplier??1,d=h*c*u;if(d<=0)return;const f=a&16777215,p=l&16777215,m=Zt(Kt(p,f)),g=s._roundPixels|t._roundPixels;n.save(),i.setContextTransform(o,g===1),i.setBlendMode(t.groupBlendMode);const _=t.context.instructions;for(let x=0;x<_.length;x++){const y=_[x];if(y.action==="texture"){const T=y.data,A=T.image,I=A?Y.getCanvasSource(A):null;if(!I)continue;const F=T.alpha*d;if(F<=0)continue;const X=Kt(T.style,m);n.globalAlpha=F;let R=I;X!==16777215&&(R=Y.getTintedCanvas({texture:A},X));const M=A.frame,G=A.source._resolution??A.source.resolution??1;let B=M.x*G,U=M.y*G;const W=M.width*G,se=M.height*G;R!==I&&(B=0,U=0);const te=T.transform,ie=te&&!te.isIdentity(),$=A.rotate;ie||$?(Nr.copyFrom(o),ie&&Nr.append(te),$&&Z.matrixAppendRotationInv(Nr,$,T.dx,T.dy,T.dw,T.dh),i.setContextTransform(Nr,g===1)):i.setContextTransform(o,g===1),n.drawImage(R,B,U,R===I?W:R.width,R===I?se:R.height,$?0:T.dx,$?0:T.dy,T.dw,T.dh),(ie||$)&&i.setContextTransform(o,g===1);continue}const b=y.data,w=b?.path?.shapePath;if(!w?.shapePrimitives?.length)continue;const v=b.style,S=Kt(v.color,m),E=v.alpha*d;if(E<=0)continue;const k=y.action==="stroke";if(n.globalAlpha=E,k){const T=v;n.lineWidth=T.width,n.lineCap=T.cap,n.lineJoin=T.join,n.miterLimit=T.miterLimit}const P=w.shapePrimitives;if(!k&&b.hole?.shapePath?.shapePrimitives?.length){const T=P[P.length-1];T.holes=b.hole.shapePath.shapePrimitives}for(let T=0;T<P.length;T++){const A=P[T];if(!A?.shape)continue;const I=A.transform,F=I&&!I.isIdentity(),X=v.texture&&v.texture!==H.WHITE,R=v.textureSpace==="global"?I:null,M=X?xa(wy,v,A.shape,R):null,G=F?Ty.copyFrom(o).append(I):o,B=Py(v,S,M,G);if(F&&(n.save(),n.transform(I.a,I.b,I.c,I.d,I.tx,I.ty)),k){const U=v;if(U.alignment!==.5&&!U.pixelLine){const se=[],te=[],ie=[];if(hs[A.shape.type]?.build(A.shape,se)){const Ze=A.shape.closePath??!0;Gi(se,U,!1,Ze,te,ie),n.fillStyle=B,Cy(n,te,ie)}else n.strokeStyle=B,n.beginPath(),qr(n,A.shape),n.stroke()}else n.strokeStyle=B,n.beginPath(),qr(n,A.shape),n.stroke()}else n.fillStyle=B,n.beginPath(),qr(n,A.shape),ky(n,A.holes)?n.fill("evenodd"):n.fill();F&&n.restore()}}n.restore()}destroy(){this.shader=null}}tl.extension={type:[C.CanvasPipesAdaptor],name:"graphics"};class Hi{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,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 Fi;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}}Hi.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"sprite"};const rr={};q.handle(C.BlendMode,r=>{if(!r.name)throw new Error("BlendMode extension must have a name property");rr[r.name]=r.ref},r=>{delete rr[r.name]});class zi{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,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){const i=e instanceof ri;if(this._activeBlendMode===t){this._isAdvanced&&e&&!i&&this._renderableList?.push(e);return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!rr[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!rr[s]){N(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const i=this._ensureFilterEffect(s),n=e instanceof ri,o={renderPipeId:"filter",action:"pushFilter",filterEffect:i,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 lr,t.filters=[new rr[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}}zi.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"blendMode"};function ci(r,e){e||(e=0);for(let t=e;t<r.length&&r[t];t++)r[t]=null}const Ay=new _e,Ac=ws|cr|bi;function sl(r,e=!1){kp(r);const t=r.childrenToUpdate,s=r.updateTick++;for(const i in t){const n=Number(i),o=t[i],a=o.list,l=o.index;for(let h=0;h<l;h++){const c=a[h];c.parentRenderGroup===r&&c.relativeRenderGroupDepth===n&&rl(c,s,0)}ci(a,l),o.index=0}if(e)for(let i=0;i<r.renderGroupChildren.length;i++)sl(r.renderGroupChildren[i],e)}function kp(r){const e=r.root;let t;if(r.renderGroupParent){const s=r.renderGroupParent;r.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),r.worldColor=hr(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else r.worldTransform.copyFrom(e.localTransform),r.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,r.worldAlpha=t,r.worldColorAlpha=r.worldColor+((t*255|0)<<24)}function rl(r,e,t){if(e===r.updateTick)return;r.updateTick=e,r.didChange=!1;const s=r.localTransform;r.updateLocalTransform();const i=r.parent;if(i&&!i.renderGroup?(t|=r._updateFlags,r.relativeGroupTransform.appendFrom(s,i.relativeGroupTransform),t&Ac&&Rc(r,i,t)):(t=r._updateFlags,r.relativeGroupTransform.copyFrom(s),t&Ac&&Rc(r,Ay,t)),!r.renderGroup){const n=r.children,o=n.length;for(let h=0;h<o;h++)rl(n[h],e,t);const a=r.parentRenderGroup,l=r;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function Rc(r,e,t){if(t&cr){r.groupColor=hr(r.localColor,e.groupColor);let s=r.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,r.groupAlpha=s,r.groupColorAlpha=r.groupColor+((s*255|0)<<24)}t&bi&&(r.groupBlendMode=r.localBlendMode==="inherit"?e.groupBlendMode:r.localBlendMode),t&ws&&(r.globalDisplayStatus=r.localDisplayStatus&e.globalDisplayStatus),r._updateFlags=0}function Pp(r,e){const{list:t}=r.childrenRenderablesToUpdate;let s=!1;for(let i=0;i<r.childrenRenderablesToUpdate.index;i++){const n=t[i];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return r.structureDidChange=s,s}const Ry=new L;class il{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,i=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=Ry;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}),hi(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=i}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds(),i=this._renderer,n=e.textureOptions.resolution||i.view.resolution,o=e.textureOptions.antialias??i.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;s.ceil(),e.texture&&Te.returnTexture(e.texture);const h=Te.getOptimalTexture({width:s.width,height:s.height,resolution:n,antialias:o,scaleMode:a});e.texture=h,e._textureBounds||(e._textureBounds=new ke),e._textureBounds.copyFrom(s),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Te.returnTexture(e.texture),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?ci(e.childrenRenderablesToUpdate.list,0):Pp(e,s),sl(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 i=0;i<e.renderGroupChildren.length;i++)this._updateRenderGroups(e.renderGroupChildren[i])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let i=0;i<s;i++){const n=t[i];n.didViewUpdate&&e.updateRenderable(n)}ci(t,s)}_buildInstructions(e,t){const s=e.root,i=e.instructionSet;i.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(i),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(i,n,null),o.batch.buildEnd(i),o.blendMode.buildEnd(i)}}il.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"renderGroup"};const nl=class Ap{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new oe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...Ap.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){oe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&N("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(){}};nl.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"background",priority:0};nl.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Rp=nl;const En={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},ol=class Bp{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof _e||e instanceof H?{target:e,...t}:{...t,...e}}async image(e){const t=J.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Bp.defaultImageOptions);const{format:t,quality:s}=e,i=this.canvas(e);if(i.toBlob!==void 0)return new Promise((n,o)=>{i.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)},En[t],s)});if(i.toDataURL!==void 0)return i.toDataURL(En[t],s);if(i.convertToBlob!==void 0){const n=await i.convertToBlob({type:En[t],quality:s});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,s=this._renderer;if(t instanceof H)return s.texture.generateCanvas(t);const i=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(i);return i.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,i=t instanceof H?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(i);return t instanceof _e&&i.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof H?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),i=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${i}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};ol.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"extract"};ol.defaultImageOptions={format:"png",quality:1};let Ip=ol;class wr extends H{static create(e){const{dynamic:t,textureOptions:s,...i}=e;return new wr({...s,source:new de(i),dynamic:t??!1})}resize(e,t,s){return this.source.resize(e,t,s),this}}const By=new ee,Iy=new ke,Gy=[0,0,0,0];class al{constructor(e){this._renderer=e}generateTexture(e){e instanceof _e&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,i=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:oe.shared.setValue(n).toArray():n=Gy;const o=e.frame?.copyTo(By)||yi(i,Iy).rectangle,a=e.defaultAnchor&&{defaultAnchor:e.defaultAnchor};o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const l=wr.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s,textureOptions:a}),h=L.shared.translate(-o.x,-o.y);return this._renderer.render({container:i,transform:h,target:l,clearColor:n}),l.source.updateMipmaps(),l}destroy(){this._renderer=null}}al.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"textureGenerator"};function Gp(r){let e=!1;for(const s in r)if(r[s]==null){e=!0;break}if(!e)return r;const t=Object.create(null);for(const s in r){const i=r[s];i&&(t[s]=i)}return t}function Dp(r){let e=0;for(let t=0;t<r.length;t++)r[t]==null?e++:r[t-e]=r[t];return r.length-=e,r}const ll=class Fp{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._running=!1,this._renderer=e}init(e){e={...Fp.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:s,collection:i,type:n}=t;n==="hash"?s[i]=Gp(s[i]):s[i]=Dp(s[i])}},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 s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}addCollection(e,t,s){this._managedCollections.push({context:e,collection:t,type:s})}addResource(e,t){if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,e._onTouch?.(this.now);return}const s=this._managedResources.length;e._gcData={index:s,type:t},e._gcLastUsed=this.now,e._onTouch?.(this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const s=t.index,i=this._managedResources.length-1;if(this._running)this._managedResources[s]=null;else{if(s!==i){const n=this._managedResources[i];this._managedResources[s]=n,n._gcData.index=s}this._managedResources.length--}e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,s,i=0){this._managedResourceHashes.push({context:e,hash:t,type:s,priority:i}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){if(this._running)return;const e=performance.now(),t=this._managedResourceHashes,s=this._managedResources;this._running=!0;try{for(const n of t)this.runOnHash(n,e);const i=s.length;for(let n=0;n<i;n++){const o=s[n];o&&this.runOnResource(o,e)}}finally{let i=0;for(let n=0;n<s.length;n++){const o=s[n];o&&(i!==n&&(s[i]=o,o._gcData.index=i),i++)}s.length=i,this._running=!1}}updateRenderableGCTick(e,t){const s=e.renderGroup??e.parentRenderGroup,i=s?.instructionSet?.gcTick??-1;(s?.gcTick??0)===i&&(e._gcLastUsed=t,e._onTouch?.(t))}runOnResource(e,t){e._gcData.type==="renderable"&&this.updateRenderableGCTick(e,t),!(t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect)&&(e.off("unload",this.removeResource,this),e.unload(),this.removeResource(e))}_createHashClone(e,t){const s=Object.create(null);for(const i in e){if(i===t)break;e[i]!==null&&(s[i]=e[i])}return s}runOnHash(e,t){const{context:s,hash:i,type:n}=e,o=s[i];let a=null,l=0;for(const h in o){const c=o[h];if(c===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(c._gcLastUsed===-1){c._gcLastUsed=t,c._onTouch?.(t),a&&(a[h]=c);continue}if(n==="renderable"&&this.updateRenderableGCTick(c,t),!(t-c._gcLastUsed<this.maxUnusedTime)&&c.autoGarbageCollect){if(n==="renderable"){const d=c,f=d.renderGroup??d.parentRenderGroup;f&&(f.structureDidChange=!0)}c.unload(),c._gcData=null,c._gcLastUsed=-1,a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h))}else a&&(a[h]=c)}a&&(s[i]=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}};ll.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"gc",priority:0};ll.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Lp=ll;class hl{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:s,worldColor:i,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new L,worldColor:4294967295,offset:new he},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:i||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,Ra(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 St,this._activeBindGroups.push(u),u.setResource(h,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===Ke.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 rt({uProjectionMatrix:{value:new L,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new L,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}}hl.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"globalUniforms"};let Dy=1;class cl{constructor(){this._tasks=[],this._offset=0}init(){We.system.add(this._update,this)}repeat(e,t,s=!0){const i=Dy++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:i}),i}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 s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const i=e-s.start;s.func(i),s.last=e}}}destroy(){We.system.remove(this._update,this),this._tasks.length=0}}cl.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"scheduler",priority:0};let Bc=!1;function Op(r){if(!Bc){if(J.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${gr} (${r}) http://www.pixijs.com/
583
+ `}},my=new ke;class gy extends lr{constructor(){super(),this._placeholderSprite=new ss(H.EMPTY),this.filters=[new Yf({sprite:this._placeholderSprite,inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].setSprite(e)}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}get channel(){return this.filters[0].channel}set channel(e){this.filters[0].channel=e}reset(){this._placeholderSprite.texture=H.EMPTY,this.sprite=this._placeholderSprite}}class Oi{constructor(e){this._activeMaskStage=[],this._usedEffects=[],this._renderer=e,e.runners.postrender.add(this)}push(e,t,s){const i=this._renderer;if(i.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.channel=t._maskOptions.channel??"red",e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(s,i,null),n.includeInBuild=!1}i.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,s=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const i=Se.get(gy);if(i.inverse=e.inverse,i.channel=e.mask.channel,s){e.mask.mask.measurable=!0;const n=gi(e.mask.mask,!0,my);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Te.getOptimalTexture({width:n.width,height:n.height,resolution:o._resolution,antialias:o.antialias});t.renderTarget.push({target:a,clear:!0}),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=i.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:i,maskedContainer:e.maskedContainer,filterTexture:a})}else i.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:i,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const i=this._activeMaskStage[this._activeMaskStage.length-1];s&&(t.type===Ke.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:i.maskedContainer,filterEffect:i.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const i=this._activeMaskStage.pop();s&&Te.returnTexture(i.filterTexture),this._usedEffects.push(i.filterEffect)}}postrender(){const e=this._usedEffects;for(let t=0;t<e.length;t++)Se.return(e[t]);e.length=0}destroy(){this.postrender(),this._renderer.runners.postrender.remove(this),this._renderer=null,this._activeMaskStage=null,this._usedEffects=null}}Oi.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"alphaMask"};class Ya{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,s){this._renderer.renderPipes.batch.break(s);const i=this._colorStack;i[this._colorStackIndex]=i[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const i=this._colorStack;this._colorStackIndex--;const n=i[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}Ya.extension={type:[S.CanvasPipes],name:"colorMask"};class Ka{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,s){this._renderer.renderPipes.batch.break(s);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,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}Ka.extension={type:[S.WebGLPipes,S.WebGPUPipes],name:"colorMask"};function _y(r,e,t,s,i,n){n=Math.max(0,Math.min(n,Math.min(s,i)/2)),r.moveTo(e+n,t),r.lineTo(e+s-n,t),r.quadraticCurveTo(e+s,t,e+s,t+n),r.lineTo(e+s,t+i-n),r.quadraticCurveTo(e+s,t+i,e+s-n,t+i),r.lineTo(e+n,t+i),r.quadraticCurveTo(e,t+i,e,t+i-n),r.lineTo(e,t+n),r.quadraticCurveTo(e,t,e+n,t)}function Mp(r,e){switch(e.type){case"rectangle":{const t=e;r.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;_y(r,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;r.moveTo(t.x+t.radius,t.y),r.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;r.ellipse?(r.moveTo(t.x+t.halfWidth,t.y),r.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(r.save(),r.translate(t.x,t.y),r.scale(t.halfWidth,t.halfHeight),r.moveTo(1,0),r.arc(0,0,1,0,Math.PI*2),r.restore());break}case"triangle":{const t=e;r.moveTo(t.x,t.y),r.lineTo(t.x2,t.y2),r.lineTo(t.x3,t.y3),r.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!s?.length)break;r.moveTo(s[0],s[1]);for(let i=2;i<s.length;i+=2)r.lineTo(s[i],s[i+1]);t.closePath&&r.closePath();break}}}function yy(r,e,t){const s=[],i=[],n=[];if(!hs[e.type]?.build(e,s))return!1;const a=e.closePath??!0;Gi(s,t,!1,a,i,n);for(let l=0;l<n.length;l+=3){const h=n[l]*2,c=n[l+1]*2,u=n[l+2]*2;r.moveTo(i[h],i[h+1]),r.lineTo(i[c],i[c+1]),r.lineTo(i[u],i[u+1]),r.closePath()}return!0}function xy(r,e){if(!e?.length)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!s?.shape)continue;const i=s.transform,n=i&&!i.isIdentity();n&&(r.save(),r.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Mp(r,s.shape),n&&r.restore()}return!0}class Za{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,s=t.canvasContext,i=s?.activeContext;if(!i)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&i.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 Pe)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=o.context?.instructions;if(!a?.length){this._canvasMaskStack.push(!1);return}i.save(),s.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),i.beginPath();let l=!1,h=!1;for(let c=0;c<a.length;c++){const u=a[c],d=u.action;if(d!=="fill"&&d!=="stroke")continue;const f=u.data,p=f?.path?.shapePath;if(!p?.shapePrimitives?.length)continue;const m=d==="stroke",g=p.shapePrimitives;for(let _=0;_<g.length;_++){const x=g[_];if(!x?.shape)continue;const y=x.transform,b=y&&!y.isIdentity();b&&(i.save(),i.transform(y.a,y.b,y.c,y.d,y.tx,y.ty)),m&&f.style?l=yy(i,x.shape,f.style)||l:(Mp(i,x.shape),h=xy(i,x.holes)||h,l=!0),b&&i.restore()}}if(!l){i.restore(),this._canvasMaskStack.push(!1);return}h?i.clip("evenodd"):i.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),N(t))}}Za.extension={type:[S.CanvasPipes],name:"stencilMask"};class Qa{constructor(e){this._maskHash=new WeakMap,this._renderer=e}push(e,t,s){const i=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(i.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const o=i.mask;o.includeInBuild=!0,this._maskHash.has(i)||this._maskHash.set(i,{instructionsStart:0,instructionsLength:0});const a=this._maskHash.get(i);a.instructionsStart=s.instructionSize,o.collectRenderables(s,n,null),o.includeInBuild=!1,n.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const l=s.instructionSize-a.instructionsStart-1;a.instructionsLength=l}pop(e,t,s){const i=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(i.mask,"none",s),s.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++)s.instructions[s.instructionSize++]=s.instructions[o.instructionsStart++];s.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){const s=this._renderer,i=s.renderTarget.getGpuRenderTarget(s.renderTarget.renderTarget);let n=i.maskStackIndex;e.action==="pushMaskBegin"?(s.renderTarget.ensureDepthStencil(),s.stencil.setStencilMode(me.RENDERING_MASK_ADD,n),n++,s.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?s.stencil.setStencilMode(me.INVERSE_MASK_ACTIVE,n):s.stencil.setStencilMode(me.MASK_ACTIVE,n),s.colorMask.setMask(15)):e.action==="popMaskBegin"?(s.colorMask.setMask(0),n!==0?s.stencil.setStencilMode(me.RENDERING_MASK_REMOVE,n):(s.renderTarget.clear(null,ye.STENCIL),s.stencil.setStencilMode(me.DISABLED,n)),n--):e.action==="popMaskEnd"&&(e.inverse?s.stencil.setStencilMode(me.INVERSE_MASK_ACTIVE,n):s.stencil.setStencilMode(me.MASK_ACTIVE,n),s.colorMask.setMask(15)),i.maskStackIndex=n}destroy(){this._renderer=null,this._maskHash=null}}Qa.extension={type:[S.WebGLPipes,S.WebGPUPipes],name:"stencilMask"};const ae="source-over";function Ep(){const r=Ma(),e=Object.create(null);return e.inherit=ae,e.none=ae,e.normal="source-over",e.add="lighter",e.multiply=r?"multiply":ae,e.screen=r?"screen":ae,e.overlay=r?"overlay":ae,e.darken=r?"darken":ae,e.lighten=r?"lighten":ae,e["color-dodge"]=r?"color-dodge":ae,e["color-burn"]=r?"color-burn":ae,e["hard-light"]=r?"hard-light":ae,e["soft-light"]=r?"soft-light":ae,e.difference=r?"difference":ae,e.exclusion=r?"exclusion":ae,e.saturation=r?"saturation":ae,e.color=r?"color":ae,e.luminosity=r?"luminosity":ae,e["linear-burn"]=r?"color-burn":ae,e["linear-dodge"]=r?"color-dodge":ae,e["linear-light"]=r?"hard-light":ae,e["pin-light"]=r?"hard-light":ae,e["vivid-light"]=r?"hard-light":ae,e["hard-mix"]=ae,e.negation=r?"difference":ae,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=ae,e.divide=ae,e.min=ae,e.max=ae,e}const by=new L;class Ja{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=Ep(),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,s,i){const n=i?L.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||L.IDENTITY;let o=by;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(s=s||l,a){const h=L.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l,o.ty*l)}clear(e,t){const s=this.activeContext,i=this._renderer;if(s.clearRect(0,0,i.width,i.height),e){const n=oe.shared.setValue(e);s.globalAlpha=t??n.alpha,s.fillStyle=n.toHex(),s.fillRect(0,0,i.width,i.height),s.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()}}Ja.extension={type:[S.CanvasSystem],name:"canvasContext"};class el{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}el.extension={type:[S.CanvasSystem],name:"limits"};class Ui{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}}Ui.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"customRender"};function hi(r,e){const t=r.instructionSet,s=t.instructions;for(let i=0;i<t.instructionSize;i++){const n=s[i];e[n.renderPipeId].execute(n)}}class Ni{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&&(Se.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Se.get(Fi));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new L().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push({target:e.texture,clear:!0,frame:e.texture.frame}),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),hi(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}),hi(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Ni.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"renderGroup"};const vy="#808080",Nr=new L,wy=new L,Ty=new L,Mn=new L,Sy=new L;function Cy(r,e,t){r.beginPath();for(let s=0;s<t.length;s+=3){const i=t[s]*2,n=t[s+1]*2,o=t[s+2]*2;r.moveTo(e[i],e[i+1]),r.lineTo(e[n],e[n+1]),r.lineTo(e[o],e[o+1]),r.closePath()}r.fill()}function My(r){return`#${(r&16777215).toString(16).padStart(6,"0")}`}function Ey(r,e,t,s,i,n){n=Math.max(0,Math.min(n,Math.min(s,i)/2)),r.moveTo(e+n,t),r.lineTo(e+s-n,t),r.quadraticCurveTo(e+s,t,e+s,t+n),r.lineTo(e+s,t+i-n),r.quadraticCurveTo(e+s,t+i,e+s-n,t+i),r.lineTo(e+n,t+i),r.quadraticCurveTo(e,t+i,e,t+i-n),r.lineTo(e,t+n),r.quadraticCurveTo(e,t,e+n,t)}function qr(r,e){switch(e.type){case"rectangle":{const t=e;r.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Ey(r,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;r.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;r.ellipse?r.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(r.save(),r.translate(t.x,t.y),r.scale(t.halfWidth,t.halfHeight),r.arc(0,0,1,0,Math.PI*2),r.restore());break}case"triangle":{const t=e;r.moveTo(t.x,t.y),r.lineTo(t.x2,t.y2),r.lineTo(t.x3,t.y3),r.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!s?.length)break;r.moveTo(s[0],s[1]);for(let i=2;i<s.length;i+=2)r.lineTo(s[i],s[i+1]);t.closePath&&r.closePath();break}}}function ky(r,e){if(!e?.length)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!s?.shape)continue;const i=s.transform,n=i&&!i.isIdentity();n&&(r.save(),r.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),qr(r,s.shape),n&&r.restore()}return!0}function Py(r,e,t,s){const i=r.fill;if(i instanceof Xe){i.buildGradient();const o=i.texture;if(o){const a=Y.getTintedPattern(o,e),l=t?Mn.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):Mn.copyFrom(i.transform);return s&&!r.textureSpace&&l.append(s),Y.applyPatternTransform(a,l),a}}if(i instanceof Gs){const o=Y.getTintedPattern(i.texture,e);return Y.applyPatternTransform(o,i.transform,!1),o}const n=r.texture;if(n&&n!==H.WHITE){if(!n.source.resource)return vy;const o=Y.getTintedPattern(n,e);let a=r.matrix;if(t){const{resolution:l}=n.source;if(a=Mn.copyFrom(t),n.rotate){const{uvs:h,orig:c}=n;a.prepend(Sy.set(h.x1-h.x0,h.y1-h.y0,h.x3-h.x0,h.y3-h.y0,h.x0,h.y0).invert()).scale(c.width*l,c.height*l)}else a.scale(n.source.pixelWidth,n.source.pixelHeight).translate(-n.frame.x*l,-n.frame.y*l)}return Y.applyPatternTransform(o,a),o}return My(e)}class tl{constructor(){this.shader=null}contextChange(e){}execute(e,t){const s=e.renderer,i=s.canvasContext,n=i.activeContext,o=t.groupTransform,a=s.globalUniforms.globalUniformData?.worldColor??4294967295,l=t.groupColorAlpha,h=(a>>>24&255)/255,c=(l>>>24&255)/255,u=s.filter?.alphaMultiplier??1,d=h*c*u;if(d<=0)return;const f=a&16777215,p=l&16777215,m=Zt(Kt(p,f)),g=s._roundPixels|t._roundPixels;n.save(),i.setContextTransform(o,g===1),i.setBlendMode(t.groupBlendMode);const _=t.context.instructions;for(let x=0;x<_.length;x++){const y=_[x];if(y.action==="texture"){const C=y.data,E=C.image,B=E?Y.getCanvasSource(E):null;if(!B)continue;const G=C.alpha*d;if(G<=0)continue;const V=Kt(C.style,m);n.globalAlpha=G;let I=B;V!==16777215&&(I=Y.getTintedCanvas({texture:E},V));const M=E.frame,D=E.source._resolution??E.source.resolution??1;let R=M.x*D,U=M.y*D;const W=M.width*D,se=M.height*D;I!==B&&(R=0,U=0);const te=C.transform,ie=te&&!te.isIdentity(),$=E.rotate;ie||$?(Nr.copyFrom(o),ie&&Nr.append(te),$&&Z.matrixAppendRotationInv(Nr,$,C.dx,C.dy,C.dw,C.dh),i.setContextTransform(Nr,g===1)):i.setContextTransform(o,g===1),n.drawImage(I,R,U,I===B?W:I.width,I===B?se:I.height,$?0:C.dx,$?0:C.dy,C.dw,C.dh),(ie||$)&&i.setContextTransform(o,g===1);continue}const b=y.data,w=b?.path?.shapePath;if(!w?.shapePrimitives?.length)continue;const v=b.style,T=Kt(v.color,m),k=v.alpha*d;if(k<=0)continue;const P=y.action==="stroke";if(n.globalAlpha=k,P){const C=v;n.lineWidth=C.width,n.lineCap=C.cap,n.lineJoin=C.join,n.miterLimit=C.miterLimit}const A=w.shapePrimitives;if(!P&&b.hole?.shapePath?.shapePrimitives?.length){const C=A[A.length-1];C.holes=b.hole.shapePath.shapePrimitives}for(let C=0;C<A.length;C++){const E=A[C];if(!E?.shape)continue;const B=E.transform,G=B&&!B.isIdentity(),V=v.texture&&v.texture!==H.WHITE,I=v.textureSpace==="global"?B:null,M=V?xa(wy,v,E.shape,I):null,D=G?Ty.copyFrom(o).append(B):o,R=Py(v,T,M,D);if(G&&(n.save(),n.transform(B.a,B.b,B.c,B.d,B.tx,B.ty)),P){const U=v;if(U.alignment!==.5&&!U.pixelLine){const se=[],te=[],ie=[];if(hs[E.shape.type]?.build(E.shape,se)){const Ze=E.shape.closePath??!0;Gi(se,U,!1,Ze,te,ie),n.fillStyle=R,Cy(n,te,ie)}else n.strokeStyle=R,n.beginPath(),qr(n,E.shape),n.stroke()}else n.strokeStyle=R,n.beginPath(),qr(n,E.shape),n.stroke()}else n.fillStyle=R,n.beginPath(),qr(n,E.shape),ky(n,E.holes)?n.fill("evenodd"):n.fill();G&&n.restore()}}n.restore()}destroy(){this.shader=null}}tl.extension={type:[S.CanvasPipesAdaptor],name:"graphics"};class Hi{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,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 Fi;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}}Hi.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"sprite"};const rr={};q.handle(S.BlendMode,r=>{if(!r.name)throw new Error("BlendMode extension must have a name property");rr[r.name]=r.ref},r=>{delete rr[r.name]});class zi{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,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){const i=e instanceof ri;if(this._activeBlendMode===t){this._isAdvanced&&e&&!i&&this._renderableList?.push(e);return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!rr[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!rr[s]){N(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const i=this._ensureFilterEffect(s),n=e instanceof ri,o={renderPipeId:"filter",action:"pushFilter",filterEffect:i,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 lr,t.filters=[new rr[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}}zi.extension={type:[S.WebGLPipes,S.WebGPUPipes,S.CanvasPipes],name:"blendMode"};function ci(r,e){e||(e=0);for(let t=e;t<r.length&&r[t];t++)r[t]=null}const Ay=new _e,Ac=ws|cr|bi;function sl(r,e=!1){kp(r);const t=r.childrenToUpdate,s=r.updateTick++;for(const i in t){const n=Number(i),o=t[i],a=o.list,l=o.index;for(let h=0;h<l;h++){const c=a[h];c.parentRenderGroup===r&&c.relativeRenderGroupDepth===n&&rl(c,s,0)}ci(a,l),o.index=0}if(e)for(let i=0;i<r.renderGroupChildren.length;i++)sl(r.renderGroupChildren[i],e)}function kp(r){const e=r.root;let t;if(r.renderGroupParent){const s=r.renderGroupParent;r.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),r.worldColor=hr(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else r.worldTransform.copyFrom(e.localTransform),r.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,r.worldAlpha=t,r.worldColorAlpha=r.worldColor+((t*255|0)<<24)}function rl(r,e,t){if(e===r.updateTick)return;r.updateTick=e,r.didChange=!1;const s=r.localTransform;r.updateLocalTransform();const i=r.parent;if(i&&!i.renderGroup?(t|=r._updateFlags,r.relativeGroupTransform.appendFrom(s,i.relativeGroupTransform),t&Ac&&Rc(r,i,t)):(t=r._updateFlags,r.relativeGroupTransform.copyFrom(s),t&Ac&&Rc(r,Ay,t)),!r.renderGroup){const n=r.children,o=n.length;for(let h=0;h<o;h++)rl(n[h],e,t);const a=r.parentRenderGroup,l=r;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function Rc(r,e,t){if(t&cr){r.groupColor=hr(r.localColor,e.groupColor);let s=r.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,r.groupAlpha=s,r.groupColorAlpha=r.groupColor+((s*255|0)<<24)}t&bi&&(r.groupBlendMode=r.localBlendMode==="inherit"?e.groupBlendMode:r.localBlendMode),t&ws&&(r.globalDisplayStatus=r.localDisplayStatus&e.globalDisplayStatus),r._updateFlags=0}function Pp(r,e){const{list:t}=r.childrenRenderablesToUpdate;let s=!1;for(let i=0;i<r.childrenRenderablesToUpdate.index;i++){const n=t[i];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return r.structureDidChange=s,s}const Ry=new L;class il{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,i=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=Ry;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}),hi(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=i}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds(),i=this._renderer,n=e.textureOptions.resolution||i.view.resolution,o=e.textureOptions.antialias??i.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;s.ceil(),e.texture&&Te.returnTexture(e.texture);const h=Te.getOptimalTexture({width:s.width,height:s.height,resolution:n,antialias:o,scaleMode:a});e.texture=h,e._textureBounds||(e._textureBounds=new ke),e._textureBounds.copyFrom(s),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Te.returnTexture(e.texture),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?ci(e.childrenRenderablesToUpdate.list,0):Pp(e,s),sl(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 i=0;i<e.renderGroupChildren.length;i++)this._updateRenderGroups(e.renderGroupChildren[i])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let i=0;i<s;i++){const n=t[i];n.didViewUpdate&&e.updateRenderable(n)}ci(t,s)}_buildInstructions(e,t){const s=e.root,i=e.instructionSet;i.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(i),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(i,n,null),o.batch.buildEnd(i),o.blendMode.buildEnd(i)}}il.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"renderGroup"};const nl=class Ap{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new oe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...Ap.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){oe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&N("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(){}};nl.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"background",priority:0};nl.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Rp=nl;const En={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},ol=class Bp{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof _e||e instanceof H?{target:e,...t}:{...t,...e}}async image(e){const t=J.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Bp.defaultImageOptions);const{format:t,quality:s}=e,i=this.canvas(e);if(i.toBlob!==void 0)return new Promise((n,o)=>{i.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)},En[t],s)});if(i.toDataURL!==void 0)return i.toDataURL(En[t],s);if(i.convertToBlob!==void 0){const n=await i.convertToBlob({type:En[t],quality:s});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,s=this._renderer;if(t instanceof H)return s.texture.generateCanvas(t);const i=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(i);return i.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,i=t instanceof H?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(i);return t instanceof _e&&i.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof H?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),i=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${i}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};ol.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"extract"};ol.defaultImageOptions={format:"png",quality:1};let Ip=ol;class wr extends H{static create(e){const{dynamic:t,textureOptions:s,...i}=e;return new wr({...s,source:new de(i),dynamic:t??!1})}resize(e,t,s){return this.source.resize(e,t,s),this}}const By=new ee,Iy=new ke,Gy=[0,0,0,0];class al{constructor(e){this._renderer=e}generateTexture(e){e instanceof _e&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,i=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:oe.shared.setValue(n).toArray():n=Gy;const o=e.frame?.copyTo(By)||yi(i,Iy).rectangle,a=e.defaultAnchor&&{defaultAnchor:e.defaultAnchor};o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const l=wr.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s,textureOptions:a}),h=L.shared.translate(-o.x,-o.y);return this._renderer.render({container:i,transform:h,target:l,clearColor:n}),l.source.updateMipmaps(),l}destroy(){this._renderer=null}}al.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"textureGenerator"};function Gp(r){let e=!1;for(const s in r)if(r[s]==null){e=!0;break}if(!e)return r;const t=Object.create(null);for(const s in r){const i=r[s];i&&(t[s]=i)}return t}function Dp(r){let e=0;for(let t=0;t<r.length;t++)r[t]==null?e++:r[t-e]=r[t];return r.length-=e,r}const ll=class Fp{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._running=!1,this._renderer=e}init(e){e={...Fp.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:s,collection:i,type:n}=t;n==="hash"?s[i]=Gp(s[i]):s[i]=Dp(s[i])}},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 s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}addCollection(e,t,s){this._managedCollections.push({context:e,collection:t,type:s})}addResource(e,t){if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,e._onTouch?.(this.now);return}const s=this._managedResources.length;e._gcData={index:s,type:t},e._gcLastUsed=this.now,e._onTouch?.(this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const s=t.index,i=this._managedResources.length-1;if(this._running)this._managedResources[s]=null;else{if(s!==i){const n=this._managedResources[i];this._managedResources[s]=n,n._gcData.index=s}this._managedResources.length--}e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,s,i=0){this._managedResourceHashes.push({context:e,hash:t,type:s,priority:i}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){if(this._running)return;const e=performance.now(),t=this._managedResourceHashes,s=this._managedResources;this._running=!0;try{for(const n of t)this.runOnHash(n,e);const i=s.length;for(let n=0;n<i;n++){const o=s[n];o&&this.runOnResource(o,e)}}finally{let i=0;for(let n=0;n<s.length;n++){const o=s[n];o&&(i!==n&&(s[i]=o,o._gcData.index=i),i++)}s.length=i,this._running=!1}}updateRenderableGCTick(e,t){const s=e.renderGroup??e.parentRenderGroup,i=s?.instructionSet?.gcTick??-1;(s?.gcTick??0)===i&&(e._gcLastUsed=t,e._onTouch?.(t))}runOnResource(e,t){e._gcData.type==="renderable"&&this.updateRenderableGCTick(e,t),!(t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect)&&(e.off("unload",this.removeResource,this),e.unload(),this.removeResource(e))}_createHashClone(e,t){const s=Object.create(null);for(const i in e){if(i===t)break;e[i]!==null&&(s[i]=e[i])}return s}runOnHash(e,t){const{context:s,hash:i,type:n}=e,o=s[i];let a=null,l=0;for(const h in o){const c=o[h];if(c===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(c._gcLastUsed===-1){c._gcLastUsed=t,c._onTouch?.(t),a&&(a[h]=c);continue}if(n==="renderable"&&this.updateRenderableGCTick(c,t),!(t-c._gcLastUsed<this.maxUnusedTime)&&c.autoGarbageCollect){if(n==="renderable"){const d=c,f=d.renderGroup??d.parentRenderGroup;f&&(f.structureDidChange=!0)}c.unload(),c._gcData=null,c._gcLastUsed=-1,a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h))}else a&&(a[h]=c)}a&&(s[i]=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}};ll.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"gc",priority:0};ll.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Lp=ll;class hl{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:s,worldColor:i,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new L,worldColor:4294967295,offset:new he},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:i||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,Ra(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 St,this._activeBindGroups.push(u),u.setResource(h,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===Ke.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 rt({uProjectionMatrix:{value:new L,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new L,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}}hl.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"globalUniforms"};let Dy=1;class cl{constructor(){this._tasks=[],this._offset=0}init(){We.system.add(this._update,this)}repeat(e,t,s=!0){const i=Dy++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:i}),i}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 s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const i=e-s.start;s.func(i),s.last=e}}}destroy(){We.system.remove(this._update,this),this._tasks.length=0}}cl.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"scheduler",priority:0};let Bc=!1;function Op(r){if(!Bc){if(J.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${gr} (${r}) http://www.pixijs.com/
584
584
 
585
- `,"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 ${gr} - ${r} - http://www.pixijs.com/`);Bc=!0}}class Wi{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===Ke.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),Op(t)}}}Wi.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"hello",priority:-2};Wi.defaultOptions={hello:!1};const ul=class Up{constructor(e){this._renderer=e}init(e){e={...Up.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return O("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){O("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){O("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){O("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){O("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){O("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};ul.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"renderableGC",priority:0};ul.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Np=ul;const dl=class Yr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){O("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){O("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){O("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){O("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!==Yr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==Yr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==Yr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){O("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};dl.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"textureGC"};dl.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Hp=dl;const zp=class Wp extends Re{constructor(e={}){super(),this.uid=ne("renderTarget"),this.colorAttachments=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,this._depth=!1,this._stencil=!1,this._colorTextures=null;const t="colorAttachments"in e?e:this._normalizeOptions(e);if(this.isRoot=t.isRoot??!1,this.label=t.label,this.colorAttachments=t.colorAttachments,this.depthStencilAttachment=t.depthStencilAttachment,this.depthStencilAttachment){const s=this.depthStencilAttachment.texture.format;this._depth||(this._depth=s.includes("depth")),this._stencil||(this._stencil=s.includes("stencil"))}if(this.colorAttachments.length===0&&!this.depthStencilAttachment)throw new Error("[RenderTarget] no color textures or depth textures were provided. Provide a depthStencilTexture or set depth/stencil to true when using colorTextures: 0.");if(this.colorAttachments.length>0){const s=this.colorTexture;this.resize(s.width,s.height,s._resolution)}this.sizeSource&&this.sizeSource.on("resize",this.onSourceResize,this)}_normalizeOptions(e){const t={...Wp.defaultOptions,...e},s=[];let i;if(typeof t.colorTextures=="number"){if(t.colorTextures>0){this._managedColorTextures=!0;for(let o=0;o<t.colorTextures;o++)s.push({texture:new de({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}),loadOp:"clear",storeOp:"store"})}}else t.colorTextures.forEach(o=>{s.push({texture:o.source,loadOp:"clear",storeOp:"store"})});const n=t.depthStencilTexture===!0;if(this._depth=!!(t.depth||n),this._stencil=!!(t.stencil||n),t.depthStencilTexture instanceof H||t.depthStencilTexture instanceof de){if(t.isRoot)throw new Error("[RenderTarget] cannot attach a depth-stencil texture to the screen — the canvas owns its own depth/stencil buffers. Render to a texture target instead.");i={texture:t.depthStencilTexture.source}}else(n&&!t.isRoot||(t.stencil||t.depth)&&s.length===0)&&(i=this._createDepthStencilTexture(t.width,t.height,t.resolution));return{colorAttachments:s,depthStencilAttachment:i,isRoot:t.isRoot,label:t.label}}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.sizeSource.width}get height(){return this.sizeSource.height}get pixelWidth(){return this.sizeSource.pixelWidth}get pixelHeight(){return this.sizeSource.pixelHeight}get resolution(){return this.sizeSource._resolution}get colorTextures(){return this._colorTextures||(this._colorTextures=this.colorAttachments.map(e=>e.texture)),this._colorTextures}get depthStencilTexture(){return this.depthStencilAttachment?.texture??null}get depth(){return this._depth}get stencil(){return this._stencil}get colorTexture(){return this.colorAttachments[0]?.texture}get sizeSource(){return this.colorAttachments[0]?.texture??this.depthStencilAttachment?.texture}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this._createDepthStencilTexture(this.sizeSource.width,this.sizeSource.height,this.sizeSource._resolution),this._depth=!0,this._stencil=!0}resize(e,t,s=this.resolution,i=!1){if(this.dirtyId++,this.colorAttachments.forEach((n,o)=>{i&&o===0||n.texture.resize(e,t,s)}),this.depthStencilAttachment){if(i&&this.colorAttachments.length===0)return;this.depthStencilAttachment.texture.resize(e,t,s)}}destroy(){!this.colorAttachments&&!this.depthStencilAttachment||(this.emit("destroy",this),this.sizeSource.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorAttachments.forEach(e=>{e.texture.destroy()}),this.depthStencilAttachment&&(this.depthStencilAttachment.texture.destroy(),delete this.depthStencilAttachment),this.colorAttachments=null,this._colorTextures=null,this.removeAllListeners())}_createDepthStencilTexture(e,t,s){return this.depthStencilAttachment??(this.depthStencilAttachment={texture:new de({width:e,height:t,resolution:s,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1})}),this.depthStencilAttachment}};zp.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let ir=zp;const xs=new Map;as.register(xs);function fl(r,e){if(!xs.has(r)){const t=new H({source:new Ve({resource:r,...e})}),s=()=>{xs.get(r)===t&&xs.delete(r)};t.once("destroy",s),t.source.once("destroy",s),xs.set(r,t)}return xs.get(r)}const pl=class $p{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)}constructor(e){this._renderer=e}init(e){e={...$p.defaultOptions,...e},e.view&&(O(ue,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new ee(0,0,e.width,e.height),this.canvas=e.canvas||J.get().createCanvas(),this.antialias=!!e.antialias;const{depth:t,...s}=e;this.texture=fl(this.canvas,s),this.renderTarget=new ir({colorTextures:[this.texture],depth:!!t,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.texture.source.on("resize",this._updateScreenSize,this),this.resolution=e.resolution,this._updateScreenSize()}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.source.off("resize",this._updateScreenSize,this),Te.removeScreen(this._renderer.uid),Mt.removeScreen(this._renderer.uid),this.texture.destroy()}_updateScreenSize(){const{pixelWidth:e,pixelHeight:t}=this.texture.source,s=this._renderer.uid;Te.setScreenSize(s,e,t),Mt.setScreenSize(s,e,t)}};pl.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"view",priority:0};pl.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};let Vp=pl;const $i=[Rp,hl,Wi,Vp,il,Lp,Hp,al,Ip,ra,Np,cl],ml=[zi,Li,Hi,Ni,Oi,Qa,Ka,Ui];function Xp(r,e,t,s,i,n){const o=n?1:-1;return r.identity(),r.a=1/s*2,r.d=o*(1/i*2),r.tx=-1-e*r.a,r.ty=-o-t*r.d,r}function jp(r){if(r.colorAttachments.length===0)return!1;const e=r.colorTexture.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class Vi{constructor(e){this.rootViewPort=new ee,this.viewport=new ee,this.onRenderTargetChange=new ta("onRenderTargetChange"),this.projectionMatrix=new L,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._bindState={target:null,frame:void 0,mipLevel:0,layer:0,flipY:!1},this._bindFrame=new ee,this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}get renderSurface(){return this._bindState.target}get mipLevel(){return this._bindState.mipLevel}get layer(){return this._bindState.layer}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart(e){this._renderTargetStack.length=0,this.push(e),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=jp(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,s,i,n=0,o=0,a){let l;"target"in e?l=e:(O("8.20.0","RenderTargetSystem.bind: positional arguments are deprecated, please use an options object instead: bind({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),l={target:e,clear:t,clearColor:s,frame:i,mipLevel:n,layer:o,flipY:a});const h=l.target;t=l.clear??!0,s=l.clearColor,n=(l.mipLevel??0)|0,o=(l.layer??0)|0,a=l.flipY,i=l.frame;const c=this.getRenderTarget(h),u=this.renderTarget!==c||!!c.flipY!=!!a;this.renderTarget=c;const d=this.getGpuRenderTarget(c);(c.pixelWidth!==d.width||c.pixelHeight!==d.height)&&(this.adaptor.resizeGpuRenderTarget(c),d.width=c.pixelWidth,d.height=c.pixelHeight);const f=c.colorAttachments[0]?.texture||c.depthStencilAttachment?.texture,p=this.viewport,m=f.dimension==="3d"?Math.max(f.depth>>n,1):f.depthOrArrayLayers;if(o<0||o>=m)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (layer count=${m}).`);const g=this._bindState;g.target=h,g.frame=i?this._bindFrame.copyFrom(i):void 0,g.mipLevel=n,g.layer=o,g.flipY=a;const _=Math.max(f.pixelWidth>>n,1),x=Math.max(f.pixelHeight>>n,1);if(!i&&h instanceof H&&(i=h.frame),i){const y=f._resolution,b=1<<Math.max(n,0),w=i.x*y+.5|0,v=i.y*y+.5|0,S=i.width*y+.5|0,E=i.height*y+.5|0;let k=Math.floor(w/b),P=Math.floor(v/b),T=Math.ceil(S/b),A=Math.ceil(E/b);k<0&&(T+=k,k=0),P<0&&(A+=P,P=0),k=Math.min(k,_-1),P=Math.min(P,x-1),T=Math.min(T,_-k),A=Math.min(A,x-P),T=Math.max(T,1),A=Math.max(A,1),p.x=k,p.y=P,p.width=T,p.height=A}else p.x=0,p.y=0,p.width=_,p.height=x;return c.flipY=a,Xp(this.projectionMatrix,0,0,p.width/f.resolution,p.height/f.resolution,!c.isRoot!=!!c.flipY),this.adaptor.startRenderPass(c,t,s,p,n,o),u&&this.onRenderTargetChange.emit(c),c}getBindState(e){if(!this.renderTarget)throw new Error("[RenderTargetSystem] getBindState is only valid while a render surface is bound");const t=this._bindState;return e??(e={}),e.target=t.target,e.clear=ye.NONE,e.clearColor=void 0,t.frame?e.frame?e.frame.copyFrom(t.frame):e.frame=t.frame.clone():e.frame=void 0,e.mipLevel=t.mipLevel,e.layer=t.layer,e.flipY=!!t.flipY,e}isFrontFaceInverted(e,t){if(!e){if(e=this.renderTarget,!e)return!1;t=e.flipY}return!!t!=(this._renderer.type===Ke.WEBGL&&!e.isRoot)}get frontFaceInverted(){return O(lt,"RenderTargetSystem.frontFaceInverted is deprecated, use isFrontFaceInverted() instead"),this.isFrontFaceInverted()}clear(e,t=ye.ALL,s,i=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport,i,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=ye.ALL,s,i,n=0,o=0,a){let l;"target"in e?l=e:(O("8.20.0","RenderTargetSystem.push: positional arguments are deprecated, please use an options object instead: push({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),l={target:e,clear:t,clearColor:s,frame:i,mipLevel:n,layer:o,flipY:a});const h=this.bind(l);return this._renderTargetStack.push({target:l.target,clear:!1,clearColor:void 0,frame:l.frame?l.frame.clone():void 0,mipLevel:l.mipLevel,layer:l.layer,flipY:l.flipY}),h}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];if(!e)throw new Error("[RenderTargetSystem] pop: no previous binding to restore (unbalanced pop)");return this.bind(e)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,i,n){const o=this.getRenderTarget(e);s.x<0&&(i.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(i.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:a,pixelHeight:l}=o;return i.width=Math.min(i.width,a-s.x),i.height=Math.min(i.height,l-s.y),this.adaptor.copyToTexture(o,t,s,i,n)}copyDepthTexture(e,t,s,i,n={x:0,y:0}){const o=this.getRenderTarget(e);if(!o.depthStencilAttachment){N("[RenderTargetSystem] copyDepthTexture: the source render target has no depth attachment to copy from");return}const a=t.source;if(!a.format.includes("depth")&&!a.format.includes("stencil")){N(`[RenderTargetSystem] copyDepthTexture: the destination texture must have a depth/stencil format (got '${a.format}')`);return}let l=s.x,h=s.y,c=n.x,u=n.y,d=i.width,f=i.height;l<0&&(d+=l,c-=l,l=0),h<0&&(f+=h,u-=h,h=0),d=Math.min(d,o.pixelWidth-l),f=Math.min(f,o.pixelHeight-h),d=Math.min(d,a.pixelWidth-c),f=Math.min(f,a.pixelHeight-u),!(d<=0||f<=0)&&this.adaptor.copyDepthTexture(o,t,{x:l,y:h},{width:d,height:f},{x:c,y:u})}ensureDepthStencil(){if(!this.renderTarget.stencil){if(this.renderTarget.depthStencilTexture){N(`[RenderTargetSystem] a stencil mask is being used, but the render target's depthStencilTexture format '${this.renderTarget.depthStencilTexture.format}' has no stencil aspect, so masking cannot work here. Use a 'depth24plus-stencil8' texture instead.`);return}this.renderTarget._depth=!0,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?this._releaseRenderTarget(t,e):e.off("destroy",this._onRenderTargetDestroy,this)}),this._renderSurfaceToRenderTargetHash.clear();for(const e of Object.values(this._gpuRenderTargetHash))e&&this.adaptor.destroyGpuRenderTarget(e);this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;if(Ve.test(e)&&(e=fl(e).source),e instanceof ir)t=e,e.once("destroy",this._onRenderTargetDestroy,this);else if(e instanceof de){const s=e.format;t=s.includes("depth")||s.includes("stencil")?new ir({colorTextures:0,depthStencilTexture:e}):new ir({colorTextures:[e]}),e.source instanceof Ve&&(t.isRoot=!0),e.once("destroy",this._onRenderSurfaceDestroy,this)}return this._renderSurfaceToRenderTargetHash.set(e,t),t}_onRenderSurfaceDestroy(e){const t=this._renderSurfaceToRenderTargetHash.get(e);t&&this._releaseRenderTarget(e,t)}_onRenderTargetDestroy(e){this._renderSurfaceToRenderTargetHash.delete(e),this._releaseGpuRenderTarget(e)}_releaseRenderTarget(e,t){t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e),e.off("destroy",this._onRenderSurfaceDestroy,this),this._releaseGpuRenderTarget(t)}_releaseGpuRenderTarget(e){const t=this._gpuRenderTargetHash[e.uid];t&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(t))}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this._bindState.target=null}}class qp{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:s,context:i}=this._ensureCanvas(t);return{canvas:s,context:i,width:s.width,height:s.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:s}=this._ensureCanvas(t);s.width=e.pixelWidth,s.height=e.pixelHeight}startRenderPass(e,t,s,i){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,s,i)}clear(e,t,s,i){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=i||{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),s){const l=oe.shared.setValue(s);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,s,i,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:h}=this._ensureCanvas(l),c=n?.x??0,u=n?.y??0;return h.drawImage(a,s.x,s.y,i.width,i.height,c,u,i.width,i.height),l.update(),t}copyDepthTexture(e,t,s,i,n){N("[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer")}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!Ve.test(t))&&(t=J.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 s=t.getContext("2d");return{canvas:t,context:s}}}class gl extends Vi{constructor(e){super(e),this.adaptor=new qp,this.adaptor.init(e,this)}}gl.extension={type:[C.CanvasSystem],name:"renderTarget"};class _l{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=J.get().createCanvas(),s=t.getContext("2d"),i=Y.getCanvasSource(e);if(!i)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,h=n.width*o,c=n.height*o;return t.width=Math.ceil(h),t.height=Math.ceil(c),s.drawImage(i,a,l,h,c,0,0,h,c),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(){}}_l.extension={type:[C.CanvasSystem],name:"texture"};const Fy=[...$i,Ja,el,_l,gl],Ly=[zi,Li,Hi,Ni,Oi,Za,Ya,Ui],Oy=[wp,tl],Yp=[],Kp=[],Zp=[],Qp=[];q.handleByNamedList(C.CanvasSystem,Yp);q.handleByNamedList(C.CanvasPipes,Kp);q.handleByNamedList(C.CanvasPipesAdaptor,Zp);q.handleByNamedList(C.CanvasLoader,Qp);q.add(...Fy,...Ly,...Oy);class Jp extends Is{constructor(){const e={name:"canvas",type:Ke.CANVAS,systems:Yp,renderPipes:Kp,renderPipeAdaptors:Zp,loaders:Qp};super(e)}}const Uy=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:Jp},Symbol.toStringTag,{value:"Module"}));var nr=(r=>(r[r.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",r[r.ARRAY_BUFFER=34962]="ARRAY_BUFFER",r[r.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",r))(nr||{});class em{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 yl{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new it({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,s=this.getGlBuffer(e);t.bindBuffer(s.type,s.buffer)}bindBufferBase(e,t){const{_gl:s}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,s.bindBufferBase(s.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 s=0,i=this._nextBindBaseIndex;for(;s<2;){i>=this._maxBindings&&(i=this._minBaseLocation,s++);const n=this._boundBufferBases[i];if(n&&n._lastBindCallId===this._bindCallId){i++;continue}break}return t=i,this._nextBindBaseIndex=i+1,s>=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,s,i){const{_gl:n}=this;s||(s=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,s*256,i||256)}updateBuffer(e){const{_gl:t}=this,s=this.getGlBuffer(e);if(e._updateID===s.updateID)return s;s.updateID=e._updateID,t.bindBuffer(s.type,s.buffer);const i=e.data,n=e.descriptor.usage&ce.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return i?s.byteLength>=i.byteLength?t.bufferSubData(s.type,e._updateOffset,i,e._updateOffset/i.BYTES_PER_ELEMENT,(e._updateSize||i.byteLength)/i.BYTES_PER_ELEMENT):(s.byteLength=i.byteLength,t.bufferData(s.type,i,n)):(s.byteLength=e.descriptor.size,t.bufferData(s.type,s.byteLength,n)),s}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||this._gl.deleteBuffer(s.buffer))}createGLBuffer(e){const{_gl:t}=this;let s=nr.ARRAY_BUFFER;e.descriptor.usage&ce.INDEX?s=nr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&ce.UNIFORM&&(s=nr.UNIFORM_BUFFER);const i=new em(t.createBuffer(),s);return e._gpuData[this._renderer.uid]=i,this._managedBuffers.add(e),i}resetState(){this._boundBufferBases=Object.create(null)}}yl.extension={type:[C.WebGLSystem],name:"buffer"};const xl=class tm{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={...tm.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(N("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=J.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const s=this._renderer.background.alpha<1,i=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:s,premultipliedAlpha:i,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&N("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 J.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 s;const i=this.canvas;if(e===2&&(s=i.getContext("webgl2",t)),!s&&(s=i.getContext("webgl",t),!s))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=s,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 s=e.getExtension("WEBGL_provoking_vertex");s&&s.provokingVertexWEBGL(s.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&N("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=this.supports,i=this.webGLVersion===2,n=this.extensions;s.uint32Indices=i||!!n.uint32ElementIndex,s.uniformBufferObject=i,s.vertexArrayObject=i||!!n.vertexArrayObject,s.srgbTextures=i||!!n.srgb,s.nonPowOf2wrapping=i,s.nonPowOf2mipmaps=i,s.msaa=i,s.uint32Indices||N("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};xl.extension={type:[C.WebGLSystem],name:"context"};xl.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let sm=xl;function ui(r,e){for(const t in r.attributes){const s=r.attributes[t],i=e[t];i?(s.format??(s.format=i.format),s.offset??(s.offset=i.offset),s.instance??(s.instance=i.instance)):s.format||N(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Ny(r)}function Ny(r){const{buffers:e,attributes:t}=r,s={},i={};for(const n in e){const o=e[n];s[o.uid]=0,i[o.uid]=0}for(const n in t){const o=t[n];s[o.buffer.uid]+=Ms(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=s[o.buffer.uid]),o.start??(o.start=i[o.buffer.uid]),i[o.buffer.uid]+=Ms(o.format).stride}}var di=(r=>(r[r.RGBA=6408]="RGBA",r[r.RGB=6407]="RGB",r[r.RG=33319]="RG",r[r.RED=6403]="RED",r[r.RGBA_INTEGER=36249]="RGBA_INTEGER",r[r.RGB_INTEGER=36248]="RGB_INTEGER",r[r.RG_INTEGER=33320]="RG_INTEGER",r[r.RED_INTEGER=36244]="RED_INTEGER",r[r.ALPHA=6406]="ALPHA",r[r.LUMINANCE=6409]="LUMINANCE",r[r.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",r[r.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",r[r.DEPTH_STENCIL=34041]="DEPTH_STENCIL",r))(di||{}),As=(r=>(r[r.TEXTURE_2D=3553]="TEXTURE_2D",r[r.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",r[r.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",r[r.TEXTURE_3D=32879]="TEXTURE_3D",r[r.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",r[r.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",r[r.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",r[r.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",r))(As||{}),re=(r=>(r[r.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",r[r.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",r[r.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",r[r.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",r[r.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",r[r.UNSIGNED_INT=5125]="UNSIGNED_INT",r[r.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",r[r.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",r[r.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",r[r.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",r[r.BYTE=5120]="BYTE",r[r.SHORT=5122]="SHORT",r[r.INT=5124]="INT",r[r.FLOAT=5126]="FLOAT",r[r.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",r[r.HALF_FLOAT=36193]="HALF_FLOAT",r))(re||{});const Ic={uint8x2:re.UNSIGNED_BYTE,uint8x4:re.UNSIGNED_BYTE,sint8x2:re.BYTE,sint8x4:re.BYTE,unorm8x2:re.UNSIGNED_BYTE,unorm8x4:re.UNSIGNED_BYTE,snorm8x2:re.BYTE,snorm8x4:re.BYTE,uint16x2:re.UNSIGNED_SHORT,uint16x4:re.UNSIGNED_SHORT,sint16x2:re.SHORT,sint16x4:re.SHORT,unorm16x2:re.UNSIGNED_SHORT,unorm16x4:re.UNSIGNED_SHORT,snorm16x2:re.SHORT,snorm16x4:re.SHORT,float16x2:re.HALF_FLOAT,float16x4:re.HALF_FLOAT,float32:re.FLOAT,float32x2:re.FLOAT,float32x3:re.FLOAT,float32x4:re.FLOAT,uint32:re.UNSIGNED_INT,uint32x2:re.UNSIGNED_INT,uint32x3:re.UNSIGNED_INT,uint32x4:re.UNSIGNED_INT,sint32:re.INT,sint32x2:re.INT,sint32x3:re.INT,sint32x4:re.INT};function rm(r){return Ic[r]??Ic.float32}const Hy={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class im{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class bl{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new it({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=i=>t.bindVertexArrayOES(i),e.deleteVertexArray=i=>t.deleteVertexArrayOES(i));const s=this._renderer.context.extensions.vertexAttribDivisorANGLE;s&&(e.drawArraysInstanced=(i,n,o,a)=>{s.drawArraysInstancedANGLE(i,n,o,a)},e.drawElementsInstanced=(i,n,o,a,l)=>{s.drawElementsInstancedANGLE(i,n,o,a,l)},e.vertexAttribDivisor=(i,n)=>s.vertexAttribDivisorANGLE(i,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const s=this.gl;this._activeGeometry=e;const i=this.getVao(e,t);this._activeVao!==i&&(this._activeVao=i,s.bindVertexArray(i)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let s=0;s<e.buffers.length;s++){const i=e.buffers[s];t.updateBuffer(i)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const s=e.attributes,i=t._attributeData;for(const n in i)if(!s[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const s=e.attributes,i=t._attributeData,n=["g",e.uid];for(const o in s)i[o]&&n.push(o,i[o].location);return n.join("-")}getVao(e,t){return e._gpuData[this._renderer.uid]?.vaoCache[t._key]||this.initGeometryVao(e,t)}initGeometryVao(e,t,s=!0){const i=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 im,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let h=l[o];if(h)return l[t._key]=h,h;ui(e,t._attributeData);const c=e.buffers;h=i.createVertexArray(),i.bindVertexArray(h);for(let u=0;u<c.length;u++){const d=c[u];n.bind(d)}return this.activateVao(e,t),l[t._key]=h,l[o]=h,i.bindVertexArray(null),h}onGeometryUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];if(!s)return;const i=s.vaoCache;if(!t)for(const n in i)this._activeVao===i[n]&&this.resetState(),this.gl.deleteVertexArray(i[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){const s=this._renderer.gl,i=this._renderer.buffer,n=e.attributes;e.indexBuffer&&i.bind(e.indexBuffer);let o=null;for(const a in n){const l=n[a],h=l.buffer,c=i.getGlBuffer(h),u=t._attributeData[a];if(u){o!==c&&(i.bind(h),o=c);const d=u.location;s.enableVertexAttribArray(d);const f=Ms(l.format),p=rm(l.format);if(u.format?.substring(1,4)==="int"?s.vertexAttribIPointer(d,f.size,p,l.stride,l.offset):s.vertexAttribPointer(d,f.size,p,f.normalised,l.stride,l.offset),l.instance)if(this.hasInstance){const m=l.divisor??1;s.vertexAttribDivisor(d,m)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,s,i){const{gl:n}=this._renderer,o=this._activeGeometry,a=Hy[e||o.topology];if(i??(i=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,h=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT,c=t||o.indexCount||o.indexBuffer.data.length,u=(s||0)*l;i!==1?n.drawElementsInstanced(a,c,h,u,i):n.drawElements(a,c,h,u)}else i!==1?n.drawArraysInstanced(a,s||0,t||o.vertexCount,i):n.drawArrays(a,s||0,t||o.vertexCount);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}}bl.extension={type:[C.WebGLSystem],name:"geometry"};const zy=new Ei({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),vl=class nm{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:s}={...nm.defaultOptions,...e};this.useBackBuffer=t,this._antialias=s,this._renderer.context.supports.msaa||(N("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=ft.for2d();const i=new ls({vertex:`
585
+ `,"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 ${gr} - ${r} - http://www.pixijs.com/`);Bc=!0}}class Wi{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===Ke.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),Op(t)}}}Wi.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"hello",priority:-2};Wi.defaultOptions={hello:!1};const ul=class Up{constructor(e){this._renderer=e}init(e){e={...Up.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return O("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){O("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){O("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){O("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){O("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){O("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};ul.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"renderableGC",priority:0};ul.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Np=ul;const dl=class Yr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){O("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){O("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){O("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){O("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!==Yr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==Yr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==Yr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){O("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};dl.extension={type:[S.WebGLSystem,S.WebGPUSystem],name:"textureGC"};dl.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Hp=dl;const zp=class Wp extends Re{constructor(e={}){super(),this.uid=ne("renderTarget"),this.colorAttachments=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,this._depth=!1,this._stencil=!1,this._colorTextures=null;const t="colorAttachments"in e?e:this._normalizeOptions(e);if(this.isRoot=t.isRoot??!1,this.label=t.label,this.colorAttachments=t.colorAttachments,this.depthStencilAttachment=t.depthStencilAttachment,this.depthStencilAttachment){const s=this.depthStencilAttachment.texture.format;this._depth||(this._depth=s.includes("depth")),this._stencil||(this._stencil=s.includes("stencil"))}if(this.colorAttachments.length===0&&!this.depthStencilAttachment)throw new Error("[RenderTarget] no color textures or depth textures were provided. Provide a depthStencilTexture or set depth/stencil to true when using colorTextures: 0.");if(this.colorAttachments.length>0){const s=this.colorTexture;this.resize(s.width,s.height,s._resolution)}this.sizeSource&&this.sizeSource.on("resize",this.onSourceResize,this)}_normalizeOptions(e){const t={...Wp.defaultOptions,...e},s=[];let i;if(typeof t.colorTextures=="number"){if(t.colorTextures>0){this._managedColorTextures=!0;for(let o=0;o<t.colorTextures;o++)s.push({texture:new de({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}),loadOp:"clear",storeOp:"store"})}}else t.colorTextures.forEach(o=>{s.push({texture:o.source,loadOp:"clear",storeOp:"store"})});const n=t.depthStencilTexture===!0;if(this._depth=!!(t.depth||n),this._stencil=!!(t.stencil||n),t.depthStencilTexture instanceof H||t.depthStencilTexture instanceof de){if(t.isRoot)throw new Error("[RenderTarget] cannot attach a depth-stencil texture to the screen — the canvas owns its own depth/stencil buffers. Render to a texture target instead.");i={texture:t.depthStencilTexture.source}}else(n&&!t.isRoot||(t.stencil||t.depth)&&s.length===0)&&(i=this._createDepthStencilTexture(t.width,t.height,t.resolution));return{colorAttachments:s,depthStencilAttachment:i,isRoot:t.isRoot,label:t.label}}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.sizeSource.width}get height(){return this.sizeSource.height}get pixelWidth(){return this.sizeSource.pixelWidth}get pixelHeight(){return this.sizeSource.pixelHeight}get resolution(){return this.sizeSource._resolution}get colorTextures(){return this._colorTextures||(this._colorTextures=this.colorAttachments.map(e=>e.texture)),this._colorTextures}get depthStencilTexture(){return this.depthStencilAttachment?.texture??null}get depth(){return this._depth}get stencil(){return this._stencil}get colorTexture(){return this.colorAttachments[0]?.texture}get sizeSource(){return this.colorAttachments[0]?.texture??this.depthStencilAttachment?.texture}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this._createDepthStencilTexture(this.sizeSource.width,this.sizeSource.height,this.sizeSource._resolution),this._depth=!0,this._stencil=!0}resize(e,t,s=this.resolution,i=!1){if(this.dirtyId++,this.colorAttachments.forEach((n,o)=>{i&&o===0||n.texture.resize(e,t,s)}),this.depthStencilAttachment){if(i&&this.colorAttachments.length===0)return;this.depthStencilAttachment.texture.resize(e,t,s)}}destroy(){!this.colorAttachments&&!this.depthStencilAttachment||(this.emit("destroy",this),this.sizeSource.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorAttachments.forEach(e=>{e.texture.destroy()}),this.depthStencilAttachment&&(this.depthStencilAttachment.texture.destroy(),delete this.depthStencilAttachment),this.colorAttachments=null,this._colorTextures=null,this.removeAllListeners())}_createDepthStencilTexture(e,t,s){return this.depthStencilAttachment??(this.depthStencilAttachment={texture:new de({width:e,height:t,resolution:s,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1})}),this.depthStencilAttachment}};zp.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let ir=zp;const xs=new Map;as.register(xs);function fl(r,e){if(!xs.has(r)){const t=new H({source:new Ve({resource:r,...e})}),s=()=>{xs.get(r)===t&&xs.delete(r)};t.once("destroy",s),t.source.once("destroy",s),xs.set(r,t)}return xs.get(r)}const pl=class $p{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)}constructor(e){this._renderer=e}init(e){e={...$p.defaultOptions,...e},e.view&&(O(ue,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new ee(0,0,e.width,e.height),this.canvas=e.canvas||J.get().createCanvas(),this.antialias=!!e.antialias;const{depth:t,...s}=e;this.texture=fl(this.canvas,s),this.renderTarget=new ir({colorTextures:[this.texture],depth:!!t,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.texture.source.on("resize",this._updateScreenSize,this),this.resolution=e.resolution,this._updateScreenSize()}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.source.off("resize",this._updateScreenSize,this),Te.removeScreen(this._renderer.uid),Mt.removeScreen(this._renderer.uid),this.texture.destroy()}_updateScreenSize(){const{pixelWidth:e,pixelHeight:t}=this.texture.source,s=this._renderer.uid;Te.setScreenSize(s,e,t),Mt.setScreenSize(s,e,t)}};pl.extension={type:[S.WebGLSystem,S.WebGPUSystem,S.CanvasSystem],name:"view",priority:0};pl.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};let Vp=pl;const $i=[Rp,hl,Wi,Vp,il,Lp,Hp,al,Ip,ra,Np,cl],ml=[zi,Li,Hi,Ni,Oi,Qa,Ka,Ui];function Xp(r,e,t,s,i,n){const o=n?1:-1;return r.identity(),r.a=1/s*2,r.d=o*(1/i*2),r.tx=-1-e*r.a,r.ty=-o-t*r.d,r}function jp(r){if(r.colorAttachments.length===0)return!1;const e=r.colorTexture.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class Vi{constructor(e){this.rootViewPort=new ee,this.viewport=new ee,this.onRenderTargetChange=new ta("onRenderTargetChange"),this.projectionMatrix=new L,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._bindState={target:null,frame:void 0,mipLevel:0,layer:0,flipY:!1},this._bindFrame=new ee,this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}get renderSurface(){return this._bindState.target}get mipLevel(){return this._bindState.mipLevel}get layer(){return this._bindState.layer}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart(e){this._renderTargetStack.length=0,this.push(e),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=jp(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,s,i,n=0,o=0,a){let l;"target"in e?l=e:(O("8.20.0","RenderTargetSystem.bind: positional arguments are deprecated, please use an options object instead: bind({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),l={target:e,clear:t,clearColor:s,frame:i,mipLevel:n,layer:o,flipY:a});const h=l.target;t=l.clear??!0,s=l.clearColor,n=(l.mipLevel??0)|0,o=(l.layer??0)|0,a=l.flipY,i=l.frame;const c=this.getRenderTarget(h),u=this.renderTarget!==c||!!c.flipY!=!!a;this.renderTarget=c;const d=this.getGpuRenderTarget(c);(c.pixelWidth!==d.width||c.pixelHeight!==d.height)&&(this.adaptor.resizeGpuRenderTarget(c),d.width=c.pixelWidth,d.height=c.pixelHeight);const f=c.colorAttachments[0]?.texture||c.depthStencilAttachment?.texture,p=this.viewport,m=f.dimension==="3d"?Math.max(f.depth>>n,1):f.depthOrArrayLayers;if(o<0||o>=m)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (layer count=${m}).`);const g=this._bindState;g.target=h,g.frame=i?this._bindFrame.copyFrom(i):void 0,g.mipLevel=n,g.layer=o,g.flipY=a;const _=Math.max(f.pixelWidth>>n,1),x=Math.max(f.pixelHeight>>n,1);if(!i&&h instanceof H&&(i=h.frame),i){const y=f._resolution,b=1<<Math.max(n,0),w=i.x*y+.5|0,v=i.y*y+.5|0,T=i.width*y+.5|0,k=i.height*y+.5|0;let P=Math.floor(w/b),A=Math.floor(v/b),C=Math.ceil(T/b),E=Math.ceil(k/b);P<0&&(C+=P,P=0),A<0&&(E+=A,A=0),P=Math.min(P,_-1),A=Math.min(A,x-1),C=Math.min(C,_-P),E=Math.min(E,x-A),C=Math.max(C,1),E=Math.max(E,1),p.x=P,p.y=A,p.width=C,p.height=E}else p.x=0,p.y=0,p.width=_,p.height=x;return c.flipY=a,Xp(this.projectionMatrix,0,0,p.width/f.resolution,p.height/f.resolution,!c.isRoot!=!!c.flipY),this.adaptor.startRenderPass(c,t,s,p,n,o),u&&this.onRenderTargetChange.emit(c),c}getBindState(e){if(!this.renderTarget)throw new Error("[RenderTargetSystem] getBindState is only valid while a render surface is bound");const t=this._bindState;return e??(e={}),e.target=t.target,e.clear=ye.NONE,e.clearColor=void 0,t.frame?e.frame?e.frame.copyFrom(t.frame):e.frame=t.frame.clone():e.frame=void 0,e.mipLevel=t.mipLevel,e.layer=t.layer,e.flipY=!!t.flipY,e}isFrontFaceInverted(e,t){if(!e){if(e=this.renderTarget,!e)return!1;t=e.flipY}return!!t!=(this._renderer.type===Ke.WEBGL&&!e.isRoot)}get frontFaceInverted(){return O(lt,"RenderTargetSystem.frontFaceInverted is deprecated, use isFrontFaceInverted() instead"),this.isFrontFaceInverted()}clear(e,t=ye.ALL,s,i=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport,i,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=ye.ALL,s,i,n=0,o=0,a){let l;"target"in e?l=e:(O("8.20.0","RenderTargetSystem.push: positional arguments are deprecated, please use an options object instead: push({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),l={target:e,clear:t,clearColor:s,frame:i,mipLevel:n,layer:o,flipY:a});const h=this.bind(l);return this._renderTargetStack.push({target:l.target,clear:!1,clearColor:void 0,frame:l.frame?l.frame.clone():void 0,mipLevel:l.mipLevel,layer:l.layer,flipY:l.flipY}),h}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];if(!e)throw new Error("[RenderTargetSystem] pop: no previous binding to restore (unbalanced pop)");return this.bind(e)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,i,n){const o=this.getRenderTarget(e);s.x<0&&(i.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(i.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:a,pixelHeight:l}=o;return i.width=Math.min(i.width,a-s.x),i.height=Math.min(i.height,l-s.y),this.adaptor.copyToTexture(o,t,s,i,n)}copyDepthTexture(e,t,s,i,n={x:0,y:0}){const o=this.getRenderTarget(e);if(!o.depthStencilAttachment){N("[RenderTargetSystem] copyDepthTexture: the source render target has no depth attachment to copy from");return}const a=t.source;if(!a.format.includes("depth")&&!a.format.includes("stencil")){N(`[RenderTargetSystem] copyDepthTexture: the destination texture must have a depth/stencil format (got '${a.format}')`);return}let l=s.x,h=s.y,c=n.x,u=n.y,d=i.width,f=i.height;l<0&&(d+=l,c-=l,l=0),h<0&&(f+=h,u-=h,h=0),d=Math.min(d,o.pixelWidth-l),f=Math.min(f,o.pixelHeight-h),d=Math.min(d,a.pixelWidth-c),f=Math.min(f,a.pixelHeight-u),!(d<=0||f<=0)&&this.adaptor.copyDepthTexture(o,t,{x:l,y:h},{width:d,height:f},{x:c,y:u})}ensureDepthStencil(){if(!this.renderTarget.stencil){if(this.renderTarget.depthStencilTexture){N(`[RenderTargetSystem] a stencil mask is being used, but the render target's depthStencilTexture format '${this.renderTarget.depthStencilTexture.format}' has no stencil aspect, so masking cannot work here. Use a 'depth24plus-stencil8' texture instead.`);return}this.renderTarget._depth=!0,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?this._releaseRenderTarget(t,e):e.off("destroy",this._onRenderTargetDestroy,this)}),this._renderSurfaceToRenderTargetHash.clear();for(const e of Object.values(this._gpuRenderTargetHash))e&&this.adaptor.destroyGpuRenderTarget(e);this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;if(Ve.test(e)&&(e=fl(e).source),e instanceof ir)t=e,e.once("destroy",this._onRenderTargetDestroy,this);else if(e instanceof de){const s=e.format;t=s.includes("depth")||s.includes("stencil")?new ir({colorTextures:0,depthStencilTexture:e}):new ir({colorTextures:[e]}),e.source instanceof Ve&&(t.isRoot=!0),e.once("destroy",this._onRenderSurfaceDestroy,this)}return this._renderSurfaceToRenderTargetHash.set(e,t),t}_onRenderSurfaceDestroy(e){const t=this._renderSurfaceToRenderTargetHash.get(e);t&&this._releaseRenderTarget(e,t)}_onRenderTargetDestroy(e){this._renderSurfaceToRenderTargetHash.delete(e),this._releaseGpuRenderTarget(e)}_releaseRenderTarget(e,t){t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e),e.off("destroy",this._onRenderSurfaceDestroy,this),this._releaseGpuRenderTarget(t)}_releaseGpuRenderTarget(e){const t=this._gpuRenderTargetHash[e.uid];t&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(t))}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this._bindState.target=null}}class qp{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:s,context:i}=this._ensureCanvas(t);return{canvas:s,context:i,width:s.width,height:s.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:s}=this._ensureCanvas(t);s.width=e.pixelWidth,s.height=e.pixelHeight}startRenderPass(e,t,s,i){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,s,i)}clear(e,t,s,i){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=i||{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),s){const l=oe.shared.setValue(s);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,s,i,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:h}=this._ensureCanvas(l),c=n?.x??0,u=n?.y??0;return h.drawImage(a,s.x,s.y,i.width,i.height,c,u,i.width,i.height),l.update(),t}copyDepthTexture(e,t,s,i,n){N("[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer")}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!Ve.test(t))&&(t=J.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 s=t.getContext("2d");return{canvas:t,context:s}}}class gl extends Vi{constructor(e){super(e),this.adaptor=new qp,this.adaptor.init(e,this)}}gl.extension={type:[S.CanvasSystem],name:"renderTarget"};class _l{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=J.get().createCanvas(),s=t.getContext("2d"),i=Y.getCanvasSource(e);if(!i)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,h=n.width*o,c=n.height*o;return t.width=Math.ceil(h),t.height=Math.ceil(c),s.drawImage(i,a,l,h,c,0,0,h,c),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(){}}_l.extension={type:[S.CanvasSystem],name:"texture"};const Fy=[...$i,Ja,el,_l,gl],Ly=[zi,Li,Hi,Ni,Oi,Za,Ya,Ui],Oy=[wp,tl],Yp=[],Kp=[],Zp=[],Qp=[];q.handleByNamedList(S.CanvasSystem,Yp);q.handleByNamedList(S.CanvasPipes,Kp);q.handleByNamedList(S.CanvasPipesAdaptor,Zp);q.handleByNamedList(S.CanvasLoader,Qp);q.add(...Fy,...Ly,...Oy);class Jp extends Is{constructor(){const e={name:"canvas",type:Ke.CANVAS,systems:Yp,renderPipes:Kp,renderPipeAdaptors:Zp,loaders:Qp};super(e)}}const Uy=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:Jp},Symbol.toStringTag,{value:"Module"}));var nr=(r=>(r[r.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",r[r.ARRAY_BUFFER=34962]="ARRAY_BUFFER",r[r.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",r))(nr||{});class em{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 yl{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new it({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,s=this.getGlBuffer(e);t.bindBuffer(s.type,s.buffer)}bindBufferBase(e,t){const{_gl:s}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,s.bindBufferBase(s.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 s=0,i=this._nextBindBaseIndex;for(;s<2;){i>=this._maxBindings&&(i=this._minBaseLocation,s++);const n=this._boundBufferBases[i];if(n&&n._lastBindCallId===this._bindCallId){i++;continue}break}return t=i,this._nextBindBaseIndex=i+1,s>=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,s,i){const{_gl:n}=this;s||(s=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,s*256,i||256)}updateBuffer(e){const{_gl:t}=this,s=this.getGlBuffer(e);if(e._updateID===s.updateID)return s;s.updateID=e._updateID,t.bindBuffer(s.type,s.buffer);const i=e.data,n=e.descriptor.usage&ce.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return i?s.byteLength>=i.byteLength?t.bufferSubData(s.type,e._updateOffset,i,e._updateOffset/i.BYTES_PER_ELEMENT,(e._updateSize||i.byteLength)/i.BYTES_PER_ELEMENT):(s.byteLength=i.byteLength,t.bufferData(s.type,i,n)):(s.byteLength=e.descriptor.size,t.bufferData(s.type,s.byteLength,n)),s}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||this._gl.deleteBuffer(s.buffer))}createGLBuffer(e){const{_gl:t}=this;let s=nr.ARRAY_BUFFER;e.descriptor.usage&ce.INDEX?s=nr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&ce.UNIFORM&&(s=nr.UNIFORM_BUFFER);const i=new em(t.createBuffer(),s);return e._gpuData[this._renderer.uid]=i,this._managedBuffers.add(e),i}resetState(){this._boundBufferBases=Object.create(null)}}yl.extension={type:[S.WebGLSystem],name:"buffer"};const xl=class tm{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={...tm.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(N("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=J.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const s=this._renderer.background.alpha<1,i=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:s,premultipliedAlpha:i,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&N("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 J.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 s;const i=this.canvas;if(e===2&&(s=i.getContext("webgl2",t)),!s&&(s=i.getContext("webgl",t),!s))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=s,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 s=e.getExtension("WEBGL_provoking_vertex");s&&s.provokingVertexWEBGL(s.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&N("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=this.supports,i=this.webGLVersion===2,n=this.extensions;s.uint32Indices=i||!!n.uint32ElementIndex,s.uniformBufferObject=i,s.vertexArrayObject=i||!!n.vertexArrayObject,s.srgbTextures=i||!!n.srgb,s.nonPowOf2wrapping=i,s.nonPowOf2mipmaps=i,s.msaa=i,s.uint32Indices||N("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};xl.extension={type:[S.WebGLSystem],name:"context"};xl.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let sm=xl;function ui(r,e){for(const t in r.attributes){const s=r.attributes[t],i=e[t];i?(s.format??(s.format=i.format),s.offset??(s.offset=i.offset),s.instance??(s.instance=i.instance)):s.format||N(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Ny(r)}function Ny(r){const{buffers:e,attributes:t}=r,s={},i={};for(const n in e){const o=e[n];s[o.uid]=0,i[o.uid]=0}for(const n in t){const o=t[n];s[o.buffer.uid]+=Ms(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=s[o.buffer.uid]),o.start??(o.start=i[o.buffer.uid]),i[o.buffer.uid]+=Ms(o.format).stride}}var di=(r=>(r[r.RGBA=6408]="RGBA",r[r.RGB=6407]="RGB",r[r.RG=33319]="RG",r[r.RED=6403]="RED",r[r.RGBA_INTEGER=36249]="RGBA_INTEGER",r[r.RGB_INTEGER=36248]="RGB_INTEGER",r[r.RG_INTEGER=33320]="RG_INTEGER",r[r.RED_INTEGER=36244]="RED_INTEGER",r[r.ALPHA=6406]="ALPHA",r[r.LUMINANCE=6409]="LUMINANCE",r[r.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",r[r.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",r[r.DEPTH_STENCIL=34041]="DEPTH_STENCIL",r))(di||{}),As=(r=>(r[r.TEXTURE_2D=3553]="TEXTURE_2D",r[r.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",r[r.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",r[r.TEXTURE_3D=32879]="TEXTURE_3D",r[r.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",r[r.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",r[r.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",r[r.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",r))(As||{}),re=(r=>(r[r.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",r[r.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",r[r.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",r[r.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",r[r.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",r[r.UNSIGNED_INT=5125]="UNSIGNED_INT",r[r.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",r[r.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",r[r.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",r[r.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",r[r.BYTE=5120]="BYTE",r[r.SHORT=5122]="SHORT",r[r.INT=5124]="INT",r[r.FLOAT=5126]="FLOAT",r[r.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",r[r.HALF_FLOAT=36193]="HALF_FLOAT",r))(re||{});const Ic={uint8x2:re.UNSIGNED_BYTE,uint8x4:re.UNSIGNED_BYTE,sint8x2:re.BYTE,sint8x4:re.BYTE,unorm8x2:re.UNSIGNED_BYTE,unorm8x4:re.UNSIGNED_BYTE,snorm8x2:re.BYTE,snorm8x4:re.BYTE,uint16x2:re.UNSIGNED_SHORT,uint16x4:re.UNSIGNED_SHORT,sint16x2:re.SHORT,sint16x4:re.SHORT,unorm16x2:re.UNSIGNED_SHORT,unorm16x4:re.UNSIGNED_SHORT,snorm16x2:re.SHORT,snorm16x4:re.SHORT,float16x2:re.HALF_FLOAT,float16x4:re.HALF_FLOAT,float32:re.FLOAT,float32x2:re.FLOAT,float32x3:re.FLOAT,float32x4:re.FLOAT,uint32:re.UNSIGNED_INT,uint32x2:re.UNSIGNED_INT,uint32x3:re.UNSIGNED_INT,uint32x4:re.UNSIGNED_INT,sint32:re.INT,sint32x2:re.INT,sint32x3:re.INT,sint32x4:re.INT};function rm(r){return Ic[r]??Ic.float32}const Hy={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class im{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class bl{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new it({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=i=>t.bindVertexArrayOES(i),e.deleteVertexArray=i=>t.deleteVertexArrayOES(i));const s=this._renderer.context.extensions.vertexAttribDivisorANGLE;s&&(e.drawArraysInstanced=(i,n,o,a)=>{s.drawArraysInstancedANGLE(i,n,o,a)},e.drawElementsInstanced=(i,n,o,a,l)=>{s.drawElementsInstancedANGLE(i,n,o,a,l)},e.vertexAttribDivisor=(i,n)=>s.vertexAttribDivisorANGLE(i,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const s=this.gl;this._activeGeometry=e;const i=this.getVao(e,t);this._activeVao!==i&&(this._activeVao=i,s.bindVertexArray(i)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let s=0;s<e.buffers.length;s++){const i=e.buffers[s];t.updateBuffer(i)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const s=e.attributes,i=t._attributeData;for(const n in i)if(!s[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const s=e.attributes,i=t._attributeData,n=["g",e.uid];for(const o in s)i[o]&&n.push(o,i[o].location);return n.join("-")}getVao(e,t){return e._gpuData[this._renderer.uid]?.vaoCache[t._key]||this.initGeometryVao(e,t)}initGeometryVao(e,t,s=!0){const i=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 im,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let h=l[o];if(h)return l[t._key]=h,h;ui(e,t._attributeData);const c=e.buffers;h=i.createVertexArray(),i.bindVertexArray(h);for(let u=0;u<c.length;u++){const d=c[u];n.bind(d)}return this.activateVao(e,t),l[t._key]=h,l[o]=h,i.bindVertexArray(null),h}onGeometryUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];if(!s)return;const i=s.vaoCache;if(!t)for(const n in i)this._activeVao===i[n]&&this.resetState(),this.gl.deleteVertexArray(i[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){const s=this._renderer.gl,i=this._renderer.buffer,n=e.attributes;e.indexBuffer&&i.bind(e.indexBuffer);let o=null;for(const a in n){const l=n[a],h=l.buffer,c=i.getGlBuffer(h),u=t._attributeData[a];if(u){o!==c&&(i.bind(h),o=c);const d=u.location;s.enableVertexAttribArray(d);const f=Ms(l.format),p=rm(l.format);if(u.format?.substring(1,4)==="int"?s.vertexAttribIPointer(d,f.size,p,l.stride,l.offset):s.vertexAttribPointer(d,f.size,p,f.normalised,l.stride,l.offset),l.instance)if(this.hasInstance){const m=l.divisor??1;s.vertexAttribDivisor(d,m)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,s,i){const{gl:n}=this._renderer,o=this._activeGeometry,a=Hy[e||o.topology];if(i??(i=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,h=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT,c=t||o.indexCount||o.indexBuffer.data.length,u=(s||0)*l;i!==1?n.drawElementsInstanced(a,c,h,u,i):n.drawElements(a,c,h,u)}else i!==1?n.drawArraysInstanced(a,s||0,t||o.vertexCount,i):n.drawArrays(a,s||0,t||o.vertexCount);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}}bl.extension={type:[S.WebGLSystem],name:"geometry"};const zy=new Ei({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),vl=class nm{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:s}={...nm.defaultOptions,...e};this.useBackBuffer=t,this._antialias=s,this._renderer.context.supports.msaa||(N("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=ft.for2d();const i=new ls({vertex:`
586
586
  attribute vec2 aPosition;
587
587
  out vec2 vUv;
588
588
 
@@ -601,7 +601,7 @@ fn mainFragment(
601
601
 
602
602
  void main() {
603
603
  finalColor = texture(uTexture, vUv);
604
- }`,name:"big-triangle"});this._bigTriangleShader=new dt({glProgram:i,resources:{uTexture:H.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind({target:this._targetTexture,clear:!1}),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:zy,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new H({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)}};vl.extension={type:[C.WebGLSystem],name:"backBuffer",priority:1};vl.defaultOptions={useBackBuffer:!1};let om=vl;class wl{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)))}}wl.extension={type:[C.WebGLSystem],name:"colorMask"};class Tl{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:s,shader:i,state:n,skipSync:o,topology:a,size:l,start:h,instanceCount:c}=e;t.shader.bind(i,o),t.geometry.bind(s,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,h,c??s.instanceCount)}destroy(){this._renderer=null}}Tl.extension={type:[C.WebGLSystem],name:"encoder"};class Sl{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=la(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}Sl.extension={type:[C.WebGLSystem],name:"limits"};class am{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[],this.stencilMode=me.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}const kt=[];kt[me.NONE]=void 0;kt[me.DISABLED]={stencilWriteMask:0,stencilReadMask:0};kt[me.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}};kt[me.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}};kt[me.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}};kt[me.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Cl{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:me.NONE},this._renderer=e,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._activeGpuRenderTarget=null,this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=me.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const s=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget)),i=this._gl,n=kt[e],o=this._stencilCache;if(s.stencilMode=e,s.stencilReference=t,e===me.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,i.disable(i.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,i.enable(i.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,i.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),i.stencilOp(i.KEEP,i.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._gl=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}Cl.extension={type:[C.WebGLSystem],name:"stencil"};class Ml{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!ea())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 Ct({data:new Float32Array(t.layout.size/4),usage:ce.UNIFORM|ce.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let s=this._syncFunctionHash[t];if(!s){const i=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(i),o=this._generateUboSync(n.uboElements);s=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,s){const i=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ct({data:new Float32Array(i.layout.size/4),usage:ce.UNIFORM|ce.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),s||(s=0),i.syncFunction(e.uniforms,t,n,s),!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 El={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,u32:4,"vec2<u32>":8,"vec3<u32>":12,"vec4<u32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function lm(r){const e=r.map(n=>({data:n,offset:0,size:0})),t=16;let s=0,i=0;for(let n=0;n<e.length;n++){const o=e[n];if(s=El[o.data.type],!s)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(s=Math.max(s,t)*o.data.size);const a=s===12?16:s;o.size=s;const l=i%t;l>0&&t-l<a?i+=(t-l)%16:i+=(s-l%s)%s,o.offset=i,i+=s}return i=Math.ceil(i/16)*16,{uboElements:e,size:i}}const Qt=[{type:"mat3x3<f32>",test:r=>r.value.a!==void 0,ubo:`
604
+ }`,name:"big-triangle"});this._bigTriangleShader=new dt({glProgram:i,resources:{uTexture:H.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind({target:this._targetTexture,clear:!1}),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:zy,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new H({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)}};vl.extension={type:[S.WebGLSystem],name:"backBuffer",priority:1};vl.defaultOptions={useBackBuffer:!1};let om=vl;class wl{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)))}}wl.extension={type:[S.WebGLSystem],name:"colorMask"};class Tl{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:s,shader:i,state:n,skipSync:o,topology:a,size:l,start:h,instanceCount:c}=e;t.shader.bind(i,o),t.geometry.bind(s,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,h,c??s.instanceCount)}destroy(){this._renderer=null}}Tl.extension={type:[S.WebGLSystem],name:"encoder"};class Sl{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=la(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}Sl.extension={type:[S.WebGLSystem],name:"limits"};class am{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[],this.stencilMode=me.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}const kt=[];kt[me.NONE]=void 0;kt[me.DISABLED]={stencilWriteMask:0,stencilReadMask:0};kt[me.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}};kt[me.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}};kt[me.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}};kt[me.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Cl{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:me.NONE},this._renderer=e,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._activeGpuRenderTarget=null,this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=me.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const s=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget)),i=this._gl,n=kt[e],o=this._stencilCache;if(s.stencilMode=e,s.stencilReference=t,e===me.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,i.disable(i.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,i.enable(i.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,i.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),i.stencilOp(i.KEEP,i.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._gl=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}Cl.extension={type:[S.WebGLSystem],name:"stencil"};class Ml{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!ea())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 Ct({data:new Float32Array(t.layout.size/4),usage:ce.UNIFORM|ce.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let s=this._syncFunctionHash[t];if(!s){const i=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(i),o=this._generateUboSync(n.uboElements);s=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,s){const i=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ct({data:new Float32Array(i.layout.size/4),usage:ce.UNIFORM|ce.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),s||(s=0),i.syncFunction(e.uniforms,t,n,s),!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 El={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,u32:4,"vec2<u32>":8,"vec3<u32>":12,"vec4<u32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function lm(r){const e=r.map(n=>({data:n,offset:0,size:0})),t=16;let s=0,i=0;for(let n=0;n<e.length;n++){const o=e[n];if(s=El[o.data.type],!s)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(s=Math.max(s,t)*o.data.size);const a=s===12?16:s;o.size=s;const l=i%t;l>0&&t-l<a?i+=(t-l)%16:i+=(s-l%s)%s,o.offset=i,i+=s}return i=Math.ceil(i/16)*16,{uboElements:e,size:i}}const Qt=[{type:"mat3x3<f32>",test:r=>r.value.a!==void 0,ubo:`
605
605
  var matrix = uv[name].toArray(true);
606
606
  data[offset] = matrix[0];
607
607
  data[offset + 1] = matrix[1];
@@ -755,7 +755,7 @@ fn mainFragment(
755
755
  }
756
756
  ${i!==0?`arrayOffset += ${i};`:""}
757
757
  }
758
- `}function um(r){return kl(r,Pl,cm)}class Al extends Ml{constructor(){super({createUboElements:lm,generateUboSync:um})}}Al.extension={type:[C.WebGLSystem],name:"ubo"};class dm{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ee,this._boundFramebuffer=void 0}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ee,this._boundFramebuffer=void 0;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(s,i)=>e.COLOR_ATTACHMENT0+i)}copyToTexture(e,t,s,i,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),h=a.gl;return this.finishRenderPass(e),h.bindFramebuffer(h.FRAMEBUFFER,l.resolveTargetFramebuffer),this._boundFramebuffer=l.resolveTargetFramebuffer,a.texture.bind(t,0),h.copyTexSubImage2D(h.TEXTURE_2D,0,n.x,n.y,s.x,s.y,i.width,i.height),t}copyDepthTexture(e,t,s,i,n){const o=this._renderTargetSystem,a=this._renderer.gl;this.finishRenderPass(e);const l=o.getRenderTarget(t),h=o.getGpuRenderTarget(e),c=o.getGpuRenderTarget(l);a.bindFramebuffer(a.READ_FRAMEBUFFER,h.framebuffer),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,c.framebuffer),this._boundFramebuffer=void 0,a.blitFramebuffer(s.x,s.y,s.x+i.width,s.y+i.height,n.x,n.y,n.x+i.width,n.y+i.height,a.DEPTH_BUFFER_BIT,a.NEAREST)}startRenderPass(e,t=!0,s,i,n=0,o=0){const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(l.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.")}e.colorAttachments.forEach(d=>{this._renderer.texture.unbind(d.texture)});const h=this._renderer.gl;this.bindFramebuffer(l.framebuffer),!e.isRoot&&e.colorAttachments.length>0&&(l._attachedMipLevel!==n||l._attachedLayer!==o)&&(e.colorAttachments.forEach((d,f)=>{const p=d.texture,m=this._renderer.texture.getGlSource(p);if(m.target===h.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,h.TEXTURE_2D,m.texture,n)}else if(m.target===h.TEXTURE_2D_ARRAY||m.target===h.TEXTURE_3D)h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,m.texture,n,o);else if(m.target===h.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,h.TEXTURE_CUBE_MAP_POSITIVE_X+o,m.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),l._attachedMipLevel=n,l._attachedLayer=o),l.framebuffer&&(e.depthStencilAttachment?this._attachDepthStencilTexture(e,n,o):!l.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(l)),e.colorAttachments.length>1&&this._setDrawBuffers(e,h);let c=i.y;e.isRoot&&(c=e.pixelHeight-i.height-i.y);const u=this._viewPortCache;(u.x!==i.x||u.y!==c||u.width!==i.width||u.height!==i.height)&&(u.x=i.x,u.y=c,u.width=i.width,u.height=i.height,h.viewport(i.x,c,i.width,i.height)),this.clear(e,t,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa||e.colorAttachments.length===0)return;const i=this._renderer.gl;i.bindFramebuffer(i.FRAMEBUFFER,s.resolveTargetFramebuffer),i.bindFramebuffer(i.READ_FRAMEBUFFER,s.framebuffer),i.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,i.COLOR_BUFFER_BIT,i.NEAREST),i.bindFramebuffer(i.FRAMEBUFFER,s.framebuffer),this._boundFramebuffer=s.framebuffer}initGpuRenderTarget(e){const s=this._renderer.gl,i=new am;i._attachedMipLevel=0,i._attachedLayer=0;const n=e.colorTexture;return n instanceof Ve?(this._renderer.context.ensureCanvasSize(n.resource),i.framebuffer=null,i):(i.width=e.pixelWidth,i.height=e.pixelHeight,e.colorAttachments.length===0?this._initDepth(e,i):this._initColor(e,i),e.depthStencilAttachment&&this._attachDepthStencilTexture(e,0,0),s.bindFramebuffer(s.FRAMEBUFFER,null),this._boundFramebuffer=null,i)}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(s=>{t.deleteRenderbuffer(s)}),e.msaaRenderBuffer.length=0}clear(e,t,s,i,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;if(typeof t=="boolean"&&(t=t?ye.ALL:ye.NONE),e.colorAttachments.length===0&&(t&=~ye.COLOR,!t))return;const l=this._renderer.gl,h=!!(t&ye.DEPTH)&&!this._renderer.state.depthMaskEnabled;if(t&ye.COLOR){s??(s=a.defaultClearColor);const c=this._clearColorCache,u=s;(c[0]!==u[0]||c[1]!==u[1]||c[2]!==u[2]||c[3]!==u[3])&&(c[0]=u[0],c[1]=u[1],c[2]=u[2],c[3]=u[3],l.clearColor(u[0],u[1],u[2],u[3]))}h&&l.depthMask(!0),l.clear(t),h&&l.depthMask(!1)}resizeGpuRenderTarget(e){if(e.isRoot)return;const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.pixelWidth,t.height=e.pixelHeight,e.colorAttachments.length>0&&this._resizeColor(e,t),t.depthStencilRenderBuffer&&this._resizeStencil(t),this._boundFramebuffer=void 0}_initColor(e,t){const s=this._renderer,i=s.gl,n=i.createFramebuffer();if(t.resolveTargetFramebuffer=n,i.bindFramebuffer(i.FRAMEBUFFER,n),e.colorAttachments.forEach((a,l)=>{const h=a.texture;h.antialias&&(s.context.supports.msaa?t.msaa=!0:N("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(h,0);const c=s.texture.getGlSource(h),u=c.texture;if(c.target===i.TEXTURE_2D)i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,i.TEXTURE_2D,u,0);else if(c.target===i.TEXTURE_2D_ARRAY||c.target===i.TEXTURE_3D)i.framebufferTextureLayer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,u,0,0);else if(c.target===i.TEXTURE_CUBE_MAP)i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,i.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=i.createFramebuffer();t.framebuffer=a,i.bindFramebuffer(i.FRAMEBUFFER,a),e.colorAttachments.forEach((l,h)=>{const c=i.createRenderbuffer();t.msaaRenderBuffer[h]=c})}else t.framebuffer=n;this._resizeColor(e,t)}_initDepth(e,t){const s=this._renderer;if(s.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Depth-only render targets require WebGL2.");const i=s.gl,n=i.createFramebuffer();t.resolveTargetFramebuffer=n,t.framebuffer=n,i.bindFramebuffer(i.FRAMEBUFFER,n),i.drawBuffers([i.NONE]),i.readBuffer(i.NONE)}_resizeColor(e,t){const s=e.colorAttachments[0].texture;if(t._attachedMipLevel=0,t._attachedLayer=0,e.colorAttachments.forEach((i,n)=>{n!==0&&i.texture.resize(s.width,s.height,s._resolution)}),t.msaa){const i=this._renderer,n=i.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorAttachments.forEach((a,l)=>{const h=a.texture;i.texture.bindSource(h,0);const u=i.texture.getGlSource(h).internalFormat,d=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,d),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,h.pixelWidth,h.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,d)})}}_attachDepthStencilTexture(e,t,s){const i=this._renderer,n=i.gl,o=e.depthStencilAttachment.texture,a=i.texture.getGlSource(o),l=a.texture,h=o.format;let c;h==="depth24plus-stencil8"||h==="depth32float-stencil8"?c=n.DEPTH_STENCIL_ATTACHMENT:h==="stencil8"?c=n.STENCIL_ATTACHMENT:c=n.DEPTH_ATTACHMENT,a.target===n.TEXTURE_2D?n.framebufferTexture2D(n.FRAMEBUFFER,c,n.TEXTURE_2D,l,t):a.target===n.TEXTURE_2D_ARRAY||a.target===n.TEXTURE_3D?n.framebufferTextureLayer(n.FRAMEBUFFER,c,l,t,s):a.target===n.TEXTURE_CUBE_MAP&&n.framebufferTexture2D(n.FRAMEBUFFER,c,n.TEXTURE_CUBE_MAP_POSITIVE_X+s,l,t)}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,s=t.createRenderbuffer();e.depthStencilRenderBuffer=s,t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,s),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){if(e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture.resource;this._renderer.context.multiView&&Ve.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(!this._renderer.context.multiView||e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture;if(Ve.test(t.resource)){const s=this._renderer.context.canvas,i=t;i.context2D.drawImage(s,0,i.pixelHeight-s.height)}}_setDrawBuffers(e,t){const s=e.colorAttachments.length,i=this._drawBuffersCache[s];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(i):N("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(i)}resetState(){this._boundFramebuffer=void 0,this._viewPortCache=new ee,this._clearColorCache=[0,0,0,0]}bindFramebuffer(e){this._boundFramebuffer!==e&&(this._boundFramebuffer=e,this._renderer.gl.bindFramebuffer(this._renderer.gl.FRAMEBUFFER,e))}}class Rl extends Vi{constructor(e){super(e),this.adaptor=new dm,this.adaptor.init(e,this)}resetState(){this.adaptor.resetState()}}Rl.extension={type:[C.WebGLSystem],name:"renderTarget"};class Xi extends Re{constructor({buffer:e,offset:t,size:s}){super(),this.uid=ne("buffer"),this._resourceType="bufferResource",this._resourceId=ne("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=s,this.buffer.on("change",this.onBufferChange,this)}get _gcLastUsed(){return this.buffer?._gcLastUsed??-1}set _gcLastUsed(e){this.buffer&&(this.buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=ne("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}class fm extends Re{constructor(e,t){super(),this._resourceType="textureView",this._resourceId=ne("resource"),this.source=e,this.viewDescriptor=t,this._onChange=this._onChange.bind(this),this._onDestroy=this._onDestroy.bind(this),this.source.on("change",this._onChange),this.source.on("destroy",this._onDestroy)}_onChange(){this.emit("change",this)}_onDestroy(){this.destroy()}get destroyed(){return this.source.destroyed}destroy(){this.source&&(this.source.off("change",this._onChange),this.source.off("destroy",this._onDestroy)),this.emit("destroy",this),this.removeAllListeners()}}function pm(r,e){const t=[],s=[`
758
+ `}function um(r){return kl(r,Pl,cm)}class Al extends Ml{constructor(){super({createUboElements:lm,generateUboSync:um})}}Al.extension={type:[S.WebGLSystem],name:"ubo"};class dm{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ee,this._boundFramebuffer=void 0}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ee,this._boundFramebuffer=void 0;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(s,i)=>e.COLOR_ATTACHMENT0+i)}copyToTexture(e,t,s,i,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),h=a.gl;return this.finishRenderPass(e),h.bindFramebuffer(h.FRAMEBUFFER,l.resolveTargetFramebuffer),this._boundFramebuffer=l.resolveTargetFramebuffer,a.texture.bind(t,0),h.copyTexSubImage2D(h.TEXTURE_2D,0,n.x,n.y,s.x,s.y,i.width,i.height),t}copyDepthTexture(e,t,s,i,n){const o=this._renderTargetSystem,a=this._renderer.gl;this.finishRenderPass(e);const l=o.getRenderTarget(t),h=o.getGpuRenderTarget(e),c=o.getGpuRenderTarget(l);a.bindFramebuffer(a.READ_FRAMEBUFFER,h.framebuffer),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,c.framebuffer),this._boundFramebuffer=void 0,a.blitFramebuffer(s.x,s.y,s.x+i.width,s.y+i.height,n.x,n.y,n.x+i.width,n.y+i.height,a.DEPTH_BUFFER_BIT,a.NEAREST)}startRenderPass(e,t=!0,s,i,n=0,o=0){const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(l.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.")}e.colorAttachments.forEach(d=>{this._renderer.texture.unbind(d.texture)});const h=this._renderer.gl;this.bindFramebuffer(l.framebuffer),!e.isRoot&&e.colorAttachments.length>0&&(l._attachedMipLevel!==n||l._attachedLayer!==o)&&(e.colorAttachments.forEach((d,f)=>{const p=d.texture,m=this._renderer.texture.getGlSource(p);if(m.target===h.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,h.TEXTURE_2D,m.texture,n)}else if(m.target===h.TEXTURE_2D_ARRAY||m.target===h.TEXTURE_3D)h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,m.texture,n,o);else if(m.target===h.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0+f,h.TEXTURE_CUBE_MAP_POSITIVE_X+o,m.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),l._attachedMipLevel=n,l._attachedLayer=o),l.framebuffer&&(e.depthStencilAttachment?this._attachDepthStencilTexture(e,n,o):!l.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(l)),e.colorAttachments.length>1&&this._setDrawBuffers(e,h);let c=i.y;e.isRoot&&(c=e.pixelHeight-i.height-i.y);const u=this._viewPortCache;(u.x!==i.x||u.y!==c||u.width!==i.width||u.height!==i.height)&&(u.x=i.x,u.y=c,u.width=i.width,u.height=i.height,h.viewport(i.x,c,i.width,i.height)),this.clear(e,t,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa||e.colorAttachments.length===0)return;const i=this._renderer.gl;i.bindFramebuffer(i.FRAMEBUFFER,s.resolveTargetFramebuffer),i.bindFramebuffer(i.READ_FRAMEBUFFER,s.framebuffer),i.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,i.COLOR_BUFFER_BIT,i.NEAREST),i.bindFramebuffer(i.FRAMEBUFFER,s.framebuffer),this._boundFramebuffer=s.framebuffer}initGpuRenderTarget(e){const s=this._renderer.gl,i=new am;i._attachedMipLevel=0,i._attachedLayer=0;const n=e.colorTexture;return n instanceof Ve?(this._renderer.context.ensureCanvasSize(n.resource),i.framebuffer=null,i):(i.width=e.pixelWidth,i.height=e.pixelHeight,e.colorAttachments.length===0?this._initDepth(e,i):this._initColor(e,i),e.depthStencilAttachment&&this._attachDepthStencilTexture(e,0,0),s.bindFramebuffer(s.FRAMEBUFFER,null),this._boundFramebuffer=null,i)}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(s=>{t.deleteRenderbuffer(s)}),e.msaaRenderBuffer.length=0}clear(e,t,s,i,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;if(typeof t=="boolean"&&(t=t?ye.ALL:ye.NONE),e.colorAttachments.length===0&&(t&=~ye.COLOR,!t))return;const l=this._renderer.gl,h=!!(t&ye.DEPTH)&&!this._renderer.state.depthMaskEnabled;if(t&ye.COLOR){s??(s=a.defaultClearColor);const c=this._clearColorCache,u=s;(c[0]!==u[0]||c[1]!==u[1]||c[2]!==u[2]||c[3]!==u[3])&&(c[0]=u[0],c[1]=u[1],c[2]=u[2],c[3]=u[3],l.clearColor(u[0],u[1],u[2],u[3]))}h&&l.depthMask(!0),l.clear(t),h&&l.depthMask(!1)}resizeGpuRenderTarget(e){if(e.isRoot)return;const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.pixelWidth,t.height=e.pixelHeight,e.colorAttachments.length>0&&this._resizeColor(e,t),t.depthStencilRenderBuffer&&this._resizeStencil(t),this._boundFramebuffer=void 0}_initColor(e,t){const s=this._renderer,i=s.gl,n=i.createFramebuffer();if(t.resolveTargetFramebuffer=n,i.bindFramebuffer(i.FRAMEBUFFER,n),e.colorAttachments.forEach((a,l)=>{const h=a.texture;h.antialias&&(s.context.supports.msaa?t.msaa=!0:N("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(h,0);const c=s.texture.getGlSource(h),u=c.texture;if(c.target===i.TEXTURE_2D)i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,i.TEXTURE_2D,u,0);else if(c.target===i.TEXTURE_2D_ARRAY||c.target===i.TEXTURE_3D)i.framebufferTextureLayer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,u,0,0);else if(c.target===i.TEXTURE_CUBE_MAP)i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+l,i.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=i.createFramebuffer();t.framebuffer=a,i.bindFramebuffer(i.FRAMEBUFFER,a),e.colorAttachments.forEach((l,h)=>{const c=i.createRenderbuffer();t.msaaRenderBuffer[h]=c})}else t.framebuffer=n;this._resizeColor(e,t)}_initDepth(e,t){const s=this._renderer;if(s.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Depth-only render targets require WebGL2.");const i=s.gl,n=i.createFramebuffer();t.resolveTargetFramebuffer=n,t.framebuffer=n,i.bindFramebuffer(i.FRAMEBUFFER,n),i.drawBuffers([i.NONE]),i.readBuffer(i.NONE)}_resizeColor(e,t){const s=e.colorAttachments[0].texture;if(t._attachedMipLevel=0,t._attachedLayer=0,e.colorAttachments.forEach((i,n)=>{n!==0&&i.texture.resize(s.width,s.height,s._resolution)}),t.msaa){const i=this._renderer,n=i.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorAttachments.forEach((a,l)=>{const h=a.texture;i.texture.bindSource(h,0);const u=i.texture.getGlSource(h).internalFormat,d=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,d),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,h.pixelWidth,h.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,d)})}}_attachDepthStencilTexture(e,t,s){const i=this._renderer,n=i.gl,o=e.depthStencilAttachment.texture,a=i.texture.getGlSource(o),l=a.texture,h=o.format;let c;h==="depth24plus-stencil8"||h==="depth32float-stencil8"?c=n.DEPTH_STENCIL_ATTACHMENT:h==="stencil8"?c=n.STENCIL_ATTACHMENT:c=n.DEPTH_ATTACHMENT,a.target===n.TEXTURE_2D?n.framebufferTexture2D(n.FRAMEBUFFER,c,n.TEXTURE_2D,l,t):a.target===n.TEXTURE_2D_ARRAY||a.target===n.TEXTURE_3D?n.framebufferTextureLayer(n.FRAMEBUFFER,c,l,t,s):a.target===n.TEXTURE_CUBE_MAP&&n.framebufferTexture2D(n.FRAMEBUFFER,c,n.TEXTURE_CUBE_MAP_POSITIVE_X+s,l,t)}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,s=t.createRenderbuffer();e.depthStencilRenderBuffer=s,t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,s),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){if(e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture.resource;this._renderer.context.multiView&&Ve.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(!this._renderer.context.multiView||e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture;if(Ve.test(t.resource)){const s=this._renderer.context.canvas,i=t;i.context2D.drawImage(s,0,i.pixelHeight-s.height)}}_setDrawBuffers(e,t){const s=e.colorAttachments.length,i=this._drawBuffersCache[s];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(i):N("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(i)}resetState(){this._boundFramebuffer=void 0,this._viewPortCache=new ee,this._clearColorCache=[0,0,0,0]}bindFramebuffer(e){this._boundFramebuffer!==e&&(this._boundFramebuffer=e,this._renderer.gl.bindFramebuffer(this._renderer.gl.FRAMEBUFFER,e))}}class Rl extends Vi{constructor(e){super(e),this.adaptor=new dm,this.adaptor.init(e,this)}resetState(){this.adaptor.resetState()}}Rl.extension={type:[S.WebGLSystem],name:"renderTarget"};class Xi extends Re{constructor({buffer:e,offset:t,size:s}){super(),this.uid=ne("buffer"),this._resourceType="bufferResource",this._resourceId=ne("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=s,this.buffer.on("change",this.onBufferChange,this)}get _gcLastUsed(){return this.buffer?._gcLastUsed??-1}set _gcLastUsed(e){this.buffer&&(this.buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=ne("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}class fm extends Re{constructor(e,t){super(),this._resourceType="textureView",this._resourceId=ne("resource"),this.source=e,this.viewDescriptor=t,this._onChange=this._onChange.bind(this),this._onDestroy=this._onDestroy.bind(this),this.source.on("change",this._onChange),this.source.on("destroy",this._onDestroy)}_onChange(){this.emit("change",this)}_onDestroy(){this.destroy()}get destroyed(){return this.source.destroyed}destroy(){this.source&&(this.source.off("change",this._onChange),this.source.off("destroy",this._onDestroy)),this.emit("destroy",this),this.removeAllListeners()}}function pm(r,e){const t=[],s=[`
759
759
  var g = s.groups;
760
760
  var sS = r.shader;
761
761
  var p = s.glProgram;
@@ -785,7 +785,7 @@ fn mainFragment(
785
785
  `);return new Function("r","s","sD",a)}class mm{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 To(r,e,t){const s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}function kn(r){const e=new Array(r);for(let t=0;t<e.length;t++)e[t]=!1;return e}function Bl(r,e){switch(r){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":case"sampler3D":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 kn(2*e);case"bvec3":return kn(3*e);case"bvec4":return kn(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 Hr=null;const Gc={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_2D_SHADOW:"sampler2DShadow",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_CUBE_SHADOW:"samplerCubeShadow",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray",SAMPLER_2D_ARRAY_SHADOW:"sampler2DArrayShadow",SAMPLER_3D:"sampler3D",INT_SAMPLER_3D:"sampler3D",UNSIGNED_INT_SAMPLER_3D:"sampler3D"},Wy={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 Il(r,e){if(!Hr){const t=Object.keys(Gc);Hr={};for(let s=0;s<t.length;++s){const i=t[s];Hr[r[i]]=Gc[i]}}return Hr[e]}function gm(r,e){const t=Il(r,e);return Wy[t]||"float32"}function _m(r,e,t=!1){const s={},i=e.getProgramParameter(r,e.ACTIVE_ATTRIBUTES);for(let o=0;o<i;o++){const a=e.getActiveAttrib(r,o);if(a.name.startsWith("gl_"))continue;const l=gm(e,a.type);s[a.name]={location:0,format:l,stride:Ms(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(s);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)s[n[o]].location=o,e.bindAttribLocation(r,o,n[o]);e.linkProgram(r)}else for(let o=0;o<n.length;o++)s[n[o]].location=e.getAttribLocation(r,n[o]);return s}function ym(r,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},s=e.getProgramParameter(r,e.ACTIVE_UNIFORM_BLOCKS);for(let i=0;i<s;i++){const n=e.getActiveUniformBlockName(r,i),o=e.getUniformBlockIndex(r,n),a=e.getActiveUniformBlockParameter(r,i,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function xm(r,e){const t={},s=e.getProgramParameter(r,e.ACTIVE_UNIFORMS);for(let i=0;i<s;i++){const n=e.getActiveUniform(r,i),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=Il(e,n.type);t[o]={name:o,index:i,type:l,size:n.size,isArray:a,value:Bl(l,n.size)}}return t}function Dc(r,e){const t=r.getShaderSource(e);if(t===null){console.error("PixiJS Error: Could not retrieve shader source (WebGL context may be lost).");return}const s=t.split(`
786
786
  `).map((c,u)=>`${u}: ${c}`),i=r.getShaderInfoLog(e)??"",n=i.split(`
787
787
  `),o={},a=n.map(c=>parseFloat(c.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(c=>c&&!o[c]?(o[c]=!0,!0):!1),l=[""];a.forEach(c=>{s[c-1]=`%c${s[c-1]}%c`,l.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const h=s.join(`
788
- `);l[0]=h,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...l),console.groupEnd()}function bm(r,e,t,s){r.getProgramParameter(e,r.LINK_STATUS)||(r.getShaderParameter(t,r.COMPILE_STATUS)||Dc(r,t),r.getShaderParameter(s,r.COMPILE_STATUS)||Dc(r,s),console.error("PixiJS Error: Could not initialize shader."),r.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",r.getProgramInfoLog(e)))}function vm(r,e){const t=To(r,r.VERTEX_SHADER,e.vertex),s=To(r,r.FRAGMENT_SHADER,e.fragment),i=r.createProgram();r.attachShader(i,t),r.attachShader(i,s);const n=e.transformFeedbackVaryings;n&&(typeof r.transformFeedbackVaryings!="function"?N("TransformFeedback is not supported but TransformFeedbackVaryings are given."):r.transformFeedbackVaryings(i,n.names,n.bufferMode==="separate"?r.SEPARATE_ATTRIBS:r.INTERLEAVED_ATTRIBS)),r.linkProgram(i),r.getProgramParameter(i,r.LINK_STATUS)||bm(r,i,t,s),e._attributeData=_m(i,r,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=xm(i,r),e._uniformBlockData=ym(i,r),r.deleteShader(t),r.deleteShader(s);const o={};for(const l in e._uniformData){const h=e._uniformData[l];o[l]={location:r.getUniformLocation(i,l),value:Bl(h.type,h.size)}}return new mm(i,o)}const zr={textureCount:0,blockIndex:0};class Gl{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;zr.textureCount=0,zr.blockIndex=0;let s=this._shaderSyncFunctions[e.glProgram._key];s||(s=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),s(this._renderer,e,zr)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,zr)}bindUniformBlock(e,t,s=0){const i=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=i.updateBuffer(a),h=i.freeLocationForBufferBase(l);if(o){const{offset:u,size:d}=e;u===0&&d===a.data.byteLength?i.bindBufferBase(l,h):i.bindBufferRange(l,h,u)}else i.getLastBindBaseLocation(l)!==h&&i.bindBufferBase(l,h);const c=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[s]!==h&&(n.uniformBlockBindings[s]=h,this._renderer.gl.uniformBlockBinding(n.program,c,h))}_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]=vm(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 pm(e,t)}resetState(){this._activeProgram=null}}Gl.extension={type:[C.WebGLSystem],name:"shader"};const wm={f32:`if (cv !== v) {
788
+ `);l[0]=h,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...l),console.groupEnd()}function bm(r,e,t,s){r.getProgramParameter(e,r.LINK_STATUS)||(r.getShaderParameter(t,r.COMPILE_STATUS)||Dc(r,t),r.getShaderParameter(s,r.COMPILE_STATUS)||Dc(r,s),console.error("PixiJS Error: Could not initialize shader."),r.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",r.getProgramInfoLog(e)))}function vm(r,e){const t=To(r,r.VERTEX_SHADER,e.vertex),s=To(r,r.FRAGMENT_SHADER,e.fragment),i=r.createProgram();r.attachShader(i,t),r.attachShader(i,s);const n=e.transformFeedbackVaryings;n&&(typeof r.transformFeedbackVaryings!="function"?N("TransformFeedback is not supported but TransformFeedbackVaryings are given."):r.transformFeedbackVaryings(i,n.names,n.bufferMode==="separate"?r.SEPARATE_ATTRIBS:r.INTERLEAVED_ATTRIBS)),r.linkProgram(i),r.getProgramParameter(i,r.LINK_STATUS)||bm(r,i,t,s),e._attributeData=_m(i,r,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=xm(i,r),e._uniformBlockData=ym(i,r),r.deleteShader(t),r.deleteShader(s);const o={};for(const l in e._uniformData){const h=e._uniformData[l];o[l]={location:r.getUniformLocation(i,l),value:Bl(h.type,h.size)}}return new mm(i,o)}const zr={textureCount:0,blockIndex:0};class Gl{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;zr.textureCount=0,zr.blockIndex=0;let s=this._shaderSyncFunctions[e.glProgram._key];s||(s=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),s(this._renderer,e,zr)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,zr)}bindUniformBlock(e,t,s=0){const i=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=i.updateBuffer(a),h=i.freeLocationForBufferBase(l);if(o){const{offset:u,size:d}=e;u===0&&d===a.data.byteLength?i.bindBufferBase(l,h):i.bindBufferRange(l,h,u)}else i.getLastBindBaseLocation(l)!==h&&i.bindBufferBase(l,h);const c=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[s]!==h&&(n.uniformBlockBindings[s]=h,this._renderer.gl.uniformBlockBinding(n.program,c,h))}_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]=vm(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 pm(e,t)}resetState(){this._activeProgram=null}}Gl.extension={type:[S.WebGLSystem],name:"shader"};const wm={f32:`if (cv !== v) {
789
789
  cu.value = v;
790
790
  gl.uniform1f(location, v);
791
791
  }`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
@@ -875,8 +875,8 @@ fn mainFragment(
875
875
  cv = cu.value;
876
876
  v = uv["${s}"];
877
877
  ${a};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
878
- `))}class Dl{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const i=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==i.uniformDirtyGroups[e.uid])&&(i.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(i.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),i=this._getSignature(e,t._uniformData,"u");return this._cache[i]||(this._cache[i]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[i],s[t._key]}_generateUniformsSync(e,t){return Sm(e,t)}_getSignature(e,t,s){const i=e.uniforms,n=[`${s}-`];for(const o in i)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Dl.extension={type:[C.WebGLSystem],name:"uniformGroup"};function Cm(r){const e={};if(e.normal=[r.ONE,r.ONE_MINUS_SRC_ALPHA],e.add=[r.ONE,r.ONE],e.multiply=[r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.screen=[r.ONE,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[r.SRC_ALPHA,r.ONE,r.ONE,r.ONE],e["screen-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.erase=[r.ZERO,r.ONE_MINUS_SRC_ALPHA],!(r instanceof J.get().getWebGLRenderingContext()))e.min=[r.ONE,r.ONE,r.ONE,r.ONE,r.MIN,r.MIN],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,r.MAX,r.MAX];else{const s=r.getExtension("EXT_blend_minmax");s&&(e.min=[r.ONE,r.ONE,r.ONE,r.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const{BLEND:$y,OFFSET:Vy,CULLING:Xy,DEPTH_TEST:jy,WINDING:qy,DEPTH_MASK:Fc}=Qo,Mm=class So{constructor(e){this._invertFrontFace=!1,this._renderer=e,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[$y]=this.setBlend,this.map[Vy]=this.setOffset,this.map[Xy]=this.setCullFace,this.map[jy]=this.setDepthTest,this.map[qy]=this.setFrontFace,this.map[Fc]=this.setDepthMask,this.checks=[],this.defaultState=ft.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=Cm(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;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(So._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(So._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)}get depthMaskEnabled(){return!!(this.stateId&1<<Fc)}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],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.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 s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,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,this._renderer=null}};Mm.extension={type:[C.WebGLSystem],name:"state"};let Em=Mm;class km{constructor(e){this.target=As.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=re.UNSIGNED_BYTE,this.internalFormat=di.RGBA,this.format=di.RGBA,this.samplerType=0}destroy(){}}function Fl(r,e,t,s,i){if(r=Math.max(0,r),e=Math.min(e,t*s),r>=e)return 0;const n=Math.floor(r/t),o=r-n*t,a=Math.floor(e/t),l=e-a*t;if(n===a)return i[0].set(o,n,l-o,1),1;let h=0,c=n;return o>0&&(i[h++].set(o,n,t-o,1),c++),a>c&&i[h++].set(0,c,t,a-c),l>0&&i[h++].set(0,a,l,1),h}const Lc=[new ee,new ee,new ee],Pm={id:"buffer",upload(r,e,t,s,i,n=!1){const o=i||e.target,a=r.resource;if(o===As.TEXTURE_3D||o===As.TEXTURE_2D_ARRAY){n||e.width!==r.width||e.height!==r.height?t.texImage3D(o,0,e.internalFormat,r.width,r.height,r.depthOrArrayLayers,0,e.format,e.type,a):t.texSubImage3D(o,0,0,0,0,r.width,r.height,r.depthOrArrayLayers,e.format,e.type,a),e.width=r.width,e.height=r.height;return}const l=r.width*r.height,h=n||e.width!==r.width||e.height!==r.height,c=r._updateStart>0||r._updateEnd<l;if(h)t.texImage2D(o,0,e.internalFormat,r.width,r.height,0,e.format,e.type,a);else if(c){const u=a.length/l,d=Fl(r._updateStart,r._updateEnd,r.width,r.height,Lc);for(let f=0;f<d;f++){const p=Lc[f],m=(p.y*r.width+p.x)*u;t.texSubImage2D(o,0,p.x,p.y,p.width,p.height,e.format,e.type,a.subarray(m,m+p.width*p.height*u))}}else t.texSubImage2D(o,0,0,0,r.width,r.height,e.format,e.type,a);e.width=r.width,e.height=r.height}},Yy={"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},Am={id:"compressed",upload(r,e,t,s,i,n){const o=i??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=r.pixelWidth,l=r.pixelHeight;const h=!!Yy[r.format];for(let c=0;c<r.resource.length;c++){const u=r.resource[c];h?t.compressedTexImage2D(o,c,e.internalFormat,a,l,0,u):t.texImage2D(o,c,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},Oc=["right","left","top","bottom","front","back"];function Rm(r){return{id:"cube",upload(e,t,s,i){const n=e.faces;for(let o=0;o<Oc.length;o++){const a=Oc[o],l=n[a];if(!l.resource)continue;(r[l.uploadMethodId]||r.image).upload(l,t,s,i,As.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const Ll={id:"image",upload(r,e,t,s,i,n=!1){const o=i||e.target,a=r.pixelWidth,l=r.pixelHeight,h=r.resourceWidth,c=r.resourceHeight,u=s===2,d=n||e.width!==a||e.height!==l,f=h>=a&&c>=l,p=r.resource;(u?Ky:Zy)(t,o,e,a,l,h,c,p,d,f),e.width=a,e.height=l}};function Ky(r,e,t,s,i,n,o,a,l,h){if(!h){l&&r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,a)}function Zy(r,e,t,s,i,n,o,a,l,h){if(!h){l&&r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}r.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const Qy=vp(),Bm={id:"video",upload(r,e,t,s,i,n=Qy){if(!r.isValid){const o=i??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}Ll.upload(r,e,t,s,i,n)}},Co={linear:9729,nearest:9728},Im={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Kr={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Gm={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Mo(r,e,t,s,i,n,o,a){const l=n;if(!a||r.addressModeU!=="repeat"||r.addressModeV!=="repeat"||r.addressModeW!=="repeat"){const h=Kr[o?"clamp-to-edge":r.addressModeU],c=Kr[o?"clamp-to-edge":r.addressModeV],u=Kr[o?"clamp-to-edge":r.addressModeW];e[i](l,e.TEXTURE_WRAP_S,h),e[i](l,e.TEXTURE_WRAP_T,c),e.TEXTURE_WRAP_R&&e[i](l,e.TEXTURE_WRAP_R,u)}if((!a||r.magFilter!=="linear")&&e[i](l,e.TEXTURE_MAG_FILTER,Co[r.magFilter]),t){if(!a||r.mipmapFilter!=="linear"){const h=Im[r.minFilter][r.mipmapFilter];e[i](l,e.TEXTURE_MIN_FILTER,h)}}else e[i](l,e.TEXTURE_MIN_FILTER,Co[r.minFilter]);if(s&&r.maxAnisotropy>1){const h=Math.min(r.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[i](l,s.TEXTURE_MAX_ANISOTROPY_EXT,h)}r.compare?(e[i](l,e.TEXTURE_COMPARE_FUNC,Gm[r.compare]),e[i](l,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE)):a||e[i](l,e.TEXTURE_COMPARE_MODE,e.NONE)}function Dm(r){return{r8unorm:r.RED,r8snorm:r.RED,r8uint:r.RED_INTEGER,r8sint:r.RED_INTEGER,r16uint:r.RED_INTEGER,r16sint:r.RED_INTEGER,r16float:r.RED,rg8unorm:r.RG,rg8snorm:r.RG,rg8uint:r.RG_INTEGER,rg8sint:r.RG_INTEGER,r32uint:r.RED_INTEGER,r32sint:r.RED_INTEGER,r32float:r.RED,rg16uint:r.RG_INTEGER,rg16sint:r.RG_INTEGER,rg16float:r.RG,rgba8unorm:r.RGBA,"rgba8unorm-srgb":r.RGBA,rgba8snorm:r.RGBA,rgba8uint:r.RGBA_INTEGER,rgba8sint:r.RGBA_INTEGER,bgra8unorm:r.RGBA,"bgra8unorm-srgb":r.RGBA,rgb9e5ufloat:r.RGB,rgb10a2unorm:r.RGBA,rg11b10ufloat:r.RGB,rg32uint:r.RG_INTEGER,rg32sint:r.RG_INTEGER,rg32float:r.RG,rgba16uint:r.RGBA_INTEGER,rgba16sint:r.RGBA_INTEGER,rgba16float:r.RGBA,rgba32uint:r.RGBA_INTEGER,rgba32sint:r.RGBA_INTEGER,rgba32float:r.RGBA,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT,depth24plus:r.DEPTH_COMPONENT,"depth24plus-stencil8":r.DEPTH_STENCIL,depth32float:r.DEPTH_COMPONENT,"depth32float-stencil8":r.DEPTH_STENCIL}}function Fm(r,e){let t={},s=r.RGBA;return r instanceof J.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":r.SRGB8_ALPHA8,"bgra8unorm-srgb":r.SRGB8_ALPHA8},s=r.RGBA8),{r8unorm:r.R8,r8snorm:r.R8_SNORM,r8uint:r.R8UI,r8sint:r.R8I,r16uint:r.R16UI,r16sint:r.R16I,r16float:r.R16F,rg8unorm:r.RG8,rg8snorm:r.RG8_SNORM,rg8uint:r.RG8UI,rg8sint:r.RG8I,r32uint:r.R32UI,r32sint:r.R32I,r32float:r.R32F,rg16uint:r.RG16UI,rg16sint:r.RG16I,rg16float:r.RG16F,rgba8unorm:r.RGBA,...t,rgba8snorm:r.RGBA8_SNORM,rgba8uint:r.RGBA8UI,rgba8sint:r.RGBA8I,bgra8unorm:s,rgb9e5ufloat:r.RGB9_E5,rgb10a2unorm:r.RGB10_A2,rg11b10ufloat:r.R11F_G11F_B10F,rg32uint:r.RG32UI,rg32sint:r.RG32I,rg32float:r.RG32F,rgba16uint:r.RGBA16UI,rgba16sint:r.RGBA16I,rgba16float:r.RGBA16F,rgba32uint:r.RGBA32UI,rgba32sint:r.RGBA32I,rgba32float:r.RGBA32F,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT16,depth24plus:r.DEPTH_COMPONENT24,"depth24plus-stencil8":r.DEPTH24_STENCIL8,depth32float:r.DEPTH_COMPONENT32F,"depth32float-stencil8":r.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 Lm(r){return{r8unorm:r.UNSIGNED_BYTE,r8snorm:r.BYTE,r8uint:r.UNSIGNED_BYTE,r8sint:r.BYTE,r16uint:r.UNSIGNED_SHORT,r16sint:r.SHORT,r16float:r.HALF_FLOAT,rg8unorm:r.UNSIGNED_BYTE,rg8snorm:r.BYTE,rg8uint:r.UNSIGNED_BYTE,rg8sint:r.BYTE,r32uint:r.UNSIGNED_INT,r32sint:r.INT,r32float:r.FLOAT,rg16uint:r.UNSIGNED_SHORT,rg16sint:r.SHORT,rg16float:r.HALF_FLOAT,rgba8unorm:r.UNSIGNED_BYTE,"rgba8unorm-srgb":r.UNSIGNED_BYTE,rgba8snorm:r.BYTE,rgba8uint:r.UNSIGNED_BYTE,rgba8sint:r.BYTE,bgra8unorm:r.UNSIGNED_BYTE,"bgra8unorm-srgb":r.UNSIGNED_BYTE,rgb9e5ufloat:r.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:r.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:r.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:r.UNSIGNED_INT,rg32sint:r.INT,rg32float:r.FLOAT,rgba16uint:r.UNSIGNED_SHORT,rgba16sint:r.SHORT,rgba16float:r.HALF_FLOAT,rgba32uint:r.UNSIGNED_INT,rgba32sint:r.INT,rgba32float:r.FLOAT,stencil8:r.UNSIGNED_BYTE,depth16unorm:r.UNSIGNED_SHORT,depth24plus:r.UNSIGNED_INT,"depth24plus-stencil8":r.UNSIGNED_INT_24_8,depth32float:r.FLOAT,"depth32float-stencil8":r.FLOAT_32_UNSIGNED_INT_24_8_REV}}function Om(r){return{"2d":r.TEXTURE_2D,cube:r.TEXTURE_CUBE_MAP,"1d":null,"3d":r?.TEXTURE_3D||null,"2d-array":r?.TEXTURE_2D_ARRAY||null,"cube-array":r?.TEXTURE_CUBE_MAP_ARRAY||null}}const Jy=4,Ol=class Um{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._integerUnits=0,this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new it({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:Ll,buffer:Pm,video:Bm,compressed:Am,...Um.uploadExtensions};this._uploads={...t,cube:Rm(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Fm(e,this._renderer.context.extensions),this._mapFormatToType=Lm(e),this._mapFormatToFormat=Dm(e),this._mapViewDimensionToGlTarget=Om(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(H.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._setBoundTexture(t,e),this._activateLocation(t),e||(e=H.EMPTY.source);const i=this.getGlSource(e);s.bindTexture(i.target,i.texture)}}unbindIntegerTextures(e){if(e>=32)return;let t=this._integerUnits>>>e<<e;for(;t;){const s=31-Math.clz32(t);t&=~(1<<s),this.bind(H.EMPTY,s)}}_setBoundTexture(e,t){this._boundTextures[e]=t,!(e<0||e>31)&&(!t||t.viewDimension!=="2d"||(ti(t.format)?this._integerUnits|=1<<e:this._integerUnits&=~(1<<e)))}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const i=this._getGlSampler(e);this._boundSamplers[t]!==i&&(this._boundSamplers[t]=i,s.bindSampler(t,i))}unbind(e){const t=e.source,s=this._boundTextures,i=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);i.bindTexture(o.target,null),this._setBoundTexture(n,null)}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new km(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],s.target=this._mapViewDimensionToGlTarget[e.viewDimension],s.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height,e.depth);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=s,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),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,i=this.getGlSource(e);s.bindTexture(i.target,i.texture),this._setBoundTexture(this._activeTextureLocation,e),Mo(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",i.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||(this.unbind(e),this._gl.deleteTexture(s.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,s=this.getGlSource(e);t.bindTexture(s.target,s.texture),this._setBoundTexture(this._activeTextureLocation,e);const i=e.alphaMode==="premultiply-alpha-on-upload"&&!ti(e.format)&&s.target!==t.TEXTURE_3D&&s.target!==t.TEXTURE_2D_ARRAY;if(this._premultiplyAlpha!==i&&(this._premultiplyAlpha=i,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion);else if(s.target===t.TEXTURE_2D)this._initEmptyTexture2D(s,e);else if(s.target===t.TEXTURE_2D_ARRAY||s.target===t.TEXTURE_3D)this._initEmptyTexture3D(s,e);else if(s.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(s,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(s,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}_initEmptyTexture2D(e,t){const s=this._gl;s.texImage2D(s.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let i=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)s.texImage2D(s.TEXTURE_2D,o,e.internalFormat,i,n,0,e.format,e.type,null),i=Math.max(i>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture3D(e,t){const s=this._gl,i=e.target===s.TEXTURE_3D;let n=t.pixelWidth,o=t.pixelHeight,a=t.depthOrArrayLayers;for(let l=0;l<t.mipLevelCount;l++)s.texImage3D(e.target,l,e.internalFormat,n,o,a,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1),i&&(a=Math.max(a>>1,1))}_initEmptyTextureCube(e,t){const s=this._gl,i=6;for(let a=0;a<i;a++)s.texImage2D(s.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<i;l++)s.texImage2D(s.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||t.mipLevelCount<=1)return;const s=this._gl,i=Math.max((t.mipLevelCount|0)-1,0);s.texParameteri(e.target,s.TEXTURE_BASE_LEVEL,0),s.texParameteri(e.target,s.TEXTURE_MAX_LEVEL,i)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,Mo(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!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:s,height:i}=this.getPixels(e),n=J.get().createCanvas();n.width=s,n.height=i;const o=n.getContext("2d");if(o){const a=o.createImageData(s,i);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,i=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(Jy*i*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),h=a.renderTarget.getGpuRenderTarget(l),c=a.gl;return a.renderTarget.adaptor.bindFramebuffer(h.resolveTargetFramebuffer),c.readPixels(Math.round(s.x*t),Math.round(s.y*t),i,n,c.RGBA,c.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:i,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(){const e=this._renderer.limits.maxTextures;this._activeTextureLocation=-1,this._boundTextures.fill(null),this._integerUnits=e>=32?-1:(1<<e)-1,this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}};Ol.extension={type:[C.WebGLSystem],name:"texture"};Ol.uploadExtensions=Object.create(null);let Ul=Ol;q.handleByMap(C.TextureUploaderWebGL,Ul.uploadExtensions);class Nl{contextChange(e){const t=new rt({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new L,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,i=Pi({name:"graphics",bits:[ua,fa(s),Ia,Ri]});this.shader=new dt({glProgram:i,resources:{localUniforms:t,batchSamplers:pa(s)}})}execute(e,t){const s=t.context,i=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);i.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(i),n.geometry.bind(a.geometry,i.glProgram);const h=l.instructions;for(let c=0;c<l.instructionSize;c++){const u=h[c];if(u.size){for(let d=0;d<u.textures.count;d++)n.texture.bind(u.textures.textures[d],d);n.texture.unbindIntegerTextures(u.textures.count),n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Nl.extension={type:[C.WebGLPipesAdaptor],name:"graphics"};class Hl{init(){const e=Pi({name:"mesh",bits:[Ia,Cp,Ri]});this._shader=new dt({glProgram:e,resources:{uTexture:H.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new L}}}})}execute(e,t){const s=e.renderer;let i=t._shader;if(i){if(!i.glProgram){N("Mesh shader has no glProgram",t.shader);return}}else{i=this._shader;const n=t.texture,o=n.source;i.resources.uTexture=o,i.resources.uSampler=o.style,i.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}i.groups[100]=s.globalUniforms.bindGroup,i.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:i,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Hl.extension={type:[C.WebGLPipesAdaptor],name:"mesh"};const ex=[...$i,Al,om,sm,Sl,yl,Ul,Rl,bl,Dl,Gl,Tl,Em,Cl,wl],tx=[...ml],sx=[Xa,Hl,Nl],Nm=[],Hm=[],zm=[],Wm=[];q.handleByNamedList(C.WebGLSystem,Nm);q.handleByNamedList(C.WebGLPipes,Hm);q.handleByNamedList(C.WebGLPipesAdaptor,zm);q.handleByNamedList(C.WebGLLoader,Wm);q.add(...ex,...tx,...sx);class $m extends Is{constructor(){const e={name:"webgl",type:Ke.WEBGL,systems:Nm,renderPipes:Hm,renderPipeAdaptors:zm,loaders:Wm};super(e)}}const rx=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:$m},Symbol.toStringTag,{value:"Module"}));class ix{constructor(e,t){this.autoGarbageCollect=!0,this._gpuData=null,this.gpuBindGroup=e,this._gcLastUsed=t}unload(){this.gpuBindGroup=null}}class zl{constructor(e){this._hash=Object.create(null),this._renderer=e,e.gc.addResourceHash(this,"_hash","resource"),e.gc.addCollection(this,"_hash","hash")}contextChange(e){this._gpu=e,this._hash=Object.create(null)}getBindGroup(e,t,s){const i=`${e._key}:${t._layoutKey<<4|s}`,n=this._hash[i];return n?(n._gcLastUsed=this._renderer.gc.now,n.gpuBindGroup):this._createBindGroup(i,e,t,s)}_createBindGroup(e,t,s,i){const n=this._gpu.device,o=s.layout[i],a=[],l=this._renderer;for(const u in o){const d=t.resources[u]??t.resources[o[u]];if(!d||d.destroyed)throw new Error(`[BindGroup] the resource bound as '${u}' was destroyed while a shader still uses it. Remove it from the shader before destroying it.`);let f;if(d._resourceType==="uniformGroup"){const p=d;l.ubo.updateUniformGroup(p);const m=p.buffer;f={buffer:l.buffer.getGPUBuffer(m),offset:0,size:m.descriptor.size}}else if(d._resourceType==="buffer"){const p=d;f={buffer:l.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(d._resourceType==="bufferResource"){const p=d;f={buffer:l.buffer.getGPUBuffer(p.buffer),offset:p.offset,size:p.size??p.buffer.descriptor.size}}else if(d._resourceType==="textureSampler"){const p=d;f=l.texture.getGpuSampler(p)}else if(d._resourceType==="textureSource"){const p=d;f=l.texture.getTextureView(p)}else if(d._resourceType==="textureView"){const p=d;f=l.texture.getTextureView(p.source,p.viewDescriptor)}a.push({binding:o[u],resource:f})}const h=l.shader.getProgramData(s).bindGroups[i],c=n.createBindGroup({layout:h,entries:a});return this._hash[e]=new ix(c,l.gc.now),c}destroy(){this._hash=null,this._renderer=null}}zl.extension={type:[C.WebGPUSystem],name:"bindGroup"};class Vm{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class Wl{constructor(e){this._renderer=e,this._managedBuffers=new it({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e,this.destroyAll()}getGPUBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuBuffer||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,e._updateOffset,s.buffer,s.byteOffset+e._updateOffset,(e._updateSize||s.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.data&&(oi(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new Vm(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}}Wl.extension={type:[C.WebGPUSystem],name:"buffer"};class Xm{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 s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class $l{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}}$l.extension={type:[C.WebGPUSystem],name:"colorMask"};const nx=new Set(["apple","arm","qualcomm","img-tec"]);class ji{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._options=e,this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>this._setGpu(t)),this._initPromise)}_setGpu(e){this.gpu=e,this.extensions={transientAttachment:typeof GPUTextureUsage.TRANSIENT_ATTACHMENT=="number",tileBased:nx.has(e.adapter?.info?.vendor)},this._options.gpu||e.device.lost.then(()=>this._restoreDevice()).catch(t=>N("WebGPU device was lost and could not be restored",t)),this._renderer.runners.contextChange.emit(this.gpu)}async _restoreDevice(){if(!this._renderer)return;const e=await this._createDeviceAndAdaptor(this._options);if(!this._renderer){e.device.destroy();return}this._setGpu(e)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await J.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter});if(!t)throw new Error("WebGPU not supported. No GPU adapter was returned by navigator.gpu.requestAdapter().");const s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2","indirect-first-instance","bgra8unorm-storage","texture-formats-tier1"].filter(n=>t.features.has(n)),i=await t.requestDevice({requiredFeatures:s,requiredLimits:{maxSampledTexturesPerShaderStage:t.limits.maxSampledTexturesPerShaderStage,maxSamplersPerShaderStage:t.limits.maxSamplersPerShaderStage}});return{adapter:t,device:i}}destroy(){this._options?.gpu||this.gpu?.device.destroy(),this.gpu=null,this.extensions=null,this._renderer=null}}ji.extension={type:[C.WebGPUSystem],name:"device"};ji.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class jm{constructor(e,t,s,i){this.gpuBundle=e,this.stateKey=t,this.device=s,this.label=i}}class Vl{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e;for(let t=0;t<16;t++)this._boundBindGroup[t]={bindGroup:null,program:null,key:null}}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){return this.endRenderPass(),this._clearCache(),this._passEncoder=this.commandEncoder.beginRenderPass(e.descriptor),this.renderPassEncoder=this._passEncoder,this._passEncoder}endRenderPass(){this._passEncoder&&this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null}beginBundle(e){if(this._passEncoder!==this.renderPassEncoder)throw new Error("Cannot begin a new render bundle while one is already being recorded.");this._clearCache();const t=this._renderer.pipeline,s=t.getBundleDescriptor();s.label=e,this._bundleStateKey=t.bundleStateKey,this._bundleLabel=e,this.renderPassEncoder=this._gpu.device.createRenderBundleEncoder(s)}endBundle(){const e=this.renderPassEncoder;if(!e||!("finish"in e))throw new Error("endBundle called without an active render bundle.");const t=e.finish({label:this._bundleLabel});return this.renderPassEncoder=this._passEncoder,this._clearCache(),new jm(t,this._bundleStateKey,this._gpu.device,this._bundleLabel)}isBundleValid(e){return e?.stateKey===this._renderer.pipeline.bundleStateKey&&e.device===this._gpu.device}executeBundle(e){const t=[];if(Array.isArray(e))for(let s=0;s<e.length;s++)t[s]=this._getGpuBundle(e[s]);else t[0]=this._getGpuBundle(e);this._clearCache(),this._passEncoder.executeBundles(t)}_getGpuBundle(e){return this.isBundleValid(e)||N(`Render bundle ${e?.label??"(unlabeled)"} was recorded against a different render target state or on a lost device. Re-record it — replaying it will either be rejected by WebGPU or draw with the wrong winding. Check encoder.isBundleValid(bundle) before executing.`),e.gpuBundle}setViewport(e){this._passEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setStencilReference(e){this._passEncoder.setStencilReference(e)}setPipelineFromGeometryProgramAndState(e,t,s,i,n){const o=this._renderer.pipeline.getPipeline(e,t,s,i,n);this.setPipeline(o)}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){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null}setBindGroup(e,t,s){const i=this._boundBindGroup[e];if(i.bindGroup===t&&i.program===s&&i.key===t._key)return;i.bindGroup=t,i.program=s,i.key=t._key,t._touch(this._renderer.gc.now);const n=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,n)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(let i=0;i<s.length;i++)this._setVertexBuffer(i,e.attributes[s[i]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){const s=e.gpuProgram,i=s.layout;for(let n=0;n<i.length;n++){const o=e.groups[n];!i[n]||!o||(t||this._syncBindGroup(o),this.setBindGroup(n,o,s))}}_syncBindGroup(e){const t=e.resources,s=e._resourceKeys;for(let i=0;i<s.length;i++){const n=t[s[i]];n&&n.isUniformGroup&&this._renderer.ubo.updateUniformGroup(n)}}draw(e){const{geometry:t,shader:s,state:i,topology:n,size:o,start:a,baseVertex:l,instanceCount:h,skipSync:c,firstInstance:u}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,i,n,s._overrides),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexCount||t.indexBuffer.data.length,h??t.instanceCount,a||0,l||0,u||0):this.renderPassEncoder.draw(o||t.vertexCount,h??t.instanceCount,a||0,u||0)}drawIndirect(e){const{geometry:t,shader:s,state:i,topology:n,skipSync:o,indirectBuffer:a,indirectOffset:l}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,i,n,s._overrides),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,o),t.indexBuffer?this.renderPassEncoder.drawIndexedIndirect(a,l):this.renderPassEncoder.drawIndirect(a,l)}finishRenderPass(){this._passEncoder&&(this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}_clearCache(){for(let e=0;e<16;e++){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=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,this.renderPassEncoder=null,this._passEncoder=null}contextChange(e){this._gpu=e}}Vl.extension={type:[C.WebGPUSystem],name:"encoder",priority:1};class Xl{constructor(e){this.supportsOverrideConstants=!1,this._renderer=e}contextChange(){const e=this._renderer.device.gpu.device;this.maxTextures=Math.min(e.limits.maxSampledTexturesPerShaderStage,e.limits.maxSamplersPerShaderStage),this.maxBatchableTextures=this.maxTextures,this._detectOverrideConstantsSupport(e)}_detectOverrideConstantsSupport(e){e.pushErrorScope("validation");const t=e.createShaderModule({code:`override TEST_VALUE: f32 = 0.0;
879
- @compute @workgroup_size(1) fn main() {}`});e.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main",constants:{TEST_VALUE:1}}}),e.popErrorScope().then(s=>{this.supportsOverrideConstants=!s})}destroy(){}}Xl.extension={type:[C.WebGPUSystem],name:"limits"};class jl{constructor(e){this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(){this._activeGpuRenderTarget=null}onRenderTargetChange(e){const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeRenderTarget=e,this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget));s.stencilMode=e,s.stencilReference=t;const i=this._renderer;i.pipeline.setStencilMode(e),i.encoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}jl.extension={type:[C.WebGPUSystem],name:"stencil"};const or={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 qm(r){const e=r.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const i=e[s];let n=or[i.data.type].size;const o=or[i.data.type].align;if(!or[i.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${i.data.type}`);i.data.size>1&&(n=Math.max(n,o)*i.data.size),t=Math.ceil(t/o)*o,i.size=n,i.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function Ym(r,e){const{size:t,align:s}=or[r.data.type],i=(Math.max(t,s)-t)/4,n=r.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
878
+ `))}class Dl{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const i=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==i.uniformDirtyGroups[e.uid])&&(i.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(i.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),i=this._getSignature(e,t._uniformData,"u");return this._cache[i]||(this._cache[i]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[i],s[t._key]}_generateUniformsSync(e,t){return Sm(e,t)}_getSignature(e,t,s){const i=e.uniforms,n=[`${s}-`];for(const o in i)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Dl.extension={type:[S.WebGLSystem],name:"uniformGroup"};function Cm(r){const e={};if(e.normal=[r.ONE,r.ONE_MINUS_SRC_ALPHA],e.add=[r.ONE,r.ONE],e.multiply=[r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.screen=[r.ONE,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[r.SRC_ALPHA,r.ONE,r.ONE,r.ONE],e["screen-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.erase=[r.ZERO,r.ONE_MINUS_SRC_ALPHA],!(r instanceof J.get().getWebGLRenderingContext()))e.min=[r.ONE,r.ONE,r.ONE,r.ONE,r.MIN,r.MIN],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,r.MAX,r.MAX];else{const s=r.getExtension("EXT_blend_minmax");s&&(e.min=[r.ONE,r.ONE,r.ONE,r.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const{BLEND:$y,OFFSET:Vy,CULLING:Xy,DEPTH_TEST:jy,WINDING:qy,DEPTH_MASK:Fc}=Qo,Mm=class So{constructor(e){this._invertFrontFace=!1,this._renderer=e,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[$y]=this.setBlend,this.map[Vy]=this.setOffset,this.map[Xy]=this.setCullFace,this.map[jy]=this.setDepthTest,this.map[qy]=this.setFrontFace,this.map[Fc]=this.setDepthMask,this.checks=[],this.defaultState=ft.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=Cm(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;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(So._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(So._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)}get depthMaskEnabled(){return!!(this.stateId&1<<Fc)}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],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.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 s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,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,this._renderer=null}};Mm.extension={type:[S.WebGLSystem],name:"state"};let Em=Mm;class km{constructor(e){this.target=As.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=re.UNSIGNED_BYTE,this.internalFormat=di.RGBA,this.format=di.RGBA,this.samplerType=0}destroy(){}}function Fl(r,e,t,s,i){if(r=Math.max(0,r),e=Math.min(e,t*s),r>=e)return 0;const n=Math.floor(r/t),o=r-n*t,a=Math.floor(e/t),l=e-a*t;if(n===a)return i[0].set(o,n,l-o,1),1;let h=0,c=n;return o>0&&(i[h++].set(o,n,t-o,1),c++),a>c&&i[h++].set(0,c,t,a-c),l>0&&i[h++].set(0,a,l,1),h}const Lc=[new ee,new ee,new ee],Pm={id:"buffer",upload(r,e,t,s,i,n=!1){const o=i||e.target,a=r.resource;if(o===As.TEXTURE_3D||o===As.TEXTURE_2D_ARRAY){n||e.width!==r.width||e.height!==r.height?t.texImage3D(o,0,e.internalFormat,r.width,r.height,r.depthOrArrayLayers,0,e.format,e.type,a):t.texSubImage3D(o,0,0,0,0,r.width,r.height,r.depthOrArrayLayers,e.format,e.type,a),e.width=r.width,e.height=r.height;return}const l=r.width*r.height,h=n||e.width!==r.width||e.height!==r.height,c=r._updateStart>0||r._updateEnd<l;if(h)t.texImage2D(o,0,e.internalFormat,r.width,r.height,0,e.format,e.type,a);else if(c){const u=a.length/l,d=Fl(r._updateStart,r._updateEnd,r.width,r.height,Lc);for(let f=0;f<d;f++){const p=Lc[f],m=(p.y*r.width+p.x)*u;t.texSubImage2D(o,0,p.x,p.y,p.width,p.height,e.format,e.type,a.subarray(m,m+p.width*p.height*u))}}else t.texSubImage2D(o,0,0,0,r.width,r.height,e.format,e.type,a);e.width=r.width,e.height=r.height}},Yy={"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},Am={id:"compressed",upload(r,e,t,s,i,n){const o=i??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=r.pixelWidth,l=r.pixelHeight;const h=!!Yy[r.format];for(let c=0;c<r.resource.length;c++){const u=r.resource[c];h?t.compressedTexImage2D(o,c,e.internalFormat,a,l,0,u):t.texImage2D(o,c,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},Oc=["right","left","top","bottom","front","back"];function Rm(r){return{id:"cube",upload(e,t,s,i){const n=e.faces;for(let o=0;o<Oc.length;o++){const a=Oc[o],l=n[a];if(!l.resource)continue;(r[l.uploadMethodId]||r.image).upload(l,t,s,i,As.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const Ll={id:"image",upload(r,e,t,s,i,n=!1){const o=i||e.target,a=r.pixelWidth,l=r.pixelHeight,h=r.resourceWidth,c=r.resourceHeight,u=s===2,d=n||e.width!==a||e.height!==l,f=h>=a&&c>=l,p=r.resource;(u?Ky:Zy)(t,o,e,a,l,h,c,p,d,f),e.width=a,e.height=l}};function Ky(r,e,t,s,i,n,o,a,l,h){if(!h){l&&r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,a)}function Zy(r,e,t,s,i,n,o,a,l,h){if(!h){l&&r.texImage2D(e,0,t.internalFormat,s,i,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){r.texSubImage2D(e,0,0,0,t.format,t.type,a);return}r.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const Qy=vp(),Bm={id:"video",upload(r,e,t,s,i,n=Qy){if(!r.isValid){const o=i??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}Ll.upload(r,e,t,s,i,n)}},Co={linear:9729,nearest:9728},Im={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Kr={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Gm={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Mo(r,e,t,s,i,n,o,a){const l=n;if(!a||r.addressModeU!=="repeat"||r.addressModeV!=="repeat"||r.addressModeW!=="repeat"){const h=Kr[o?"clamp-to-edge":r.addressModeU],c=Kr[o?"clamp-to-edge":r.addressModeV],u=Kr[o?"clamp-to-edge":r.addressModeW];e[i](l,e.TEXTURE_WRAP_S,h),e[i](l,e.TEXTURE_WRAP_T,c),e.TEXTURE_WRAP_R&&e[i](l,e.TEXTURE_WRAP_R,u)}if((!a||r.magFilter!=="linear")&&e[i](l,e.TEXTURE_MAG_FILTER,Co[r.magFilter]),t){if(!a||r.mipmapFilter!=="linear"){const h=Im[r.minFilter][r.mipmapFilter];e[i](l,e.TEXTURE_MIN_FILTER,h)}}else e[i](l,e.TEXTURE_MIN_FILTER,Co[r.minFilter]);if(s&&r.maxAnisotropy>1){const h=Math.min(r.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[i](l,s.TEXTURE_MAX_ANISOTROPY_EXT,h)}r.compare?(e[i](l,e.TEXTURE_COMPARE_FUNC,Gm[r.compare]),e[i](l,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE)):a||e[i](l,e.TEXTURE_COMPARE_MODE,e.NONE)}function Dm(r){return{r8unorm:r.RED,r8snorm:r.RED,r8uint:r.RED_INTEGER,r8sint:r.RED_INTEGER,r16uint:r.RED_INTEGER,r16sint:r.RED_INTEGER,r16float:r.RED,rg8unorm:r.RG,rg8snorm:r.RG,rg8uint:r.RG_INTEGER,rg8sint:r.RG_INTEGER,r32uint:r.RED_INTEGER,r32sint:r.RED_INTEGER,r32float:r.RED,rg16uint:r.RG_INTEGER,rg16sint:r.RG_INTEGER,rg16float:r.RG,rgba8unorm:r.RGBA,"rgba8unorm-srgb":r.RGBA,rgba8snorm:r.RGBA,rgba8uint:r.RGBA_INTEGER,rgba8sint:r.RGBA_INTEGER,bgra8unorm:r.RGBA,"bgra8unorm-srgb":r.RGBA,rgb9e5ufloat:r.RGB,rgb10a2unorm:r.RGBA,rg11b10ufloat:r.RGB,rg32uint:r.RG_INTEGER,rg32sint:r.RG_INTEGER,rg32float:r.RG,rgba16uint:r.RGBA_INTEGER,rgba16sint:r.RGBA_INTEGER,rgba16float:r.RGBA,rgba32uint:r.RGBA_INTEGER,rgba32sint:r.RGBA_INTEGER,rgba32float:r.RGBA,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT,depth24plus:r.DEPTH_COMPONENT,"depth24plus-stencil8":r.DEPTH_STENCIL,depth32float:r.DEPTH_COMPONENT,"depth32float-stencil8":r.DEPTH_STENCIL}}function Fm(r,e){let t={},s=r.RGBA;return r instanceof J.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":r.SRGB8_ALPHA8,"bgra8unorm-srgb":r.SRGB8_ALPHA8},s=r.RGBA8),{r8unorm:r.R8,r8snorm:r.R8_SNORM,r8uint:r.R8UI,r8sint:r.R8I,r16uint:r.R16UI,r16sint:r.R16I,r16float:r.R16F,rg8unorm:r.RG8,rg8snorm:r.RG8_SNORM,rg8uint:r.RG8UI,rg8sint:r.RG8I,r32uint:r.R32UI,r32sint:r.R32I,r32float:r.R32F,rg16uint:r.RG16UI,rg16sint:r.RG16I,rg16float:r.RG16F,rgba8unorm:r.RGBA,...t,rgba8snorm:r.RGBA8_SNORM,rgba8uint:r.RGBA8UI,rgba8sint:r.RGBA8I,bgra8unorm:s,rgb9e5ufloat:r.RGB9_E5,rgb10a2unorm:r.RGB10_A2,rg11b10ufloat:r.R11F_G11F_B10F,rg32uint:r.RG32UI,rg32sint:r.RG32I,rg32float:r.RG32F,rgba16uint:r.RGBA16UI,rgba16sint:r.RGBA16I,rgba16float:r.RGBA16F,rgba32uint:r.RGBA32UI,rgba32sint:r.RGBA32I,rgba32float:r.RGBA32F,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT16,depth24plus:r.DEPTH_COMPONENT24,"depth24plus-stencil8":r.DEPTH24_STENCIL8,depth32float:r.DEPTH_COMPONENT32F,"depth32float-stencil8":r.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 Lm(r){return{r8unorm:r.UNSIGNED_BYTE,r8snorm:r.BYTE,r8uint:r.UNSIGNED_BYTE,r8sint:r.BYTE,r16uint:r.UNSIGNED_SHORT,r16sint:r.SHORT,r16float:r.HALF_FLOAT,rg8unorm:r.UNSIGNED_BYTE,rg8snorm:r.BYTE,rg8uint:r.UNSIGNED_BYTE,rg8sint:r.BYTE,r32uint:r.UNSIGNED_INT,r32sint:r.INT,r32float:r.FLOAT,rg16uint:r.UNSIGNED_SHORT,rg16sint:r.SHORT,rg16float:r.HALF_FLOAT,rgba8unorm:r.UNSIGNED_BYTE,"rgba8unorm-srgb":r.UNSIGNED_BYTE,rgba8snorm:r.BYTE,rgba8uint:r.UNSIGNED_BYTE,rgba8sint:r.BYTE,bgra8unorm:r.UNSIGNED_BYTE,"bgra8unorm-srgb":r.UNSIGNED_BYTE,rgb9e5ufloat:r.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:r.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:r.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:r.UNSIGNED_INT,rg32sint:r.INT,rg32float:r.FLOAT,rgba16uint:r.UNSIGNED_SHORT,rgba16sint:r.SHORT,rgba16float:r.HALF_FLOAT,rgba32uint:r.UNSIGNED_INT,rgba32sint:r.INT,rgba32float:r.FLOAT,stencil8:r.UNSIGNED_BYTE,depth16unorm:r.UNSIGNED_SHORT,depth24plus:r.UNSIGNED_INT,"depth24plus-stencil8":r.UNSIGNED_INT_24_8,depth32float:r.FLOAT,"depth32float-stencil8":r.FLOAT_32_UNSIGNED_INT_24_8_REV}}function Om(r){return{"2d":r.TEXTURE_2D,cube:r.TEXTURE_CUBE_MAP,"1d":null,"3d":r?.TEXTURE_3D||null,"2d-array":r?.TEXTURE_2D_ARRAY||null,"cube-array":r?.TEXTURE_CUBE_MAP_ARRAY||null}}const Jy=4,Ol=class Um{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._integerUnits=0,this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new it({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:Ll,buffer:Pm,video:Bm,compressed:Am,...Um.uploadExtensions};this._uploads={...t,cube:Rm(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Fm(e,this._renderer.context.extensions),this._mapFormatToType=Lm(e),this._mapFormatToFormat=Dm(e),this._mapViewDimensionToGlTarget=Om(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(H.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._setBoundTexture(t,e),this._activateLocation(t),e||(e=H.EMPTY.source);const i=this.getGlSource(e);s.bindTexture(i.target,i.texture)}}unbindIntegerTextures(e){if(e>=32)return;let t=this._integerUnits>>>e<<e;for(;t;){const s=31-Math.clz32(t);t&=~(1<<s),this.bind(H.EMPTY,s)}}_setBoundTexture(e,t){this._boundTextures[e]=t,!(e<0||e>31)&&(!t||t.viewDimension!=="2d"||(ti(t.format)?this._integerUnits|=1<<e:this._integerUnits&=~(1<<e)))}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const i=this._getGlSampler(e);this._boundSamplers[t]!==i&&(this._boundSamplers[t]=i,s.bindSampler(t,i))}unbind(e){const t=e.source,s=this._boundTextures,i=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);i.bindTexture(o.target,null),this._setBoundTexture(n,null)}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new km(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],s.target=this._mapViewDimensionToGlTarget[e.viewDimension],s.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height,e.depth);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=s,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),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,i=this.getGlSource(e);s.bindTexture(i.target,i.texture),this._setBoundTexture(this._activeTextureLocation,e),Mo(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",i.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||(this.unbind(e),this._gl.deleteTexture(s.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,s=this.getGlSource(e);t.bindTexture(s.target,s.texture),this._setBoundTexture(this._activeTextureLocation,e);const i=e.alphaMode==="premultiply-alpha-on-upload"&&!ti(e.format)&&s.target!==t.TEXTURE_3D&&s.target!==t.TEXTURE_2D_ARRAY;if(this._premultiplyAlpha!==i&&(this._premultiplyAlpha=i,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion);else if(s.target===t.TEXTURE_2D)this._initEmptyTexture2D(s,e);else if(s.target===t.TEXTURE_2D_ARRAY||s.target===t.TEXTURE_3D)this._initEmptyTexture3D(s,e);else if(s.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(s,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(s,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}_initEmptyTexture2D(e,t){const s=this._gl;s.texImage2D(s.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let i=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)s.texImage2D(s.TEXTURE_2D,o,e.internalFormat,i,n,0,e.format,e.type,null),i=Math.max(i>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture3D(e,t){const s=this._gl,i=e.target===s.TEXTURE_3D;let n=t.pixelWidth,o=t.pixelHeight,a=t.depthOrArrayLayers;for(let l=0;l<t.mipLevelCount;l++)s.texImage3D(e.target,l,e.internalFormat,n,o,a,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1),i&&(a=Math.max(a>>1,1))}_initEmptyTextureCube(e,t){const s=this._gl,i=6;for(let a=0;a<i;a++)s.texImage2D(s.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<i;l++)s.texImage2D(s.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||t.mipLevelCount<=1)return;const s=this._gl,i=Math.max((t.mipLevelCount|0)-1,0);s.texParameteri(e.target,s.TEXTURE_BASE_LEVEL,0),s.texParameteri(e.target,s.TEXTURE_MAX_LEVEL,i)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,Mo(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!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:s,height:i}=this.getPixels(e),n=J.get().createCanvas();n.width=s,n.height=i;const o=n.getContext("2d");if(o){const a=o.createImageData(s,i);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,i=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(Jy*i*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),h=a.renderTarget.getGpuRenderTarget(l),c=a.gl;return a.renderTarget.adaptor.bindFramebuffer(h.resolveTargetFramebuffer),c.readPixels(Math.round(s.x*t),Math.round(s.y*t),i,n,c.RGBA,c.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:i,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(){const e=this._renderer.limits.maxTextures;this._activeTextureLocation=-1,this._boundTextures.fill(null),this._integerUnits=e>=32?-1:(1<<e)-1,this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}};Ol.extension={type:[S.WebGLSystem],name:"texture"};Ol.uploadExtensions=Object.create(null);let Ul=Ol;q.handleByMap(S.TextureUploaderWebGL,Ul.uploadExtensions);class Nl{contextChange(e){const t=new rt({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new L,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,i=Pi({name:"graphics",bits:[ua,fa(s),Ia,Ri]});this.shader=new dt({glProgram:i,resources:{localUniforms:t,batchSamplers:pa(s)}})}execute(e,t){const s=t.context,i=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);i.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(i),n.geometry.bind(a.geometry,i.glProgram);const h=l.instructions;for(let c=0;c<l.instructionSize;c++){const u=h[c];if(u.size){for(let d=0;d<u.textures.count;d++)n.texture.bind(u.textures.textures[d],d);n.texture.unbindIntegerTextures(u.textures.count),n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Nl.extension={type:[S.WebGLPipesAdaptor],name:"graphics"};class Hl{init(){const e=Pi({name:"mesh",bits:[Ia,Cp,Ri]});this._shader=new dt({glProgram:e,resources:{uTexture:H.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new L}}}})}execute(e,t){const s=e.renderer;let i=t._shader;if(i){if(!i.glProgram){N("Mesh shader has no glProgram",t.shader);return}}else{i=this._shader;const n=t.texture,o=n.source;i.resources.uTexture=o,i.resources.uSampler=o.style,i.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}i.groups[100]=s.globalUniforms.bindGroup,i.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:i,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Hl.extension={type:[S.WebGLPipesAdaptor],name:"mesh"};const ex=[...$i,Al,om,sm,Sl,yl,Ul,Rl,bl,Dl,Gl,Tl,Em,Cl,wl],tx=[...ml],sx=[Xa,Hl,Nl],Nm=[],Hm=[],zm=[],Wm=[];q.handleByNamedList(S.WebGLSystem,Nm);q.handleByNamedList(S.WebGLPipes,Hm);q.handleByNamedList(S.WebGLPipesAdaptor,zm);q.handleByNamedList(S.WebGLLoader,Wm);q.add(...ex,...tx,...sx);class $m extends Is{constructor(){const e={name:"webgl",type:Ke.WEBGL,systems:Nm,renderPipes:Hm,renderPipeAdaptors:zm,loaders:Wm};super(e)}}const rx=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:$m},Symbol.toStringTag,{value:"Module"}));class ix{constructor(e,t){this.autoGarbageCollect=!0,this._gpuData=null,this.gpuBindGroup=e,this._gcLastUsed=t}unload(){this.gpuBindGroup=null}}class zl{constructor(e){this._hash=Object.create(null),this._renderer=e,e.gc.addResourceHash(this,"_hash","resource"),e.gc.addCollection(this,"_hash","hash")}contextChange(e){this._gpu=e,this._hash=Object.create(null)}getBindGroup(e,t,s){const i=`${e._key}:${t._layoutKey<<4|s}`,n=this._hash[i];return n?(n._gcLastUsed=this._renderer.gc.now,n.gpuBindGroup):this._createBindGroup(i,e,t,s)}_createBindGroup(e,t,s,i){const n=this._gpu.device,o=s.layout[i],a=[],l=this._renderer;for(const u in o){const d=t.resources[u]??t.resources[o[u]];if(!d||d.destroyed)throw new Error(`[BindGroup] the resource bound as '${u}' was destroyed while a shader still uses it. Remove it from the shader before destroying it.`);let f;if(d._resourceType==="uniformGroup"){const p=d;l.ubo.updateUniformGroup(p);const m=p.buffer;f={buffer:l.buffer.getGPUBuffer(m),offset:0,size:m.descriptor.size}}else if(d._resourceType==="buffer"){const p=d;f={buffer:l.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(d._resourceType==="bufferResource"){const p=d;f={buffer:l.buffer.getGPUBuffer(p.buffer),offset:p.offset,size:p.size??p.buffer.descriptor.size}}else if(d._resourceType==="textureSampler"){const p=d;f=l.texture.getGpuSampler(p)}else if(d._resourceType==="textureSource"){const p=d;f=l.texture.getTextureView(p)}else if(d._resourceType==="textureView"){const p=d;f=l.texture.getTextureView(p.source,p.viewDescriptor)}a.push({binding:o[u],resource:f})}const h=l.shader.getProgramData(s).bindGroups[i],c=n.createBindGroup({layout:h,entries:a});return this._hash[e]=new ix(c,l.gc.now),c}destroy(){this._hash=null,this._renderer=null}}zl.extension={type:[S.WebGPUSystem],name:"bindGroup"};class Vm{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class Wl{constructor(e){this._renderer=e,this._managedBuffers=new it({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e,this.destroyAll()}getGPUBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuBuffer||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,e._updateOffset,s.buffer,s.byteOffset+e._updateOffset,(e._updateSize||s.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.data&&(oi(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new Vm(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}}Wl.extension={type:[S.WebGPUSystem],name:"buffer"};class Xm{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 s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class $l{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}}$l.extension={type:[S.WebGPUSystem],name:"colorMask"};const nx=new Set(["apple","arm","qualcomm","img-tec"]);class ji{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._options=e,this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>this._setGpu(t)),this._initPromise)}_setGpu(e){this.gpu=e,this.extensions={transientAttachment:typeof GPUTextureUsage.TRANSIENT_ATTACHMENT=="number",tileBased:nx.has(e.adapter?.info?.vendor)},this._options.gpu||e.device.lost.then(()=>this._restoreDevice()).catch(t=>N("WebGPU device was lost and could not be restored",t)),this._renderer.runners.contextChange.emit(this.gpu)}async _restoreDevice(){if(!this._renderer)return;const e=await this._createDeviceAndAdaptor(this._options);if(!this._renderer){e.device.destroy();return}this._setGpu(e)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await J.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter});if(!t)throw new Error("WebGPU not supported. No GPU adapter was returned by navigator.gpu.requestAdapter().");const s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2","indirect-first-instance","bgra8unorm-storage","texture-formats-tier1"].filter(n=>t.features.has(n)),i=await t.requestDevice({requiredFeatures:s,requiredLimits:{maxSampledTexturesPerShaderStage:t.limits.maxSampledTexturesPerShaderStage,maxSamplersPerShaderStage:t.limits.maxSamplersPerShaderStage}});return{adapter:t,device:i}}destroy(){this._options?.gpu||this.gpu?.device.destroy(),this.gpu=null,this.extensions=null,this._renderer=null}}ji.extension={type:[S.WebGPUSystem],name:"device"};ji.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class jm{constructor(e,t,s,i){this.gpuBundle=e,this.stateKey=t,this.device=s,this.label=i}}class Vl{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e;for(let t=0;t<16;t++)this._boundBindGroup[t]={bindGroup:null,program:null,key:null}}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){return this.endRenderPass(),this._clearCache(),this._passEncoder=this.commandEncoder.beginRenderPass(e.descriptor),this.renderPassEncoder=this._passEncoder,this._passEncoder}endRenderPass(){this._passEncoder&&this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null}beginBundle(e){if(this._passEncoder!==this.renderPassEncoder)throw new Error("Cannot begin a new render bundle while one is already being recorded.");this._clearCache();const t=this._renderer.pipeline,s=t.getBundleDescriptor();s.label=e,this._bundleStateKey=t.bundleStateKey,this._bundleLabel=e,this.renderPassEncoder=this._gpu.device.createRenderBundleEncoder(s)}endBundle(){const e=this.renderPassEncoder;if(!e||!("finish"in e))throw new Error("endBundle called without an active render bundle.");const t=e.finish({label:this._bundleLabel});return this.renderPassEncoder=this._passEncoder,this._clearCache(),new jm(t,this._bundleStateKey,this._gpu.device,this._bundleLabel)}isBundleValid(e){return e?.stateKey===this._renderer.pipeline.bundleStateKey&&e.device===this._gpu.device}executeBundle(e){const t=[];if(Array.isArray(e))for(let s=0;s<e.length;s++)t[s]=this._getGpuBundle(e[s]);else t[0]=this._getGpuBundle(e);this._clearCache(),this._passEncoder.executeBundles(t)}_getGpuBundle(e){return this.isBundleValid(e)||N(`Render bundle ${e?.label??"(unlabeled)"} was recorded against a different render target state or on a lost device. Re-record it — replaying it will either be rejected by WebGPU or draw with the wrong winding. Check encoder.isBundleValid(bundle) before executing.`),e.gpuBundle}setViewport(e){this._passEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setStencilReference(e){this._passEncoder.setStencilReference(e)}setPipelineFromGeometryProgramAndState(e,t,s,i,n){const o=this._renderer.pipeline.getPipeline(e,t,s,i,n);this.setPipeline(o)}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){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null}setBindGroup(e,t,s){const i=this._boundBindGroup[e];if(i.bindGroup===t&&i.program===s&&i.key===t._key)return;i.bindGroup=t,i.program=s,i.key=t._key,t._touch(this._renderer.gc.now);const n=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,n)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(let i=0;i<s.length;i++)this._setVertexBuffer(i,e.attributes[s[i]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){const s=e.gpuProgram,i=s.layout;for(let n=0;n<i.length;n++){const o=e.groups[n];!i[n]||!o||(t||this._syncBindGroup(o),this.setBindGroup(n,o,s))}}_syncBindGroup(e){const t=e.resources,s=e._resourceKeys;for(let i=0;i<s.length;i++){const n=t[s[i]];n&&n.isUniformGroup&&this._renderer.ubo.updateUniformGroup(n)}}draw(e){const{geometry:t,shader:s,state:i,topology:n,size:o,start:a,baseVertex:l,instanceCount:h,skipSync:c,firstInstance:u}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,i,n,s._overrides),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexCount||t.indexBuffer.data.length,h??t.instanceCount,a||0,l||0,u||0):this.renderPassEncoder.draw(o||t.vertexCount,h??t.instanceCount,a||0,u||0)}drawIndirect(e){const{geometry:t,shader:s,state:i,topology:n,skipSync:o,indirectBuffer:a,indirectOffset:l}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,i,n,s._overrides),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,o),t.indexBuffer?this.renderPassEncoder.drawIndexedIndirect(a,l):this.renderPassEncoder.drawIndirect(a,l)}finishRenderPass(){this._passEncoder&&(this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}_clearCache(){for(let e=0;e<16;e++){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=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,this.renderPassEncoder=null,this._passEncoder=null}contextChange(e){this._gpu=e}}Vl.extension={type:[S.WebGPUSystem],name:"encoder",priority:1};class Xl{constructor(e){this.supportsOverrideConstants=!1,this._renderer=e}contextChange(){const e=this._renderer.device.gpu.device;this.maxTextures=Math.min(e.limits.maxSampledTexturesPerShaderStage,e.limits.maxSamplersPerShaderStage),this.maxBatchableTextures=this.maxTextures,this._detectOverrideConstantsSupport(e)}_detectOverrideConstantsSupport(e){e.pushErrorScope("validation");const t=e.createShaderModule({code:`override TEST_VALUE: f32 = 0.0;
879
+ @compute @workgroup_size(1) fn main() {}`});e.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main",constants:{TEST_VALUE:1}}}),e.popErrorScope().then(s=>{this.supportsOverrideConstants=!s})}destroy(){}}Xl.extension={type:[S.WebGPUSystem],name:"limits"};class jl{constructor(e){this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(){this._activeGpuRenderTarget=null}onRenderTargetChange(e){const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeRenderTarget=e,this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget));s.stencilMode=e,s.stencilReference=t;const i=this._renderer;i.pipeline.setStencilMode(e),i.encoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}jl.extension={type:[S.WebGPUSystem],name:"stencil"};const or={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 qm(r){const e=r.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const i=e[s];let n=or[i.data.type].size;const o=or[i.data.type].align;if(!or[i.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${i.data.type}`);i.data.size>1&&(n=Math.max(n,o)*i.data.size),t=Math.ceil(t/o)*o,i.size=n,i.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function Ym(r,e){const{size:t,align:s}=or[r.data.type],i=(Math.max(t,s)-t)/4,n=r.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
880
880
  v = uv.${r.data.name};
881
881
  ${e!==0?`offset += ${e};`:""}
882
882
 
@@ -892,7 +892,7 @@ fn mainFragment(
892
892
  }
893
893
  ${i!==0?`arrayOffset += ${i};`:""}
894
894
  }
895
- `}function Km(r){return kl(r,hm,Ym)}class ql extends Ml{constructor(){super({createUboElements:qm,generateUboSync:Km})}}ql.extension={type:[C.WebGPUSystem],name:"ubo"};const At=128;class Yl{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Xm({minUniformOffsetAlignment:At});const t=256/At;for(let s=0;s<t;s++){let i=ce.UNIFORM|ce.COPY_DST;s===0&&(i|=ce.COPY_SRC),this._buffers.push(new Ct({data:this._batchBuffer.data,usage:i}))}}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 s=e.buffer.data,i=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,i/4),this._bindGroupHash[e.uid]=this._getBindGroup(i/At),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/At)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/At)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/At;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Xi({buffer:t,offset:(e/2|0)*256,size:At})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new St({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 s=this._renderer.gpu.device.createCommandEncoder();for(let i=1;i<this._buffers.length;i++){const n=this._buffers[i];s.copyBufferToBuffer(e.getGPUBuffer(t),At,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.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}}Yl.extension={type:[C.WebGPUPipes],name:"uniformBatch"};const Uc={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4},ox=new Es({}),ax={"depth24plus-stencil8":{depth:!0,stencil:!0,index:1},depth24plus:{depth:!0,stencil:!1,index:2},depth32float:{depth:!0,stencil:!1,index:3},"depth32float-stencil8":{depth:!0,stencil:!0,index:4},depth16unorm:{depth:!0,stencil:!1,index:5},stencil8:{depth:!1,stencil:!0,index:6}},Nc={depth:!1,stencil:!1,index:0};function Eo(r,e){for(const[t,s]of Object.entries(e)){const i=new RegExp(`override\\s+${t}\\s*:\\s*(\\w+)\\s*(?:=[^;]*)?;`);r=r.replace(i,(n,o)=>{let a;return o==="u32"?a=`${Math.trunc(s)}u`:o==="i32"?a=`${Math.trunc(s)}`:a=Number.isInteger(s)?`${s}.0`:`${s}`,`const ${t}: ${o} = ${a};`})}return r}function Hc(r,e,t,s,i,n){return r*35184372088832+e*536870912+n*16384+(t<<8)+(s<<3)+i}const zc=Object.create(null);let lx=0;function Wc(r){let e=zc[r];return e===void 0&&(e=zc[r]=lx++),e}function hx(r,e,t,s,i,n,o,a){return a<<20|n<<16|i<<13|t<<9|r<<6|o<<5|s<<1|e}function cx(r,e,t,s,i,n,o){return o<<11|n<<10|i<<9|s<<8|t<<5|e<<1|r}class Kl{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=new Map,this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._colorFormat="bgra8unorm",this._colorFormatId=Wc("bgra8unorm"),this._depthStencilFormat="depth24plus-stencil8",this._depthStencilFormatData=Nc,this._depthReadOnly=!1,this._stencilReadOnly=!1,this._invertFrontFace=!1,this._renderer=e}contextChange(e){this._gpu=e,this._moduleCache=Object.create(null),this._pipeStateCaches=Object.create(null),this.setStencilMode(me.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){const t=e.colorAttachments[0]?.texture;this._multisampleCount=t?.source.antialias?4:1,this._colorTargetCount=e.colorAttachments.length,this._colorFormat=t?.format??"bgra8unorm",this._colorFormatId=Wc(this._colorFormat),this._depthStencilFormat=e.depthStencilAttachment?.texture.format,this._depthStencilFormatData=ax[this._depthStencilFormat]||Nc,this._depthReadOnly=e.depthStencilAttachment?.depthReadOnly??!1,this._stencilReadOnly=e.depthStencilAttachment?.stencilReadOnly??this._depthReadOnly,this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=kt[e],this._updatePipeHash())}get bundleStateKey(){const e=this._depthStencilFormatData;return cx(this._multisampleCount===1?0:1,this._colorTargetCount,e.index,e.depth&&this._depthReadOnly?1:0,e.stencil&&this._stencilReadOnly?1:0,this._invertFrontFace?1:0,this._colorFormatId)}getBundleDescriptor(){const e=[];for(let i=0;i<this._colorTargetCount;i++)e.push(this._colorFormat);const t={colorFormats:e,sampleCount:this._multisampleCount},s=this._depthStencilFormatData;return(s.depth||s.stencil)&&(t.depthStencilFormat=this._depthStencilFormat,s.depth&&this._depthReadOnly&&(t.depthReadOnly=!0),s.stencil&&this._stencilReadOnly&&(t.stencilReadOnly=!0)),t}setPipeline(e,t,s,i){const n=this.getPipeline(e,t,s);i.setPipeline(n)}getPipelineKey(e,t,s,i,n){return e._layoutKey||(ui(e,t.attributeData),this._generateBufferKey(e)),Hc(e._layoutKey,t._layoutKey,s.data,s._blendModeId,Uc[i],n.id)}getPipeline(e,t,s,i,n){e._layoutKey||(ui(e,t.attributeData),this._generateBufferKey(e)),i||(i=e.topology),n||(n=ox);const o=Hc(e._layoutKey,t._layoutKey,s.data,s._blendModeId,Uc[i],n.id);let a=this._pipeCache.get(o);return a||(a=this._createPipeline(e,t,s,i,n),this._pipeCache.set(o,a)),a}_createPipeline(e,t,s,i,n){const o=this._gpu.device,a=this._createVertexBufferLayouts(e,t),l=this._renderer.state.getColorTargets(s,this._colorTargetCount,this._colorFormat),h=this._stencilMode===me.RENDERING_MASK_ADD?0:this._colorMask;for(let _=0;_<l.length;_++)l[_].writeMask=h;const c=this._renderer.shader.getProgramData(t).pipeline,u=Object.keys(n.data).length>0;let d=t.vertex.source,f=t.fragment.source,p;u&&(this._renderer.limits.supportsOverrideConstants?p=n.data:(d=Eo(d,n.data),f=Eo(f,n.data)));const m={vertex:{module:this._getModule(d),entryPoint:t.vertex.entryPoint,constants:p,buffers:a},fragment:{module:this._getModule(f),entryPoint:t.fragment.entryPoint,targets:l,constants:p},primitive:{topology:i,cullMode:s.culling?"back":"none",frontFace:s.clockwiseFrontFace!==this._invertFrontFace?"cw":"ccw"},layout:c,multisample:{count:this._multisampleCount},label:t.name?`PIXI Pipeline (${t.name})`:"PIXI Pipeline"};if(this._depthStencilFormatData.depth||this._depthStencilFormatData.stencil){const _=this._depthStencilFormatData;m.depthStencil={...this._stencilState,format:this._depthStencilFormat,depthWriteEnabled:_.depth?s.depthMask&&!this._depthReadOnly:!1,depthCompare:_.depth&&s.depthTest?"less":"always"}}return o.createRenderPipeline(m)}_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 s=0;const i=Object.keys(e.attributes).sort();for(let o=0;o<i.length;o++){const a=e.attributes[i[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=is(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const i=Object.keys(e.attributeData).sort();for(let o=0;o<i.length;o++){const a=e.attributeData[i[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=is(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const i=this._createVertexBufferLayouts(e,t),n=[],o=t.attributeData;for(let a=0;a<i.length;a++){const h=Object.values(i[a].attributes)[0].shaderLocation;for(const c in o)if(o[c].location===h){n[a]=c;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const i=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const h=e.attributes[l];(h.divisor??1)!==1&&N(`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:t.attributeData[l].location,offset:h.offset,format:h.format}))}a.length&&i.push(o)}),this._bufferLayoutsCache[s]=i,i}_updatePipeHash(){var e;const t=hx(this._stencilMode,this._multisampleCount===1?0:1,this._colorMask,this._colorTargetCount,this._depthStencilFormatData.index,this._colorFormatId,this._depthReadOnly?1:0,this._invertFrontFace?1:0);this._pipeCache=(e=this._pipeStateCaches)[t]??(e[t]=new Map)}destroy(){this._bufferLayoutsCache=null,this._pipeCache=null,this._gpu=null,this._renderer=null,this._bindingNamesCache=null,this._pipeStateCaches=null,this._moduleCache=null}}Kl.extension={type:[C.WebGPUSystem],name:"pipeline"};class Zm{constructor(e){this._pipelines=Object.create(null),this._modules=Object.create(null),this._bindGroups=new WeakMap,this._renderer=e,this._device=e.gpu.device,this._layout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._layout]})}copy(e,t,s,i){var n;const o=this._renderer.renderTarget.getGpuRenderTarget(t),a=t.colorAttachments[s].texture;(n=o.msaaBackTextures)[s]??(n[s]=new de({label:"msaa-back-texture",width:a.width,height:a.height,resolution:a._resolution,format:o.msaaTextures[s].format,autoGenerateMipmaps:!1,autoGarbageCollect:!0}));const l=this._renderer.texture.getGpuSource(o.msaaBackTextures[s]);e.copyTextureToTexture({texture:i},{texture:l},{width:Math.min(i.width,l.width),height:Math.min(i.height,l.height)})}draw(e,t,s){var i;const n=this._renderer.renderTarget.getGpuRenderTarget(t),o=this._renderer.texture.getGpuSource(n.msaaBackTextures[s]);let a=t.depthStencilAttachment?.texture.format??"";for(const c of t.colorAttachments)a+=`|${c.texture.format}`;const l=(i=this._pipelines)[a]??(i[a]=[]);let h=this._bindGroups.get(o);h||(h=this._device.createBindGroup({layout:this._layout,entries:[{binding:0,resource:o.createView()}]}),this._bindGroups.set(o,h)),e.setPipeline(l[s]??(l[s]=this._createPipeline(t,s))),e.setBindGroup(0,h),e.draw(3)}_getModule(e){var t;return(t=this._modules)[e]??(t[e]=this._device.createShaderModule({label:"msaa-restore",code:`
895
+ `}function Km(r){return kl(r,hm,Ym)}class ql extends Ml{constructor(){super({createUboElements:qm,generateUboSync:Km})}}ql.extension={type:[S.WebGPUSystem],name:"ubo"};const At=128;class Yl{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Xm({minUniformOffsetAlignment:At});const t=256/At;for(let s=0;s<t;s++){let i=ce.UNIFORM|ce.COPY_DST;s===0&&(i|=ce.COPY_SRC),this._buffers.push(new Ct({data:this._batchBuffer.data,usage:i}))}}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 s=e.buffer.data,i=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,i/4),this._bindGroupHash[e.uid]=this._getBindGroup(i/At),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/At)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/At)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/At;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Xi({buffer:t,offset:(e/2|0)*256,size:At})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new St({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 s=this._renderer.gpu.device.createCommandEncoder();for(let i=1;i<this._buffers.length;i++){const n=this._buffers[i];s.copyBufferToBuffer(e.getGPUBuffer(t),At,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.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}}Yl.extension={type:[S.WebGPUPipes],name:"uniformBatch"};const Uc={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4},ox=new Es({}),ax={"depth24plus-stencil8":{depth:!0,stencil:!0,index:1},depth24plus:{depth:!0,stencil:!1,index:2},depth32float:{depth:!0,stencil:!1,index:3},"depth32float-stencil8":{depth:!0,stencil:!0,index:4},depth16unorm:{depth:!0,stencil:!1,index:5},stencil8:{depth:!1,stencil:!0,index:6}},Nc={depth:!1,stencil:!1,index:0};function Eo(r,e){for(const[t,s]of Object.entries(e)){const i=new RegExp(`override\\s+${t}\\s*:\\s*(\\w+)\\s*(?:=[^;]*)?;`);r=r.replace(i,(n,o)=>{let a;return o==="u32"?a=`${Math.trunc(s)}u`:o==="i32"?a=`${Math.trunc(s)}`:a=Number.isInteger(s)?`${s}.0`:`${s}`,`const ${t}: ${o} = ${a};`})}return r}function Hc(r,e,t,s,i,n){return r*35184372088832+e*536870912+n*16384+(t<<8)+(s<<3)+i}const zc=Object.create(null);let lx=0;function Wc(r){let e=zc[r];return e===void 0&&(e=zc[r]=lx++),e}function hx(r,e,t,s,i,n,o,a){return a<<20|n<<16|i<<13|t<<9|r<<6|o<<5|s<<1|e}function cx(r,e,t,s,i,n,o){return o<<11|n<<10|i<<9|s<<8|t<<5|e<<1|r}class Kl{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=new Map,this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._colorFormat="bgra8unorm",this._colorFormatId=Wc("bgra8unorm"),this._depthStencilFormat="depth24plus-stencil8",this._depthStencilFormatData=Nc,this._depthReadOnly=!1,this._stencilReadOnly=!1,this._invertFrontFace=!1,this._renderer=e}contextChange(e){this._gpu=e,this._moduleCache=Object.create(null),this._pipeStateCaches=Object.create(null),this.setStencilMode(me.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){const t=e.colorAttachments[0]?.texture;this._multisampleCount=t?.source.antialias?4:1,this._colorTargetCount=e.colorAttachments.length,this._colorFormat=t?.format??"bgra8unorm",this._colorFormatId=Wc(this._colorFormat),this._depthStencilFormat=e.depthStencilAttachment?.texture.format,this._depthStencilFormatData=ax[this._depthStencilFormat]||Nc,this._depthReadOnly=e.depthStencilAttachment?.depthReadOnly??!1,this._stencilReadOnly=e.depthStencilAttachment?.stencilReadOnly??this._depthReadOnly,this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=kt[e],this._updatePipeHash())}get bundleStateKey(){const e=this._depthStencilFormatData;return cx(this._multisampleCount===1?0:1,this._colorTargetCount,e.index,e.depth&&this._depthReadOnly?1:0,e.stencil&&this._stencilReadOnly?1:0,this._invertFrontFace?1:0,this._colorFormatId)}getBundleDescriptor(){const e=[];for(let i=0;i<this._colorTargetCount;i++)e.push(this._colorFormat);const t={colorFormats:e,sampleCount:this._multisampleCount},s=this._depthStencilFormatData;return(s.depth||s.stencil)&&(t.depthStencilFormat=this._depthStencilFormat,s.depth&&this._depthReadOnly&&(t.depthReadOnly=!0),s.stencil&&this._stencilReadOnly&&(t.stencilReadOnly=!0)),t}setPipeline(e,t,s,i){const n=this.getPipeline(e,t,s);i.setPipeline(n)}getPipelineKey(e,t,s,i,n){return e._layoutKey||(ui(e,t.attributeData),this._generateBufferKey(e)),Hc(e._layoutKey,t._layoutKey,s.data,s._blendModeId,Uc[i],n.id)}getPipeline(e,t,s,i,n){e._layoutKey||(ui(e,t.attributeData),this._generateBufferKey(e)),i||(i=e.topology),n||(n=ox);const o=Hc(e._layoutKey,t._layoutKey,s.data,s._blendModeId,Uc[i],n.id);let a=this._pipeCache.get(o);return a||(a=this._createPipeline(e,t,s,i,n),this._pipeCache.set(o,a)),a}_createPipeline(e,t,s,i,n){const o=this._gpu.device,a=this._createVertexBufferLayouts(e,t),l=this._renderer.state.getColorTargets(s,this._colorTargetCount,this._colorFormat),h=this._stencilMode===me.RENDERING_MASK_ADD?0:this._colorMask;for(let _=0;_<l.length;_++)l[_].writeMask=h;const c=this._renderer.shader.getProgramData(t).pipeline,u=Object.keys(n.data).length>0;let d=t.vertex.source,f=t.fragment.source,p;u&&(this._renderer.limits.supportsOverrideConstants?p=n.data:(d=Eo(d,n.data),f=Eo(f,n.data)));const m={vertex:{module:this._getModule(d),entryPoint:t.vertex.entryPoint,constants:p,buffers:a},fragment:{module:this._getModule(f),entryPoint:t.fragment.entryPoint,targets:l,constants:p},primitive:{topology:i,cullMode:s.culling?"back":"none",frontFace:s.clockwiseFrontFace!==this._invertFrontFace?"cw":"ccw"},layout:c,multisample:{count:this._multisampleCount},label:t.name?`PIXI Pipeline (${t.name})`:"PIXI Pipeline"};if(this._depthStencilFormatData.depth||this._depthStencilFormatData.stencil){const _=this._depthStencilFormatData;m.depthStencil={...this._stencilState,format:this._depthStencilFormat,depthWriteEnabled:_.depth?s.depthMask&&!this._depthReadOnly:!1,depthCompare:_.depth&&s.depthTest?"less":"always"}}return o.createRenderPipeline(m)}_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 s=0;const i=Object.keys(e.attributes).sort();for(let o=0;o<i.length;o++){const a=e.attributes[i[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=is(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const i=Object.keys(e.attributeData).sort();for(let o=0;o<i.length;o++){const a=e.attributeData[i[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=is(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const i=this._createVertexBufferLayouts(e,t),n=[],o=t.attributeData;for(let a=0;a<i.length;a++){const h=Object.values(i[a].attributes)[0].shaderLocation;for(const c in o)if(o[c].location===h){n[a]=c;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const i=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const h=e.attributes[l];(h.divisor??1)!==1&&N(`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:t.attributeData[l].location,offset:h.offset,format:h.format}))}a.length&&i.push(o)}),this._bufferLayoutsCache[s]=i,i}_updatePipeHash(){var e;const t=hx(this._stencilMode,this._multisampleCount===1?0:1,this._colorMask,this._colorTargetCount,this._depthStencilFormatData.index,this._colorFormatId,this._depthReadOnly?1:0,this._invertFrontFace?1:0);this._pipeCache=(e=this._pipeStateCaches)[t]??(e[t]=new Map)}destroy(){this._bufferLayoutsCache=null,this._pipeCache=null,this._gpu=null,this._renderer=null,this._bindingNamesCache=null,this._pipeStateCaches=null,this._moduleCache=null}}Kl.extension={type:[S.WebGPUSystem],name:"pipeline"};class Zm{constructor(e){this._pipelines=Object.create(null),this._modules=Object.create(null),this._bindGroups=new WeakMap,this._renderer=e,this._device=e.gpu.device,this._layout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._layout]})}copy(e,t,s,i){var n;const o=this._renderer.renderTarget.getGpuRenderTarget(t),a=t.colorAttachments[s].texture;(n=o.msaaBackTextures)[s]??(n[s]=new de({label:"msaa-back-texture",width:a.width,height:a.height,resolution:a._resolution,format:o.msaaTextures[s].format,autoGenerateMipmaps:!1,autoGarbageCollect:!0}));const l=this._renderer.texture.getGpuSource(o.msaaBackTextures[s]);e.copyTextureToTexture({texture:i},{texture:l},{width:Math.min(i.width,l.width),height:Math.min(i.height,l.height)})}draw(e,t,s){var i;const n=this._renderer.renderTarget.getGpuRenderTarget(t),o=this._renderer.texture.getGpuSource(n.msaaBackTextures[s]);let a=t.depthStencilAttachment?.texture.format??"";for(const c of t.colorAttachments)a+=`|${c.texture.format}`;const l=(i=this._pipelines)[a]??(i[a]=[]);let h=this._bindGroups.get(o);h||(h=this._device.createBindGroup({layout:this._layout,entries:[{binding:0,resource:o.createView()}]}),this._bindGroups.set(o,h)),e.setPipeline(l[s]??(l[s]=this._createPipeline(t,s))),e.setBindGroup(0,h),e.draw(3)}_getModule(e){var t;return(t=this._modules)[e]??(t[e]=this._device.createShaderModule({label:"msaa-restore",code:`
896
896
  @group(0) @binding(0) var resolved: texture_2d<f32>;
897
897
 
898
898
  @vertex
@@ -906,7 +906,7 @@ fn mainFragment(
906
906
  fn fragmentMain(@builtin(position) position: vec4<f32>) -> @location(${e}) vec4<f32> {
907
907
  return textureLoad(resolved, vec2<i32>(position.xy), 0);
908
908
  }
909
- `})),this._modules[e]}_createPipeline(e,t){const s=e.depthStencilAttachment?.texture.format;let i;s&&(i={format:s},s.includes("depth")&&(i.depthWriteEnabled=!1,i.depthCompare="always"));const n=this._getModule(t);return this._device.createRenderPipeline({label:"msaa-restore",layout:this._pipelineLayout,vertex:{module:n,entryPoint:"vertexMain"},fragment:{module:n,entryPoint:"fragmentMain",targets:e.colorAttachments.map((o,a)=>({format:o.texture.format,writeMask:a===t?GPUColorWrite.ALL:0}))},depthStencil:i,multisample:{count:4}})}}class Qm{constructor(){this.contexts=[],this.canvasTextures=[],this.msaaTextures=[],this.transient=!1,this.msaaSamples=1,this.msaaBackTextures=[],this.stencilMode=me.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}const ux={bgra8unorm:!0,rgba8unorm:!0,rgba16float:!0};function dx(r){if(ux[r])return r;const e=navigator.gpu.getPreferredCanvasFormat();return N(`[WebGPU] CanvasSource format '${r}' is not a valid GPUCanvasContext format. Falling back to '${e}'. Allowed formats are: bgra8unorm, rgba8unorm, rgba16float.`),e}class Jm{constructor(){this._activePass=null}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this),e.runners.destroy.add(this)}contextChange(){this._msaaRestore=null}destroy(){this._msaaRestore=null}copyToTexture(e,t,s,i,n){const o=this._renderer;this.finishRenderPass();const a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},i),t}copyDepthTexture(e,t,s,i,n){const o=this._renderer;this.finishRenderPass();const a=e.depthStencilAttachment.texture,l=o.texture.getGpuSource(a),h=o.texture.getGpuSource(t.source),c=o.encoder.commandEncoder===null,u=c?o.gpu.device.createCommandEncoder():o.encoder.commandEncoder;u.copyTextureToTexture({texture:l,origin:s},{texture:h,origin:n},{width:i.width,height:i.height}),c&&o.gpu.device.queue.submit([u.finish()])}startRenderPass(e,t=!0,s,i,n=0,o=0){const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&l.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&l.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");let h=t;typeof h=="boolean"&&(h=h?ye.ALL:ye.NONE),(e.stencil||e.depth)&&!e.depthStencilAttachment&&e.ensureDepthStencilTexture();const c=!!e.depthStencilAttachment,u=this._activePass,d=u!==null&&u.renderTarget===e&&u.mipLevel===n&&u.layer===o&&u.depthStencil===c&&this._renderer.encoder.renderPassEncoder!==null&&h===ye.NONE;if(this._renderer.pipeline.setRenderTarget(e),d){this._renderer.encoder.setViewport(i);return}const{descriptor:f,restore:p}=this._buildDescriptor(e,t,s,n,o);l.descriptor=f;const m=this._renderer.encoder;p?(m.endRenderPass(),this._beginRestoredPass(e,p,m.commandEncoder,()=>m.beginRenderPass(l))):m.beginRenderPass(l),m.setViewport(i),this._activePass={renderTarget:e,mipLevel:n,layer:o,depthStencil:c}}finishRenderPass(){this._renderer.encoder.endRenderPass(),this._activePass=null}_beginRestoredPass(e,t,s,i){const n=this._msaaRestore??(this._msaaRestore=new Zm(this._renderer));for(const a of t)n.copy(s,e,a,this._getGpuColorTexture(e,a));const o=i();for(const a of t)n.draw(o,e,a);return o}_getGpuColorTexture(e,t=0){if(e.colorAttachments.length===0)throw new Error("[GpuRenderTargetAdaptor] cannot get gpu color texture from a depth-only render target");const s=e.colorAttachments[t].texture;return s instanceof Ve&&s._gpuContext?s._gpuContext.getCurrentTexture():this._renderer.texture.getGpuSource(s)}getDescriptor(e,t,s,i=0,n=0){return this._buildDescriptor(e,t,s,i,n).descriptor}_buildDescriptor(e,t,s,i=0,n=0){let o=null;typeof t=="boolean"&&(t=t?ye.ALL:ye.NONE);const a=this._renderTargetSystem,l=a.getGpuRenderTarget(e),h=e.colorAttachments.map((d,f)=>{const p=d.texture,m=p instanceof Ve?p._gpuContext:null;let g,_,x=!1;if(m){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");const k=m.getCurrentTexture();x=l.canvasTextures[f]!==k,l.canvasTextures[f]=k,g=k.createView(d.viewDescriptor)}else g=this._renderer.texture.getTextureRenderTargetView(d.texture,i,n,d.viewDescriptor);const y=l.msaaTextures[f];y&&(_=g,g=this._renderer.texture.getTextureView(y));let b=d.loadOp;t!==void 0&&(b=t&ye.COLOR?"clear":"load"),s??(s=a.defaultClearColor);const w=!!y?.transient,v=w&&b!=="clear",S=v&&!x;v&&(b="clear",S&&(o??(o=[])).push(f));const E={view:g,resolveTarget:_,storeOp:w?"discard":d.storeOp??"store",loadOp:b};p.dimension==="3d"&&(E.depthSlice=n),v?E.clearValue=[0,0,0,0]:b==="clear"&&(s??(s=d.clearValue??a.defaultClearColor),E.clearValue=s);for(const k in d)k!=="texture"&&k!=="viewDescriptor"&&k!=="clearValue"&&k!=="loadOp"&&k!=="storeOp"&&(E[k]=d[k]);return E});let c;if(e.depthStencilAttachment){this._prepareDepthStencil(e,l);const d=e.depthStencilAttachment,f=d.texture.format.includes("stencil"),p=d.texture.format.includes("depth"),m=l.transient?"discard":"store",g=l.transient?"clear":"load";c={view:this._renderer.texture.getTextureRenderTargetView(d.texture,i,n,d.viewDescriptor)};const _=d.depthReadOnly??!1,x=d.stencilReadOnly??_;f&&!x?(c.stencilLoadOp=t&ye.STENCIL?"clear":d.stencilLoadOp??g,c.stencilStoreOp=d.stencilStoreOp??m,c.stencilLoadOp==="clear"&&(c.stencilClearValue=d.stencilClearValue??0)):f&&x&&(c.stencilReadOnly=!0),p&&!_?(c.depthLoadOp=t&ye.DEPTH?"clear":d.depthLoadOp??g,c.depthStoreOp=d.depthStoreOp??m,c.depthLoadOp==="clear"&&(c.depthClearValue=d.depthClearValue??1)):p&&_&&(c.depthReadOnly=!0);for(const y in d)y!=="texture"&&y!=="viewDescriptor"&&y!=="stencilLoadOp"&&y!=="stencilStoreOp"&&y!=="stencilClearValue"&&y!=="stencilReadOnly"&&y!=="depthLoadOp"&&y!=="depthStoreOp"&&y!=="depthClearValue"&&y!=="depthReadOnly"&&(c[y]=d[y])}return{descriptor:{colorAttachments:h,depthStencilAttachment:c,label:e.label},restore:o}}clear(e,t=!0,s,i,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,h=a.device;if(l.commandEncoder===null){const u=h.createCommandEncoder(),{descriptor:d,restore:f}=this._buildDescriptor(e,t,s,n,o),p=()=>u.beginRenderPass(d),m=f?this._beginRestoredPass(e,f,u,p):p();m.setViewport(i.x,i.y,i.width,i.height,0,1),m.end();const g=u.finish();h.queue.submit([g])}else this.startRenderPass(e,t,s,i,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Qm;return t.transient=!!e.colorTexture?.antialias&&!!e.colorTexture.transient,e.colorAttachments.forEach((s,i)=>{const n=s.texture;if(n instanceof Ve){const o=n._gpuContext??(n._gpuContext=n.resource.getContext("webgpu")),a=n.transparent?"premultiplied":"opaque",l=dx(n.format);try{o.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:l,alphaMode:a,...l==="rgba16float"?{toneMapping:{mode:"extended"}}:{}})}catch(h){console.error(h)}t.contexts[i]=o}if(t.msaa=n.source.antialias,n.antialias){const o=new de({width:0,height:0,sampleCount:4,autoGenerateMipmaps:!1,transient:this._renderer.device.extensions.tileBased||t.transient,arrayLayerCount:n.arrayLayerCount,format:n.format});t.msaaTextures[i]=o}}),t.msaa&&(t.msaaSamples=4),t}_prepareDepthStencil(e,t){const s=e.depthStencilAttachment?.texture;!s||!t.msaa||(s.sampleCount=4,s.transient=t.transient)}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaBackTextures.forEach(t=>{t?.destroy()}),e.msaaTextures.length=0,e.msaaBackTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){this._prepareDepthStencil(e,this._renderTargetSystem.getGpuRenderTarget(e))}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorAttachments.forEach((s,i)=>{const n=s.texture;t.msaaTextures[i]?.resize(n.width,n.height,n._resolution),t.msaaBackTextures[i]?.resize(n.width,n.height,n._resolution)})}}class Zl extends Vi{constructor(e){super(e),this.adaptor=new Jm,this.adaptor.init(e,this)}}Zl.extension={type:[C.WebGPUSystem],name:"renderTarget"};class Ql{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e,this._gpuProgramData=Object.create(null)}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),i={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(i)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Ql.extension={type:[C.WebGPUSystem],name:"shader"};const Ge={};Ge.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}};Ge.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};Ge.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};Ge.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}};Ge["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}};Ge["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}};Ge.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}};Ge.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}};Ge.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class Jl{constructor(){this.defaultState=new ft,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t,s){const i=e.blend?Ge[e.blendMode]||Ge.normal:void 0,n=[];for(let o=0;o<t;o++)n[o]={format:s,writeMask:0,blend:i};return n}destroy(){this.gpu=null}}Jl.extension={type:[C.WebGPUSystem],name:"state"};const $c=[new ee,new ee,new ee],eg={type:"image",upload(r,e,t,s=0){const i=r.resource,n=r.pixelWidth|0,o=r.pixelHeight|0,a=r.depthOrArrayLayers,l=i.byteLength/(n*o*a);if(a>1){t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:s}},i,{offset:0,rowsPerImage:o,bytesPerRow:n*l},{width:n,height:o,depthOrArrayLayers:a});return}const h=Fl(r._updateStart,r._updateEnd,n,o,$c);for(let c=0;c<h;c++){const u=$c[c];t.device.queue.writeTexture({texture:e,origin:{x:u.x,y:u.y,z:s}},i,{offset:(u.y*n+u.x)*l,rowsPerImage:u.height,bytesPerRow:n*l},{width:u.width,height:u.height,depthOrArrayLayers:1})}}},eh={"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}},fx={blockBytes:4,blockWidth:1,blockHeight:1},tg={type:"compressed",upload(r,e,t,s=0){let i=r.pixelWidth,n=r.pixelHeight;const o=eh[r.format]||fx;for(let a=0;a<r.resource.length;a++){const l=r.resource[a],h=Math.ceil(i/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:s}},l,{offset:0,bytesPerRow:h},{width:Math.ceil(i/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),i=Math.max(i>>1,1),n=Math.max(n>>1,1)}}},Vc=["right","left","top","bottom","front","back"];function sg(r){return{type:"cube",upload(e,t,s){const i=e.faces;for(let n=0;n<Vc.length;n++){const o=Vc[n],a=i[o];(r[a.uploadMethodId]||r.image).upload(a,t,s,n)}}}}const th={type:"image",upload(r,e,t,s=0){const i=r.resource;if(!i)return;if(globalThis.HTMLImageElement&&i instanceof HTMLImageElement){const l=J.get().createCanvas(i.width,i.height);l.getContext("2d").drawImage(i,0,0,i.width,i.height),r.resource=l,N("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,r.resourceWidth||r.pixelWidth),o=Math.min(e.height,r.resourceHeight||r.pixelHeight),a=r.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:i},{texture:e,origin:{x:0,y:0,z:s},premultipliedAlpha:a},{width:n,height:o})}},rg={type:"video",upload(r,e,t,s){th.upload(r,e,t,s)}},Xc=["rgba8unorm","rgba16float"],gs=4;function sh(r,e){if(!e)throw new Error("[Gpu3dMipmapGenerator] generating mipmaps for a 3D texture needs storage: true.");if(!Xc.includes(r))throw new Error(`[Gpu3dMipmapGenerator] format '${r}' can't be downsampled. Use ${Xc.join(", ")}.`)}class ig{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({magFilter:"linear",minFilter:"linear"})}_getMipmapPipeline(e){var t;return(t=this._pipelines)[e]??(t[e]=this._device.createComputePipeline({layout:"auto",compute:{module:this._device.createShaderModule({code:`
909
+ `})),this._modules[e]}_createPipeline(e,t){const s=e.depthStencilAttachment?.texture.format;let i;s&&(i={format:s},s.includes("depth")&&(i.depthWriteEnabled=!1,i.depthCompare="always"));const n=this._getModule(t);return this._device.createRenderPipeline({label:"msaa-restore",layout:this._pipelineLayout,vertex:{module:n,entryPoint:"vertexMain"},fragment:{module:n,entryPoint:"fragmentMain",targets:e.colorAttachments.map((o,a)=>({format:o.texture.format,writeMask:a===t?GPUColorWrite.ALL:0}))},depthStencil:i,multisample:{count:4}})}}class Qm{constructor(){this.contexts=[],this.canvasTextures=[],this.msaaTextures=[],this.transient=!1,this.msaaSamples=1,this.msaaBackTextures=[],this.stencilMode=me.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}const ux={bgra8unorm:!0,rgba8unorm:!0,rgba16float:!0};function dx(r){if(ux[r])return r;const e=navigator.gpu.getPreferredCanvasFormat();return N(`[WebGPU] CanvasSource format '${r}' is not a valid GPUCanvasContext format. Falling back to '${e}'. Allowed formats are: bgra8unorm, rgba8unorm, rgba16float.`),e}class Jm{constructor(){this._activePass=null}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this),e.runners.destroy.add(this)}contextChange(){this._msaaRestore=null}destroy(){this._msaaRestore=null}copyToTexture(e,t,s,i,n){const o=this._renderer;this.finishRenderPass();const a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},i),t}copyDepthTexture(e,t,s,i,n){const o=this._renderer;this.finishRenderPass();const a=e.depthStencilAttachment.texture,l=o.texture.getGpuSource(a),h=o.texture.getGpuSource(t.source),c=o.encoder.commandEncoder===null,u=c?o.gpu.device.createCommandEncoder():o.encoder.commandEncoder;u.copyTextureToTexture({texture:l,origin:s},{texture:h,origin:n},{width:i.width,height:i.height}),c&&o.gpu.device.queue.submit([u.finish()])}startRenderPass(e,t=!0,s,i,n=0,o=0){const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&l.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&l.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");let h=t;typeof h=="boolean"&&(h=h?ye.ALL:ye.NONE),(e.stencil||e.depth)&&!e.depthStencilAttachment&&e.ensureDepthStencilTexture();const c=!!e.depthStencilAttachment,u=this._activePass,d=u!==null&&u.renderTarget===e&&u.mipLevel===n&&u.layer===o&&u.depthStencil===c&&this._renderer.encoder.renderPassEncoder!==null&&h===ye.NONE;if(this._renderer.pipeline.setRenderTarget(e),d){this._renderer.encoder.setViewport(i);return}const{descriptor:f,restore:p}=this._buildDescriptor(e,t,s,n,o);l.descriptor=f;const m=this._renderer.encoder;p?(m.endRenderPass(),this._beginRestoredPass(e,p,m.commandEncoder,()=>m.beginRenderPass(l))):m.beginRenderPass(l),m.setViewport(i),this._activePass={renderTarget:e,mipLevel:n,layer:o,depthStencil:c}}finishRenderPass(){this._renderer.encoder.endRenderPass(),this._activePass=null}_beginRestoredPass(e,t,s,i){const n=this._msaaRestore??(this._msaaRestore=new Zm(this._renderer));for(const a of t)n.copy(s,e,a,this._getGpuColorTexture(e,a));const o=i();for(const a of t)n.draw(o,e,a);return o}_getGpuColorTexture(e,t=0){if(e.colorAttachments.length===0)throw new Error("[GpuRenderTargetAdaptor] cannot get gpu color texture from a depth-only render target");const s=e.colorAttachments[t].texture;return s instanceof Ve&&s._gpuContext?s._gpuContext.getCurrentTexture():this._renderer.texture.getGpuSource(s)}getDescriptor(e,t,s,i=0,n=0){return this._buildDescriptor(e,t,s,i,n).descriptor}_buildDescriptor(e,t,s,i=0,n=0){let o=null;typeof t=="boolean"&&(t=t?ye.ALL:ye.NONE);const a=this._renderTargetSystem,l=a.getGpuRenderTarget(e),h=e.colorAttachments.map((d,f)=>{const p=d.texture,m=p instanceof Ve?p._gpuContext:null;let g,_,x=!1;if(m){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");const P=m.getCurrentTexture();x=l.canvasTextures[f]!==P,l.canvasTextures[f]=P,g=P.createView(d.viewDescriptor)}else g=this._renderer.texture.getTextureRenderTargetView(d.texture,i,n,d.viewDescriptor);const y=l.msaaTextures[f];y&&(_=g,g=this._renderer.texture.getTextureView(y));let b=d.loadOp;t!==void 0&&(b=t&ye.COLOR?"clear":"load"),s??(s=a.defaultClearColor);const w=!!y?.transient,v=w&&b!=="clear",T=v&&!x;v&&(b="clear",T&&(o??(o=[])).push(f));const k={view:g,resolveTarget:_,storeOp:w?"discard":d.storeOp??"store",loadOp:b};p.dimension==="3d"&&(k.depthSlice=n),v?k.clearValue=[0,0,0,0]:b==="clear"&&(s??(s=d.clearValue??a.defaultClearColor),k.clearValue=s);for(const P in d)P!=="texture"&&P!=="viewDescriptor"&&P!=="clearValue"&&P!=="loadOp"&&P!=="storeOp"&&(k[P]=d[P]);return k});let c;if(e.depthStencilAttachment){this._prepareDepthStencil(e,l);const d=e.depthStencilAttachment,f=d.texture.format.includes("stencil"),p=d.texture.format.includes("depth"),m=l.transient?"discard":"store",g=l.transient?"clear":"load";c={view:this._renderer.texture.getTextureRenderTargetView(d.texture,i,n,d.viewDescriptor)};const _=d.depthReadOnly??!1,x=d.stencilReadOnly??_;f&&!x?(c.stencilLoadOp=t&ye.STENCIL?"clear":d.stencilLoadOp??g,c.stencilStoreOp=d.stencilStoreOp??m,c.stencilLoadOp==="clear"&&(c.stencilClearValue=d.stencilClearValue??0)):f&&x&&(c.stencilReadOnly=!0),p&&!_?(c.depthLoadOp=t&ye.DEPTH?"clear":d.depthLoadOp??g,c.depthStoreOp=d.depthStoreOp??m,c.depthLoadOp==="clear"&&(c.depthClearValue=d.depthClearValue??1)):p&&_&&(c.depthReadOnly=!0);for(const y in d)y!=="texture"&&y!=="viewDescriptor"&&y!=="stencilLoadOp"&&y!=="stencilStoreOp"&&y!=="stencilClearValue"&&y!=="stencilReadOnly"&&y!=="depthLoadOp"&&y!=="depthStoreOp"&&y!=="depthClearValue"&&y!=="depthReadOnly"&&(c[y]=d[y])}return{descriptor:{colorAttachments:h,depthStencilAttachment:c,label:e.label},restore:o}}clear(e,t=!0,s,i,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,h=a.device;if(l.commandEncoder===null){const u=h.createCommandEncoder(),{descriptor:d,restore:f}=this._buildDescriptor(e,t,s,n,o),p=()=>u.beginRenderPass(d),m=f?this._beginRestoredPass(e,f,u,p):p();m.setViewport(i.x,i.y,i.width,i.height,0,1),m.end();const g=u.finish();h.queue.submit([g])}else this.startRenderPass(e,t,s,i,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Qm;return t.transient=!!e.colorTexture?.antialias&&!!e.colorTexture.transient,e.colorAttachments.forEach((s,i)=>{const n=s.texture;if(n instanceof Ve){const o=n._gpuContext??(n._gpuContext=n.resource.getContext("webgpu")),a=n.transparent?"premultiplied":"opaque",l=dx(n.format);try{o.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:l,alphaMode:a,...l==="rgba16float"?{toneMapping:{mode:"extended"}}:{}})}catch(h){console.error(h)}t.contexts[i]=o}if(t.msaa=n.source.antialias,n.antialias){const o=new de({width:0,height:0,sampleCount:4,autoGenerateMipmaps:!1,transient:this._renderer.device.extensions.tileBased||t.transient,arrayLayerCount:n.arrayLayerCount,format:n.format});t.msaaTextures[i]=o}}),t.msaa&&(t.msaaSamples=4),t}_prepareDepthStencil(e,t){const s=e.depthStencilAttachment?.texture;!s||!t.msaa||(s.sampleCount=4,s.transient=t.transient)}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaBackTextures.forEach(t=>{t?.destroy()}),e.msaaTextures.length=0,e.msaaBackTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){this._prepareDepthStencil(e,this._renderTargetSystem.getGpuRenderTarget(e))}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorAttachments.forEach((s,i)=>{const n=s.texture;t.msaaTextures[i]?.resize(n.width,n.height,n._resolution),t.msaaBackTextures[i]?.resize(n.width,n.height,n._resolution)})}}class Zl extends Vi{constructor(e){super(e),this.adaptor=new Jm,this.adaptor.init(e,this)}}Zl.extension={type:[S.WebGPUSystem],name:"renderTarget"};class Ql{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e,this._gpuProgramData=Object.create(null)}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),i={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(i)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Ql.extension={type:[S.WebGPUSystem],name:"shader"};const Ge={};Ge.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}};Ge.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};Ge.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};Ge.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}};Ge["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}};Ge["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}};Ge["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}};Ge.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}};Ge.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}};Ge.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class Jl{constructor(){this.defaultState=new ft,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t,s){const i=e.blend?Ge[e.blendMode]||Ge.normal:void 0,n=[];for(let o=0;o<t;o++)n[o]={format:s,writeMask:0,blend:i};return n}destroy(){this.gpu=null}}Jl.extension={type:[S.WebGPUSystem],name:"state"};const $c=[new ee,new ee,new ee],eg={type:"image",upload(r,e,t,s=0){const i=r.resource,n=r.pixelWidth|0,o=r.pixelHeight|0,a=r.depthOrArrayLayers,l=i.byteLength/(n*o*a);if(a>1){t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:s}},i,{offset:0,rowsPerImage:o,bytesPerRow:n*l},{width:n,height:o,depthOrArrayLayers:a});return}const h=Fl(r._updateStart,r._updateEnd,n,o,$c);for(let c=0;c<h;c++){const u=$c[c];t.device.queue.writeTexture({texture:e,origin:{x:u.x,y:u.y,z:s}},i,{offset:(u.y*n+u.x)*l,rowsPerImage:u.height,bytesPerRow:n*l},{width:u.width,height:u.height,depthOrArrayLayers:1})}}},eh={"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}},fx={blockBytes:4,blockWidth:1,blockHeight:1},tg={type:"compressed",upload(r,e,t,s=0){let i=r.pixelWidth,n=r.pixelHeight;const o=eh[r.format]||fx;for(let a=0;a<r.resource.length;a++){const l=r.resource[a],h=Math.ceil(i/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:s}},l,{offset:0,bytesPerRow:h},{width:Math.ceil(i/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),i=Math.max(i>>1,1),n=Math.max(n>>1,1)}}},Vc=["right","left","top","bottom","front","back"];function sg(r){return{type:"cube",upload(e,t,s){const i=e.faces;for(let n=0;n<Vc.length;n++){const o=Vc[n],a=i[o];(r[a.uploadMethodId]||r.image).upload(a,t,s,n)}}}}const th={type:"image",upload(r,e,t,s=0){const i=r.resource;if(!i)return;if(globalThis.HTMLImageElement&&i instanceof HTMLImageElement){const l=J.get().createCanvas(i.width,i.height);l.getContext("2d").drawImage(i,0,0,i.width,i.height),r.resource=l,N("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,r.resourceWidth||r.pixelWidth),o=Math.min(e.height,r.resourceHeight||r.pixelHeight),a=r.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:i},{texture:e,origin:{x:0,y:0,z:s},premultipliedAlpha:a},{width:n,height:o})}},rg={type:"video",upload(r,e,t,s){th.upload(r,e,t,s)}},Xc=["rgba8unorm","rgba16float"],gs=4;function sh(r,e){if(!e)throw new Error("[Gpu3dMipmapGenerator] generating mipmaps for a 3D texture needs storage: true.");if(!Xc.includes(r))throw new Error(`[Gpu3dMipmapGenerator] format '${r}' can't be downsampled. Use ${Xc.join(", ")}.`)}class ig{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({magFilter:"linear",minFilter:"linear"})}_getMipmapPipeline(e){var t;return(t=this._pipelines)[e]??(t[e]=this._device.createComputePipeline({layout:"auto",compute:{module:this._device.createShaderModule({code:`
910
910
  @group(0) @binding(0) var srcSampler : sampler;
911
911
  @group(0) @binding(1) var src : texture_3d<f32>;
912
912
  @group(0) @binding(2) var dst : texture_storage_3d<${e}, write>;
@@ -949,8 +949,8 @@ fn mainFragment(
949
949
  fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
950
950
  return textureSample(img, imgSampler, texCoord);
951
951
  }
952
- `})),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){if(e.dimension==="3d")throw new Error("[GpuMipmapGenerator] a 3D texture uses Gpu3dMipmapGenerator.");if(e.dimension==="1d")throw new Error("Generating mipmaps for 1d textures is currently unsupported!");const t=this._getMipmapPipeline(e.format);let s=e;const i=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:i},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};s=this._device.createTexture(l)}const o=this._device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<i;++l){let h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),c=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const d=s.createView({baseMipLevel:c++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:d,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),p=this._device.createBindGroup({layout:a,entries:[{binding:0,resource:this._sampler},{binding:1,resource:h}]});f.setPipeline(t),f.setBindGroup(0,p),f.draw(3,1,0,0),f.end(),h=d}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:i};for(let h=1;h<e.mipLevelCount;++h)o.copyTextureToTexture({texture:s,mipLevel:h-1},{texture:e,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||s.destroy(),e}}class og{constructor(e){this.textureView=null,this.textureViews=Object.create(null),this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.textureViews=null,this.gpuTexture=null}}const px=/^(rgba8|bgra8|bc[1237]-rgba-|etc2-rgb8|etc2-rgb8a1|etc2-rgba8|astc-\d+x\d+-)unorm$/;function mx(r){return px.test(r)?[`${r}-srgb`]:void 0}function jc(r){return`${r.format||""}.${r.dimension||""}.${r.aspect||""}.${r.baseMipLevel||0}.${r.mipLevelCount||""}.${r.baseArrayLayer||0}.${r.arrayLayerCount||""}`}const rh=class ag{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new it({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:th,buffer:eg,video:rg,compressed:tg,...ag.uploadExtensions};this._uploads={...t,cube:sg(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e,this._managedTextures.removeAll(),this._gpuSamplers=Object.create(null),this._mipmapGenerator=null,this._mipmap3dGenerator=null}initSource(e){return e._gpuData[this._renderer.uid]?.gpuTexture||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){e.dimension==="3d"&&sh(e.format,e.storage);const c=Math.max(e.pixelWidth,e.pixelHeight,e.depth);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t,s;e.sampleCount>1?(t=GPUTextureUsage.RENDER_ATTACHMENT,e.transient&&this._renderer.device.extensions.transientAttachment&&(t|=GPUTextureUsage.TRANSIENT_ATTACHMENT)):(t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC),e.storage&&(t|=GPUTextureUsage.STORAGE_BINDING),s=mx(e.format));const i=eh[e.format]||{blockWidth:1,blockHeight:1},n=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,o=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,a={label:e.label,size:{width:n,height:o,depthOrArrayLayers:e.depthOrArrayLayers},format:e.format,viewFormats:s,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},l=this._gpu.device.createTexture(a);return e._gpuData[this._renderer.uid]=new og(l),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),l}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){const t=this.getGpuSource(e);if(e.dimension==="3d"){this._mipmap3dGenerator??(this._mipmap3dGenerator=new ig(this._gpu.device)),this._mipmap3dGenerator.generateMipmap(t);return}this._mipmapGenerator??(this._mipmapGenerator=new ng(this._gpu.device)),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],s=t?.gpuTexture;s?(s.width!==e.pixelWidth||s.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){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.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 St({0:t,1:t.style,2:new rt({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e,t){var s;const i=e.source;i._gcLastUsed=this._renderer.gc.now;let n=i._gpuData[this._renderer.uid];n||(this.initSource(i),n=i._gpuData[this._renderer.uid]);const o=t?jc(t):0;return(s=n.textureViews)[o]||(s[o]=n.gpuTexture.createView({dimension:i.viewDimension,...t})),n.textureViews[o]}getTextureRenderTargetView(e,t=0,s=0,i){var n;const o=e.source;o._gcLastUsed=this._renderer.gc.now;let a=o._gpuData[this._renderer.uid];a||(this.initSource(o),a=o._gpuData[this._renderer.uid]);const l=o.dimension==="3d";l&&(s=0);let h=s*(o.mipLevelCount||1)+t+1;return i&&(h=`${h}.${jc(i)}`),(n=a.textureViews)[h]||(n[h]=a.gpuTexture.createView({dimension:l?"3d":"2d",baseMipLevel:t,mipLevelCount:1,baseArrayLayer:s,arrayLayerCount:1,...i})),a.textureViews[h]}generateCanvas(e){const t=this._renderer,s=t.gpu.device.createCommandEncoder(),i=J.get().createCanvas();i.width=e.source.pixelWidth,i.height=e.source.pixelHeight;const n=i.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:J.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),s.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:i.width,height:i.height}),t.gpu.device.queue.submit([s.finish()]),i}getPixels(e){const t=this.generateCanvas(e),s=Mt.getOptimalCanvasAndContext(t.width,t.height),i=s.context;i.drawImage(t,0,0);const{width:n,height:o}=t,a=i.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return Mt.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e);this._bindGroupHash[t]?.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._mipmap3dGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}};rh.extension={type:[C.WebGPUSystem],name:"texture"};rh.uploadExtensions=Object.create(null);let ih=rh;q.handleByMap(C.TextureUploaderWebGPU,ih.uploadExtensions);class nh{constructor(){this._maxTextures=0}contextChange(e){const t=new rt({uTransformMatrix:{value:new L,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 s=ki({name:"graphics",bits:[ca,da(this._maxTextures),Qf,Ai]});this.shader=new dt({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,i=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),h=n.encoder;h.setGeometry(a.geometry,i.gpuProgram);const c=n.globalUniforms.bindGroup;h.setBindGroup(0,c,i.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(i.resources.localUniforms,!0);h.setBindGroup(2,u,i.gpuProgram);const d=l.instructions;let f=null;for(let p=0;p<l.instructionSize;p++){const m=d[p];if(m.topology!==f&&(f=m.topology,h.setPipelineFromGeometryProgramAndState(a.geometry,i.gpuProgram,e.state,m.topology,i._overrides)),i.groups[1]=m.bindGroup,!m.gpuBindGroup){const g=m.textures;m.bindGroup=Mi(g.textures,g.count,this._maxTextures),m.gpuBindGroup=n.bindGroup.getBindGroup(m.bindGroup,i.gpuProgram,1)}h.setBindGroup(1,m.bindGroup,i.gpuProgram),h.renderPassEncoder.drawIndexed(m.size,1,m.start)}}destroy(){this.shader.destroy(),this.shader=null}}nh.extension={type:[C.WebGPUPipesAdaptor],name:"graphics"};class oh{init(){const e=ki({name:"mesh",bits:[sr,Sp,Ai]});this._shader=new dt({gpuProgram:e,resources:{uTexture:H.EMPTY._source,uSampler:H.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new L}}}})}execute(e,t){const s=e.renderer;let i=t._shader;if(!i)i=this._shader,i.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!i.gpuProgram){N("Mesh shader has no gpuProgram",t.shader);return}const n=i.gpuProgram;if(n.autoAssignGlobalUniforms&&(i.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;i.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:i,state:t.state})}destroy(){this._shader.destroy(),this._shader=null}}oh.extension={type:[C.WebGPUPipesAdaptor],name:"mesh"};const gx=[...$i,ql,Vl,ji,Xl,Wl,ih,Zl,Ql,Jl,Kl,$l,jl,zl],_x=[...ml,Yl],yx=[ja,oh,nh],lg=[],hg=[],cg=[],ug=[];q.handleByNamedList(C.WebGPUSystem,lg);q.handleByNamedList(C.WebGPUPipes,hg);q.handleByNamedList(C.WebGPUPipesAdaptor,cg);q.handleByNamedList(C.WebGPULoader,ug);q.add(...gx,..._x,...yx);class dg extends Is{constructor(){const e={name:"webgpu",type:Ke.WEBGPU,systems:lg,renderPipes:hg,renderPipeAdaptors:cg,loaders:ug};super(e)}}const xx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:dg},Symbol.toStringTag,{value:"Module"}));q.add(du,fu);const bx=Object.freeze(Object.defineProperty({__proto__:null,AbstractRenderer:Is,AbstractText:Jf,AbstractTextSystem:za,AccessibilitySystem:T_,AlphaMask:Wo,AlphaMaskPipe:Oi,Application:oa,ApplicationInitHook:sa,BLEND_TO_NPM:zd,BREAKING_SPACES:np,BREAKING_SPACES_SET:op,BREAK_AFTER_CHARS:lp,BREAK_AFTER_CHARS_SET:hp,BUFFER_TYPE:nr,BackgroundSystem:Rp,Batch:Vd,BatchGeometry:Kd,BatchTextureArray:$d,BatchableGraphics:Ii,BatchableSprite:Fi,BatchableText:xp,Batcher:qd,BatcherPipe:Li,BigPool:Se,BindGroup:St,BindGroupSystem:zl,BlendModePipe:zi,Bounds:ke,BrowserAdapter:ju,Buffer:Ct,BufferImageSource:mi,BufferResource:Xi,BufferUsage:ce,CLEAR:ye,COLLAPSIBLE_SPACES:ap,Cache:qt,CanvasBatchAdaptor:wp,CanvasColorMaskPipe:Ya,CanvasContextSystem:Ja,CanvasFilterSystem:Hf,CanvasGraphicsAdaptor:tl,CanvasGraphicsContextSystem:Kf,CanvasGraphicsPipe:Aa,CanvasLimitsSystem:el,CanvasObserver:qo,CanvasPool:Mt,CanvasPoolClass:Nf,CanvasRenderTargetAdaptor:qp,CanvasRenderTargetSystem:gl,CanvasRenderer:Jp,CanvasRendererTextSystem:Wa,CanvasSource:Ve,CanvasStencilMaskPipe:Za,CanvasTextGenerator:Yt,CanvasTextMetrics:yt,CanvasTextPipe:Ha,CanvasTextSystem:$a,CanvasTextureSystem:_l,Circle:Ti,Color:oe,ColorMask:$o,ColorMaskPipe:Ka,Container:_e,CustomRenderPipe:Ui,DEG_TO_RAD:gu,DOMAdapter:J,DOMPipe:Lf,DefaultBatcher:Bi,DefaultShader:lo,Ellipse:Si,EventBoundary:Of,EventEmitter:Re,EventSystem:Uf,EventsTicker:ht,ExtensionType:C,ExtractSystem:Ip,FederatedContainer:J0,FederatedEvent:Bs,FederatedMouseEvent:yr,FederatedPointerEvent:Fe,FederatedWheelEvent:os,FillGradient:Xe,FillPattern:Gs,Filter:Jo,FilterEffect:lr,FilterPipe:Vf,FilterSystem:Xf,GCManagedHash:it,GCSystem:Lp,GL_FORMATS:di,GL_TARGETS:As,GL_TYPES:re,GPUTextureGpuData:og,GenerateTextureSystem:al,Geometry:Ei,GlBackBufferSystem:om,GlBatchAdaptor:Xa,GlBuffer:em,GlBufferSystem:yl,GlColorMaskSystem:wl,GlContextSystem:sm,GlEncoderSystem:Tl,GlGeometryGpuData:im,GlGeometrySystem:bl,GlGraphicsAdaptor:Nl,GlLimitsSystem:Sl,GlMeshAdaptor:Hl,GlProgram:ls,GlProgramData:mm,GlRenderTarget:am,GlRenderTargetAdaptor:dm,GlRenderTargetSystem:Rl,GlShaderSystem:Gl,GlStateSystem:Em,GlStencilSystem:Cl,GlTexture:km,GlTextureSystem:Ul,GlUboSystem:Al,GlUniformGroupSystem:Dl,GlobalResourceRegistry:as,GlobalUniformSystem:hl,Gpu3dMipmapGenerator:ig,GpuBatchAdaptor:ja,GpuBlendModesToPixi:Ge,GpuBufferData:Vm,GpuBufferSystem:Wl,GpuColorMaskSystem:$l,GpuDeviceSystem:ji,GpuEncoderSystem:Vl,GpuGraphicsAdaptor:nh,GpuGraphicsContext:bf,GpuLimitsSystem:Xl,GpuMeshAdapter:oh,GpuMipmapGenerator:ng,GpuMsaaRestore:Zm,GpuProgram:Ft,GpuRenderTarget:Qm,GpuRenderTargetAdaptor:Jm,GpuRenderTargetSystem:Zl,GpuShaderSystem:Ql,GpuStateSystem:Jl,GpuStencilModesToPixi:kt,GpuStencilSystem:jl,GpuTextureSystem:ih,GpuUboSystem:ql,GpuUniformBatchPipe:Yl,Graphics:Pe,GraphicsContext:qe,GraphicsContextRenderData:vf,GraphicsContextSystem:Di,GraphicsGpuData:Zf,GraphicsPath:ut,GraphicsPipe:Ba,HelloSystem:Wi,ImageSource:ur,InstructionSet:xi,LoaderParserPriority:Xo,MaskEffectManager:si,MaskEffectManagerClass:Iu,MaskFilter:Yf,Matrix:L,NEWLINES:rp,NEWLINES_SET:ip,NEWLINE_MATCH_REGEX:up,NEWLINE_SPLIT_REGEX:cp,NOOP:Go,ObservablePoint:Ce,PI_2:pu,PassthroughFilter:$f,PipelineSystem:Kl,Point:he,Polygon:Ts,Pool:ku,PoolGroupClass:Pu,RAD_TO_DEG:mu,Rectangle:ee,RenderBundle:jm,RenderGroup:ri,RenderGroupPipe:Ni,RenderGroupSystem:il,RenderTarget:ir,RenderTargetSystem:Vi,RenderTexture:wr,RenderableGCSystem:Np,RendererInitHook:ra,RendererType:Ke,ResizePlugin:ia,Resolver:jo,RoundedRectangle:Ci,STATE_BITS:Qo,STENCIL_MODES:me,SVGParser:Gf,SchedulerSystem:cl,ScreenSizeRegistry:No,Shader:dt,ShaderOverrides:Es,ShaderStage:fe,ShapePath:Ef,SharedRenderPipes:ml,SharedSystems:$i,Sprite:ss,SpritePipe:Hi,Spritesheet:Wn,State:ft,StencilMask:Vo,StencilMaskPipe:Qa,SystemRunner:ta,Text:bp,TextStyle:Ps,Texture:H,TextureGCSystem:Hp,TextureMatrix:Fo,TexturePool:Te,TexturePoolClass:$u,TextureSource:de,TextureStyle:Dt,TextureView:fm,Ticker:We,TickerListener:Xr,TickerPlugin:na,UNIFORM_TO_ARRAY_SETTERS:Tm,UNIFORM_TO_SINGLE_SETTERS:wm,UNIFORM_TYPES_MAP:bd,UNIFORM_TYPES_VALUES:Zo,UPDATE_BLEND:bi,UPDATE_COLOR:cr,UPDATE_PRIORITY:rs,UPDATE_VISIBLE:ws,UboBatch:Xm,UboSystem:Ml,UniformGroup:rt,VERSION:gr,VideoSource:Zu,ViewContainer:vi,ViewSystem:Vp,ViewableBuffer:so,WGSL_ALIGN_SIZE_DATA:or,WGSL_TO_STD40_SIZE:El,WebGLRenderer:$m,WebGPURenderer:dg,accessibilityTarget:S_,addBits:io,addMaskBounds:Ho,addMaskLocalBounds:zo,addProgramDefines:cd,appendSVGPath:_o,applyStyleParams:Mo,assertMipmap3dTexture:sh,assignWithIgnore:Vu,autoDetectRenderer:Ld,bakeOverridesIntoSource:Eo,bgr2rgb:Zt,blockDataMap:eh,boundsPool:ct,browserExt:du,buildAdaptiveBezier:va,buildAdaptiveQuadratic:wf,buildArc:wa,buildArcTo:Tf,buildArcToSvg:Sf,buildCircle:ks,buildContextBatches:xf,buildEllipse:ff,buildLine:Gi,buildPixelLine:mf,buildPolygon:gf,buildRectangle:_f,buildRoundedRectangle:pf,buildSimpleUvs:df,buildTriangle:yf,buildUvs:uf,cacheAsTextureMixin:Au,calculatePathArea:If,calculateProjection:Xp,canUseNewCanvasBlendModes:Ma,canvasUtils:Y,checkChildrenDidChange:Uo,checkForNestedPattern:Rf,checkMaxIfStatementsInShader:la,childrenHelperMixin:Ru,cleanArray:Dp,cleanHash:Gp,clearList:ci,closePointEps:ga,collapseNewlines:La,collapseSpaces:Fa,collectRenderablesMixin:Bu,color32BitToUniform:Ra,colorBit:ca,colorBitGl:ua,compareModeToGlCompare:Gm,compileBufferSync:kl,compileHighShader:Qd,compileHighShaderGl:Jd,compileHighShaderGlProgram:Pi,compileHighShaderGpuProgram:ki,compileHooks:no,compileInputs:oo,compileOutputs:Zd,compileShader:To,convertToList:jt,copySearchParams:zn,createGlUploadCubeTextureResource:Rm,createGpuUploadCubeTextureResource:sg,createIdFromString:is,createStringVariations:sd,createUboElementsSTD40:lm,createUboElementsWGSL:qm,createUboSyncFunctionSTD40:um,createUboSyncFunctionWGSL:Km,cullingMixin:Eu,curveEps:ho,defaultFilterVert:zf,defaultValue:Bl,definedProps:Do,deprecation:O,detectVideoAlphaMode:Yu,earcut:Bd,effectsMixin:Gu,ensureAttributes:ui,ensureIsBuffer:ha,ensurePrecision:ud,ensureTextOptions:ep,executeInstructions:hi,extensions:q,extractAttributesFromGlProgram:_m,extractAttributesFromGpuProgram:gd,extractStructAndGroups:jr,extractSubpaths:Bf,extractSvgUrlId:mo,fastCopy:oi,findMixin:Du,fontStringFromTextStyle:li,fragmentGPUTemplate:rf,fragmentGlTemplate:of,generateArraySyncSTD40:cm,generateArraySyncWGSL:Ym,generateGpuLayoutGroups:_d,generateLayoutHash:yd,generateProgram:vm,generateShaderSyncCode:pm,generateTextureBatchBit:da,generateTextureBatchBitGl:fa,generateTextureMatrix:xa,generateUniformsSync:Sm,getAdjustedBlendModeBlend:ro,getAttributeInfoFromFormat:Ms,getBatchSamplersUniformGroup:pa,getCanvasBoundingBox:tp,getCanvasFillStyle:Qs,getCanvasTexture:fl,getCharacterGroups:Ua,getDefaultUniformValue:vd,getFastGlobalBoundsMixin:Fu,getGeometryBounds:Yd,getGlTypeFromFormat:rm,getGlobalBounds:gi,getGlobalMixin:Ou,getGlobalRenderableBounds:Ea,getLocalBounds:yi,getMaxFragmentPrecision:hd,getMaxMiterRatio:Ff,getMaxTexturesPerBatch:Wd,getOrientationOfPoints:aa,getPo2TextureFromSource:ka,getTestContext:Ko,getTexelRangeRects:Fl,getTextureBatchBindGroup:Mi,getUboData:ym,getUniformData:xm,getUrlExtension:rd,glUploadBufferImageResource:Pm,glUploadCompressedTextureResource:Am,glUploadImageResource:Ll,glUploadVideoResource:Bm,globalUniformsBit:af,globalUniformsBitGl:lf,gpuUploadBufferImageResource:eg,gpuUploadCompressedTextureResource:tg,gpuUploadImageResource:th,gpuUploadVideoResource:rg,groupD8:Z,hasTagMarkup:Da,hasTagStyles:Ga,injectBits:ao,insertVersion:dd,isBreakAfterChar:dp,isBreakingSpace:$e,isCanvasFilterCapable:xo,isIntegerFormat:ti,isMobile:ad,isNewline:xr,isPow2:ts,isRenderingToScreen:jp,isSafari:vp,isSingleItem:Hn,isWebGLSupported:Dd,isWebGPUSupported:Fd,loadEnvironmentExtensions:Md,localUniformBit:sr,localUniformBitGl:Ia,localUniformBitGroup2:Qf,logProgramError:bm,mapCanvasBlendModesToPixi:Ep,mapFormatToGlFormat:Dm,mapFormatToGlInternalFormat:Fm,mapFormatToGlType:Lm,mapGlToVertexFormat:gm,mapType:Il,mapViewDimensionToGlTarget:Om,mapWebGLBlendModesToPixi:Cm,maskFrag:jf,maskVert:qf,maskWgsl:vo,matrixPool:Ae,measureMixin:Nu,measureTaggedText:fp,mipmapScaleModeToGlFilter:Im,multiplyColors:hr,multiplyHexColors:Kt,nextPow2:es,normalizeExtensionPriority:Ys,onRenderMixin:Hu,parseSVGDefinitions:kf,parseSVGFloatAttribute:ve,parseSVGPath:Ud,parseSVGStyle:Ta,parseTaggedText:sp,passthroughFrag:Wf,passthroughWgsl:bo,path:Cs,removeItems:Oo,removeStructAndGroupDuplicates:xd,resourceToTexture:Ju,roundPixelsBit:Ai,roundPixelsBitGl:Ri,roundedShapeArc:Cf,roundedShapeQuadraticCurve:Mf,sayHello:Op,scaleModeToGlFilter:Co,setProgramName:fd,shapeBuilders:hs,sortMixin:zu,spritesheetAsset:od,squaredDistanceToLineSegment:Nd,stripVersion:pd,styleAttributes:go,textureBit:Sp,textureBitGl:Cp,textureFrom:ed,toFillStyle:Gt,toLocalGlobalMixin:Wu,toStrokeStyle:_r,tokenize:Oa,tokenizeTaggedRuns:mp,transformVertices:ma,triangulateWithHoles:_a,trimRight:at,uboSyncFunctionsSTD40:Pl,uboSyncFunctionsWGSL:hm,uid:ne,uniformParsers:Qt,unsafeEvalSupported:ea,updateQuadBounds:Lo,updateRenderGroupTransform:kp,updateRenderGroupTransforms:sl,updateTextBounds:yp,updateTransformAndChildren:rl,updateTransformBackwards:_i,v8_0_0:ue,v8_21_0:lt,v8_22_0:xu,v8_3_4:yu,validateRenderables:Pp,vertexGPUTemplate:sf,vertexGlTemplate:nf,warn:N,warnIgnoredTextureStyle:_p,webworkerExt:fu,wordWrap:gp,wordWrapTaggedLines:pp,wrapModeToGlAddress:Kr},Symbol.toStringTag,{value:"Module"}));function Zr(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function vx(r,e){const t=Zr(r),s=Zr(e.cwd);if(s&&(t===s||t.startsWith(s+"/")))return t.slice(s.length+1)||".";if(e.home){const n=Zr(e.home);if(n&&(t===n||t.startsWith(n+"/")))return"~/"+t.slice(n.length+1)}return t.startsWith("/")?`//ext/${t.slice(t.lastIndexOf("/")+1)}`:t}function wx(r){const e=Zr(r);return e.slice(e.lastIndexOf("/")+1)}function fg(r){return/(^|\/)(tests?|__tests__|spec|specs)\//i.test(r)||/\.(test|spec)\.[cm]?[jt]sx?$/i.test(r)||/(^|\/)test_[^/]+\.py$/i.test(r)||/_test\.(go|rs|py)$/i.test(r)}var Tx=/\b(vitest|jest|mocha|pytest|py\.test|go\s+test|cargo\s+test|npm\s+test|pnpm\s+test|yarn\s+test|bun\s+test|npx\s+(vitest|jest|playwright)|rspec|phpunit|dotnet\s+test|mvn\s+test|gradle\s+test|make\s+test)\b/,Sx=/\b(tsc|tsup|vite\s+build|webpack|esbuild|rollup|next\s+build|cargo\s+build|go\s+build|make\b(?!\s+test)|npm\s+run\s+build|pnpm\s+(run\s+)?build|yarn\s+build|gradle\s+build|mvn\s+package|docker\s+build)\b/,Cx=/\b(npm\s+(i|install|ci)|pnpm\s+(i|install|add)|yarn(\s+add|\s+install)?|pip3?\s+install|poetry\s+(add|install)|cargo\s+add|go\s+get|brew\s+install|apt(-get)?\s+install|bun\s+(i|install|add))\b/,Mx=/\b(grep|rg|ag|ack|find|fd|locate)\b/,Ex=/^\s*(cat|head|tail|less|more|bat|wc|stat|jq)\b/;function pg(r){const t=(r.split(/\s*(?:&&|\|\||;|\|)\s*/)[0]??"").trim().split(/\s+/).map(n=>n.replace(/^[({]+/,"")).filter(Boolean);let s=0;for(;s<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[s]);)s++;if(t[s]==="cd"&&t.length>s+1){const n=r.split(/\s*&&\s*/)[1];if(n)return pg(n)}return(t[s]??"").replace(/^.*\//,"").slice(0,40)||"sh"}function bs(r){const e=r.replace(/^["']|["']$/g,"").trim();return!e||e.startsWith("-")||e==="/dev/null"||e.includes("$(")||e.startsWith("$")||/^\/dev\//.test(e)||/^&\d/.test(e)?null:e}function kx(r){const e=new Set;for(const t of r.matchAll(/(?:^|[\s)])\d?>{1,2}\s*([^\s|&;<>]+)/g)){const s=bs(t[1]??"");s&&e.add(s)}for(const t of r.matchAll(/\btee\s+(?:-[a-z]+\s+)*((?:[^\s|&;<>]+\s*)+)/g))for(const s of(t[1]??"").split(/\s+/)){const i=bs(s);i&&e.add(i)}for(const t of r.matchAll(/\bsed\s+-i\S*\s+(.+?)(?=\s*(?:&&|\|\||;|\||$))/g)){const i=((t[1]??"").match(/"[^"]*"|'[^']*'|\S+/g)??[]).filter(n=>!n.startsWith("-")&&!n.startsWith("'")&&!n.startsWith('"')&&!/^s[/|#]/.test(n)&&!/^-e$/.test(n));for(const n of i){const o=bs(n);o&&e.add(o)}}for(const t of r.matchAll(/\b(?:cp|mv)\s+(?:-[a-zA-Z]+\s+)*((?:[^\s|&;<>]+\s+)+)([^\s|&;<>]+)/g)){const s=bs(t[2]??"");s&&e.add(s)}for(const t of r.matchAll(/\btouch\s+((?:[^\s|&;<>]+\s*)+)/g))for(const s of(t[1]??"").split(/\s+/)){const i=bs(s);i&&e.add(i)}return[...e]}function Px(r){const e=new Set;for(const t of r.split(/\s*(?:&&|\|\||;|\|)\s*/)){const s=t.match(/^\s*(?:cat|head|tail|less|more|bat|wc)\s+(?:-[^\s]+\s+)*((?:[^\s|&;<>]+\s*)+)/);if(s)for(const i of(s[1]??"").split(/\s+/)){const n=bs(i);n&&!/^\d+$/.test(n)&&e.add(n)}}return[...e]}function Ax(r){const e=pg(r),t=kx(r),s=Px(r);let i="other";return Tx.test(r)?i="test":Sx.test(r)?i="build":Cx.test(r)?i="install":/^\s*git\b/.test(r)||e==="git"||e==="gh"?i="git":t.length?i="write_file":Mx.test(r)&&e!=="cd"?i="search":Ex.test(r)&&s.length&&(i="read_file"),{argv0:e,intent:i,writes:t,reads:s}}var ge=r=>r?parseInt(r,10):0;function Rx(r){const e=r.length>2e4?r.slice(-2e4):r;let t=e.match(/Tests\s+(?:(\d+)\s+failed\s*\|\s*)?(\d+)\s+passed(?:\s*\|\s*(\d+)\s+skipped)?/);if(t)return{failed:ge(t[1]),passed:ge(t[2]),...t[3]?{skipped:ge(t[3])}:{},framework:"vitest"};if(t=e.match(/Tests\s+(\d+)\s+failed\s*\((\d+)\)/),t)return{failed:ge(t[1]),passed:Math.max(0,ge(t[2])-ge(t[1])),framework:"vitest"};if(t=e.match(/Tests:\s+(?:(\d+)\s+failed,\s*)?(?:(\d+)\s+skipped,\s*)?(\d+)\s+passed,\s*(?:(\d+)\s+skipped,\s*)?\d+\s+total/),t)return{failed:ge(t[1]),passed:ge(t[3]),...t[2]??t[4]?{skipped:ge(t[2]??t[4])}:{},framework:"jest"};if(t=e.match(/Tests:\s+(\d+)\s+failed,\s*\d+\s+total/),t)return{failed:ge(t[1]),passed:0,framework:"jest"};if(t=e.match(/=+\s*(?:(\d+)\s+failed,?\s*)?(?:(\d+)\s+passed,?\s*)?(?:(\d+)\s+skipped,?\s*)?(?:\d+\s+(?:error|errors|warnings?|deselected|xfailed|xpassed),?\s*)*in\s+[\d.]+s/),t&&(t[1]||t[2]))return{failed:ge(t[1]),passed:ge(t[2]),...t[3]?{skipped:ge(t[3])}:{},framework:"pytest"};if(/^--- (?:PASS|FAIL):/m.test(e)||/^(?:ok|FAIL)\s+\S+\s+(?:[\d.]+s|\(cached\))/m.test(e)){const a=(e.match(/^--- FAIL:/gm)??[]).length||(e.match(/^FAIL\s+\S+\s+[\d.]+s/gm)??[]).length,l=(e.match(/^--- PASS:/gm)??[]).length||(e.match(/^ok\s+\S+/gm)??[]).length;return{failed:a,passed:l,framework:"go"}}if(t=e.match(/test result:\s*\w+\.\s*(\d+)\s+passed;\s*(\d+)\s+failed;\s*(\d+)\s+ignored/),t)return{passed:ge(t[1]),failed:ge(t[2]),skipped:ge(t[3]),framework:"cargo"};const s=e.match(/^\s*(\d+)\s+passing\b/m),i=e.match(/^\s*(\d+)\s+failing\b/m);if(s||i){const a=e.match(/^\s*(\d+)\s+pending\b/m);return{passed:ge(s?.[1]),failed:ge(i?.[1]),...a?{skipped:ge(a[1])}:{},framework:"mocha"}}const n=e.match(/^\s*(\d+)\s+passed\s*\(/m),o=e.match(/^\s*(\d+)\s+failed\b/m);return n||o?{passed:ge(n?.[1]),failed:ge(o?.[1]),framework:"playwright"}:null}var ze=r=>r&&typeof r=="object"?r:{},we=r=>typeof r=="string"?r:void 0,Qr=r=>r?(r.match(/\n/g)?.length??0)+(r.endsWith(`
952
+ `})),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){if(e.dimension==="3d")throw new Error("[GpuMipmapGenerator] a 3D texture uses Gpu3dMipmapGenerator.");if(e.dimension==="1d")throw new Error("Generating mipmaps for 1d textures is currently unsupported!");const t=this._getMipmapPipeline(e.format);let s=e;const i=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:i},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};s=this._device.createTexture(l)}const o=this._device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<i;++l){let h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),c=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const d=s.createView({baseMipLevel:c++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:d,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),p=this._device.createBindGroup({layout:a,entries:[{binding:0,resource:this._sampler},{binding:1,resource:h}]});f.setPipeline(t),f.setBindGroup(0,p),f.draw(3,1,0,0),f.end(),h=d}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:i};for(let h=1;h<e.mipLevelCount;++h)o.copyTextureToTexture({texture:s,mipLevel:h-1},{texture:e,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||s.destroy(),e}}class og{constructor(e){this.textureView=null,this.textureViews=Object.create(null),this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.textureViews=null,this.gpuTexture=null}}const px=/^(rgba8|bgra8|bc[1237]-rgba-|etc2-rgb8|etc2-rgb8a1|etc2-rgba8|astc-\d+x\d+-)unorm$/;function mx(r){return px.test(r)?[`${r}-srgb`]:void 0}function jc(r){return`${r.format||""}.${r.dimension||""}.${r.aspect||""}.${r.baseMipLevel||0}.${r.mipLevelCount||""}.${r.baseArrayLayer||0}.${r.arrayLayerCount||""}`}const rh=class ag{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new it({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:th,buffer:eg,video:rg,compressed:tg,...ag.uploadExtensions};this._uploads={...t,cube:sg(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e,this._managedTextures.removeAll(),this._gpuSamplers=Object.create(null),this._mipmapGenerator=null,this._mipmap3dGenerator=null}initSource(e){return e._gpuData[this._renderer.uid]?.gpuTexture||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){e.dimension==="3d"&&sh(e.format,e.storage);const c=Math.max(e.pixelWidth,e.pixelHeight,e.depth);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t,s;e.sampleCount>1?(t=GPUTextureUsage.RENDER_ATTACHMENT,e.transient&&this._renderer.device.extensions.transientAttachment&&(t|=GPUTextureUsage.TRANSIENT_ATTACHMENT)):(t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC),e.storage&&(t|=GPUTextureUsage.STORAGE_BINDING),s=mx(e.format));const i=eh[e.format]||{blockWidth:1,blockHeight:1},n=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,o=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,a={label:e.label,size:{width:n,height:o,depthOrArrayLayers:e.depthOrArrayLayers},format:e.format,viewFormats:s,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},l=this._gpu.device.createTexture(a);return e._gpuData[this._renderer.uid]=new og(l),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),l}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){const t=this.getGpuSource(e);if(e.dimension==="3d"){this._mipmap3dGenerator??(this._mipmap3dGenerator=new ig(this._gpu.device)),this._mipmap3dGenerator.generateMipmap(t);return}this._mipmapGenerator??(this._mipmapGenerator=new ng(this._gpu.device)),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],s=t?.gpuTexture;s?(s.width!==e.pixelWidth||s.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){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.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 St({0:t,1:t.style,2:new rt({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e,t){var s;const i=e.source;i._gcLastUsed=this._renderer.gc.now;let n=i._gpuData[this._renderer.uid];n||(this.initSource(i),n=i._gpuData[this._renderer.uid]);const o=t?jc(t):0;return(s=n.textureViews)[o]||(s[o]=n.gpuTexture.createView({dimension:i.viewDimension,...t})),n.textureViews[o]}getTextureRenderTargetView(e,t=0,s=0,i){var n;const o=e.source;o._gcLastUsed=this._renderer.gc.now;let a=o._gpuData[this._renderer.uid];a||(this.initSource(o),a=o._gpuData[this._renderer.uid]);const l=o.dimension==="3d";l&&(s=0);let h=s*(o.mipLevelCount||1)+t+1;return i&&(h=`${h}.${jc(i)}`),(n=a.textureViews)[h]||(n[h]=a.gpuTexture.createView({dimension:l?"3d":"2d",baseMipLevel:t,mipLevelCount:1,baseArrayLayer:s,arrayLayerCount:1,...i})),a.textureViews[h]}generateCanvas(e){const t=this._renderer,s=t.gpu.device.createCommandEncoder(),i=J.get().createCanvas();i.width=e.source.pixelWidth,i.height=e.source.pixelHeight;const n=i.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:J.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),s.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:i.width,height:i.height}),t.gpu.device.queue.submit([s.finish()]),i}getPixels(e){const t=this.generateCanvas(e),s=Mt.getOptimalCanvasAndContext(t.width,t.height),i=s.context;i.drawImage(t,0,0);const{width:n,height:o}=t,a=i.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return Mt.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e);this._bindGroupHash[t]?.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._mipmap3dGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}};rh.extension={type:[S.WebGPUSystem],name:"texture"};rh.uploadExtensions=Object.create(null);let ih=rh;q.handleByMap(S.TextureUploaderWebGPU,ih.uploadExtensions);class nh{constructor(){this._maxTextures=0}contextChange(e){const t=new rt({uTransformMatrix:{value:new L,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 s=ki({name:"graphics",bits:[ca,da(this._maxTextures),Qf,Ai]});this.shader=new dt({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,i=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),h=n.encoder;h.setGeometry(a.geometry,i.gpuProgram);const c=n.globalUniforms.bindGroup;h.setBindGroup(0,c,i.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(i.resources.localUniforms,!0);h.setBindGroup(2,u,i.gpuProgram);const d=l.instructions;let f=null;for(let p=0;p<l.instructionSize;p++){const m=d[p];if(m.topology!==f&&(f=m.topology,h.setPipelineFromGeometryProgramAndState(a.geometry,i.gpuProgram,e.state,m.topology,i._overrides)),i.groups[1]=m.bindGroup,!m.gpuBindGroup){const g=m.textures;m.bindGroup=Mi(g.textures,g.count,this._maxTextures),m.gpuBindGroup=n.bindGroup.getBindGroup(m.bindGroup,i.gpuProgram,1)}h.setBindGroup(1,m.bindGroup,i.gpuProgram),h.renderPassEncoder.drawIndexed(m.size,1,m.start)}}destroy(){this.shader.destroy(),this.shader=null}}nh.extension={type:[S.WebGPUPipesAdaptor],name:"graphics"};class oh{init(){const e=ki({name:"mesh",bits:[sr,Sp,Ai]});this._shader=new dt({gpuProgram:e,resources:{uTexture:H.EMPTY._source,uSampler:H.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new L}}}})}execute(e,t){const s=e.renderer;let i=t._shader;if(!i)i=this._shader,i.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!i.gpuProgram){N("Mesh shader has no gpuProgram",t.shader);return}const n=i.gpuProgram;if(n.autoAssignGlobalUniforms&&(i.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;i.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:i,state:t.state})}destroy(){this._shader.destroy(),this._shader=null}}oh.extension={type:[S.WebGPUPipesAdaptor],name:"mesh"};const gx=[...$i,ql,Vl,ji,Xl,Wl,ih,Zl,Ql,Jl,Kl,$l,jl,zl],_x=[...ml,Yl],yx=[ja,oh,nh],lg=[],hg=[],cg=[],ug=[];q.handleByNamedList(S.WebGPUSystem,lg);q.handleByNamedList(S.WebGPUPipes,hg);q.handleByNamedList(S.WebGPUPipesAdaptor,cg);q.handleByNamedList(S.WebGPULoader,ug);q.add(...gx,..._x,...yx);class dg extends Is{constructor(){const e={name:"webgpu",type:Ke.WEBGPU,systems:lg,renderPipes:hg,renderPipeAdaptors:cg,loaders:ug};super(e)}}const xx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:dg},Symbol.toStringTag,{value:"Module"}));q.add(du,fu);const bx=Object.freeze(Object.defineProperty({__proto__:null,AbstractRenderer:Is,AbstractText:Jf,AbstractTextSystem:za,AccessibilitySystem:T_,AlphaMask:Wo,AlphaMaskPipe:Oi,Application:oa,ApplicationInitHook:sa,BLEND_TO_NPM:zd,BREAKING_SPACES:np,BREAKING_SPACES_SET:op,BREAK_AFTER_CHARS:lp,BREAK_AFTER_CHARS_SET:hp,BUFFER_TYPE:nr,BackgroundSystem:Rp,Batch:Vd,BatchGeometry:Kd,BatchTextureArray:$d,BatchableGraphics:Ii,BatchableSprite:Fi,BatchableText:xp,Batcher:qd,BatcherPipe:Li,BigPool:Se,BindGroup:St,BindGroupSystem:zl,BlendModePipe:zi,Bounds:ke,BrowserAdapter:ju,Buffer:Ct,BufferImageSource:mi,BufferResource:Xi,BufferUsage:ce,CLEAR:ye,COLLAPSIBLE_SPACES:ap,Cache:qt,CanvasBatchAdaptor:wp,CanvasColorMaskPipe:Ya,CanvasContextSystem:Ja,CanvasFilterSystem:Hf,CanvasGraphicsAdaptor:tl,CanvasGraphicsContextSystem:Kf,CanvasGraphicsPipe:Aa,CanvasLimitsSystem:el,CanvasObserver:qo,CanvasPool:Mt,CanvasPoolClass:Nf,CanvasRenderTargetAdaptor:qp,CanvasRenderTargetSystem:gl,CanvasRenderer:Jp,CanvasRendererTextSystem:Wa,CanvasSource:Ve,CanvasStencilMaskPipe:Za,CanvasTextGenerator:Yt,CanvasTextMetrics:yt,CanvasTextPipe:Ha,CanvasTextSystem:$a,CanvasTextureSystem:_l,Circle:Ti,Color:oe,ColorMask:$o,ColorMaskPipe:Ka,Container:_e,CustomRenderPipe:Ui,DEG_TO_RAD:gu,DOMAdapter:J,DOMPipe:Lf,DefaultBatcher:Bi,DefaultShader:lo,Ellipse:Si,EventBoundary:Of,EventEmitter:Re,EventSystem:Uf,EventsTicker:ht,ExtensionType:S,ExtractSystem:Ip,FederatedContainer:J0,FederatedEvent:Bs,FederatedMouseEvent:yr,FederatedPointerEvent:Fe,FederatedWheelEvent:os,FillGradient:Xe,FillPattern:Gs,Filter:Jo,FilterEffect:lr,FilterPipe:Vf,FilterSystem:Xf,GCManagedHash:it,GCSystem:Lp,GL_FORMATS:di,GL_TARGETS:As,GL_TYPES:re,GPUTextureGpuData:og,GenerateTextureSystem:al,Geometry:Ei,GlBackBufferSystem:om,GlBatchAdaptor:Xa,GlBuffer:em,GlBufferSystem:yl,GlColorMaskSystem:wl,GlContextSystem:sm,GlEncoderSystem:Tl,GlGeometryGpuData:im,GlGeometrySystem:bl,GlGraphicsAdaptor:Nl,GlLimitsSystem:Sl,GlMeshAdaptor:Hl,GlProgram:ls,GlProgramData:mm,GlRenderTarget:am,GlRenderTargetAdaptor:dm,GlRenderTargetSystem:Rl,GlShaderSystem:Gl,GlStateSystem:Em,GlStencilSystem:Cl,GlTexture:km,GlTextureSystem:Ul,GlUboSystem:Al,GlUniformGroupSystem:Dl,GlobalResourceRegistry:as,GlobalUniformSystem:hl,Gpu3dMipmapGenerator:ig,GpuBatchAdaptor:ja,GpuBlendModesToPixi:Ge,GpuBufferData:Vm,GpuBufferSystem:Wl,GpuColorMaskSystem:$l,GpuDeviceSystem:ji,GpuEncoderSystem:Vl,GpuGraphicsAdaptor:nh,GpuGraphicsContext:bf,GpuLimitsSystem:Xl,GpuMeshAdapter:oh,GpuMipmapGenerator:ng,GpuMsaaRestore:Zm,GpuProgram:Ft,GpuRenderTarget:Qm,GpuRenderTargetAdaptor:Jm,GpuRenderTargetSystem:Zl,GpuShaderSystem:Ql,GpuStateSystem:Jl,GpuStencilModesToPixi:kt,GpuStencilSystem:jl,GpuTextureSystem:ih,GpuUboSystem:ql,GpuUniformBatchPipe:Yl,Graphics:Pe,GraphicsContext:qe,GraphicsContextRenderData:vf,GraphicsContextSystem:Di,GraphicsGpuData:Zf,GraphicsPath:ut,GraphicsPipe:Ba,HelloSystem:Wi,ImageSource:ur,InstructionSet:xi,LoaderParserPriority:Xo,MaskEffectManager:si,MaskEffectManagerClass:Iu,MaskFilter:Yf,Matrix:L,NEWLINES:rp,NEWLINES_SET:ip,NEWLINE_MATCH_REGEX:up,NEWLINE_SPLIT_REGEX:cp,NOOP:Go,ObservablePoint:Ce,PI_2:pu,PassthroughFilter:$f,PipelineSystem:Kl,Point:he,Polygon:Ts,Pool:ku,PoolGroupClass:Pu,RAD_TO_DEG:mu,Rectangle:ee,RenderBundle:jm,RenderGroup:ri,RenderGroupPipe:Ni,RenderGroupSystem:il,RenderTarget:ir,RenderTargetSystem:Vi,RenderTexture:wr,RenderableGCSystem:Np,RendererInitHook:ra,RendererType:Ke,ResizePlugin:ia,Resolver:jo,RoundedRectangle:Ci,STATE_BITS:Qo,STENCIL_MODES:me,SVGParser:Gf,SchedulerSystem:cl,ScreenSizeRegistry:No,Shader:dt,ShaderOverrides:Es,ShaderStage:fe,ShapePath:Ef,SharedRenderPipes:ml,SharedSystems:$i,Sprite:ss,SpritePipe:Hi,Spritesheet:Wn,State:ft,StencilMask:Vo,StencilMaskPipe:Qa,SystemRunner:ta,Text:bp,TextStyle:Ps,Texture:H,TextureGCSystem:Hp,TextureMatrix:Fo,TexturePool:Te,TexturePoolClass:$u,TextureSource:de,TextureStyle:Dt,TextureView:fm,Ticker:We,TickerListener:Xr,TickerPlugin:na,UNIFORM_TO_ARRAY_SETTERS:Tm,UNIFORM_TO_SINGLE_SETTERS:wm,UNIFORM_TYPES_MAP:bd,UNIFORM_TYPES_VALUES:Zo,UPDATE_BLEND:bi,UPDATE_COLOR:cr,UPDATE_PRIORITY:rs,UPDATE_VISIBLE:ws,UboBatch:Xm,UboSystem:Ml,UniformGroup:rt,VERSION:gr,VideoSource:Zu,ViewContainer:vi,ViewSystem:Vp,ViewableBuffer:so,WGSL_ALIGN_SIZE_DATA:or,WGSL_TO_STD40_SIZE:El,WebGLRenderer:$m,WebGPURenderer:dg,accessibilityTarget:S_,addBits:io,addMaskBounds:Ho,addMaskLocalBounds:zo,addProgramDefines:cd,appendSVGPath:_o,applyStyleParams:Mo,assertMipmap3dTexture:sh,assignWithIgnore:Vu,autoDetectRenderer:Ld,bakeOverridesIntoSource:Eo,bgr2rgb:Zt,blockDataMap:eh,boundsPool:ct,browserExt:du,buildAdaptiveBezier:va,buildAdaptiveQuadratic:wf,buildArc:wa,buildArcTo:Tf,buildArcToSvg:Sf,buildCircle:ks,buildContextBatches:xf,buildEllipse:ff,buildLine:Gi,buildPixelLine:mf,buildPolygon:gf,buildRectangle:_f,buildRoundedRectangle:pf,buildSimpleUvs:df,buildTriangle:yf,buildUvs:uf,cacheAsTextureMixin:Au,calculatePathArea:If,calculateProjection:Xp,canUseNewCanvasBlendModes:Ma,canvasUtils:Y,checkChildrenDidChange:Uo,checkForNestedPattern:Rf,checkMaxIfStatementsInShader:la,childrenHelperMixin:Ru,cleanArray:Dp,cleanHash:Gp,clearList:ci,closePointEps:ga,collapseNewlines:La,collapseSpaces:Fa,collectRenderablesMixin:Bu,color32BitToUniform:Ra,colorBit:ca,colorBitGl:ua,compareModeToGlCompare:Gm,compileBufferSync:kl,compileHighShader:Qd,compileHighShaderGl:Jd,compileHighShaderGlProgram:Pi,compileHighShaderGpuProgram:ki,compileHooks:no,compileInputs:oo,compileOutputs:Zd,compileShader:To,convertToList:jt,copySearchParams:zn,createGlUploadCubeTextureResource:Rm,createGpuUploadCubeTextureResource:sg,createIdFromString:is,createStringVariations:sd,createUboElementsSTD40:lm,createUboElementsWGSL:qm,createUboSyncFunctionSTD40:um,createUboSyncFunctionWGSL:Km,cullingMixin:Eu,curveEps:ho,defaultFilterVert:zf,defaultValue:Bl,definedProps:Do,deprecation:O,detectVideoAlphaMode:Yu,earcut:Bd,effectsMixin:Gu,ensureAttributes:ui,ensureIsBuffer:ha,ensurePrecision:ud,ensureTextOptions:ep,executeInstructions:hi,extensions:q,extractAttributesFromGlProgram:_m,extractAttributesFromGpuProgram:gd,extractStructAndGroups:jr,extractSubpaths:Bf,extractSvgUrlId:mo,fastCopy:oi,findMixin:Du,fontStringFromTextStyle:li,fragmentGPUTemplate:rf,fragmentGlTemplate:of,generateArraySyncSTD40:cm,generateArraySyncWGSL:Ym,generateGpuLayoutGroups:_d,generateLayoutHash:yd,generateProgram:vm,generateShaderSyncCode:pm,generateTextureBatchBit:da,generateTextureBatchBitGl:fa,generateTextureMatrix:xa,generateUniformsSync:Sm,getAdjustedBlendModeBlend:ro,getAttributeInfoFromFormat:Ms,getBatchSamplersUniformGroup:pa,getCanvasBoundingBox:tp,getCanvasFillStyle:Qs,getCanvasTexture:fl,getCharacterGroups:Ua,getDefaultUniformValue:vd,getFastGlobalBoundsMixin:Fu,getGeometryBounds:Yd,getGlTypeFromFormat:rm,getGlobalBounds:gi,getGlobalMixin:Ou,getGlobalRenderableBounds:Ea,getLocalBounds:yi,getMaxFragmentPrecision:hd,getMaxMiterRatio:Ff,getMaxTexturesPerBatch:Wd,getOrientationOfPoints:aa,getPo2TextureFromSource:ka,getTestContext:Ko,getTexelRangeRects:Fl,getTextureBatchBindGroup:Mi,getUboData:ym,getUniformData:xm,getUrlExtension:rd,glUploadBufferImageResource:Pm,glUploadCompressedTextureResource:Am,glUploadImageResource:Ll,glUploadVideoResource:Bm,globalUniformsBit:af,globalUniformsBitGl:lf,gpuUploadBufferImageResource:eg,gpuUploadCompressedTextureResource:tg,gpuUploadImageResource:th,gpuUploadVideoResource:rg,groupD8:Z,hasTagMarkup:Da,hasTagStyles:Ga,injectBits:ao,insertVersion:dd,isBreakAfterChar:dp,isBreakingSpace:$e,isCanvasFilterCapable:xo,isIntegerFormat:ti,isMobile:ad,isNewline:xr,isPow2:ts,isRenderingToScreen:jp,isSafari:vp,isSingleItem:Hn,isWebGLSupported:Dd,isWebGPUSupported:Fd,loadEnvironmentExtensions:Md,localUniformBit:sr,localUniformBitGl:Ia,localUniformBitGroup2:Qf,logProgramError:bm,mapCanvasBlendModesToPixi:Ep,mapFormatToGlFormat:Dm,mapFormatToGlInternalFormat:Fm,mapFormatToGlType:Lm,mapGlToVertexFormat:gm,mapType:Il,mapViewDimensionToGlTarget:Om,mapWebGLBlendModesToPixi:Cm,maskFrag:jf,maskVert:qf,maskWgsl:vo,matrixPool:Ae,measureMixin:Nu,measureTaggedText:fp,mipmapScaleModeToGlFilter:Im,multiplyColors:hr,multiplyHexColors:Kt,nextPow2:es,normalizeExtensionPriority:Ys,onRenderMixin:Hu,parseSVGDefinitions:kf,parseSVGFloatAttribute:ve,parseSVGPath:Ud,parseSVGStyle:Ta,parseTaggedText:sp,passthroughFrag:Wf,passthroughWgsl:bo,path:Cs,removeItems:Oo,removeStructAndGroupDuplicates:xd,resourceToTexture:Ju,roundPixelsBit:Ai,roundPixelsBitGl:Ri,roundedShapeArc:Cf,roundedShapeQuadraticCurve:Mf,sayHello:Op,scaleModeToGlFilter:Co,setProgramName:fd,shapeBuilders:hs,sortMixin:zu,spritesheetAsset:od,squaredDistanceToLineSegment:Nd,stripVersion:pd,styleAttributes:go,textureBit:Sp,textureBitGl:Cp,textureFrom:ed,toFillStyle:Gt,toLocalGlobalMixin:Wu,toStrokeStyle:_r,tokenize:Oa,tokenizeTaggedRuns:mp,transformVertices:ma,triangulateWithHoles:_a,trimRight:at,uboSyncFunctionsSTD40:Pl,uboSyncFunctionsWGSL:hm,uid:ne,uniformParsers:Qt,unsafeEvalSupported:ea,updateQuadBounds:Lo,updateRenderGroupTransform:kp,updateRenderGroupTransforms:sl,updateTextBounds:yp,updateTransformAndChildren:rl,updateTransformBackwards:_i,v8_0_0:ue,v8_21_0:lt,v8_22_0:xu,v8_3_4:yu,validateRenderables:Pp,vertexGPUTemplate:sf,vertexGlTemplate:nf,warn:N,warnIgnoredTextureStyle:_p,webworkerExt:fu,wordWrap:gp,wordWrapTaggedLines:pp,wrapModeToGlAddress:Kr},Symbol.toStringTag,{value:"Module"}));function Zr(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function vx(r,e){const t=Zr(r),s=Zr(e.cwd);if(s&&(t===s||t.startsWith(s+"/")))return t.slice(s.length+1)||".";if(e.home){const n=Zr(e.home);if(n&&(t===n||t.startsWith(n+"/")))return"~/"+t.slice(n.length+1)}return t.startsWith("/")?`//ext/${t.slice(t.lastIndexOf("/")+1)}`:t}function wx(r){const e=Zr(r);return e.slice(e.lastIndexOf("/")+1)}function fg(r){return/(^|\/)(tests?|__tests__|spec|specs)\//i.test(r)||/\.(test|spec)\.[cm]?[jt]sx?$/i.test(r)||/(^|\/)test_[^/]+\.py$/i.test(r)||/_test\.(go|rs|py)$/i.test(r)}var Tx=/\b(vitest|jest|mocha|pytest|py\.test|go\s+test|cargo\s+test|npm\s+test|pnpm\s+test|yarn\s+test|bun\s+test|npx\s+(vitest|jest|playwright)|rspec|phpunit|dotnet\s+test|mvn\s+test|gradle\s+test|make\s+test)\b/,Sx=/\b(tsc|tsup|vite\s+build|webpack|esbuild|rollup|next\s+build|cargo\s+build|go\s+build|make\b(?!\s+test)|npm\s+run\s+build|pnpm\s+(run\s+)?build|yarn\s+build|gradle\s+build|mvn\s+package|docker\s+build)\b/,Cx=/\b(npm\s+(i|install|ci)|pnpm\s+(i|install|add)|yarn(\s+add|\s+install)?|pip3?\s+install|poetry\s+(add|install)|cargo\s+add|go\s+get|brew\s+install|apt(-get)?\s+install|bun\s+(i|install|add))\b/,Mx=/\b(grep|rg|ag|ack|find|fd|locate)\b/,Ex=/^\s*(cat|head|tail|less|more|bat|wc|stat|jq)\b/;function pg(r){const t=(r.split(/\s*(?:&&|\|\||;|\|)\s*/)[0]??"").trim().split(/\s+/).map(n=>n.replace(/^[({]+/,"")).filter(Boolean);let s=0;for(;s<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[s]);)s++;if(t[s]==="cd"&&t.length>s+1){const n=r.split(/\s*&&\s*/)[1];if(n)return pg(n)}return(t[s]??"").replace(/^.*\//,"").slice(0,40)||"sh"}function bs(r){const e=r.replace(/^["']|["']$/g,"").trim();return!e||e.startsWith("-")||e==="/dev/null"||e.includes("$(")||e.startsWith("$")||/^\/dev\//.test(e)||/^&\d/.test(e)?null:e}function kx(r){const e=new Set;for(const t of r.matchAll(/(?:^|[\s)])\d?>{1,2}\s*([^\s|&;<>]+)/g)){const s=bs(t[1]??"");s&&e.add(s)}for(const t of r.matchAll(/\btee\s+(?:-[a-z]+\s+)*((?:[^\s|&;<>]+\s*)+)/g))for(const s of(t[1]??"").split(/\s+/)){const i=bs(s);i&&e.add(i)}for(const t of r.matchAll(/\bsed\s+-i\S*\s+(.+?)(?=\s*(?:&&|\|\||;|\||$))/g)){const i=((t[1]??"").match(/"[^"]*"|'[^']*'|\S+/g)??[]).filter(n=>!n.startsWith("-")&&!n.startsWith("'")&&!n.startsWith('"')&&!/^s[/|#]/.test(n)&&!/^-e$/.test(n));for(const n of i){const o=bs(n);o&&e.add(o)}}for(const t of r.matchAll(/\b(?:cp|mv)\s+(?:-[a-zA-Z]+\s+)*((?:[^\s|&;<>]+\s+)+)([^\s|&;<>]+)/g)){const s=bs(t[2]??"");s&&e.add(s)}for(const t of r.matchAll(/\btouch\s+((?:[^\s|&;<>]+\s*)+)/g))for(const s of(t[1]??"").split(/\s+/)){const i=bs(s);i&&e.add(i)}return[...e]}function Px(r){const e=new Set;for(const t of r.split(/\s*(?:&&|\|\||;|\|)\s*/)){const s=t.match(/^\s*(?:cat|head|tail|less|more|bat|wc)\s+(?:-[^\s]+\s+)*((?:[^\s|&;<>]+\s*)+)/);if(s)for(const i of(s[1]??"").split(/\s+/)){const n=bs(i);n&&!/^\d+$/.test(n)&&e.add(n)}}return[...e]}function Ax(r){const e=pg(r),t=kx(r),s=Px(r);let i="other";return Tx.test(r)?i="test":Sx.test(r)?i="build":Cx.test(r)?i="install":/^\s*git\b/.test(r)||e==="git"||e==="gh"?i="git":t.length?i="write_file":Mx.test(r)&&e!=="cd"?i="search":Ex.test(r)&&s.length&&(i="read_file"),{argv0:e,intent:i,writes:t,reads:s}}var ge=r=>r?parseInt(r,10):0;function Rx(r){const e=r.length>2e4?r.slice(-2e4):r;let t=e.match(/Tests\s+(?:(\d+)\s+failed\s*\|\s*)?(\d+)\s+passed(?:\s*\|\s*(\d+)\s+skipped)?/);if(t)return{failed:ge(t[1]),passed:ge(t[2]),...t[3]?{skipped:ge(t[3])}:{},framework:"vitest"};if(t=e.match(/Tests\s+(\d+)\s+failed\s*\((\d+)\)/),t)return{failed:ge(t[1]),passed:Math.max(0,ge(t[2])-ge(t[1])),framework:"vitest"};if(t=e.match(/Tests:\s+(?:(\d+)\s+failed,\s*)?(?:(\d+)\s+skipped,\s*)?(\d+)\s+passed,\s*(?:(\d+)\s+skipped,\s*)?\d+\s+total/),t)return{failed:ge(t[1]),passed:ge(t[3]),...t[2]??t[4]?{skipped:ge(t[2]??t[4])}:{},framework:"jest"};if(t=e.match(/Tests:\s+(\d+)\s+failed,\s*\d+\s+total/),t)return{failed:ge(t[1]),passed:0,framework:"jest"};if(t=e.match(/=+\s*(?:(\d+)\s+failed,?\s*)?(?:(\d+)\s+passed,?\s*)?(?:(\d+)\s+skipped,?\s*)?(?:\d+\s+(?:error|errors|warnings?|deselected|xfailed|xpassed),?\s*)*in\s+[\d.]+s/),t&&(t[1]||t[2]))return{failed:ge(t[1]),passed:ge(t[2]),...t[3]?{skipped:ge(t[3])}:{},framework:"pytest"};if(/^--- (?:PASS|FAIL):/m.test(e)||/^(?:ok|FAIL)\s+\S+\s+(?:[\d.]+s|\(cached\))/m.test(e)){const a=(e.match(/^--- FAIL:/gm)??[]).length||(e.match(/^FAIL\s+\S+\s+[\d.]+s/gm)??[]).length,l=(e.match(/^--- PASS:/gm)??[]).length||(e.match(/^ok\s+\S+/gm)??[]).length;return{failed:a,passed:l,framework:"go"}}if(t=e.match(/test result:\s*\w+\.\s*(\d+)\s+passed;\s*(\d+)\s+failed;\s*(\d+)\s+ignored/),t)return{passed:ge(t[1]),failed:ge(t[2]),skipped:ge(t[3]),framework:"cargo"};const s=e.match(/^\s*(\d+)\s+passing\b/m),i=e.match(/^\s*(\d+)\s+failing\b/m);if(s||i){const a=e.match(/^\s*(\d+)\s+pending\b/m);return{passed:ge(s?.[1]),failed:ge(i?.[1]),...a?{skipped:ge(a[1])}:{},framework:"mocha"}}const n=e.match(/^\s*(\d+)\s+passed\s*\(/m),o=e.match(/^\s*(\d+)\s+failed\b/m);return n||o?{passed:ge(n?.[1]),failed:ge(o?.[1]),framework:"playwright"}:null}var ze=r=>r&&typeof r=="object"?r:{},we=r=>typeof r=="string"?r:void 0,Qr=r=>r?(r.match(/\n/g)?.length??0)+(r.endsWith(`
953
953
  `)?0:1):0;function Bx(r){const e=ze(r).structuredPatch;if(!Array.isArray(e))return null;let t=0,s=0;for(const i of e){const n=ze(i).lines;if(Array.isArray(n))for(const o of n)typeof o=="string"&&(o.startsWith("+")?t++:o.startsWith("-")&&s++)}return{added:t,removed:s,hunks:e.length}}function Ix(r){if(typeof r=="string")return r;const e=ze(r),t=[we(e.stdout),we(e.stderr),we(e.output)].filter(s=>!!s);return t.length?t.join(`
954
954
  `):Array.isArray(r)?r.map(s=>we(ze(s).text)??"").join(`
955
- `):""}function Gx(r){let e=0;for(const t of r.matchAll(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n\2(?=\n|$)/g))e+=Qr(t[3]);return e===0&&/(?:^|[\s)])\d?>{1,2}\s*[^\s|&;<>]+/.test(r)&&!/>\s*\/dev\/null/.test(r)&&(e=1),e}var Dx=new Set(["Grep","Glob","LS","ToolSearch"]),Fx=new Set(["WebSearch","WebFetch"]),Lx=new Set(["TodoWrite","TodoRead","Skill","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree","NotebookRead","ListAgents","SendMessage","TaskStop","Monitor","ScheduleWakeup","ReportFindings"]);function qc(r,e){const t=ze(r.input),s=r.response,i=!r.isError&&ze(s).interrupted!==!0,n=a=>vx(a,e),o=r.durationMs!==void 0?{durationMs:r.durationMs}:{};switch(r.name){case"Read":{const a=we(t.file_path)??we(t.path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:"Read without file_path"}};const l=we(ze(ze(s).file).content);return{bodies:[{kind:"read_file",path:n(a),...l!==void 0?{bytes:l.length}:{}}]}}case"Edit":case"MultiEdit":case"NotebookEdit":{const a=we(t.file_path)??we(t.notebook_path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:`${r.name} without file_path`}};const l=Bx(s)??{added:Qr(we(t.new_string)??we(t.new_source)),removed:Qr(we(t.old_string)),hunks:1};return{bodies:[{kind:"edit_file",path:n(a),...l}]}}case"Write":{const a=we(t.file_path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:"Write without file_path"}};const l=ze(s),h=l.type==="create"||l.type===void 0&&l.originalFile===null;return{bodies:[{kind:"write_file",path:n(a),added:Qr(we(t.content)),created:h}]}}case"Bash":{const a=we(t.command)??"",l=Ax(a),h=[...new Set([...l.writes,...l.reads].map(n))],c=[{kind:"run_command",argv0:l.argv0,intent:l.intent,touched:h,ok:i,...o}],u=Gx(a);l.writes.forEach((d,f)=>c.push({kind:"write_file",path:n(d),added:f===0?u:0,created:!1}));for(const d of l.reads)c.push({kind:"read_file",path:n(d)});if(l.intent==="test"){const d=Rx(Ix(s));d?c.push({kind:"test_result",ok:d.failed===0&&i,passed:d.passed,failed:d.failed,...d.skipped!==void 0?{skipped:d.skipped}:{},framework:d.framework,...o}):c.push({kind:"test_result",ok:i,passed:0,failed:0,framework:"unknown",...o})}return{bodies:c}}case"Agent":case"Task":{const a=ze(s),l=we(a.agentId)??we(a.agent_id)??"",h=we(t.description)??we(t.subagent_type),c={kind:"subagent_start",childId:l,...h?{label:h}:{}};return a.status==="async_launched"||a.isAsync===!0?{bodies:[c],pendingSubagent:{childId:l}}:{bodies:[c,{kind:"subagent_stop",childId:l,ok:i}]}}case"AskUserQuestion":return{bodies:[{kind:"waiting_for_user",reason:"question"}]}}if(Dx.has(r.name)){const a=ze(s).numFiles??ze(s).numLines??ze(s).count;return{bodies:[{kind:"search",scope:"repo",...typeof a=="number"?{hits:a}:{}}]}}return Fx.has(r.name)?{bodies:[{kind:"search",scope:"web"}]}:Lx.has(r.name)?{bodies:[]}:{bodies:[{kind:"run_command",argv0:r.name.slice(0,40),intent:"other",touched:[],ok:i,...o}],warning:{code:"unknown_tool",detail:r.name.slice(0,80)}}}var Ox=[/\ball (?:\d+ )?tests? (?:are )?pass(?:ing|ed)?\b/i,/\btests? (?:are |is )?(?:now )?(?:passing|green)\b/i,/\b(?:is|are|it's|that's|everything(?:'s| is)) (?:now )?(?:fixed|working|done|complete|resolved)\b/i,/\bshould (?:now )?work\b/i,/\bworks now\b/i,/\b(?:done|complete|completed|fixed|resolved|shipped|implemented)[.!]/i,/✅/],Ux=[/\bnot (?:yet )?(?:done|fixed|working|tested|verified|complete)\b/i,/\bstill (?:fail|broken|not)/i,/\b(?:could ?n[’']?t|cannot|can ?not|unable to|wasn[’']?t able)\b/i,/\bfail(?:ed|ing|s)\b/i,/\bTODO\b/,/\bhaven[’']?t (?:run|tested|verified|checked)/i,/\buntested\b/i,/\bI did not (?:run|test|verify)/i],Yc=600;function Kc(r){if(!r)return!1;const e=r.length>Yc?r.slice(-Yc):r;return Ux.some(t=>t.test(e))?!1:Ox.some(t=>t.test(e))}var Nx=new Set(["user","assistant","system"]),Wr=r=>r&&typeof r=="object"?r:{},be=r=>typeof r=="string"?r:void 0;function Hx(r,e={}){const t=[],s=[],i=r.split(/\r?\n/);for(let o=0;o<i.length;o++){const a=i[o];if(a.trim())try{t.push(JSON.parse(a))}catch{s.push({code:"bad_json",detail:`line ${o+1}`,line:o+1})}}const n=zx(t,e);return{events:n.events,warnings:[...s,...n.warnings]}}function zx(r,e={}){const t=[],s=[],i=new Set,n=new Map,o=new Map;let a="",l="",h,c=Number.NaN,u=Number.NaN,d="",f=0,p=!1;const m=()=>({cwd:l,...e.home?{home:e.home}:{}}),g=(y,b,w,v={})=>{t.push({id:b,seq:f++,ts:y,sessionId:a,source:"transcript",...v,...w})},_=y=>{const b=be(y.timestamp),w=b?Date.parse(b):Number.NaN;return Number.isFinite(w)?w:Number.isFinite(u)?u:0},x=y=>be(y.agentId)??(y.isSidechain===!0?e.sidechainAgentId??"sidechain":void 0);for(const y of r){const b=Wr(y),w=be(b.type)??"";if(!Nx.has(w)){w&&i.add(w);continue}!a&&be(b.sessionId)&&(a=be(b.sessionId)),!l&&be(b.cwd)&&(l=be(b.cwd)),!h&&be(b.gitBranch)&&(h=be(b.gitBranch));const v=_(b);Number.isFinite(c)||(c=v,g(v,`${a||"session"}:start`,{kind:"session_start",repoId:wx(l)||"repo",...h?{branch:h}:{}})),u=v;const S=x(b),E=Wr(b.message),k=E.content;if(w==="system"){if(b.subtype==="api_error"){const T=typeof b.retryAttempt=="number"?b.retryAttempt:0,A=typeof b.maxRetries=="number"?b.maxRetries:0;g(v,be(b.uuid)??`sys:${f}`,{kind:"error",where:"api",retrying:T<A},S?{agentId:S}:{})}continue}if(w==="assistant"){const T=Array.isArray(k)?k:[];for(const A of T){const I=Wr(A);if(I.type==="tool_use"&&be(I.id)&&be(I.name))n.set(be(I.id),{name:be(I.name),input:I.input,ts:v,...S?{agentId:S}:{}});else if(I.type==="text"&&!S){const F=be(I.text);F&&(d=F)}}typeof k=="string"&&!S&&(d=k),E.stop_reason==="end_turn"&&!S&&g(v,`${be(b.uuid)??f}:turn`,{kind:"turn_end",claimedSuccess:Kc(d)});continue}b.toolDenialKind!==void 0&&g(v,`${be(b.uuid)??f}:deny`,{kind:"waiting_for_user",reason:"permission"});const P=Array.isArray(k)?k:[];for(const T of P){const A=Wr(T);if(A.type!=="tool_result")continue;const I=be(A.tool_use_id);if(!I)continue;const F=n.get(I);if(!F){s.push({code:"unpaired_result",detail:I});continue}n.delete(I);const X=b.toolUseResult??A.content,R=qc({name:F.name,input:F.input,response:X,isError:A.is_error===!0,durationMs:Math.max(0,v-F.ts)},m());R.warning&&s.push(R.warning);const M=F.agentId??S,G=M?o.get(M):void 0,B={...M?{agentId:M}:{},...G?{parentId:G}:{}};R.bodies.forEach((U,W)=>g(F.ts,W===0?I:`${I}:${W}`,U,B)),R.pendingSubagent&&o.set(R.pendingSubagent.childId,I)}P.length===0&&typeof k=="string"&&/\[Request interrupted by user/i.test(k)&&g(v,`${be(b.uuid)??f}:interrupt`,{kind:"waiting_for_user",reason:"idle"})}for(const[y,b]of n){s.push({code:"unpaired_result",detail:`tool_use ${y} (${b.name}) has no result`});const w=qc({name:b.name,input:b.input,isError:!0},m());w.warning&&s.push(w.warning),w.bodies.forEach((v,S)=>g(b.ts,S===0?y:`${y}:${S}`,v,b.agentId?{agentId:b.agentId}:{}))}for(const[y,b]of o)g(u,`${b}:stop`,{kind:"subagent_stop",childId:y,ok:!0},{parentId:b});for(const y of i)s.push({code:"unknown_row_type",detail:y});return Number.isFinite(c)&&!p&&(p=!0,g(u,`${a||"session"}:end`,{kind:"session_end",reason:"stop",claimedSuccess:Kc(d)})),{events:t,warnings:s}}function ko(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function ar(r){let e=r>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}var Wx=/(^|\/)(schema\.(sql|prisma|graphql|gql)|.*\.(sql|prisma|db|sqlite)|migrations?\/|drizzle\/|models?\/.*\.(ts|js|py|rb)$)/i,$x=/(^|\/)(node_modules|\.git|dist|build|out|coverage|_site|\.next|\.turbo|target|vendor|__pycache__|\.venv|venv)(\/|$)|(^|\/)\.[^/]+$|\.(lock|map|min\.js|png|jpg|jpeg|gif|webp|svg|ico|woff2?|ttf|mp4|mp3|pdf|zip)$/i;function Vx(r){return $x.test(r)}function mg(r){return fg(r)?"beacon":Wx.test(r)?"archive":"building"}function Zc(r){return typeof r.loc=="number"?r.loc:typeof r.size=="number"?Math.max(1,Math.round(r.size/40)):1}function Xx(r,e){const t=r.filter(n=>!Vx(n.path)),s=Math.max(1,...t.map(Zc)),i=Math.max(1,...t.map(n=>n.churn??0));return t.map(n=>{const o=Zc(n),a=e.has(n.path),l=.5*Math.sqrt(o/s)+.3*((n.churn??0)/i)+(a?.2:0);return{file:n,loc:o,score:l,kind:mg(n.path),touched:a}})}function Qc(r,e){const t=Math.sqrt(r/Math.max(1,e));return Math.max(1,Math.min(5,Math.ceil(t*5)))}function Jc(r){return r>=5?3:r>=3?2:1}var jx={ts:"TypeScript",tsx:"TypeScript",js:"JavaScript",jsx:"JavaScript",mjs:"JavaScript",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",swift:"Swift",rb:"Ruby",php:"PHP",cs:"C#",cpp:"C++",cc:"C++",c:"C",h:"C",m:"Objective-C",scala:"Scala",ex:"Elixir",exs:"Elixir",dart:"Dart",lua:"Lua",zig:"Zig",sh:"Shell",sql:"SQL",md:"Markdown",mdx:"Markdown",html:"HTML",css:"CSS",scss:"CSS",vue:"Vue",svelte:"Svelte",tf:"Terraform",yaml:"YAML",yml:"YAML",ipynb:"Notebook"};function qx(r,e={}){const t=r.map(p=>p.path.toLowerCase()),s=p=>t.some(m=>p.test(m)),i=p=>t.filter(m=>p.test(m)).length,n=new Map;for(const p of t){const m=p.slice(p.lastIndexOf(".")+1),g=jx[m];g&&!/^(markdown|yaml|html|css|shell|sql)$/i.test(g)&&n.set(g,(n.get(g)??0)+1)}const o=[...n.entries()].sort((p,m)=>m[1]-p[1]).map(([p])=>p).slice(0,4),a=(e["package.json"]??"").toLowerCase(),l=((e["pyproject.toml"]??"")+(e["requirements.txt"]??"")).toLowerCase(),h=p=>p.test(a)||p.test(l),c=new Map,u=(p,m)=>c.set(p,(c.get(p)??0)+m);h(/"(react|react-dom|next|vue|nuxt|svelte|@sveltejs\/kit|@angular\/core|solid-js|astro|remix|vite)"/)&&u("web-frontend",3),i(/\.(tsx|jsx|vue|svelte)$/)>3&&u("web-frontend",2),(s(/(^|\/)(index|app)\.html$/)||i(/\.(css|scss)$/)>3)&&u("web-frontend",1),h(/"(express|fastify|hono|koa|@nestjs\/core|apollo-server|prisma|drizzle-orm|django|flask|fastapi|sqlalchemy|gin|fiber|actix|axum|rails|spring)"/)&&u("backend-api",3),(s(/(^|\/)(routes?|controllers?|api|handlers?|migrations?)\//)||s(/\.(sql|prisma)$/))&&u("backend-api",2),(a.includes('"bin"')||s(/(^|\/)(cli|cmd|bin)\//)||h(/"(commander|yargs|clap|cobra|click|typer)"/))&&u("cli-tool",3),(h(/"(torch|tensorflow|jax|pandas|numpy|scikit-learn|sklearn|transformers|xgboost|lightgbm|polars)"/)||i(/\.ipynb$/)>0||s(/(^|\/)(notebooks?|models?|datasets?|training)\//))&&u("data-ml",3),(s(/\.(swift|kt)$/)||s(/(^|\/)(ios|android)\//)||s(/package\.swift$/)||s(/build\.gradle(\.kts)?$/)||h(/"(react-native|expo|flutter)"/)||s(/\.dart$/))&&u("mobile",3),(s(/\.(unity|unitypackage|godot|tscn|gd)$/)||s(/(^|\/)assets\/.*\.(prefab|fbx)$/)||h(/"(phaser|pixi\.js|three|babylonjs|@react-three\/fiber|excalibur|kaplay|bevy|godot)"/))&&u("game",3),(s(/\.tf$/)||s(/(^|\/)(dockerfile|docker-compose\.ya?ml|helm|k8s|kubernetes|\.github\/workflows|ansible|pulumi)/))&&u("infra-devops",s(/\.tf$/)||s(/(^|\/)(helm|k8s|kubernetes|ansible|pulumi)\//)?3:1);const d=i(/\.(md|mdx|rst)$/)/Math.max(1,t.length);(d>.4||s(/(^|\/)(mkdocs|docusaurus)\.config|(^|\/)docs\/.*\.mdx?$/)&&d>.25)&&u("docs-content",3),(s(/(^|\/)pnpm-workspace\.ya?ml$/)||s(/(^|\/)packages\/[^/]+\/package\.json$/)||s(/(^|\/)(lerna|nx|turbo)\.json$/)||s(/(^|\/)cargo\.toml$/)&&i(/(^|\/)crates\/[^/]+\//)>0)&&u("monorepo",2),i(/\.(rs|go|c|cpp|cc|h|zig)$/)>5&&!c.has("web-frontend")&&u("systems",2),a.includes('"main"')&&!a.includes('"bin"')&&!c.has("web-frontend")&&!c.has("backend-api")&&u("library",2),s(/(^|\/)(lib|src\/lib)\//)&&!c.has("web-frontend")&&u("library",1);const f=[...c.entries()].filter(([,p])=>p>=2).sort((p,m)=>m[1]-p[1]).map(([p])=>p);return{kinds:f.length?f:["unknown"],languages:o,files:r.length}}function Yx(r){const e=r.cap??60,t=r.beaconCap??8,s=r.touchedCap??48,i=new Set((r.touched??[]).map(eu).slice(0,s)),n=ko(r.repoId),o=ar(n),a=r.files.map(M=>({...M,path:eu(M.path)})),l=Xx(a,i),h=Math.max(1,...l.map(M=>M.loc)),c=[...l].sort((M,G)=>G.score-M.score||M.file.path.localeCompare(G.file.path)),u=ru(c.filter(M=>M.kind==="beacon"),t),d=ru(c.filter(M=>M.kind!=="beacon"),e),f=[...d,...u],p=f.length<l.length,m=new Map;for(const M of d){const G=Pn(M.file.path);(m.get(G)??m.set(G,[]).get(G)).push(M)}const g=[...m.keys()].sort(),_=new Set,x=[],y=[],b={id:"forge",kind:"forge",path:"",label:"forge",district:"",gx:-1,gy:-1,footprint:2,height:2,score:0,touched:!1};x.push(b);const w=r.layout??br[n%br.length],v=o()*Math.PI*2,S=g.map(M=>{const G=m.get(M).sort((W,se)=>se.score-W.score||W.file.path.localeCompare(se.file.path)),B=G.reduce((W,se)=>W+Jc(Qc(se.loc,h))**2,0),U=Math.max(3,Math.ceil(Math.sqrt(B*1.45)));return{name:M,items:G,side:U}}),E=[],k={x:-2,y:-2,w:4,h:4},P=bg(w,S.map(M=>M.side),k,v,o);E.push(k,...P);const T=vg(w,P);b.gx=T[0],b.gy=T[1],_.clear(),vt(_,b),S.forEach((M,G)=>{const B=P[G],U={id:`d:${M.name}`,label:M.name===""?"/":`${M.name}/`,bounds:B,cx:B.x+Math.floor(B.w/2),cy:B.y+Math.floor(B.h/2),placeIds:[]};for(const W of M.items){const se=Qc(W.loc,h),te=Jc(se),ie=Po(_,U.cx,U.cy,te,B),$={id:`p:${W.file.path}`,kind:W.kind,path:W.file.path,label:tu(W.file.path),district:U.id,gx:ie[0],gy:ie[1],footprint:te,height:se,score:su(W.score),touched:W.touched};vt(_,$),x.push($),U.placeIds.push($.id)}y.push(U)}),Math.ceil(yg(E));for(const M of E)for(let G=M.x-1;G<M.x+M.w+1;G++)for(let B=M.y-1;B<M.y+M.h+1;B++)_.add(`${G},${B}`);for(const M of u){const G=y.find(W=>W.id===`d:${Pn(M.file.path)}`),B=G?Tg(_,G,b,1):vr(_,b.gx+1,b.gy+1,o()*Math.PI*2,4,1),U={id:`p:${M.file.path}`,kind:"beacon",path:M.file.path,label:tu(M.file.path),district:G?.id??"",gx:B[0],gy:B[1],footprint:1,height:4,score:su(M.score),touched:M.touched};vt(_,U),x.push(U),G?.placeIds.push(U.id)}const A=vr(_,b.gx+1,b.gy+1,v+Math.PI,5,2),I={id:"dock",kind:"dock",path:"",label:"dock",district:"",gx:A[0],gy:A[1],footprint:2,height:1,score:0,touched:!1};vt(_,I),x.push(I);const F=wg(w,y,b,I);if(p)for(const M of y){const G=M.id.slice(2),B=l.filter(se=>se.kind!=="beacon"&&Pn(se.file.path)===G).length;if(B<=M.placeIds.length)continue;const U=Po(_,M.cx,M.cy,1,M.bounds),W={id:`p:${G?G+"/":""}…`,kind:"overflow",path:`${G?G+"/":""}…`,label:`+${B-M.placeIds.length} more`,district:M.id,gx:U[0],gy:U[1],footprint:1,height:2,score:0,touched:!1};vt(_,W),x.push(W),M.placeIds.push(W.id)}const X=xg(x,2),R=qx(a,r.manifests??{});return{repoId:r.repoId,seed:n,layout:w,profile:R,districts:y,places:x,paths:F,bounds:X,stats:{files:l.length,placed:f.length,capped:p}}}var eu=r=>r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,""),tu=r=>r.slice(r.lastIndexOf("/")+1),Pn=r=>r.includes("/")?r.slice(0,r.indexOf("/")):"",su=r=>Math.round(r*1e3)/1e3;function ru(r,e){const t=r.filter(i=>i.touched),s=r.filter(i=>!i.touched);return[...t,...s.slice(0,Math.max(0,e-t.length))]}function iu(r,e,t){return r.x<e.x+e.w+t&&e.x<r.x+r.w+t&&r.y<e.y+e.h+t&&e.y<r.y+r.h+t}function gg(r,e,t){const s=[];for(let i=0;i<t;i++)for(let n=0;n<t;n++)s.push(`${r+i},${e+n}`);return s}function _g(r,e,t,s){return gg(e,t,s).every(i=>!r.has(i))}function vt(r,e){for(const t of gg(e.gx,e.gy,e.footprint))r.add(t)}function Po(r,e,t,s,i){let n=0,o=0,a=0,l=-1,h=null;for(let c=0;c<4096;c++){const u=e+n-Math.floor(s/2),d=t+o-Math.floor(s/2);if(_g(r,u,d,s)){if(u>=i.x-1&&d>=i.y-1&&u+s<=i.x+i.w+1&&d+s<=i.y+i.h+1)return[u,d];if(h??=[u,d],c>600)return h}(n===o||n<0&&n===-o||n>0&&n===1-o)&&([a,l]=[-l,a]),n+=a,o+=l}return h??[e,t]}function yg(r){return Math.max(...r.map(e=>Math.max(Math.abs(e.x),Math.abs(e.x+e.w),Math.abs(e.y),Math.abs(e.y+e.h))))}function xg(r,e){const t=r.flatMap(o=>[o.gx,o.gx+o.footprint]),s=r.flatMap(o=>[o.gy,o.gy+o.footprint]),i=Math.min(...t)-e,n=Math.min(...s)-e;return{x:i,y:n,w:Math.max(...t)+e-i,h:Math.max(...s)+e-n}}var br=["ring","grid","strip","scatter","terrace","spine"];function bg(r,e,t,s,i){const n=e.length,o=[],a=Math.max(3,...e),l=c=>!iu(t,c,1)&&!o.some(u=>iu(u,c,1)),h=(c,u,d)=>{const f={x:c,y:u,w:d,h:d};return o.push(f),f};switch(r){case"grid":{const c=Math.max(2,Math.ceil(Math.sqrt(n+1))),u=[];let d=0,f=0;for(;f<n;){const g=e.slice(f,f+c),_=Math.max(...g)+2;let x=0;for(const y of g)u.push({x,y:d}),x+=y+2;d+=_,f+=c}const p=Math.max(...u.map((g,_)=>g.x+e[_])),m=d;for(let g=0;g<n;g++){let _={x:u[g].x-Math.round(p/2),y:u[g].y-Math.round(m/2),w:e[g],h:e[g]};for(;!l(_);)_={..._,x:_.x+1};o.push(_)}return o}case"strip":{const c=e.reduce((d,f)=>d+f+2,0);let u=Math.round(-c/2)+6;for(let d=0;d<n;d++){const f=Math.round((i()-.5)*3);h(u,f-Math.floor(e[d]/2),e[d]),u+=e[d]+2}return o}case"terrace":{let c=-Math.round(n*(a+1)/2),u=-Math.round(n*(a+1)*.3);for(let d=0;d<n;d++)h(c,u,e[d]),c+=e[d]+1,u+=Math.round(e[d]*.6)+1;return o}case"spine":{let c=-Math.round(n*(a+2)/4);for(let u=0;u<n;u++){const d=u%2===0;h(d?-e[u]-3:3,c,e[u]),d||(c+=a+2)}return o}case"scatter":{for(let c=0;c<n;c++){let u=5+a,d=!1;for(let f=0;f<400&&!d;f++){const p=s+i()*Math.PI*2,m=u*(.5+i()*.7),g={x:Math.round(Math.cos(p)*m),y:Math.round(Math.sin(p)*m*.8),w:e[c],h:e[c]};l(g)&&(o.push(g),d=!0),f%40===39&&(u+=2)}d||h(u+c*2,0,e[c])}return o}default:{let c=3;for(let u=0;u<n;u++){const d=e[u],f=s+u/Math.max(1,n)*Math.PI*2;let p=c+d/2,m;for(;;){const g=Math.round(Math.cos(f)*p),_=Math.round(Math.sin(f)*p*.8);if(m={x:g-Math.floor(d/2),y:_-Math.floor(d/2),w:d,h:d},l(m))break;p+=1}o.push(m),c=Math.max(c,p-d/2)}return o}}}function vg(r,e){if(!e.length)return[-1,-1];const t=Math.min(...e.map(i=>i.x)),s=Math.min(...e.map(i=>i.y));switch(r){case"strip":return[t-5,-1];case"terrace":return[t-5,s-1];case"spine":return[-1,s-5];default:return[-1,-1]}}function wg(r,e,t,s){const i=[t.gx+1,t.gy+1],n=[];if(r==="strip"||r==="terrace"){const o=[...e].sort((h,c)=>h.cx-c.cx||h.cy-c.cy);let a=i,l="forge";for(const h of o)n.push({from:l,to:h.id,points:[a,[h.cx,h.cy]]}),a=[h.cx,h.cy],l=h.id}else if(r==="grid"||r==="spine")for(const o of e)n.push({from:o.id,to:"forge",points:[[o.cx,o.cy],[o.cx,i[1]],i]});else for(const o of e)n.push({from:o.id,to:"forge",points:[[o.cx,o.cy],[Math.round((o.cx+i[0])/2),Math.round((o.cy+i[1])/2)],i]});return n.push({from:"dock",to:"forge",points:[[s.gx,s.gy],i]}),n}function Kx(r,e){if(r.layout===e)return r;const t=r.seed,s=ar(t^1374496523^br.indexOf(e)),i=new Set,n=[],o={...r.places.find(x=>x.kind==="forge"),gx:-1,gy:-1};n.push(o);const a=s()*Math.PI*2,h=r.districts.map(x=>({d:x,items:r.places.filter(y=>y.district===x.id&&(y.kind==="building"||y.kind==="archive"||y.kind==="overflow")).sort((y,b)=>b.score-y.score||y.path.localeCompare(b.path))})).map(x=>{const y=x.items.reduce((b,w)=>b+w.footprint**2,0);return{...x,side:Math.max(3,Math.ceil(Math.sqrt(y*1.45)))}}),c={x:-2,y:-2,w:4,h:4},u=bg(e,h.map(x=>x.side),c,a,s),d=[c,...u],f=vg(e,u);o.gx=f[0],o.gy=f[1],vt(i,o);const p=h.map((x,y)=>{const b=u[y],w={...x.d,bounds:b,cx:b.x+Math.floor(b.w/2),cy:b.y+Math.floor(b.h/2),placeIds:[]};for(const v of x.items){const S=Po(i,w.cx,w.cy,v.footprint,b),E={...v,gx:S[0],gy:S[1]};vt(i,E),n.push(E),w.placeIds.push(E.id)}return w});Math.ceil(yg(d));for(const x of d)for(let y=x.x-1;y<x.x+x.w+1;y++)for(let b=x.y-1;b<x.y+x.h+1;b++)i.add(`${y},${b}`);for(const x of r.places.filter(y=>y.kind==="beacon")){const y=p.find(v=>v.id===x.district),b=y?Tg(i,y,o,1):vr(i,o.gx+1,o.gy+1,s()*Math.PI*2,4,1),w={...x,gx:b[0],gy:b[1]};vt(i,w),n.push(w),y?.placeIds.push(w.id)}const m=vr(i,o.gx+1,o.gy+1,a+Math.PI,5,2),g={...r.places.find(x=>x.kind==="dock"),gx:m[0],gy:m[1]};vt(i,g),n.push(g);const _=wg(e,p,o,g);return{...r,layout:e,districts:p,places:n,paths:_,bounds:xg(n,2)}}function vr(r,e,t,s,i,n){for(let o=i;o<i+40;o++)for(let a=0;a<64;a++){const l=s+(a%2?1:-1)*Math.ceil(a/2)*(Math.PI/32),h=Math.round(e+Math.cos(l)*o),c=Math.round(t+Math.sin(l)*o*.85);if(_g(r,h,c,n))return[h,c]}return[e+i,t]}function Tg(r,e,t,s){const i=Math.atan2(e.cy-t.gy,e.cx-t.gx),n=Math.ceil(Math.max(e.bounds.w,e.bounds.h)/2)+2;return vr(r,e.cx,e.cy,i,n,s)}var Zx=class{constructor(r){this.windowMs=r}windowMs;mood="curious";trouble=[];recordTrouble(r){return this.trouble=this.trouble.filter(e=>r-e<=this.windowMs),this.trouble.push(r),this.trouble.length>=2}onRead(){return this.mood=this.mood==="lost"?"lost":"curious"}onBuild(){return this.mood=this.mood==="lost"?"lost":"focused"}onFail(r){return this.mood=this.recordTrouble(r)?"lost":"uneasy"}onError(r){return this.mood=this.recordTrouble(r)?"lost":"uneasy"}onPass(){return this.trouble=[],this.mood="happy"}onClaimUnverified(){return this.mood="uneasy"}},Qx=class{constructor(r,e={}){this.world=r;for(const t of r.places)this.places.set(t.id,t),t.path&&this.byPath.set(t.path,t);this.beacons=r.places.filter(t=>t.kind==="beacon"),this.forge=r.places.find(t=>t.kind==="forge")??r.places[0],this.dock=r.places.find(t=>t.kind==="dock")??this.forge,this.maxGap=e.maxGapMs??2500,this.msPerCell=e.walkMsPerCell??90,this.mood=new Zx(e.lostWindowMs??9e4),this.actorAt.set("pip",this.forge.id)}world;places=new Map;byPath=new Map;beacons;forge;dock;maxGap;msPerCell;mood;beats=[];sceneMs=0;lastRealTs=null;seq=0;actorAt=new Map;helpers=new Map;gremlins=new Map;lastEdited=null;pendingBeacon=null;editedSinceTurn=!1;verifiedSinceEdit=!1;everVerified=!1;claimGremlin=null;get timeline(){return this.beats}feed(r){const e=this.beats.length;this.advanceClock(r.ts,r.id);const t=r.agentId&&this.helpers.has(r.agentId)?r.agentId:"pip";switch(r.kind){case"session_start":this.emit(r,t,{kind:"curtain_up",repoId:r.repoId},1200);break;case"read_file":{const s=this.placeFor(r.path,r,t);this.walk(r,t,s),this.emit(r,t,{kind:"read",target:s.id},_s(700+(r.bytes??400)/4,900,1800),this.mood.onRead());break}case"edit_file":case"write_file":{const s=this.placeFor(r.path,r,t);this.walk(r,t,s);const i=r.kind==="edit_file"?r.added+r.removed:r.added,n=_s(Math.sqrt(i/50),.15,1),o=[...this.gremlins].find(([,a])=>a===s.id);o&&this.emit(r,t,{kind:"chase",gremlinId:o[0],target:s.id},900,this.mood.mood),r.kind==="write_file"&&r.created&&this.emit(r,t,{kind:"raise",target:s.id},900,this.mood.onBuild()),this.emit(r,t,{kind:"build",target:s.id,intensity:n},_s(600+n*1900,800,2500),this.mood.onBuild()),this.lastEdited=s,this.editedSinceTurn=!0,this.verifiedSinceEdit=!1;break}case"run_command":{if(r.intent==="test"){const s=this.beaconFor(r.touched);this.walk(r,t,s),this.pendingBeacon=s,this.emit(r,t,{kind:"run_tests",target:s.id},_s(r.durationMs??1200,900,3e3),this.mood.mood)}else if(r.intent==="search")this.emit(r,t,{kind:"search",scope:"repo"},700,this.mood.onRead());else if(r.touched.length===0||r.intent==="git"||r.intent==="install"||r.intent==="build"){this.walk(r,t,this.forge);const s=r.intent==="build"||r.intent==="install"?.8:r.intent==="git"?.4:.5;this.emit(r,t,{kind:"forge",intensity:s},_s(r.durationMs??800,700,2e3),this.mood.mood)}!r.ok&&r.intent!=="test"&&this.emit(r,t,{kind:"stumble",retrying:!1},600,this.mood.onError(r.ts));break}case"test_result":{const s=this.pendingBeacon??this.beaconFor([]);this.pendingBeacon=null;const i=(r.framework==="unknown"&&r.passed===0&&r.failed===0,r.ok?"pass":"fail");if(i==="pass"){this.emit(r,t,{kind:"test_outcome",target:s.id,outcome:i,passed:r.passed,failed:r.failed},800,this.mood.onPass()),(r.passed>0||r.framework==="unknown")&&(this.verifiedSinceEdit=!0,this.everVerified=!0);for(const[n]of this.gremlins)this.emit(r,t,{kind:"banish",gremlinId:n},700,"happy");this.gremlins.clear(),this.claimGremlin&&(this.emit(r,t,{kind:"banish",gremlinId:this.claimGremlin},700,"happy"),this.claimGremlin=null),this.emit(r,t,{kind:"celebrate",target:s.id},1600,"happy")}else{this.emit(r,t,{kind:"test_outcome",target:s.id,outcome:i,passed:r.passed,failed:r.failed},800,this.mood.onFail(r.ts));const n=this.lastEdited??s,o=`g:${r.id}`;this.gremlins.set(o,n.id),this.emit(r,t,{kind:"spawn_gremlin",gremlinId:o,target:n.id},900,this.mood.mood)}break}case"search":this.emit(r,t,{kind:"search",scope:r.scope},700,this.mood.onRead());break;case"subagent_start":this.helpers.set(r.childId,r.label?{label:r.label}:{}),this.actorAt.set(r.childId,this.dock.id),this.emit(r,"pip",{kind:"summon_helper",helperId:r.childId,...r.label?{label:r.label}:{}},1400,this.mood.mood);break;case"subagent_stop":this.helpers.has(r.childId)&&(this.emit(r,r.childId,{kind:"dismiss_helper",helperId:r.childId,ok:r.ok},1e3,this.mood.mood),this.helpers.delete(r.childId),this.actorAt.delete(r.childId));break;case"waiting_for_user":r.reason==="idle"?this.emit(r,t,{kind:"your_turn"},1e3,this.mood.mood):this.emit(r,t,{kind:"blocked_on_you",reason:r.reason},1200,this.mood.mood);break;case"error":this.emit(r,t,{kind:"stumble",retrying:r.retrying},700,this.mood.onError(r.ts));break;case"turn_end":{if(r.claimedSuccess&&this.editedSinceTurn&&!this.verifiedSinceEdit){const s=`claim:${r.id}`;this.claimGremlin=s,this.emit(r,t,{kind:"unverified_claim",gremlinId:s},1400,this.mood.onClaimUnverified())}this.editedSinceTurn=!1,this.emit(r,t,{kind:"your_turn"},1e3,this.mood.mood);break}case"session_end":this.emit(r,t,{kind:"curtain_down",verified:this.everVerified&&!this.claimGremlin},1500,this.mood.mood);break}return this.beats.slice(e)}advanceClock(r,e){if(this.lastRealTs!==null){const t=this.beats.length?Math.max(...this.beats.slice(-3).map(n=>n.atMs+n.durationMs)):this.sceneMs,s=Math.min(Math.max(0,r-this.lastRealTs),this.maxGap),i=Math.max(t,this.sceneMs)+s;if(i-t>=1e3){const n={id:`b${this.seq++}`,atMs:t,durationMs:i-t,realTs:this.lastRealTs,mood:this.mood.mood,actor:"pip",sourceEventIds:[e],kind:"idle"};this.beats.push(n)}this.sceneMs=Math.max(this.sceneMs,i)}this.lastRealTs=r}emit(r,e,t,s,i=this.mood.mood){s=Math.round(s),"intensity"in t&&(t={...t,intensity:Math.round(t.intensity*1e3)/1e3});const n={id:`b${this.seq++}`,atMs:Math.round(this.sceneMs),durationMs:s,realTs:r.ts,mood:i,actor:e,sourceEventIds:[r.id],...t};return this.beats.push(n),this.sceneMs+=s,n}walk(r,e,t){const s=this.actorAt.get(e)??this.forge.id;if(s===t.id)return;const i=this.places.get(s)??this.forge,n=Math.hypot(t.gx-i.gx,t.gy-i.gy);this.emit(r,e,{kind:"walk_to",target:t.id},_s(Math.round(n*this.msPerCell),300,2500)),this.actorAt.set(e,t.id)}raised=0;placeFor(r,e,t){const s=this.byPath.get(r);if(s)return s;const i=r.includes("/")?r.slice(0,r.indexOf("/")):"",n=this.byPath.get(`${i?i+"/":""}…`);if(n&&(this.raised>=24||this.world.stats.capped))return n;if(this.raised>=24)return n??this.forge;this.raised++;const o=this.world.districts.find(h=>h.id===`d:${i}`)??this.world.districts[0],a=o?{gx:o.cx,gy:o.cy}:{gx:this.forge.gx+3,gy:this.forge.gy},l={id:`p:${r}`,kind:mg(r),path:r,label:r.slice(r.lastIndexOf("/")+1),district:o?.id??"",gx:a.gx,gy:a.gy,footprint:1,height:1,score:0,touched:!0};return this.places.set(l.id,l),this.byPath.set(r,l),l.kind==="beacon"&&this.beacons.push(l),this.emit(e,t,{kind:"raise",target:l.id,newPlace:{path:r,label:l.label,kind:l.kind,district:l.district}},900),l}beaconFor(r){const e=r.find(t=>fg(t));if(e){const t=this.byPath.get(e);if(t)return t}if(this.lastEdited){const t=this.beacons.find(s=>s.district===this.lastEdited.district);if(t)return t}return this.beacons[0]??this.forge}};function Jr(r,e,t){const s=new Qx(e,t);for(const i of r)s.feed(i);return[...s.timeline]}var _s=(r,e,t)=>Math.min(t,Math.max(e,r));function Jx(r){const e=new Map,t=(i,n)=>e.set(i,(e.get(i)??0)+n);for(const i of r)if(i.kind==="read_file")t(i.path,Math.max(5,Math.round((i.bytes??400)/40)));else if(i.kind==="edit_file")t(i.path,Math.max(5,(i.added+i.removed)*3));else if(i.kind==="write_file")t(i.path,Math.max(5,i.added*2));else if(i.kind==="run_command")for(const n of i.touched)t(n,5);const s=[...e.keys()].sort((i,n)=>e.get(n)-e.get(i));return{files:s.map(i=>({path:i,loc:e.get(i)})),touched:s}}class eb{ctx=null;master=null;sfxBus=null;ambBus=null;duck=0;_muted=!1;_volume=.6;_ambience=!0;get ambienceEnabled(){return this._ambience}setAmbienceEnabled(e){this._ambience=e,this.ambBus&&this.ctx&&this.ambBus.gain.setTargetAtTime(e?.35:0,this.ctx.currentTime,.1)}noiseBuf=null;get ready(){return!!this.ctx&&this.ctx.state==="running"}get muted(){return this._muted}get volume(){return this._volume}async arm(){if(!this.ctx){const e=globalThis.AudioContext??globalThis.webkitAudioContext;if(!e)return;this.ctx=new e,this.master=this.ctx.createGain(),this.sfxBus=this.ctx.createGain(),this.ambBus=this.ctx.createGain(),this.sfxBus.connect(this.master),this.ambBus.connect(this.master),this.master.connect(this.ctx.destination),this.ambBus.gain.value=this._ambience?.35:0,this.applyGain();const t=this.ctx.sampleRate*2;this.noiseBuf=this.ctx.createBuffer(1,t,this.ctx.sampleRate);const s=this.noiseBuf.getChannelData(0);for(let i=0;i<t;i++)s[i]=Math.random()*2-1}this.ctx.state==="suspended"&&await this.ctx.resume()}setMuted(e){this._muted=e,this.applyGain()}setVolume(e){this._volume=Math.max(0,Math.min(1,e)),this.applyGain()}applyGain(){this.master&&this.master.gain.setTargetAtTime(this._muted?0:this._volume,this.ctx.currentTime,.02)}duckAmbience(e=.5,t=350){if(!this.ambBus||!this.ctx)return;const s=this.ctx.currentTime;this.ambBus.gain.cancelScheduledValues(s),this._ambience&&(this.ambBus.gain.setTargetAtTime(.35*(1-e),s,.01),this.ambBus.gain.setTargetAtTime(.35,s+t/1e3,.12),this.duck++)}tone(e,t,s={}){if(!this.ready||!this.ctx||!this.sfxBus)return;const i=this.ctx,n=i.currentTime,o=i.createOscillator();o.type=s.type??"sine",o.frequency.setValueAtTime(e,n),s.detune&&(o.detune.value=s.detune),s.slideTo&&o.frequency.exponentialRampToValueAtTime(Math.max(20,s.slideTo),n+t);const a=i.createGain(),l=s.attack??.005,h=s.decay??t;a.gain.setValueAtTime(1e-4,n),a.gain.exponentialRampToValueAtTime(s.gain??.25,n+l),a.gain.exponentialRampToValueAtTime(1e-4,n+l+h);let c=o;if(s.lowpass){const d=i.createBiquadFilter();d.type="lowpass",d.frequency.value=s.lowpass,o.connect(d),c=d}const u=i.createStereoPanner();u.pan.value=s.pan??0,c.connect(a),a.connect(u),u.connect(this.sfxBus),o.start(n),o.stop(n+l+h+.05),this.duckAmbience(.35,(l+h)*1e3)}noise(e,t={}){if(!this.ready||!this.ctx||!this.sfxBus||!this.noiseBuf)return;const s=this.ctx,i=s.currentTime,n=s.createBufferSource();n.buffer=this.noiseBuf,n.loop=!0;const o=s.createBiquadFilter();o.type=t.filter??"bandpass",o.frequency.setValueAtTime(t.freq??1200,i),o.Q.value=t.q??.8,t.sweepTo&&o.frequency.exponentialRampToValueAtTime(Math.max(40,t.sweepTo),i+e);const a=s.createGain(),l=t.attack??.004;a.gain.setValueAtTime(1e-4,i),a.gain.exponentialRampToValueAtTime(t.gain??.12,i+l),a.gain.exponentialRampToValueAtTime(1e-4,i+e);const h=s.createStereoPanner();h.pan.value=t.pan??0,n.connect(o),o.connect(a),a.connect(h),h.connect(this.sfxBus),n.start(i),n.stop(i+e+.05)}pad(e,t,s="sine"){if(!this.ready||!this.ctx||!this.ambBus)return()=>{};const i=this.ctx,n=i.currentTime,o=[],a=i.createGain();a.gain.setValueAtTime(1e-4,n),a.gain.exponentialRampToValueAtTime(t,n+1.5),a.connect(this.ambBus);for(const l of e){const h=i.createOscillator();h.type=s,h.frequency.value=l,h.detune.value=(Math.random()-.5)*6,h.connect(a),h.start(n),o.push(h)}return()=>{const l=i.currentTime;a.gain.cancelScheduledValues(l),a.gain.setTargetAtTime(1e-4,l,.4);for(const h of o)h.stop(l+2)}}wash(e,t,s,i=.12,n=.5){if(!this.ready||!this.ctx||!this.ambBus||!this.noiseBuf)return()=>{};const o=this.ctx,a=o.currentTime,l=o.createBufferSource();l.buffer=this.noiseBuf,l.loop=!0;const h=o.createBiquadFilter();h.type="lowpass",h.frequency.value=e,h.Q.value=t;const c=o.createGain();c.gain.setValueAtTime(1e-4,a),c.gain.exponentialRampToValueAtTime(s,a+2);const u=o.createOscillator();u.frequency.value=i;const d=o.createGain();return d.gain.value=s*n,u.connect(d),d.connect(c.gain),l.connect(h),h.connect(c),c.connect(this.ambBus),l.start(a),u.start(a),()=>{const f=o.currentTime;c.gain.setTargetAtTime(1e-4,f,.5),l.stop(f+2.5),u.stop(f+2.5)}}now(){return this.ctx?.currentTime??0}extra(e,t=(Math.random()-.5)*1.2){if(!this.ready||!this.ctx||!this.ambBus)return;const s=this.ctx,i=s.currentTime,n=(a,l,h,c,u,d=.01)=>{const f=s.createOscillator();f.type=a,f.frequency.setValueAtTime(l,i),f.frequency.exponentialRampToValueAtTime(Math.max(20,h),i+c);const p=s.createGain();p.gain.setValueAtTime(1e-4,i),p.gain.exponentialRampToValueAtTime(u,i+d),p.gain.exponentialRampToValueAtTime(1e-4,i+c);const m=s.createStereoPanner();m.pan.value=t,f.connect(p),p.connect(m),m.connect(this.ambBus),f.start(i),f.stop(i+c+.05)},o=(a,l,h,c,u,d="bandpass")=>{if(!this.noiseBuf)return;const f=s.createBufferSource();f.buffer=this.noiseBuf,f.loop=!0;const p=s.createBiquadFilter();p.type=d,p.frequency.setValueAtTime(a,i),u&&p.frequency.exponentialRampToValueAtTime(u,i+h),p.Q.value=l;const m=s.createGain();m.gain.setValueAtTime(1e-4,i),m.gain.exponentialRampToValueAtTime(c,i+.05),m.gain.exponentialRampToValueAtTime(1e-4,i+h);const g=s.createStereoPanner();g.pan.value=t,f.connect(p),p.connect(m),m.connect(g),g.connect(this.ambBus),f.start(i),f.stop(i+h+.05)};switch(e){case"gull":n("sine",1800,1100,.35,.05,.03),setTimeout(()=>n("sine",1700,1250,.3,.04,.03),260);return;case"cricket":for(let a=0;a<6;a++)setTimeout(()=>n("sine",4200,4100,.04,.02),a*70);return;case"bell":n("sine",880,870,2.2,.06,.005),n("sine",1760,1740,1.4,.03,.005),n("sine",2640,2600,.8,.015,.005);return;case"bubble":n("sine",300+Math.random()*300,900+Math.random()*600,.18,.04,.01);return;case"wind":o(500+Math.random()*400,.5,2.5+Math.random()*2,.05,300+Math.random()*300);return;case"horn":n("sawtooth",180,176,.8,.03,.08);return;case"hum":n("sine",60,60,2.5,.03,.4);return;case"chime":n("sine",1318.5,1316,1.2,.035,.005);return;case"owl":n("sine",420,380,.5,.04,.05),setTimeout(()=>n("sine",400,360,.6,.035,.05),420);return;case"rumble":o(90,1.2,2.5,.09,60,"lowpass");return;case"drip":n("sine",1200,600,.12,.04,.003);return;case"market":for(let a=0;a<4;a++)setTimeout(()=>o(600+Math.random()*1200,2,.12,.02),a*120);return}}}const tb=r=>1-Math.pow(1-r,3),An=r=>sb(.4,0,.2,1,r),nu=r=>1+(1.70158+1)*Math.pow(r-1,3)+1.70158*Math.pow(r-1,2),tt=r=>Math.sin(Math.PI*Math.min(1,Math.max(0,r)));function sb(r,e,t,s,i){const n=3*r,o=3*(t-r)-n,a=1-n-o,l=3*e,h=3*(s-e)-l,c=1-l-h,u=m=>((a*m+o)*m+n)*m,d=m=>((c*m+h)*m+l)*m,f=m=>(3*a*m+2*o)*m+n;let p=i;for(let m=0;m<6;m++){const g=f(p);if(Math.abs(g)<1e-6)break;p-=(u(p)-i)/g}return d(Math.min(1,Math.max(0,p)))}const rb=64,Ao=32,K=(r,e)=>({x:(r-e)*rb/2,y:(r+e)*Ao/2}),D=(r,e)=>({x:r.x,y:r.y-e}),Jt=(r,e,t)=>r+(e-r)*t,Be=(r,e,t)=>({x:Jt(r.x,e.x,t),y:Jt(r.y,e.y,t)}),ib=(r,e,t)=>r<e?e:r>t?t:r,Ue=(r,e,t)=>ib((r-e)/(t-e),0,1),ou=(r,e,t=1)=>r+e+t;function De(r,e,t,s=0){return[K(r,e),K(r+t,e),K(r+t,e+t),K(r,e+t)].map(i=>D(i,s))}const V=r=>r.flatMap(e=>[e.x,e.y]);class nb{constructor(e,t){this.stage=e,this.reducedMotion=t}cx=0;cy=0;zoom=1;tx=0;ty=0;tz=1;punch=0;shakeT=0;drift=0;t=0;fit(e,t,s,i,n=1.08){this.tz=Math.min(s/(e*n),i/(t*n))}follow(e,t,s=1){this.tx=Jt(this.tx,e,s),this.ty=Jt(this.ty,t,s)}setZoomFactor(e){this.tz=e}pushIn(e=.08){this.reducedMotion||(this.punch=Math.max(this.punch,e))}shake(e=220){this.reducedMotion||(this.shakeT=e/1e3)}setDrift(e){this.drift=this.reducedMotion?0:e?1:0}snap(){this.cx=this.tx,this.cy=this.ty,this.zoom=this.tz}update(e,t,s){const i=Number.isFinite(e)?Math.max(0,Math.min(.05,e/1e3)):0;this.t+=i;const n=1-Math.pow(.012,i),o=1-Math.pow(.05,i);this.cx+=(this.tx-this.cx)*n,this.cy+=(this.ty-this.cy)*n,this.punch=Math.max(0,this.punch-i*.12),this.zoom+=(this.tz*(1+tb(this.punch/.08)*this.punch)-this.zoom)*o;let a=0,l=0;if(this.shakeT>0){this.shakeT-=i;const h=this.shakeT*18;a=Math.sin(this.t*60)*h,l=Math.cos(this.t*47)*h}this.drift&&(a+=Math.sin(this.t*.7)*2.2,l+=Math.cos(this.t*.5)*1.6),this.stage.scale.set(this.zoom),this.stage.position.set(t/2-(this.cx+a)*this.zoom,s/2-(this.cy+l)*this.zoom)}toScreen(e,t){return{x:this.stage.position.x+e*this.zoom,y:this.stage.position.y+t*this.zoom}}get scale(){return this.zoom}}const ob={roof:"pitched",eave:.14,furniture:"chimney",stripes:!1},ab={roof:"flat",eave:.05,furniture:"vent",stripes:!1},lb={roof:"capsule",eave:0,furniture:"dish",stripes:!1},Rn={island:ob,orbit:lb,metropolis:ab,harbour:{roof:"gable",eave:.16,furniture:"chimney",stripes:!1},observatory:{roof:"dome",eave:.04,furniture:"dish",stripes:!1},greenhouse:{roof:"gable",eave:.1,furniture:"vent",stripes:!1},workshop:{roof:"gable",eave:.12,furniture:"chimney",stripes:!1},arcade:{roof:"flat",eave:.08,furniture:"mast",stripes:!0},kingdom:{roof:"pitched",eave:.1,furniture:"finial",stripes:!1},outpost:{roof:"flat",eave:.12,furniture:"vent",stripes:!1},snowfield:{roof:"pitched",eave:.2,furniture:"chimney",stripes:!1},canopy:{roof:"pitched",eave:.22,furniture:"none",stripes:!1},lagoon:{roof:"tent",eave:.18,furniture:"none",stripes:!0},volcano:{roof:"flat",eave:.06,furniture:"vent",stripes:!1},cloudtop:{roof:"dome",eave:.06,furniture:"finial",stripes:!1},reef:{roof:"dome",eave:.02,furniture:"none",stripes:!1},bazaar:{roof:"tent",eave:.2,furniture:"none",stripes:!0},monastery:{roof:"onion",eave:.08,furniture:"finial",stripes:!1},moonbase:{roof:"capsule",eave:0,furniture:"dish",stripes:!1},lanterns:{roof:"tiered",eave:.26,furniture:"lantern",stripes:!1}};class Sg{constructor(e,t){this.world=e,this.theme=t,this.container.addChild(this.ripples,this.terrain,this.paths,this.labels,this.shadows,this.clouds,this.objects),this.objects.sortableChildren=!0,this.shadows.alpha=.9,this.drawTerrain(),this.drawPaths(),this.drawLabels();for(const s of e.places)this.addPlace(s);this.placeProps()}container=new _e;terrain=new Pe;ripples=new Pe;paths=new Pe;labels=new _e;shadows=new Pe;clouds=new Pe;objects=new _e;drawn=new Map;props=[];time=0;positionOf(e){const t=this.drawn.get(e);if(!t)return null;const s=t.place,i=s.gx+s.footprint/2,n=s.gy+s.footprint/2,o=K(i,n);return{ground:o,top:D(o,this.heightPx(t)+10),place:s}}standingSpot(e){const t=this.drawn.get(e);if(!t)return K(0,0);const s=t.place;return K(s.gx+s.footprint/2,s.gy+s.footprint+.55)}setGlow(e,t){const s=this.drawn.get(e);s&&s.glow!==t&&(s.glow=t,s.dirty=!0)}setGrowth(e,t){const s=this.drawn.get(e);s&&s.extraH!==t&&(s.extraH=t,s.dirty=!0)}setScaffold(e,t){const s=this.drawn.get(e);s&&s.scaffold!==t&&(s.scaffold=t,s.dirty=!0)}setLamp(e,t){const s=this.drawn.get(e);s&&s.lamp!==t&&(s.lamp=t,s.dirty=!0)}lampOf(e){return this.drawn.get(e)?.lamp??"idle"}has(e){return this.drawn.has(e)}addPlace(e){if(this.drawn.has(e.id))return;const t=new Pe;t.zIndex=ou(e.gx,e.gy,e.footprint);const s=Math.max(0,this.world.districts.findIndex(u=>u.id===e.district)),i=e.kind==="beacon"?this.theme.beacon:e.kind==="archive"?this.theme.archive:e.kind==="forge"?this.theme.forge:this.theme.palettes[s%this.theme.palettes.length],n=e.kind==="building"?ko(e.path):0,o=e.kind==="building"?(n%5-2)*.05:0,a=e.kind==="building"&&n%3===0?this.theme.palettes[(s+1+n%2)%this.theme.palettes.length]:i,l=u=>o>=0?Q(u,16777215,o):Q(u,0,-o),h={top:l(i.top),left:l(i.left),right:l(i.right),roof:a.roof,roofD:a.roofD,win:i.win},c={place:e,g:t,palette:h,extraH:0,glow:0,lamp:"idle",scaffold:0,dirty:!0};this.drawn.set(e.id,c),this.objects.addChild(t),this.redraw(c)}update(e){this.time+=e/1e3,this.drawRipples(),this.drawCloudShadows();for(const t of this.props)t.canopy&&(t.canopy.x=Math.sin(this.time*1.4+t.phase)*1.2);for(const t of this.drawn.values())(t.glow>0||t.lamp==="scan"||t.lamp==="fail"||t.lamp==="pass"||t.place.kind==="dock"||t.place.kind==="forge")&&(t.dirty=!0),t.dirty&&this.redraw(t)}heightPx(e){const t=e.place;return(t.kind==="beacon"?70:t.kind==="forge"?34:t.kind==="dock"?4:t.kind==="archive"?30:18+t.height*8)+e.extraH}redraw(e){const{g:t,place:s,palette:i}=e;t.clear(),e.dirty=!1;const n=this.heightPx(e),o=s.footprint,a=De(s.gx+.12,s.gy+.12,o);if(t.poly(V(a)).fill({color:this.shadowInk,alpha:.22}),s.kind!=="dock"&&this.castShadow(t,s,n),s.kind==="dock")return this.drawDock(t,s);if(s.kind==="beacon")return this.drawBeacon(e,n);const l=this.box(t,s.gx,s.gy,o,n,s.kind==="forge"?i.roof:i.top,i.left,i.right),h=e.glow>0?.6+.4*Math.sin(this.time*10):0,c=e.glow>0?Q(i.win,16771496,.5+.5*h):i.win;if(s.kind!=="archive"&&s.kind!=="forge"){const u=Math.max(1,Math.round(n/28)),d=o>=3?3:2;this.windows(t,l[3],l[2],n,u,d,c,e.glow>0?1:.9),this.windows(t,l[2],l[1],n,u,d,c,e.glow>0?1:.8);const f=Be(l[3],l[2],.3);t.poly([f.x-3,f.y-1,f.x+3,f.y+1,f.x+3,f.y-9,f.x-3,f.y-11]).fill({color:i.roofD,alpha:.9})}if(s.kind==="building"&&o<=2&&this.roof(t,s,n,i),s.kind==="building"&&o>=3&&Rn[this.theme.id].roof!=="capsule"&&Rn[this.theme.id].roof!=="dome"){const u=l.map(p=>D(p,n));t.poly(V([u[3],u[2],D(u[2],4),D(u[3],4)])).fill(i.roofD),t.poly(V([u[2],u[1],D(u[1],4),D(u[2],4)])).fill(Q(i.roofD,0,.2)),t.poly(V(u.map(p=>D(p,4)))).fill(i.roof);const d=De(s.gx+.8,s.gy+.8,o-1.6,n+4);t.poly(V([d[3],d[2],D(d[2],10),D(d[3],10)])).fill(i.left),t.poly(V([d[2],d[1],D(d[1],10),D(d[2],10)])).fill(i.right),t.poly(V(d.map(p=>D(p,10)))).fill(i.top);const f=D(K(s.gx+o/2,s.gy+o/2),n+14);t.moveTo(f.x,f.y).lineTo(f.x,f.y-12).stroke({width:1.6,color:i.roofD}),t.circle(f.x,f.y-13-14,2.2).fill(e.glow>0?16766571:i.roof)}if(s.kind==="archive"){for(let u=1;u<6;u++){const d=Be(l[3],l[2],u/6);t.moveTo(d.x,d.y-3).lineTo(d.x,d.y-n+5).stroke({width:1.3,color:16777215,alpha:.6})}for(let u=1;u<5;u++){const d=Be(l[2],l[1],u/5);t.moveTo(d.x,d.y-3).lineTo(d.x,d.y-n+5).stroke({width:1.3,color:16777215,alpha:.45})}this.pyramid(t,l.map(u=>D(u,n)),D(K(s.gx+o/2,s.gy+o/2),n+10),i.roof,i.roofD)}if(s.kind==="forge"){const u=this.theme.forge.ember,d=Be(l[3],l[2],.5);t.poly([d.x-7,d.y-2,d.x+7,d.y+2,d.x+7,d.y-18,d.x-7,d.y-22]).fill({color:u,alpha:.85}),this.windows(t,l[2],l[1],n,2,2,u,.9),this.pyramid(t,l.map(m=>D(m,n)),D(K(s.gx+o/2,s.gy+o/2),n+16),i.roof,i.roofD);const f=D(K(s.gx+o*.75,s.gy+o*.3),n+6);t.rect(f.x-4,f.y-16,8,16).fill(i.roofD);for(let m=0;m<3;m++){const g=(this.time*.35+m/3)%1;t.circle(f.x+Math.sin(g*6+m)*4,f.y-18-g*26,3+g*6).fill({color:16777215,alpha:.22*(1-g)})}const p=.5+.5*Math.sin(this.time*3);t.circle(d.x,d.y-8,12+p*4).fill({color:u,alpha:.12+.08*p})}e.glow>0&&this.outline(t,l,n,16762970,.4+.4*h),e.scaffold>0&&this.scaffold(t,s,n,e.scaffold)}roof(e,t,s,i){const n=Rn[this.theme.id],o=t.footprint,a=n.eave,l=ko(t.path),h=De(t.gx-a,t.gy-a,o+a*2,s),c=K(t.gx+o/2,t.gy+o/2),u=Q(i.roofD,this.shadowInk,.35);switch(a>0&&(e.poly(V([h[3],h[2],D(h[2],-3),D(h[3],-3)])).fill({color:u,alpha:.9}),e.poly(V([h[2],h[1],D(h[1],-3),D(h[2],-3)])).fill({color:Q(u,0,.2),alpha:.9})),n.roof){case"pitched":{this.pyramid(e,h,D(c,s+12+o*9),i.roof,i.roofD);break}case"gable":{const f=11+o*7,p=D(Be(h[0],h[3],.5),s+f),m=D(Be(h[1],h[2],.5),s+f);e.poly(V([h[3],h[2],m,p])).fill(Rt(Q(i.roof,16777215,.1),i.roof,p.y,h[3].y)),e.poly(V([h[0],h[1],m,p])).fill(Q(i.roofD,this.shadowInk,.2)),e.poly(V([h[2],h[1],m])).fill(Q(i.right,this.shadowInk,.1)),e.poly(V([h[3],h[0],p])).fill(i.left),e.moveTo(p.x,p.y).lineTo(m.x,m.y).stroke({width:1.4,color:16777215,alpha:.4,cap:"round"});break}case"flat":{const f=h.map(m=>D(m,3));e.poly(V([h[3],h[2],f[2],f[3]])).fill(i.roofD),e.poly(V([h[2],h[1],f[1],f[2]])).fill(Q(i.roofD,0,.2)),e.poly(V(f)).fill(au(Q(i.roof,16777215,.08),i.roof,f[3].x,f[1].x));const p=De(t.gx+.25+l%3*.1,t.gy+.3,.4,s+3);e.poly(V([p[3],p[2],D(p[2],6),D(p[3],6)])).fill(i.left),e.poly(V([p[2],p[1],D(p[1],6),D(p[2],6)])).fill(i.right),e.poly(V(p.map(m=>D(m,6)))).fill(i.top);break}case"dome":{const f=o*32*.78,p=c.y-s+2;e.ellipse(c.x,p,f,f*.62).fill(Rt(Q(i.roof,16777215,.22),Q(i.roofD,this.shadowInk,.15),p-f*.62,p+f*.3)),e.rect(c.x-f,p,f*2,f*.62).fill({color:0,alpha:0}),e.ellipse(c.x-f*.3,p-f*.28,f*.28,f*.14).fill({color:16777215,alpha:.32});break}case"onion":{const f=o*16,p=c.y-s;e.moveTo(c.x-f,p).quadraticCurveTo(c.x-f*1.15,p-f*1.1,c.x,p-f*2.2).quadraticCurveTo(c.x+f*1.15,p-f*1.1,c.x+f,p).fill(Rt(Q(i.roof,16777215,.2),i.roofD,p-f*2.2,p)),e.moveTo(c.x-f*.4,p-f*.3).quadraticCurveTo(c.x-f*.5,p-f*1.2,c.x-f*.05,p-f*1.9).stroke({width:1.6,color:16777215,alpha:.35,cap:"round"});break}case"tiered":{for(let f=0;f<2;f++){const p=s+f*14,m=a*(1-f*.45),g=De(t.gx-m,t.gy-m,o+m*2,p);e.poly(V([g[3],g[2],D(g[2],-2),D(g[3],-2)])).fill(u);const _=D(c,p+9+o*3);e.poly(V([D(g[3],3),D(g[2],3),_])).fill(i.roof),e.poly(V([D(g[2],3),D(g[1],3),_])).fill(i.roofD),e.poly(V([D(g[3],3),D(g[0],3),_])).fill(Q(i.roof,16777215,.1));for(const x of[g[1],g[2],g[3]])e.moveTo(x.x,x.y+1).quadraticCurveTo(x.x+(x.x<c.x?-4:4),x.y-1,x.x+(x.x<c.x?-5:5),x.y-6).stroke({width:2,color:i.roofD,cap:"round"})}break}case"tent":{const f=D(c,s+16+o*8);this.pyramid(e,h,f,i.roof,i.roofD);for(let p=0;p<o*3;p++){const m=Be(h[3],h[2],p/(o*3)),g=Be(h[3],h[2],(p+1)/(o*3));e.moveTo(m.x,m.y).quadraticCurveTo((m.x+g.x)/2,(m.y+g.y)/2+4,g.x,g.y).fill(i.roofD)}e.moveTo(f.x,f.y).lineTo(f.x,f.y-8).stroke({width:1.5,color:i.roofD}),e.poly([f.x,f.y-8,f.x+7,f.y-6,f.x,f.y-4]).fill(i.win);break}case"capsule":{const f=o*32*.7,p=c.y-s+1;e.ellipse(c.x,p,f*1.02,f*.5).fill(Rt(Q(i.top,16777215,.25),i.top,p-f*.5,p+f*.1)),e.ellipse(c.x-f*.3,p-f*.22,f*.3,f*.1).fill({color:16777215,alpha:.4}),e.ellipse(c.x,p,f*1.02,f*.5).stroke({width:1.2,color:Q(i.roofD,16777215,.1),alpha:.6});break}}const d=D(K(t.gx+o*.72,t.gy+o*.3),s+(n.roof==="flat"?3:n.roof==="pitched"||n.roof==="gable"?8:0));switch(n.furniture){case"chimney":l%2===0&&(e.rect(d.x-3,d.y-12,6,12).fill(i.roofD),e.rect(d.x-4,d.y-13,8,3).fill(Q(i.roofD,0,.2)));break;case"vent":e.rect(d.x-4,d.y-5,8,5).fill(Q(i.left,this.shadowInk,.2)),e.ellipse(d.x,d.y-5,4,1.6).fill(i.top);break;case"mast":e.moveTo(d.x,d.y).lineTo(d.x,d.y-16).stroke({width:1.4,color:i.roofD}),e.circle(d.x,d.y-17,2).fill(i.win);break;case"finial":{const f=D(c,s+12+o*9+(n.roof==="onion"?o*16*2.2-12-o*9:0));e.moveTo(f.x,f.y).lineTo(f.x,f.y-7).stroke({width:1.4,color:16766571}),e.circle(f.x,f.y-8,2).fill(16766571);break}case"lantern":{const f=Be(h[3],h[2],.5);e.moveTo(f.x,f.y).lineTo(f.x,f.y+5).stroke({width:1,color:i.roofD}),e.roundRect(f.x-3,f.y+5,6,8,2).fill(hb(i.win));break}case"dish":e.ellipse(d.x,d.y-2,6,3).stroke({width:1.4,color:16777215,alpha:.7}),e.moveTo(d.x,d.y-2).lineTo(d.x+2,d.y-7).stroke({width:1,color:16777215,alpha:.7});break}if(n.stripes){const f=De(t.gx,t.gy,o);for(let p=0;p<o*4;p+=2){const m=Be(f[3],f[2],p/(o*4)),g=Be(f[3],f[2],(p+1)/(o*4));e.poly([m.x,m.y,g.x,g.y,g.x,g.y-s*.35,m.x,m.y-s*.35]).fill({color:16777215,alpha:.22})}}}box(e,t,s,i,n,o,a,l){const[h,c,u,d]=De(t,s,i),f=this.hazeOf(s+t),p=m=>Q(m,this.theme.sky[0],f);return e.poly(V([d,u,D(u,n),D(d,n)])).fill(Rt(p(Q(a,16777215,.08)),p(Q(a,this.shadowInk,.28)),d.y-n,d.y)),e.poly(V([u,c,D(c,n),D(u,n)])).fill(Rt(p(Q(l,this.coolInk,.06)),p(Q(l,this.shadowInk,.38)),u.y-n,u.y)),e.poly(V([D(h,n),D(c,n),D(u,n),D(d,n)])).fill(au(p(Q(o,16777215,.16)),p(o),d.x,c.x)),e.moveTo(d.x,d.y-n).lineTo(h.x,h.y-n).lineTo(c.x,c.y-n).stroke({width:1.3,color:16777215,alpha:.42,cap:"round"}),e.moveTo(d.x,d.y-n).lineTo(d.x,d.y).stroke({width:1.1,color:16777215,alpha:.22}),[h,c,u,d]}hazeOf(e){const t=this.world.bounds,s=t.x+t.y,i=t.x+t.w+t.y+t.h;return .16*(1-Math.max(0,Math.min(1,(e-s)/Math.max(1,i-s))))}get shadowInk(){return Q(this.theme.vignette,0,.3)}get coolInk(){return Q(this.theme.sky[0],2768746,.5)}castShadow(e,t,s){const i=t.footprint,n=s/36,o=De(t.gx,t.gy,i),a=.55*n,l=.95*n,h=[K(t.gx+a,t.gy+l),K(t.gx+i+a,t.gy+l),K(t.gx+i+a,t.gy+i+l),K(t.gx+a,t.gy+i+l)],c=[o[1],h[1],h[2],h[3],o[3],o[2]];e.poly(V(c)).fill({color:this.shadowInk,alpha:.16});const u=[K(t.gx+a*.6,t.gy+l*.6),K(t.gx+i+a*.6,t.gy+l*.6),K(t.gx+i+a*.6,t.gy+i+l*.6)];e.poly(V([o[1],u[1],u[2],o[3],o[2]])).fill({color:this.shadowInk,alpha:.12})}drawCloudShadows(){const e=this.clouds;if(e.clear(),this.theme.terrain!=="island"&&this.theme.terrain!=="block")return;const t=this.world.bounds,s=K(t.x+t.w/2,t.y+t.h/2),i=(t.w+t.h)*24;for(let n=0;n<3;n++){const o=(this.time*.012+n*.37)%1,a=s.x-i/2+o*i*1.3-i*.15,l=s.y-90+Math.sin(n*2.1)*120;e.ellipse(a,l,150+n*30,56+n*8).fill({color:this.shadowInk,alpha:.075}),e.ellipse(a+90,l+18,110,40).fill({color:this.shadowInk,alpha:.06})}}pyramid(e,t,s,i,n){e.poly(V([t[0],t[1],s])).fill(Q(n,this.shadowInk,.25)),e.poly(V([t[3],t[0],s])).fill(Q(i,16777215,.12)),e.poly(V([t[3],t[2],s])).fill(Rt(Q(i,16777215,.06),i,s.y,t[2].y)),e.poly(V([t[2],t[1],s])).fill(Rt(n,Q(n,this.shadowInk,.3),s.y,t[1].y)),e.moveTo(t[3].x,t[3].y).lineTo(s.x,s.y).stroke({width:1.2,color:16777215,alpha:.35,cap:"round"})}windows(e,t,s,i,n,o,a,l){const h=(s.x-t.x)/o*.3,c=(s.y-t.y)/o*.3;for(let u=0;u<n;u++)for(let d=0;d<o;d++){const f=Be(t,s,(d+.5)/o),p=f.y-i*(u+.75)/(n+.5),m=f.x;e.poly([m-h,p-c,m+h,p+c,m+h,p+c-6,m-h,p-c-6]).fill({color:a,alpha:l}),e.poly([m-h,p-c-4.5,m+h,p+c-4.5,m+h,p+c-6,m-h,p-c-6]).fill({color:16777215,alpha:l*.45})}}outline(e,t,s,i,n){const o=t.map(a=>D(a,s));e.moveTo(t[3].x,t[3].y).lineTo(t[2].x,t[2].y).lineTo(t[1].x,t[1].y).lineTo(o[1].x,o[1].y).lineTo(o[0].x,o[0].y).lineTo(o[3].x,o[3].y).closePath().stroke({width:2,color:i,alpha:n,join:"round"}),e.moveTo(t[2].x,t[2].y).lineTo(o[2].x,o[2].y).stroke({width:2,color:i,alpha:n})}scaffold(e,t,s,i){const n=De(t.gx-.12,t.gy-.12,t.footprint+.24);for(const o of[n[1],n[2],n[3]])e.moveTo(o.x,o.y).lineTo(o.x,o.y-s-8).stroke({width:1.1,color:16768150,alpha:i});for(let o=10;o<s+8;o+=11)e.moveTo(n[3].x,n[3].y-o).lineTo(n[2].x,n[2].y-o).lineTo(n[1].x,n[1].y-o).stroke({width:1.1,color:16768150,alpha:i})}drawBeacon(e,t){const{g:s,place:i}=e,n=this.theme.beacon,o=n.lamp[e.lamp],a=this.box(s,i.gx+.2,i.gy+.2,.6,t,n.top,n.left,n.right);for(const[u,d]of[[.2,.33],[.52,.65]])s.poly(V([D(a[3],t*u),D(a[2],t*u),D(a[2],t*d),D(a[3],t*d)])).fill(n.roof),s.poly(V([D(a[2],t*u),D(a[1],t*u),D(a[1],t*d),D(a[2],t*d)])).fill(n.roofD);const l=D(K(i.gx+.5,i.gy+.5),t+6),h=e.lamp==="fail"?.55+.45*Math.sin(this.time*9):e.lamp==="scan"?.8+.2*Math.sin(this.time*20):1,c=e.lamp==="idle"?16:26;if(s.circle(l.x,l.y,c).fill({color:o,alpha:.22*h}),s.circle(l.x,l.y,c*.55).fill({color:o,alpha:.3*h}),e.lamp==="scan"||e.lamp==="pass"){const u=e.lamp==="scan"?this.time*5:this.time*1.1,d=e.lamp==="scan"?190:120,f=.2;s.moveTo(l.x,l.y).arc(l.x,l.y,d,u-f,u+f).closePath().fill({color:o,alpha:.18})}this.box(s,i.gx+.28,i.gy+.28,.44,11,2899538,o,Q(o,0,.25)),this.pyramid(s,De(i.gx+.2,i.gy+.2,.6,t+11),D(K(i.gx+.5,i.gy+.5),t+22),n.roof,n.roofD)}drawDock(e,t){const s=De(t.gx,t.gy,t.footprint);e.poly(V([s[3],s[2],D(s[2],-5),D(s[3],-5)])).fill(this.theme.dock.post),e.poly(V([s[2],s[1],D(s[1],-5),D(s[2],-5)])).fill(Q(this.theme.dock.post,0,.2)),e.poly(V(s)).fill(this.theme.dock.deck);for(let o=1;o<5;o++){const a=Be(s[0],s[3],o/5),l=Be(s[1],s[2],o/5);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:0,alpha:.12})}for(const o of[s[0],s[1],s[2],s[3]])e.rect(o.x-2,o.y-12,4,12).fill(this.theme.dock.post);const i=Be(s[1],s[2],.5),n=Math.sin(this.time*1.6)*1.5;e.ellipse(i.x+22,i.y+6+n,16,6).fill(this.theme.dock.vessel),e.ellipse(i.x+22,i.y+3+n,13,4).fill(Q(this.theme.dock.vessel,0,.12)),e.rect(i.x+20,i.y-12+n,3,15).fill(this.theme.dock.post),e.poly([i.x+23,i.y-12+n,i.x+34,i.y-6+n,i.x+23,i.y-2+n]).fill({color:16777215,alpha:.9})}blobPath(e,t,s){const i=this.world.bounds,n=i.x+i.w/2,o=i.y+i.h/2,a=i.w/2+1.2,l=i.h/2+1.2,h=[],c=ar(this.world.seed^1540483477)()*6.28;for(let u=0;u<80;u++){const d=u/80*Math.PI*2,f=1+.07*Math.sin(3*d+c)+.04*Math.sin(5*d+2.1+c)+.025*Math.sin(8*d+1.3),p=K(n+Math.cos(d)*a*f*t,o+Math.sin(d)*l*f*t);h.push(p.x,p.y+s)}return e.poly(h)}drawTerrain(){const e=this.terrain,t=this.theme.ground;if(this.theme.terrain==="island"){this.blobPath(e,1,18).fill(t.edgeDark),this.blobPath(e,1,10).fill(t.edge),this.blobPath(e,1,0).fill(t.sand),this.blobPath(e,.88,-1).fill(t.fill),this.blobPath(e,.6,-2).fill({color:t.fillLight,alpha:.55});const s=this.world.bounds,i=K(s.x+s.w/2,s.y+s.h/2),n=(s.w+s.h)*14;e.circle(i.x-n*.45,i.y-n*.35,n*.9).fill({color:16777215,alpha:.07}),e.circle(i.x+n*.5,i.y+n*.4,n*1.1).fill({color:this.shadowInk,alpha:.08})}else if(this.theme.terrain==="platform"){const s=this.world.bounds,i=De(s.x,s.y,Math.max(s.w,s.h));e.poly(V([i[3],i[2],D(i[2],-14),D(i[3],-14)])).fill(t.edgeDark),e.poly(V([i[2],i[1],D(i[1],-14),D(i[2],-14)])).fill(t.edge),e.poly(V(i)).fill(t.fill),e.poly(V(De(s.x+1,s.y+1,Math.max(s.w,s.h)-2))).fill({color:t.fillLight,alpha:.25}),e.poly(V(i)).stroke({width:2,color:t.sand,alpha:.6})}else{const s=this.world.bounds,i=Math.max(s.w,s.h),n=De(s.x,s.y,i);e.poly(V([n[3],n[2],D(n[2],-10),D(n[3],-10)])).fill(t.edgeDark),e.poly(V([n[2],n[1],D(n[1],-10),D(n[2],-10)])).fill(t.edge),e.poly(V(n)).fill(t.fill);for(let o=1;o<i;o+=2){const a=K(s.x+o,s.y),l=K(s.x+o,s.y+i);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:t.sand,alpha:.12})}for(let o=1;o<i;o+=2){const a=K(s.x,s.y+o),l=K(s.x+i,s.y+o);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:t.sand,alpha:.12})}}}drawRipples(){const e=this.ripples;if(e.clear(),this.theme.terrain!=="island"){const t=ar(this.world.seed);for(let s=0;s<70;s++){const i=(t()-.5)*2600,n=(t()-.5)*1600,o=.5+.5*Math.sin(this.time*(.6+t())+s);e.circle(i,n,.8+t()*1.2).fill({color:this.theme.water.ripple,alpha:this.theme.water.rippleAlpha*o})}return}for(let t=0;t<3;t++){const s=(this.time*.06+t/3)%1;this.blobPath(e,1.04+s*.45,8).stroke({width:1.4,color:this.theme.water.ripple,alpha:this.theme.water.rippleAlpha*.7*(1-s)})}}drawPaths(){const e=this.paths;for(const t of this.world.paths){const s=t.points.map(([i,n])=>K(i+.5,n+.5));e.moveTo(s[0].x,s[0].y);for(const i of s.slice(1))e.lineTo(i.x,i.y);e.stroke({width:7,color:this.theme.pathColor,alpha:.9,cap:"round",join:"round"})}}drawLabels(){const e=new Ps({fontFamily:"Fredoka, Trebuchet MS, sans-serif",fontSize:22,fontWeight:"700",fill:16777215,letterSpacing:2,stroke:{color:this.theme.vignette,width:4,join:"round"}});for(const t of this.world.districts){const s=new bp({text:t.label,style:e});s.anchor.set(.5,.5);const i=K(t.bounds.x+t.bounds.w/2+.5,t.bounds.y+t.bounds.h+.55);s.position.set(i.x,i.y),s.alpha=.55,s.skew.set(-.35,.17),this.labels.addChild(s)}}placeProps(){const e=ar(this.world.seed^2654435769),t=new Set;for(const a of this.world.places)for(let l=0;l<a.footprint;l++)for(let h=0;h<a.footprint;h++)t.add(`${a.gx+l},${a.gy+h}`);const s=this.world.bounds;let i=0,n=0;const o=Math.min(18,5+Math.floor(this.world.places.length/5));for(;n<o&&i++<700;){const a=Math.floor(s.x+1+e()*(s.w-2)),l=Math.floor(s.y+1+e()*(s.h-2));if(t.has(`${a},${l}`)||this.world.districts.some(_=>a>=_.bounds.x&&a<_.bounds.x+_.bounds.w&&l>=_.bounds.y&&l<_.bounds.y+_.bounds.h))continue;t.add(`${a},${l}`);const h=new _e;h.zIndex=ou(a,l);const c=new Pe;h.addChild(c);const u=K(a+.5,l+.5),d=(.85+e()*.4)*1.25,[f,p,m]=this.theme.propColors;let g;this.theme.prop==="tree"?(c.ellipse(u.x+3,u.y+1,9*d,4*d).fill({color:666138,alpha:.18}),c.rect(u.x-1.5,u.y-10*d,3,10*d).fill(m),g=new Pe,g.ellipse(u.x+1*d,u.y-13*d,9.5*d,7.5*d).fill(Q(f,this.shadowInk,.25)),g.ellipse(u.x,u.y-16*d,9*d,8.5*d).fill(f),g.ellipse(u.x-4*d,u.y-19*d,6.5*d,6*d).fill(p),g.ellipse(u.x+4.5*d,u.y-20*d,5.5*d,5*d).fill(p),g.ellipse(u.x-3.5*d,u.y-22*d,3.2*d,2.4*d).fill({color:16777215,alpha:.32}),h.addChild(g)):this.theme.prop==="antenna"?(c.rect(u.x-1,u.y-18*d,2,18*d).fill(f),c.circle(u.x,u.y-20*d,2.5).fill(p),c.ellipse(u.x,u.y,5*d,2.5*d).fill(m)):(c.rect(u.x-1,u.y-16*d,2,16*d).fill(m),c.circle(u.x,u.y-17*d,3).fill(f),c.circle(u.x,u.y-17*d,7).fill({color:p,alpha:.18})),this.objects.addChild(h),this.props.push({g:c,gx:a,gy:l,phase:e()*6.28,...g?{canopy:g}:{}}),n++}}}const hb=r=>Q(r,16777215,.25),js=new Map;function Cg(r,e){let t=js.get(r);if(!t){if(js.size>1500){for(const s of js.values())s.destroy();js.clear()}t=e(),js.set(r,t)}return t}const fi=r=>Math.round(r/2)*2;function Rt(r,e,t,s){const i=fi(t),n=fi(s);return Cg(`v${r}|${e}|${i}|${n}`,()=>new Xe({start:{x:0,y:i},end:{x:0,y:n},colorStops:[{offset:0,color:r},{offset:1,color:e}],textureSpace:"global"}))}function au(r,e,t,s){const i=fi(t),n=fi(s);return Cg(`h${r}|${e}|${i}|${n}`,()=>new Xe({start:{x:i,y:0},end:{x:n,y:0},colorStops:[{offset:0,color:r},{offset:1,color:e}],textureSpace:"global"}))}function Q(r,e,t){const s=r>>16&255,i=r>>8&255,n=r&255,o=e>>16&255,a=e>>8&255,l=e&255,h=Math.round(s+(o-s)*t),c=Math.round(i+(a-i)*t),u=Math.round(n+(l-n)*t);return h<<16|c<<8|u}class Ro{constructor(e,t,s){this.id=e,this.theme=t,this.reducedMotion=s,this.container.addChild(this.g)}container=new _e;g=new Pe;t=Math.random()*10;x=0;y=0;scale=1;alpha=1;lift=0;panic=0;peek=0;update(e){this.t+=e/1e3;const t=this.t,s=this.g,i=this.theme.gremlin,n=this.reducedMotion?0:Math.abs(Math.sin(t*(7+this.panic*5)))*(6+this.panic*3);this.container.position.set(this.x,this.y),this.container.alpha=this.alpha,s.clear(),s.ellipse(0,0,7*this.scale,3*this.scale).fill({color:994600,alpha:.25}),s.position.set(0,0);const o=this.scale,a=9,l=[];for(let u=0;u<=a*2;u++){const d=u/(a*2)*Math.PI*2,f=(u%2?7.2:9.6+Math.sin(t*20+u)*.7)*o;l.push(Math.cos(d)*f,-9*o-n-this.lift+Math.sin(d)*f*.9)}s.poly(l).fill(i.body);const h=-10*o-n-this.lift;s.ellipse(-3*o,h,2.4*o,2.6*o).fill(16777215),s.ellipse(3*o,h,2.4*o,2.6*o).fill(16777215);const c=this.panic?Math.sin(t*9)*.8:.4;s.ellipse(-2.6*o+c,h+.4,1.2*o,1.3*o).fill(i.eye),s.ellipse(3.4*o+c,h+.4,1.2*o,1.3*o).fill(i.eye),s.moveTo(-5.5*o,h-4*o).lineTo(-1.2*o,h-2.4*o).moveTo(5.5*o,h-4*o).lineTo(1.2*o,h-2.4*o).stroke({width:1.3*o,color:i.eye,cap:"round"}),s.moveTo(-2.6*o,h+4.4*o).lineTo(-1.2*o,h+3.4*o).lineTo(.2*o,h+4.4*o).lineTo(1.6*o,h+3.4*o).lineTo(2.9*o,h+4.4*o).stroke({width:1.3*o,color:i.eye,cap:"round"})}}const cb=Object.freeze(Object.defineProperty({__proto__:null,Gremlin:Ro},Symbol.toStringTag,{value:"Module"}));class ub{constructor(e){this.reducedMotion=e}g=new Pe;parts=[];burst(e,t,s,i,n,o=0){this.reducedMotion&&(s=Math.ceil(s/4));for(let a=0;a<s;a++){const l=Math.random()*Math.PI*2,h=n*(.4+Math.random()*.8);this.parts.push({x:e,y:t,vx:Math.cos(l)*h,vy:Math.sin(l)*h*.6-o*(.5+Math.random()),life:0,max:.7+Math.random()*.8,c:i[a%i.length],r:1.4+Math.random()*2.4})}}clear(){this.parts=[],this.g.clear()}get count(){return this.parts.length}update(e){const t=e/1e3;this.parts=this.parts.filter(s=>(s.life+=t)<s.max),this.g.clear();for(const s of this.parts)s.vy+=140*t,s.x+=s.vx*t,s.y+=s.vy*t,this.g.rect(s.x-s.r/2,s.y-s.r/2,s.r,s.r*1.3).fill({color:s.c,alpha:1-s.life/s.max})}}const bt=[{id:"pip",name:"Pip",bio:"Curious, quick, a little clumsy. The original.",shape:"round",topper:"antenna",eyes:"wide",body:16751164,bodyLight:16765566,belly:16774620,ear:14712620,cheek:16739930,ink:2759959,size:1},{id:"mo",name:"Mo",bio:"Tall, calm, measures twice.",shape:"tall",topper:"tuft",eyes:"sleepy",body:6269183,bodyLight:11129599,belly:15398143,ear:4161488,cheek:16748448,ink:1385274,size:1.1},{id:"juno",name:"Juno",bio:"Bright, chatty, finds the bug by talking to it.",shape:"bean",topper:"ears",eyes:"wide",body:8380554,bodyLight:13172672,belly:15990768,ear:5223526,cheek:16756896,ink:1456671,size:.95},{id:"rook",name:"Rook",bio:"Boxy, deliberate, never guesses.",shape:"boxy",topper:"crest",eyes:"visor",body:10134712,bodyLight:14015462,belly:15659510,ear:7239820,cheek:8188927,ink:1778224,size:1.05},{id:"fen",name:"Fen",bio:"Quiet and sharp. Reads everything first.",shape:"teardrop",topper:"leaf",eyes:"dot",body:11967743,bodyLight:14734079,belly:16183551,ear:9401062,cheek:16754392,ink:2759498,size:.9},{id:"sol",name:"Sol",bio:"Warm, loud, celebrates everything.",shape:"round",topper:"halo",eyes:"wide",body:16765503,bodyLight:16773288,belly:16776166,ear:14723072,cheek:16747610,ink:3811845,size:1.08},{id:"ivy",name:"Ivy",bio:"Patient gardener of code. Hates loose ends.",shape:"bean",topper:"leaf",eyes:"sleepy",body:4177818,bodyLight:10481880,belly:15400952,ear:2788464,cheek:16756896,ink:997934,size:1},{id:"bolt",name:"Bolt",bio:"Fast. Sometimes too fast.",shape:"teardrop",topper:"crest",eyes:"dot",body:16734878,bodyLight:16756944,belly:16773366,ear:13645178,cheek:16765566,ink:3804962,size:.92},{id:"ash",name:"Ash",bio:"Dry wit, steady hands.",shape:"tall",topper:"ears",eyes:"sleepy",body:8024976,bodyLight:12104396,belly:15657973,ear:5656684,cheek:16758087,ink:1709872,size:1.06},{id:"nimbus",name:"Nimbus",bio:"Soft, cloud-headed, surprisingly precise.",shape:"round",topper:"halo",eyes:"wide",body:15660287,bodyLight:16777215,belly:16777215,ear:13228272,cheek:16756936,ink:2767442,size:1.02},{id:"ember",name:"Ember",bio:"Runs hot. Loves a red lighthouse.",shape:"boxy",topper:"antenna",eyes:"visor",body:16739133,bodyLight:16756874,belly:16773606,ear:12862506,cheek:16769899,ink:3805704,size:1},{id:"tove",name:"Tove",bio:"Small, brave, follows the map.",shape:"bean",topper:"tuft",eyes:"dot",body:13214827,bodyLight:15653293,belly:16775142,ear:10254916,cheek:16747610,ink:3811856,size:.85}],Mg=r=>bt.find(e=>e.id===r),lu=r=>(.2126*(r>>16&255)+.7152*(r>>8&255)+.0722*(r&255))/255,Eg=(r,e)=>Math.abs(lu(r.body)-lu(e))>.22;function kg(r,e,t){const s=a=>t===void 0||Eg(a,t);let i=Mg(e)??bt[r%bt.length];s(i)||(i=bt.find((a,l)=>l>=r%bt.length&&s(a))??bt.find(s)??i);const n=bt.filter(a=>a.id!==i.id&&s(a)),o=n.length?(r>>>3)%n.length:0;return{lead:i,helpers:[...n.slice(o),...n.slice(0,o)]}}const db=Object.freeze(Object.defineProperty({__proto__:null,CAST:bt,castById:Mg,pickCompany:kg,readableOn:Eg},Symbol.toStringTag,{value:"Module"}));class Bo{constructor(e,t,s=bt[0]){this.theme=e,this.reducedMotion=t,this.spec=s,this.container.addChild(this.shadow,this.body),this.container.scale.set(1.75*s.size)}container=new _e;shadow=new Pe;body=new Pe;t=0;pose={x:0,y:0,lift:0,sx:1,sy:1,lean:0,face:1,moving:!1,look:"fwd",mood:"curious",hiding:0};shown={x:0,y:0,lift:0,sx:1,sy:1,lean:0,face:1,faceK:1};snapNext=!0;snap(){this.snapNext=!0}get drawn(){return{x:this.shown.x,y:this.shown.y}}setTheme(e){this.theme=e}update(e){this.t+=e/1e3;const t=this.pose,s=this.spec,i=this.t,n=this.shown,o=Math.min(.05,e/1e3);this.snapNext&&(Object.assign(n,{x:t.x,y:t.y,lift:t.lift,sx:t.sx,sy:t.sy,lean:t.lean,face:t.face,faceK:1}),this.snapNext=!1);const a=1-Math.pow(5e-4,o),l=1-Math.pow(.002,o);n.x+=(t.x-n.x)*l,n.y+=(t.y-n.y)*l,n.lift+=(t.lift-n.lift)*a,n.sx+=(t.sx-n.sx)*a,n.sy+=(t.sy-n.sy)*a,n.lean+=(t.lean-n.lean)*a,n.face!==t.face?(n.faceK-=o*9,n.faceK<=0&&(n.face=t.face,n.faceK=.01)):n.faceK=Math.min(1,n.faceK+o*9);const h={...t,x:n.x,y:n.y,lift:n.lift,sx:n.sx*Math.max(.15,n.faceK),sy:n.sy,lean:n.lean,face:n.face};this.container.position.set(h.x,h.y),this.container.zIndex=1e6;const c=1-Math.min(.6,h.lift/90);this.shadow.clear().ellipse(0,0,11*c,5*c).fill({color:0,alpha:.28}),this.shadow.ellipse(0,0,14*c,7*c).fill({color:0,alpha:.1});const u=this.body;u.clear(),u.position.set(0,-h.lift),u.rotation=h.lean,u.scale.set(h.sx,h.sy);const d=h.moving||this.reducedMotion?0:Math.sin(i*2.2)*.012;u.scale.set(h.sx*(1-d),h.sy*(1+d));const f=h.moving?Math.sin(i*11)*3:0;switch(u.ellipse(-5+f,-1.5,4.2,2.6).fill(s.ear),u.ellipse(5-f,-1.5,4.2,2.6).fill(s.ear),s.shape){case"tall":u.ellipse(0,-16,9.5,16.5).fill(s.body),u.ellipse(-1.5,-21,7.5,9).fill({color:s.bodyLight,alpha:.55});break;case"boxy":u.roundRect(-11,-26,22,26,6).fill(s.body),u.roundRect(-9,-24,12,10,4).fill({color:s.bodyLight,alpha:.5});break;case"teardrop":u.moveTo(0,-30).quadraticCurveTo(13,-16,11,-6).quadraticCurveTo(0,2,-11,-6).quadraticCurveTo(-13,-16,0,-30).fill(s.body),u.ellipse(-2,-16,6,7).fill({color:s.bodyLight,alpha:.5});break;case"bean":u.ellipse(0,-12,12.5,11.5).fill(s.body),u.ellipse(-2,-18,8,6).fill({color:s.bodyLight,alpha:.55});break;default:u.ellipse(0,-13.5,11.5,13.5).fill(s.body),u.ellipse(-1.5,-17,9.5,9).fill({color:s.bodyLight,alpha:.55})}const p=s.shape==="tall"?9.5:s.shape==="boxy"?11:s.shape==="bean"?12.5:11.5,m=s.shape==="tall"?-16:s.shape==="boxy"?-13:s.shape==="bean"?-12:-13.5;u.moveTo(-p*.9,m-p*.2).quadraticCurveTo(-p*.75,m-p*.95,p*.1,m-p*1.02).stroke({width:2.2,color:16777215,alpha:.5,cap:"round"}),u.moveTo(p*.95,m+p*.1).quadraticCurveTo(p*.8,m+p*.8,p*.1,m+p*.98).stroke({width:2.4,color:this.theme.sky[0],alpha:.28,cap:"round"}),u.ellipse(h.face*1.2,-7.5,6.5,5.5).fill({color:s.belly,alpha:.92}),u.ellipse(-8+h.face*1.5,-11,2.4,1.5).fill({color:s.cheek,alpha:.45}),u.ellipse(8+h.face*1.5,-11,2.4,1.5).fill({color:s.cheek,alpha:.45});const g=h.moving?Math.sin(i*14)*.25:0,_=s.shape==="tall"?-33:s.shape==="teardrop"?-30:-27;switch(s.topper){case"ears":u.ellipse(-9,_+4+g*6,3.2,5).fill(s.ear),u.ellipse(9,_+4-g*6,3.2,5).fill(s.ear);break;case"tuft":u.moveTo(-3,_+1).quadraticCurveTo(-6,_-9,1,_-12).moveTo(0,_).quadraticCurveTo(4,_-10,8,_-8).stroke({width:2.2,color:s.ear,cap:"round"});break;case"leaf":u.moveTo(0,_).quadraticCurveTo(2+g*10,_-8,8,_-12).quadraticCurveTo(4,_-4,0,_).fill(s.ear),u.moveTo(0,_).lineTo(5,_-7).stroke({width:1,color:s.belly,alpha:.7});break;case"crest":for(const S of[-6,-2,2,6])u.moveTo(S,_+1).lineTo(S*1.4,_-7-Math.abs(S)*.3).stroke({width:2.4,color:s.ear,cap:"round"});break;case"halo":u.ellipse(0,_-7,9,2.6).stroke({width:1.8,color:this.theme.mood[h.mood],alpha:.9});break;case"antenna":u.ellipse(-9,_+4+g*6,3.2,5).fill(s.ear),u.ellipse(9,_+4-g*6,3.2,5).fill(s.ear);break}const x=h.face*1.8,y=-16,b=!this.reducedMotion&&i%3.3<.13&&h.mood!=="happy";for(const S of[-1,1]){const E=x+S*4.6;if(h.mood==="happy"){u.beginPath(),u.arc(E,y+1.5,2.8,Math.PI*1.1,Math.PI*1.9).stroke({width:1.6,color:s.ink,cap:"round"});continue}if(b){u.moveTo(E-2.6,y).lineTo(E+2.6,y).stroke({width:1.6,color:s.ink,cap:"round"});continue}if(s.eyes==="visor"){S<0&&(u.roundRect(x-8.5,y-3,17,6,3).fill(16777215),u.roundRect(x-7+(h.look==="up"?0:1),y-1.5,5,3,1.5).fill(s.ink),u.roundRect(x+2+(h.look==="up"?0:1),y-1.5,5,3,1.5).fill(s.ink));continue}const k=s.eyes==="dot"?2.6:s.eyes==="sleepy"?2.4:h.mood==="focused"?3:4.3;u.ellipse(E,y,s.eyes==="dot"?2.6:3.4,k).fill(16777215),s.eyes==="sleepy"&&u.moveTo(E-3.4,y-2.2).lineTo(E+3.4,y-2.2).stroke({width:2,color:s.body});const P=!h.moving&&!this.reducedMotion&&i%4.1>3.3?Math.sin((i%4.1-3.3)/.8*Math.PI):0;let T=h.face*1.1+P*1.6,A=(h.look==="up"?-1.6:h.look==="down"?1.4:.3)-P*.8;h.mood==="lost"&&(T=Math.sin(i*3)*1.4,A=-1.2),u.ellipse(E+T,y+A,1.9,h.mood==="focused"?1.8:2.2).fill(s.ink),u.ellipse(E+T+.7,y+A-.8,.6,.6).fill(16777215),h.mood==="lost"&&u.moveTo(E-3,y-5.6-(S>0?0:1.3)).lineTo(E+3,y-5.6-(S>0?1.3:0)).stroke({width:1.6,color:s.ink,cap:"round"}),h.mood==="focused"&&u.moveTo(E-3.2,y-3.7-(S>0?1:0)).lineTo(E+3.2,y-3.7-(S>0?0:1)).stroke({width:1.6,color:s.ink,cap:"round"}),h.mood==="uneasy"&&u.moveTo(E-3,y-5).lineTo(E+3,y-6+(S>0?1.5:-1.5)).stroke({width:1.4,color:s.ink,cap:"round"})}u.beginPath(),h.mood==="happy"?u.arc(x,-10.5,3.2,0,Math.PI).fill(8007202):h.mood==="lost"||h.mood==="uneasy"?u.arc(x,-8.4,2.2,Math.PI*1.15,Math.PI*1.85).stroke({width:1.6,color:s.ink,cap:"round"}):u.arc(x,-11.2,1.9,Math.PI*.15,Math.PI*.85).stroke({width:1.6,color:s.ink,cap:"round"});const w=(this.reducedMotion?0:Math.sin(i*5)*2)-h.lean*10,v=this.theme.mood[h.mood];if(s.topper==="antenna"?(u.moveTo(0,_+.5).quadraticCurveTo(w*.5,_-5,w+1.5,_-9).stroke({width:1.4,color:s.ear}),u.circle(w+1.5,_-10,9).fill({color:v,alpha:.28}),u.circle(w+1.5,_-10,5.5).fill({color:v,alpha:.35}),u.circle(w+1.5,_-10,2.8).fill(v)):s.topper!=="halo"&&(u.circle(0,_-2,7).fill({color:v,alpha:.22}),u.circle(0,_-2,2.2).fill({color:v,alpha:.9})),h.hiding>0){const S=tt(i*.5%1)*h.hiding;u.rotation=h.lean+S*.06}}}const fb=Object.freeze(Object.defineProperty({__proto__:null,Pip:Bo},Symbol.toStringTag,{value:"Module"})),je={wave:"triangle",pitch:1,decay:1,tone:3200,surface:"grass"},Bn={wave:"square",pitch:1.18,decay:.8,tone:2600,surface:"metal"},hu={wave:"sawtooth",pitch:.95,decay:1.1,tone:2200,surface:"stone"},Pg={island:{voice:je,ambience:{washes:[{hz:520,q:.6,gain:.09,lfoHz:.11,depth:.6},{hz:240,q:.9,gain:.05,lfoHz:.07,depth:.8}],extras:["gull","cricket"],every:9}},orbit:{voice:Bn,ambience:{washes:[{hz:900,q:2,gain:.015,lfoHz:.05,depth:.9}],pad:{chord:[55,110,164.8],gain:.05,wave:"sine"},extras:["hum","chime"],every:11}},metropolis:{voice:hu,ambience:{washes:[{hz:380,q:.5,gain:.07,lfoHz:.2,depth:.5}],pad:{chord:[65.4,98],gain:.03,wave:"triangle"},extras:["horn","hum"],every:10}},harbour:{voice:{...je,surface:"wood",decay:1.3},ambience:{washes:[{hz:420,q:.6,gain:.1,lfoHz:.09,depth:.7}],extras:["gull","bell","horn"],every:8}},observatory:{voice:{...Bn,wave:"sine",pitch:1.3,decay:1.6,tone:4e3,surface:"stone"},ambience:{washes:[{hz:300,q:.8,gain:.04,lfoHz:.04,depth:.9}],pad:{chord:[49,98,146.8],gain:.04,wave:"sine"},extras:["wind","chime"],every:12}},greenhouse:{voice:{...je,pitch:1.1,decay:1.2},ambience:{washes:[{hz:600,q:.6,gain:.05,lfoHz:.1,depth:.5}],extras:["cricket","drip","bell"],every:7}},workshop:{voice:{...je,wave:"triangle",pitch:.9,decay:.8,tone:2800,surface:"wood"},ambience:{washes:[{hz:500,q:.6,gain:.05,lfoHz:.12,depth:.5}],extras:["cricket","bell"],every:9}},arcade:{voice:{wave:"square",pitch:1.35,decay:.6,tone:3600,surface:"neon"},ambience:{washes:[{hz:300,q:.5,gain:.05,lfoHz:.25,depth:.4}],pad:{chord:[65.4,82.4,98],gain:.03,wave:"square"},extras:["chime","horn"],every:6}},kingdom:{voice:{...je,wave:"triangle",pitch:.85,decay:1.5,tone:2400,surface:"stone"},ambience:{washes:[{hz:450,q:.6,gain:.07,lfoHz:.1,depth:.6}],extras:["bell","wind","owl"],every:10}},outpost:{voice:{...je,pitch:.92,decay:1.4,tone:2600,surface:"sand"},ambience:{washes:[{hz:700,q:.4,gain:.08,lfoHz:.06,depth:.9}],extras:["wind","hum"],every:9}},snowfield:{voice:{...je,wave:"sine",pitch:1.15,decay:1.7,tone:3400,surface:"snow"},ambience:{washes:[{hz:800,q:.4,gain:.05,lfoHz:.05,depth:.9}],extras:["wind","chime","owl"],every:11}},canopy:{voice:{...je,pitch:1.05,decay:1.2,tone:3e3,surface:"wood"},ambience:{washes:[{hz:650,q:.7,gain:.07,lfoHz:.09,depth:.5}],extras:["cricket","owl","drip"],every:6}},lagoon:{voice:{...je,wave:"sine",pitch:1.2,decay:1.3,tone:3600,surface:"sand"},ambience:{washes:[{hz:480,q:.6,gain:.1,lfoHz:.1,depth:.7}],extras:["gull","bubble"],every:8}},volcano:{voice:{wave:"sawtooth",pitch:.75,decay:1.6,tone:1600,surface:"stone"},ambience:{washes:[{hz:160,q:1,gain:.1,lfoHz:.08,depth:.8}],pad:{chord:[41.2,61.7],gain:.04,wave:"sawtooth"},extras:["rumble","wind"],every:8}},cloudtop:{voice:{...je,wave:"sine",pitch:1.25,decay:1.8,tone:4200,surface:"grass"},ambience:{washes:[{hz:900,q:.4,gain:.05,lfoHz:.04,depth:.9}],pad:{chord:[130.8,196,261.6],gain:.025,wave:"sine"},extras:["wind","chime"],every:12}},reef:{voice:{wave:"sine",pitch:.9,decay:1.9,tone:1400,surface:"water"},ambience:{washes:[{hz:220,q:1.2,gain:.09,lfoHz:.09,depth:.7}],extras:["bubble","drip"],every:5}},bazaar:{voice:{...je,pitch:1.05,decay:.9,tone:3e3,surface:"sand"},ambience:{washes:[{hz:500,q:.5,gain:.06,lfoHz:.3,depth:.4}],extras:["market","bell","chime"],every:6}},monastery:{voice:{...je,wave:"sine",pitch:.95,decay:2,tone:2600,surface:"stone"},ambience:{washes:[{hz:420,q:.5,gain:.05,lfoHz:.05,depth:.8}],extras:["bell","wind","owl"],every:12}},moonbase:{voice:{...Bn,pitch:1.05,decay:1.2,tone:2200},ambience:{washes:[{hz:240,q:1.5,gain:.03,lfoHz:.03,depth:.9}],pad:{chord:[55,82.4],gain:.04,wave:"sine"},extras:["hum","chime"],every:13}},lanterns:{voice:{...hu,wave:"triangle",pitch:1.1,decay:1.2,tone:3e3,surface:"stone"},ambience:{washes:[{hz:400,q:.5,gain:.05,lfoHz:.2,depth:.5}],extras:["market","chime","bell"],every:6}}},pb=new Set(["curtain_up","curtain_down","test_outcome","celebrate","blocked_on_you","unverified_claim","spawn_gremlin","banish"]),mb=[523.25,659.25,783.99,1046.5],Ie=(r,e)=>r+Math.random()*(e-r);class $r{constructor(e){this.a=e}footstep(e,t){const s=this.a;switch(e){case"stone":s.noise(.04,{filter:"bandpass",freq:Ie(1400,1900),q:2,gain:.05,pan:t}),s.tone(Ie(160,200),.03,{type:"triangle",gain:.03,pan:t});return;case"metal":s.tone(Ie(700,900),.05,{type:"square",gain:.03,lowpass:2e3,pan:t}),s.noise(.03,{filter:"highpass",freq:3e3,gain:.03,pan:t});return;case"sand":s.noise(.09,{filter:"lowpass",freq:Ie(700,1e3),q:.5,gain:.05,pan:t});return;case"snow":s.noise(.08,{filter:"bandpass",freq:Ie(2500,3500),q:.8,gain:.04,pan:t});return;case"wood":s.tone(Ie(220,300),.05,{type:"triangle",gain:.05,slideTo:120,pan:t});return;case"water":s.noise(.08,{filter:"bandpass",freq:Ie(400,700),q:1,gain:.05,sweepTo:1200,pan:t});return;case"neon":s.tone(Ie(900,1200),.035,{type:"square",gain:.025,lowpass:3e3,pan:t});return;default:s.noise(.05,{filter:"bandpass",freq:Ie(900,1300),q:1.2,gain:.05,pan:t});return}}static plays(e,t){return t<=1.01||pb.has(e)}play(e,t){const s=this.a,i=t.pan??0,n=t.intensity??.5,o=Pg[t.theme.id].voice,a={tone:(l,h,c={})=>s.tone(l*o.pitch,h*o.decay,{...c,type:c.type??o.wave,lowpass:Math.min(c.lowpass??o.tone,o.tone),...c.slideTo?{slideTo:c.slideTo*o.pitch}:{}}),noise:s.noise.bind(s)};if(e==="footstep")return this.footstep(o.surface,i);switch(e){case"curtain_up":a.tone(392,1.2,{attack:.3,gain:.14}),a.tone(587.3,1.3,{attack:.5,gain:.1}),a.tone(784,1.4,{attack:.7,gain:.08});return;case"curtain_down":a.tone(523.25,1.6,{attack:.2,gain:.12}),a.tone(392,1.8,{attack:.4,gain:.1});return;case"walk_to":return;case"read":a.noise(.14,{filter:"highpass",freq:2500,sweepTo:6e3,gain:.07,pan:i}),a.tone(2200,.05,{gain:.04,pan:i});return;case"hammer":a.tone(Ie(180,240)*(1+n*.4),.06,{type:"triangle",gain:.12+n*.1,slideTo:90,pan:i}),a.noise(.03,{filter:"bandpass",freq:3e3,q:2,gain:.05,pan:i});return;case"build":return;case"raise":a.tone(220,.7,{type:"sawtooth",slideTo:660,gain:.08,lowpass:1800,pan:i}),a.tone(440,.3,{gain:.06,pan:i,attack:.3});return;case"forge":a.tone(620,.25,{type:"square",gain:.06,slideTo:580,lowpass:2400,pan:i}),a.tone(1240,.18,{type:"triangle",gain:.05,detune:30,pan:i}),a.noise(.08,{filter:"highpass",freq:4e3,gain:.04,pan:i});return;case"spark":a.tone(Ie(2500,4200),.04,{gain:.03,pan:i});return;case"search":a.noise(.35,{filter:"bandpass",freq:700,sweepTo:2600,q:1.5,gain:.08,pan:i}),a.tone(1568,.12,{gain:.05,pan:i,attack:.02});return;case"run_tests":a.tone(330,.9,{attack:.15,gain:.06,type:"triangle",lowpass:1200,pan:i}),a.tone(495,.9,{attack:.25,gain:.04,type:"triangle",lowpass:1200,pan:i});return;case"test_outcome":t.outcome==="pass"?mb.forEach((l,h)=>setTimeout(()=>a.tone(l,.5,{gain:.12,attack:.01,pan:i}),h*70)):(a.tone(311,.35,{type:"sawtooth",gain:.09,lowpass:900,slideTo:262,pan:i}),setTimeout(()=>a.tone(233,.5,{type:"sawtooth",gain:.09,lowpass:700,slideTo:196,pan:i}),170));return;case"spawn_gremlin":for(let l=0;l<4;l++)setTimeout(()=>a.tone(Ie(900,1300)+l*80,.07,{type:"square",gain:.05,lowpass:2600,slideTo:Ie(700,1100),pan:i}),l*60);return;case"chase":for(let l=0;l<3;l++)setTimeout(()=>a.tone(600+l*120,.08,{type:"triangle",gain:.06,pan:i}),l*90);return;case"banish":a.noise(.06,{filter:"lowpass",freq:1500,gain:.14,pan:i}),setTimeout(()=>a.tone(2093,.25,{gain:.07,pan:i}),40),setTimeout(()=>a.tone(2637,.3,{gain:.05,pan:i}),90);return;case"celebrate":[523.25,659.25,783.99,1046.5,1318.5].forEach((l,h)=>setTimeout(()=>a.tone(l,.45,{gain:.11,attack:.01,pan:i}),h*60));for(let l=0;l<10;l++)setTimeout(()=>a.tone(Ie(1800,4e3),.05,{gain:.03,pan:Ie(-.8,.8)}),200+l*55);return;case"summon_helper":t.theme.id==="orbit"?a.noise(.7,{filter:"bandpass",freq:300,sweepTo:1800,q:1.2,gain:.1,pan:i}):t.theme.id==="metropolis"?(a.tone(880,.12,{type:"square",gain:.06,lowpass:2500,pan:i}),setTimeout(()=>a.tone(880,.12,{type:"square",gain:.06,lowpass:2500,pan:i}),180)):(a.tone(146.8,.8,{type:"triangle",attack:.08,gain:.12,lowpass:800,pan:i}),a.tone(147.5,.8,{type:"triangle",attack:.08,gain:.08,lowpass:800,pan:i}));return;case"dismiss_helper":a.noise(.5,{filter:"bandpass",freq:1800,sweepTo:300,q:1.2,gain:.07,pan:i});return;case"blocked_on_you":a.tone(880,.35,{gain:.16,attack:.01}),setTimeout(()=>a.tone(659.25,.6,{gain:.16,attack:.01}),220);return;case"your_turn":a.tone(1046.5,.5,{gain:.07,attack:.02});return;case"stumble":a.noise(.12,{filter:"lowpass",freq:400,gain:.14,pan:i}),a.tone(120,.25,{type:"triangle",gain:.1,slideTo:70,pan:i});return;case"unverified_claim":a.tone(196,.14,{type:"triangle",gain:.07,lowpass:900,pan:i}),setTimeout(()=>a.tone(185,.14,{type:"triangle",gain:.07,lowpass:900,pan:i}),240),setTimeout(()=>a.tone(174.6,.24,{type:"triangle",gain:.06,lowpass:900,pan:i}),480);return;case"idle":return}}}class gb{constructor(e){this.a=e}stops=[];current=null;padStop=null;padMood=null;extraTimer=null;start(e){if(!this.a.ready||this.current===e.id)return;this.stop(),this.current=e.id;const t=Pg[e.id].ambience;for(const i of t.washes)this.stops.push(this.a.wash(i.hz,i.q,i.gain,i.lfoHz,i.depth));t.pad&&this.stops.push(this.a.pad(t.pad.chord,t.pad.gain,t.pad.wave));const s=()=>{if(this.current!==e.id)return;const i=t.extras[Math.floor(Math.random()*t.extras.length)];i&&this.a.extra(i),this.extraTimer=setTimeout(s,t.every*1e3*(.5+Math.random()))};this.extraTimer=setTimeout(s,2e3+Math.random()*3e3)}setMood(e){if(!this.a.ready||e===this.padMood)return;this.padMood=e,this.padStop?.();const t=e==="happy"?[261.6,329.6,392]:e==="lost"?[261.6,311.1,370]:e==="uneasy"?[261.6,311.1,392]:e==="focused"?[261.6,392]:[261.6,329.6];this.padStop=this.a.pad(t.map(s=>s/2),.022,"sine")}stop(){this.extraTimer&&clearTimeout(this.extraTimer),this.extraTimer=null;for(const e of this.stops)e();this.stops=[],this.padStop?.(),this.padStop=null,this.padMood=null,this.current=null}}class qs{constructor(e,t,s,i,n,o){this.app=e,this.world=t,this.theme=s,this.audio=i,this.reducedMotion=n,this.worldLayer=new Sg(t,s),this.particles=new ub(n),this.company=kg(t.seed,o,s.ground.fill),this.pip=new Bo(s,n,this.company.lead),this.camera=new nb(this.stage,n),this.sfx=new $r(i),this.amb=new gb(i),this.stage.sortableChildren=!0,this.stage.addChild(this.worldLayer.container),this.worldLayer.container.sortableChildren=!0,this.worldLayer.container.addChild(this.pip.container,this.particles.g),this.particles.g.zIndex=1e7,e.stage.addChild(this.stage),this.actorAt.set("pip","forge"),this.fitCamera(),this.camera.snap()}stage=new _e;worldLayer;camera;pip;helpers=new Map;gremlins=new Map;particles;sfx;amb;beats=[];t=0;prevT=-1;_playing=!1;rate=1;duration=0;mood="curious";actorAt=new Map;walkFrom=new Map;growth=new Map;lastPass=0;signal="ok";footT=0;hammerT=0;claimGremlinId=null;evidenceCount=null;company;helperIndex=0;load(e){this.beats=e,this.duration=e.length?Math.max(...e.map(t=>t.atMs+t.durationMs)):0,this.seek(0)}get beatCount(){return this.beats.length}append(e){this.beats.push(...e),this.duration=Math.max(this.duration,...e.map(t=>t.atMs+t.durationMs))}get playing(){return this._playing}play(){this._playing=!0,this.amb.start(this.theme)}audioReady(){this.amb.stop(),this._playing&&this.amb.start(this.theme)}pause(){this._playing=!1}setRate(e){this.rate=e}setSignal(e){this.signal=e}seek(e){this.t=Math.max(0,Math.min(this.duration,e)),this.rebuild(this.t),this.prevT=this.t,this.particles.clear()}get leadName(){return this.company.lead.name}get state(){const e=this.currentBeat();return{t:this.t,duration:this.duration,playing:this._playing,rate:this.rate,current:e,mood:this.mood,bubble:this.bubble(e),labels:this.labels(e),evidence:this.evidenceCount!==null?{passed:this.evidenceCount}:null,signal:this.signal}}update(e){this._playing&&(this.t=Math.min(this.duration,this.t+e*this.rate),this.t>=this.duration&&this.duration>0&&(this._playing=!1),this.triggerBetween(this.prevT,this.t),this.prevT=this.t);const t=this.currentBeat();this.pose(t,e),this.worldState(t),this.worldLayer.update(e),this.pip.update(e);for(const s of this.helpers.values())s.update(e);for(const s of this.gremlins.values())s.update(e);this.particles.update(e),this.cameraStep(t,e),this.amb.setMood(this.mood)}currentBeat(){let e=null;for(const t of this.beats)if(t.atMs<=this.t)(!e||t.atMs>=e.atMs)&&(t.kind==="idle"&&e&&e.kind!=="idle"&&e.atMs+e.durationMs>this.t||(e=t));else break;return e}completed(){return this.beats.filter(e=>e.atMs+e.durationMs<=this.t)}rebuild(e){this.actorAt.clear(),this.actorAt.set("pip","forge"),this.growth.clear(),this.lastPass=0,this.evidenceCount=null,this.mood="curious",this.claimGremlinId=null,this.helperIndex=0;for(const s of this.gremlins.values())s.container.destroy();this.gremlins.clear();for(const s of this.helpers.values())s.container.destroy();this.helpers.clear();for(const s of this.world.places)this.worldLayer.setLamp(s.id,"idle"),this.worldLayer.setGrowth(s.id,0),this.worldLayer.setGlow(s.id,0),this.worldLayer.setScaffold(s.id,0);for(const s of this.beats){if(s.atMs>e)break;this.onStart(s,!0),s.atMs+s.durationMs<=e&&this.onEnd(s,!0)}this.pip.pose.mood=this.mood;const t=this.worldLayer.standingSpot(this.actorAt.get("pip")??"forge");this.pip.pose.x=t.x,this.pip.pose.y=t.y,this.pip.snap(),this.camTarget=null,this.fitCamera(),this.cameraStep(this.currentBeat(),0),this.camera.snap()}triggerBetween(e,t){for(const s of this.beats){s.atMs>e&&s.atMs<=t&&this.onStart(s,!1);const i=s.atMs+s.durationMs;i>e&&i<=t&&this.onEnd(s,!1)}}onStart(e,t){this.mood=e.mood;const s=this.theme,i=o=>{const a=this.worldLayer.positionOf(o);return a?Math.max(-.8,Math.min(.8,a.ground.x/600)):0},n=(o,a={})=>{!t&&$r.plays(o,this.rate)&&this.sfx.play(o,{theme:s,...a})};switch(e.kind){case"curtain_up":n("curtain_up"),t||this.camera.pushIn(.12);break;case"walk_to":{const o=this.worldLayer.standingSpot(this.actorAt.get(e.actor)??"forge");this.walkFrom.set(e.actor,o);break}case"read":n("read",{pan:i(e.target)});break;case"raise":{if(e.newPlace&&!this.worldLayer.has(e.target)){const o=this.world.districts.find(l=>l.id===e.newPlace.district)??this.world.districts[0],a={id:e.target,kind:e.newPlace.kind,path:e.newPlace.path,label:e.newPlace.label,district:e.newPlace.district,gx:(o?.cx??2)+1,gy:(o?.cy??2)+1,footprint:1,height:1,score:0,touched:!0};this.world.places.push(a),this.worldLayer.addPlace(a)}n("raise",{pan:i(e.target)});break}case"build":n("build");break;case"forge":n("forge");break;case"search":n("search",{pan:i("forge")});break;case"run_tests":this.worldLayer.setLamp(e.target,"scan"),n("run_tests",{pan:i(e.target)});break;case"test_outcome":{const o=e.outcome==="pass"?"pass":e.outcome==="fail"?"fail":"idle";if(this.worldLayer.setLamp(e.target,o),e.outcome==="pass"&&(this.lastPass=e.atMs,this.evidenceCount=e.passed),n("test_outcome",{outcome:e.outcome,pan:i(e.target)}),!t&&e.outcome==="fail"&&this.camera.shake(200),!t&&e.outcome==="pass"){const a=this.worldLayer.positionOf(e.target);a&&this.particles.burst(a.top.x,a.top.y,16,[s.beacon.lamp.pass,14090217],70,40)}break}case"spawn_gremlin":{const o=new Ro(e.gremlinId,s,this.reducedMotion),a=this.worldLayer.positionOf(e.target),l=a?a.ground:K(0,0);o.x=l.x+18,o.y=l.y+8,o.scale=t?1:.01,this.worldLayer.container.addChild(o.container),this.gremlins.set(e.gremlinId,o),n("spawn_gremlin",{pan:i(e.target)}),t||(this.camera.pushIn(.06),this.particles.burst(o.x,o.y-10,18,[s.gremlin.body,11967743],60,30));break}case"chase":{const o=this.gremlins.get(e.gremlinId);o&&(o.panic=1),n("chase",{pan:i(e.target)});break}case"banish":{const o=this.gremlins.get(e.gremlinId);o&&(t||this.particles.burst(o.x,o.y-10,30,[16777215,s.gremlin.body],80,35),o.container.destroy(),this.gremlins.delete(e.gremlinId)),this.claimGremlinId===e.gremlinId&&(this.claimGremlinId=null,this.pip.pose.hiding=0),n("banish");break}case"celebrate":{if(n("celebrate"),!t){this.camera.pushIn(.1);const o=this.worldLayer.standingSpot(this.actorAt.get("pip")??"forge");this.particles.burst(o.x,o.y-30,56,[16758087,6287526,8177919,16743273,11967743,16777215],130,90)}break}case"summon_helper":{const o=this.company.helpers[this.helperIndex++%this.company.helpers.length],a=new Bo(s,this.reducedMotion,o);a.container.scale.set(.82*o.size);const l=this.worldLayer.standingSpot("dock");a.pose.x=l.x,a.pose.y=l.y,this.worldLayer.container.addChild(a.container),this.helpers.set(e.helperId,a),this.actorAt.set(e.helperId,"dock"),n("summon_helper",{pan:i("dock")});break}case"dismiss_helper":n("dismiss_helper",{pan:i("dock")});break;case"blocked_on_you":n("blocked_on_you");break;case"your_turn":n("your_turn");break;case"stumble":n("stumble"),t||this.camera.shake(160);break;case"unverified_claim":{const o=new Ro(e.gremlinId,s,this.reducedMotion);o.scale=.8,o.alpha=.95,this.worldLayer.container.addChild(o.container),this.gremlins.set(e.gremlinId,o),this.claimGremlinId=e.gremlinId,this.pip.pose.hiding=1,n("unverified_claim");break}case"curtain_down":n("curtain_down");break}}onEnd(e,t){switch(e.kind){case"walk_to":this.actorAt.set(e.actor,e.target),this.walkFrom.delete(e.actor);break;case"build":this.growth.set(e.target,Math.min(18,(this.growth.get(e.target)??0)+3+Math.round(e.intensity*6))),this.worldLayer.setGrowth(e.target,this.growth.get(e.target)),this.worldLayer.setScaffold(e.target,0);break;case"dismiss_helper":{const s=this.helpers.get(e.helperId);s&&(s.container.destroy(),this.helpers.delete(e.helperId),this.actorAt.delete(e.helperId));break}}}pose(e,t){const s=t/1e3;for(const[i,n]of[["pip",this.pip],...this.helpers.entries()]){const o=n.pose;o.moving=!1,o.lift=0,o.sx=1,o.sy=1,o.lean=0,o.look="fwd",o.mood=this.mood;const a=e&&e.actor===i?e:null,l=this.worldLayer.standingSpot(this.actorAt.get(i)??(i==="pip"?"forge":"dock"));if(o.x=l.x,o.y=l.y,!a){i!=="pip"&&(o.sy=.96);continue}const h=Ue(this.t,a.atMs,a.atMs+a.durationMs),c="target"in a?this.worldLayer.standingSpot(a.target):l;switch(a.kind){case"curtain_up":{o.lift=(1-Math.min(1,h/.5))**2*150,o.sy=h<.5?1.1:1-.25*tt(Ue(h,.5,.75)),o.sx=1/o.sy;break}case"walk_to":{const u=this.walkFrom.get(i)??l,d=Math.min(.22,140/a.durationMs),f=h<d?0:An((h-d)/(1-d));if(o.x=Jt(u.x,c.x,f),o.y=Jt(u.y,c.y,f),o.moving=h>=d&&h<.98,o.face=c.x>=u.x?1:-1,h<d){const p=tt(h/d);o.sy=1-.1*p,o.sx=1+.08*p,o.lean=-o.face*.12*p}else{const p=this.t/1e3*(this.mood==="lost"?16:11);o.lift=Math.abs(Math.sin(p))*3.5;const m=Math.cos(p*2);if(o.sy=1+.05*m,o.sx=1-.05*m,o.lean=o.face*.07,h>.86){const g=tt((h-.86)/.14);o.lean=o.face*.16*g,o.sy=1-.06*g,o.sx=1+.05*g}}i==="pip"&&this._playing&&(this.footT+=s,this.footT>.19&&$r.plays("footstep",this.rate)&&(this.footT=0,this.sfx.play("footstep",{theme:this.theme,pan:Math.max(-.8,Math.min(.8,o.x/600))})));break}case"read":{const u=tt(this.t/1e3%1.4/.25);o.lean=-.17+Math.sin(this.t/1e3*3)*.03-u*.05,o.sy=1-u*.03,o.face=this.facing(o,a.target);break}case"build":case"forge":{const u=a.kind==="build"?.28-a.intensity*.1:.34,d=this.t/1e3%u/u,f=d<.7?d/.7:1-(d-.7)/.3;if(o.lift=f*4,o.lean=d<.7?-.06*f:.12*(1-f),o.sy=d<.7?1+.04*f:1-.08*(1-f),o.sx=1/o.sy,"target"in a&&(o.face=this.facing(o,a.target)),i==="pip"&&this._playing&&!this.reducedMotion){this.hammerT+=s;const p=a.kind==="build"?.28-a.intensity*.1:.34;if(this.hammerT>p){this.hammerT=0,$r.plays("hammer",this.rate)&&this.sfx.play(a.kind==="build"?"hammer":"spark",{theme:this.theme,intensity:a.kind==="build"?a.intensity:.5});const m="target"in a?this.worldLayer.positionOf(a.target):this.worldLayer.positionOf("forge");m&&Math.random()<.7&&this.particles.burst(m.top.x+(Math.random()*24-12),m.top.y+10,2,[16766571,16774084],50,60)}}break}case"raise":o.look="up",o.sy=1+.05*tt(h);break;case"search":o.look="up",o.lean=Math.sin(this.t/1e3*1.5)*.12;break;case"run_tests":o.look="up",o.lean=Math.sin(this.t/1e3*2)*.04;break;case"test_outcome":if(a.outcome==="fail"){const u=tt(Ue(h,0,.5));o.lean=-.25*u,o.sy=1-.1*u,o.sx=1+.08*u}else o.lift=tt(h)*14;break;case"spawn_gremlin":{const u=tt(Ue(h,0,.5));o.lift=Math.sin(Math.PI*Ue(h,.05,.45))*12,o.lean=-.22*u,o.sx=1+.1*u,o.sy=1-.1*u,o.look="down",o.x=l.x-o.face*10*u;break}case"chase":{const u=this.gremlins.get(a.gremlinId),d=c,f=h*Math.PI*2*1.5,p=26,m=d.x+Math.cos(f)*p,g=d.y+Math.sin(f)*p*.5;u&&(u.x=m,u.y=g,u.panic=1);const _=f-1.1;o.x=d.x+Math.cos(_)*p,o.y=d.y+Math.sin(_)*p*.5,o.moving=!0,o.face=Math.cos(f)>Math.cos(_)?1:-1;const x=this.t/1e3*16;o.lift=Math.abs(Math.sin(x))*4,o.lean=o.face*.12;break}case"banish":{o.sy=1-.2*tt(Ue(h,0,.4)),o.sx=1/o.sy;break}case"celebrate":{const u=(this.t-a.atMs)%1300/1300;if(u<.22){const d=Math.sin(Math.PI*u/.22);o.sy=1-.24*d,o.sx=1+.2*d}else if(u<.8){const d=(u-.22)/.58;o.lift=Math.sin(Math.PI*d)*32,o.sy=d<.5?1+.14*(1-d*2):1,o.sx=1/o.sy}else{const d=Math.sin(Math.PI*(u-.8)/.2);o.sy=1-.2*d,o.sx=1+.16*d}break}case"blocked_on_you":o.face=1,o.look="fwd",o.sy=1+.03*Math.sin(this.t/1e3*6),o.sx=1/o.sy;break;case"your_turn":o.sy=.86,o.sx=1.08;break;case"stumble":{const u=tt(Ue(h,0,.7));o.lean=Math.sin(this.t/1e3*40)*.12*u,o.sy=1-.08*u,o.sx=1+.06*u;break}case"unverified_claim":{o.face=1,o.hiding=1;const u=this.claimGremlinId?this.gremlins.get(this.claimGremlinId):null;u&&(u.x=o.x-o.face*14,u.y=o.y-2,u.peek=1);break}case"curtain_down":o.lean=Math.sin(this.t/1e3*6)*.15,o.face=1;break}if(this.claimGremlinId&&a.kind!=="unverified_claim"){const u=this.gremlins.get(this.claimGremlinId);u&&(u.x=o.x-o.face*14,u.y=o.y-2)}n.container.zIndex=o.y/(Ao/2)+.6,i!=="pip"&&(o.mood="focused")}for(const i of this.gremlins.values())i.container.zIndex=i.y/(Ao/2)+.7}facing(e,t){const s=this.worldLayer.positionOf(t);return s&&s.ground.x<e.x?-1:1}worldState(e){for(const t of this.world.places)this.worldLayer.setGlow(t.id,0);if(e){if((e.kind==="read"||e.kind==="build"||e.kind==="chase"||e.kind==="raise")&&this.worldLayer.setGlow(e.target,e.kind==="read"?.5:1),e.kind==="build"){const t=Ue(this.t,e.atMs,e.atMs+e.durationMs);this.worldLayer.setScaffold(e.target,.85*Math.min(Ue(t,0,.12),1-Ue(t,.85,1))),this.worldLayer.setGrowth(e.target,(this.growth.get(e.target)??0)+Math.round((3+e.intensity*6)*An(t)))}if(e.kind==="raise"){const t=Ue(this.t,e.atMs,e.atMs+e.durationMs);this.worldLayer.positionOf(e.target)&&this.worldLayer.setGrowth(e.target,Math.round(-30*(1-nu(t))))}if(e.kind==="spawn_gremlin"){const t=this.gremlins.get(e.gremlinId);t&&(t.scale=Math.max(.01,nu(Ue(this.t,e.atMs,e.atMs+400))))}for(const t of this.world.places)t.kind==="beacon"&&this.worldLayer.lampOf(t.id)==="pass"&&this.t-this.lastPass>12e3&&this.worldLayer.setLamp(t.id,"idle")}}fitCamera(){this.camera.setZoomFactor(this.fitZoom()),this.baseZoom=this.fitZoom()}baseZoom=1;camTarget=null;cameraStep(e,t){const s={w:this.app.renderer.width/this.app.renderer.resolution,h:this.app.renderer.height/this.app.renderer.resolution},i=s.w<640,n=!e||e.kind==="curtain_up"||e.kind==="curtain_down"||e.kind==="celebrate",o=this.world.places.map(v=>K(v.gx+v.footprint/2,v.gy+v.footprint/2)),a=Math.min(...o.map(v=>v.x))-70,l=Math.max(...o.map(v=>v.x))+70,h=Math.min(...o.map(v=>v.y))-110,c=Math.max(...o.map(v=>v.y))+50,u={x:(a+l)/2,y:(h+c)/2},d=Math.max(.05,this.camera.scale),f=s.w/d/2,p=s.h/d/2,m=(v,S,E)=>S+f>E-f?(S+E)/2:Math.max(S+f,Math.min(E-f,v)),g=(v,S,E)=>S+p>E-p?(S+E)/2:Math.max(S+p,Math.min(E-p,v)),_=this.pip.drawn,x=this.pip.pose.moving?this.pip.pose.face*f*.18:0,y={x:_.x+x,y:_.y-24};if(n||i)this.camTarget=n?{x:u.x,y:u.y}:y;else{this.camTarget||(this.camTarget=y);const v=f*.28,S=p*.26,E=y.x-this.camTarget.x,k=y.y-this.camTarget.y;Math.abs(E)>v&&(this.camTarget.x+=E-Math.sign(E)*v),Math.abs(k)>S&&(this.camTarget.y+=k-Math.sign(k)*S)}const b=m(this.camTarget.x,a,l),w=g(this.camTarget.y,h,c);this.camera.follow(b,w,1),this.camera.setDrift(this.mood==="lost"),this.camera.setZoomFactor(this.zoomFor(e,s.h)),this.camera.update(t,s.w,s.h)}zoomFor(e,t){const s=this.fitZoom();if(!e)return s;const i=Math.max(s,Math.min(1.7,Math.max(.95,t/430)));switch(e.kind){case"curtain_up":return s*Jt(1.08,1,An(Ue(this.t,e.atMs,e.atMs+e.durationMs)));case"curtain_down":return s*1.05;case"celebrate":return s*1.15;default:return i}}fitZoom(){const e=this.world.places.flatMap(l=>[K(l.gx,l.gy),K(l.gx+l.footprint,l.gy+l.footprint)]),t=e.map(l=>l.x),s=e.map(l=>l.y),i=Math.max(60,Math.max(...t)-Math.min(...t)+140),n=Math.max(60,Math.max(...s)-Math.min(...s)+150),o=this.app.renderer.width/this.app.renderer.resolution,a=this.app.renderer.height/this.app.renderer.resolution;return Math.min(o/(i*1.05),a/(n*1.05),2.2)}bubble(e){if(!e)return null;const t=this.pip.pose,s=this.camera.toScreen(t.x+16,t.y-t.lift-52);return e.kind==="read"||e.kind==="search"?{text:"…",color:4219274,screen:s}:e.kind==="spawn_gremlin"||this.mood==="lost"&&e.kind!=="celebrate"?{text:"?",color:14833484,screen:s}:e.kind==="celebrate"?{text:"!",color:2071139,screen:s}:e.kind==="blocked_on_you"?{text:"!",color:16758087,screen:s}:e.kind==="unverified_claim"?{text:"…",color:8215807,screen:s}:null}labels(e){const t=[],s=e&&"target"in e?e.target:null;for(const i of this.world.places){if(i.kind==="forge"||i.kind==="dock")continue;const n=i.id===s,o=i.kind==="beacon"?this.worldLayer.lampOf(i.id):"idle";if(!n&&o==="idle")continue;const a=this.worldLayer.positionOf(i.id);a&&t.push({text:i.label,screen:this.camera.toScreen(a.top.x,a.top.y-2),active:n})}return t}destroy(){this.amb.stop(),this.stage.destroy({children:!0})}}const Ee={id:"island",name:"Island",tagline:"A warm little island at golden hour.",fits:["cli-tool","library","unknown"],flagship:!0,sky:[2191498,1195610],terrain:"island",ground:{fill:6073960,fillLight:10740879,edge:9070154,edgeDark:6966328,sand:15915942},water:{ripple:16777215,rippleAlpha:.24},pathColor:16245940,labelColor:1592880,palettes:[{top:16310456,left:15382917,right:13605734,roof:15495007,roofD:12735050,win:9067068},{top:14478328,left:11455462,right:9153999,roof:5934020,roofD:4616351,win:4219274},{top:13625820,left:9226664,right:6464387,roof:3122570,roofD:2393199,win:3106389},{top:16507860,left:15908774,right:14261124,roof:14248828,roofD:11554657,win:8014418},{top:16774086,left:16112010,right:14268778,roof:14916398,roofD:12220959,win:8018476}],beacon:{top:16514040,left:15855592,right:14276043,roof:14833484,roofD:12141627,win:3820122,lamp:{idle:16766571,scan:16777215,fail:16734798,pass:6287526}},archive:{top:15327743,left:12891376,right:10916824,roof:9073359,roofD:7231664,win:5062278},forge:{top:7041664,left:4937059,right:3621201,roof:10265519,roofD:7041664,win:16758087,ember:16751164},dock:{deck:11569754,post:8018490,vessel:15855592},prop:"tree",propColors:[4168284,6472819,9067066],gremlin:{body:8215807,eye:1773616},pip:{body:16751164,bodyLight:16765566,belly:16774620,ear:14712620,cheek:16739930,ink:2759959},mood:{curious:16769899,focused:8177919,lost:16743273,happy:6287526,uneasy:16754250},vignette:332832},Rs={...Ee,id:"orbit",name:"Orbit",tagline:"A quiet station turning above a blue planet.",fits:["backend-api","infra-devops","systems"],flagship:!0,sky:[725030,1780309],terrain:"platform",ground:{fill:3885675,fillLight:7045032,edge:2568522,edgeDark:1712695,sand:9082808},water:{ripple:10473727,rippleAlpha:.18},pathColor:13624319,labelColor:14411775,palettes:[{top:15266303,left:12571890,right:9678036,roof:6280191,roofD:3844566,win:8188927},{top:16054011,left:14015464,right:11187143,roof:11967743,roofD:9401062,win:13481983},{top:15138806,left:12185820,right:9423800,roof:6287526,roofD:4177795,win:11075542}],beacon:{top:16777215,left:15133685,right:12174038,roof:6280191,roofD:3844566,win:8188927,lamp:{idle:10473727,scan:16777215,fail:16734798,pass:6287526}},forge:{top:10134712,left:7239820,right:5133930,roof:12634328,roofD:9081768,win:8188927,ember:8188927},dock:{deck:7239820,post:5133930,vessel:16777215},prop:"antenna",propColors:[12174038,8188927,5133930],gremlin:{body:16734878,eye:1773616},vignette:198162},pi={...Ee,id:"metropolis",name:"Metropolis",tagline:"A warm night city, lights just coming on.",fits:["web-frontend","monorepo"],flagship:!0,sky:[1708080,3874127],terrain:"block",ground:{fill:3814736,fillLight:5919864,edge:2762304,edgeDark:1709872,sand:6972296},water:{ripple:16758087,rippleAlpha:.1},pathColor:16767392,labelColor:16771527,palettes:[{top:16769730,left:15907216,right:13208422,roof:16743273,roofD:13916746,win:16766571},{top:14933247,left:12036592,right:9075664,roof:11967743,roofD:9401062,win:16771496},{top:14087423,left:10147568,right:7318220,roof:6280191,roofD:3844566,win:16774084},{top:16770799,left:16234188,right:13929126,roof:16740261,roofD:14241919,win:16766571}],beacon:{top:16119285,left:14277081,right:11579568,roof:16740261,roofD:14241919,win:3355443,lamp:{idle:16758087,scan:16777215,fail:16734798,pass:6287526}},forge:{top:8024976,left:5656684,right:3946572,roof:10656699,roofD:7301256,win:16758087,ember:16758087},dock:{deck:5656684,post:3946572,vessel:16766571},prop:"lamp",propColors:[16766571,16774084,3946572],gremlin:{body:6287526,eye:993820},vignette:525332},_b={...Ee,id:"harbour",name:"Harbour",tagline:"Fog lifting off a working port.",fits:["backend-api","infra-devops"],flagship:!1,sky:[2841971,995135],ground:{fill:8032106,fillLight:11124115,edge:6052434,edgeDark:4012853,sand:13222829},water:{ripple:14283263,rippleAlpha:.3},pathColor:14275261,labelColor:2046506,palettes:[{top:16051424,left:14273459,right:11772806,roof:4090762,roofD:2969446,win:5917242},{top:16247268,left:14925746,right:12556423,roof:13195850,roofD:10503482,win:7027248},{top:15331298,left:12898743,right:10201996,roof:5209950,roofD:3825990,win:3099192}],dock:{deck:9203532,post:5916210,vessel:15223612},prop:"lamp",propColors:[16767392,16773590,4868682],vignette:398879},yb={...Rs,id:"observatory",name:"Observatory",tagline:"A mountaintop under a hard, clear sky.",fits:["data-ml","systems"],flagship:!1,sky:[659504,2367562],terrain:"block",ground:{fill:4867942,fillLight:7236495,edge:3091781,edgeDark:1907502,sand:9275818},water:{ripple:16777215,rippleAlpha:.22},pathColor:14276336,labelColor:15394815,palettes:[{top:15855615,left:13617646,right:10722761,roof:11967743,roofD:9401062,win:16773544},{top:15135743,left:12375795,right:9415113,roof:6280191,roofD:3844566,win:16773544}],beacon:{...Rs.beacon,roof:11967743,roofD:9401062},prop:"antenna",propColors:[13617646,16773544,3091781],vignette:329756},xb={...Ee,id:"greenhouse",name:"Greenhouse",tagline:"Glass, leaves and warm afternoon light.",fits:["data-ml","library"],flagship:!1,sky:[9423280,4098938],ground:{fill:8175466,fillLight:11985823,edge:8020552,edgeDark:5916212,sand:15129779},water:{ripple:16777215,rippleAlpha:.18},pathColor:15985874,labelColor:1985843,palettes:[{top:15794166,left:13496029,right:10735033,roof:8115107,roofD:5220732,win:14286832},{top:16775654,left:15918008,right:13483407,roof:15774556,roofD:13077307,win:8018476},{top:16183551,left:14470131,right:11903953,roof:11832575,roofD:9070294,win:5062278}],prop:"tree",propColors:[5223530,9429132,8018490],vignette:731676},Ag={...Ee,id:"workshop",name:"Workshop",tagline:"A village of makers, sawdust in the air.",fits:["cli-tool","library","systems"],flagship:!1,sky:[14264428,9064238],ground:{fill:10404970,fillLight:13624221,edge:9067066,edgeDark:6701098,sand:15323811},water:{ripple:16771527,rippleAlpha:.2},pathColor:15916982,labelColor:4860432,palettes:[{top:16245699,left:14727562,right:12160867,roof:10902330,roofD:8340265,win:16765566},{top:15919320,left:14206894,right:11574144,roof:6057866,roofD:4543594,win:16765566},{top:16508889,left:15712936,right:13343362,roof:13190970,roofD:10499372,win:16765566}],forge:{...Ee.forge,ember:16758087},prop:"tree",propColors:[5940060,8832366,8014378],vignette:2757640},bb={...pi,id:"arcade",name:"Arcade",tagline:"Neon rain on a late-night strip.",fits:["game","web-frontend"],flagship:!1,sky:[1181734,2756426],ground:{fill:2366012,fillLight:3811932,edge:1445930,edgeDark:788506,sand:5913228},water:{ripple:16732120,rippleAlpha:.12},pathColor:8188927,labelColor:16773375,palettes:[{top:16766710,left:16748512,right:13916856,roof:8188927,roofD:3848406,win:8188927},{top:14284543,left:9430271,right:5944532,roof:16732120,roofD:12987048,win:16773227},{top:16774604,left:16769899,right:14071882,roof:11967743,roofD:9401062,win:16732120}],beacon:{...pi.beacon,roof:16732120,roofD:12987048,lamp:{idle:8188927,scan:16777215,fail:16734798,pass:6287526}},gremlin:{body:16773227,eye:2759173},prop:"lamp",propColors:[16732120,16766710,1445930],vignette:328206},Rg={...Ee,id:"kingdom",name:"Kingdom",tagline:"Stone walls, banners, a river below.",fits:["monorepo","backend-api","unknown"],flagship:!1,sky:[8369113,3894937],ground:{fill:7319134,fillLight:10933647,edge:8354410,edgeDark:6117709,sand:14209725},water:{ripple:16777215,rippleAlpha:.22},pathColor:13616813,labelColor:2828834,palettes:[{top:15855075,left:13880767,right:11248791,roof:4153231,roofD:3032683,win:5917242},{top:15855075,left:13880767,right:11248791,roof:11024954,roofD:8465452,win:5917242},{top:15855075,left:13880767,right:11248791,roof:4882258,roofD:3563581,win:5917242}],beacon:{...Ee.beacon,top:15328470,left:13617334,right:10722701,roof:4153231,roofD:3032683},prop:"tree",propColors:[4165458,7323498,5916212],vignette:858662},vb={...Ee,id:"outpost",name:"Outpost",tagline:"A desert station at dusk, dust in the light.",fits:["infra-devops","cli-tool","systems"],flagship:!1,sky:[15770458,7024458],ground:{fill:14267502,fillLight:15848346,edge:10842175,edgeDark:8016429,sand:15980451},water:{ripple:16769200,rippleAlpha:.14},pathColor:16509124,labelColor:4860432,palettes:[{top:16509392,left:15255450,right:12885875,roof:14246463,roofD:11094061,win:5913120},{top:16182752,left:14667960,right:12101261,roof:3116938,roofD:2321255,win:5913120}],prop:"antenna",propColors:[12885875,16769200,8016429],vignette:2756372},wb={...Ee,id:"snowfield",name:"Snowfield",tagline:"Blue hour, fresh snow, chimney smoke.",fits:["library","docs-content","unknown"],flagship:!1,sky:[10470374,4153231],ground:{fill:15397370,fillLight:16777215,edge:9346485,edgeDark:6714764,sand:14082802},water:{ripple:16777215,rippleAlpha:.3},pathColor:12833768,labelColor:2767442,palettes:[{top:16183526,left:14470070,right:11969164,roof:12077626,roofD:9188648,win:16765566},{top:15791352,left:13358560,right:10661564,roof:4090762,roofD:2969446,win:16765566},{top:15661040,left:13032912,right:10467498,roof:4882258,roofD:3563581,win:16765566}],prop:"tree",propColors:[3107658,5216874,5916212],vignette:858666},Tb={...Ee,id:"canopy",name:"Canopy",tagline:"Treehouses strung through an old forest.",fits:["docs-content","data-ml","library"],flagship:!1,sky:[6266731,2050611],ground:{fill:5214031,fillLight:8372074,edge:5916212,edgeDark:4075556,sand:11050866},water:{ripple:14218704,rippleAlpha:.18},pathColor:14076314,labelColor:15398879,palettes:[{top:15918793,left:14271643,right:11770482,roof:6983487,roofD:5139245,win:16765566},{top:16181976,left:14927782,right:12558206,roof:12085818,roofD:9195306,win:16765566}],prop:"tree",propColors:[3111487,6075226,4863268],vignette:398860},Sb={...Ee,id:"lagoon",name:"Lagoon",tagline:"Turquoise shallows and white sand at noon.",fits:["web-frontend","library","docs-content"],flagship:!1,sky:[8378351,2068408],ground:{fill:10147978,fillLight:13890493,edge:13218430,edgeDark:10719327,sand:16774102},water:{ripple:16777215,rippleAlpha:.36},pathColor:16774620,labelColor:1002074,palettes:[{top:16777215,left:15790056,right:13618628,roof:3126217,roofD:2133923,win:3107450},{top:16774886,left:16769464,right:14728332,roof:16747610,roofD:14051902,win:8014380},{top:15925240,left:13235165,right:10473913,roof:4177818,roofD:2788464,win:2054730}],prop:"tree",propColors:[4169564,9166970,10254916],vignette:536640},Cb={...Ee,id:"volcano",name:"Volcano",tagline:"Black rock, red sky, light from below.",fits:["systems","infra-devops","game"],flagship:!1,sky:[5904922,1705992],ground:{fill:3813167,fillLight:5917256,edge:2365978,edgeDark:1182218,sand:6969942},water:{ripple:16743226,rippleAlpha:.22},pathColor:16751194,labelColor:16769479,palettes:[{top:4866114,left:3813940,right:2761766,roof:16739133,roofD:12864036,win:16758087},{top:5917266,left:4602432,right:3353135,roof:16758087,roofD:14257186,win:16739133}],beacon:{...Ee.beacon,top:3813940,left:2761766,right:2038300,roof:16739133,roofD:12864036,lamp:{idle:16758087,scan:16777215,fail:16734798,pass:6287526}},forge:{...Ee.forge,ember:16739133},dock:{deck:4602432,post:2761766,vessel:16758087},prop:"antenna",propColors:[5917256,16739133,2365978],gremlin:{body:8188927,eye:666160},vignette:655874},Mb={...Rs,id:"cloudtop",name:"Cloudtop",tagline:"A floating town above a sea of cloud.",fits:["web-frontend","mobile","docs-content"],flagship:!1,sky:[13625087,8368358],terrain:"platform",ground:{fill:15988475,fillLight:16777215,edge:14147822,edgeDark:12043480,sand:16777215},water:{ripple:16777215,rippleAlpha:.5},pathColor:16771496,labelColor:2767442,palettes:[{top:16777215,left:15791354,right:13621478,roof:16748448,roofD:14051964,win:16765566},{top:16777215,left:15791354,right:13621478,roof:8177919,roofD:5216982,win:16765566},{top:16777215,left:15791354,right:13621478,roof:11967743,roofD:9401062,win:16765566}],beacon:{...Rs.beacon,roof:16748448,roofD:14051964,lamp:{idle:16765566,scan:16777215,fail:16734798,pass:6287526}},dock:{deck:15791354,post:12043480,vessel:16748448},prop:"tree",propColors:[9426848,13168832,12043480],vignette:4876954},Eb={...Ee,id:"reef",name:"Reef",tagline:"Underwater, where the light comes in ribbons.",fits:["data-ml","game","library"],flagship:!1,sky:[1802144,404032],terrain:"island",ground:{fill:13220234,fillLight:15326384,edge:9075290,edgeDark:5918266,sand:14930854},water:{ripple:10479871,rippleAlpha:.3},pathColor:15984579,labelColor:15137791,palettes:[{top:16767462,left:16752320,right:14052498,roof:16740261,roofD:14241919,win:8006218},{top:16773577,left:16765566,right:14265690,roof:16747610,roofD:14051902,win:8014380},{top:14286838,left:10481880,right:7129520,roof:4177818,roofD:2788464,win:2054730}],prop:"antenna",propColors:[16752320,10481880,9075290],gremlin:{body:1773616,eye:10479871},vignette:136224},kb={...Ag,id:"bazaar",name:"Bazaar",tagline:"Ochre walls, striped awnings, late light.",fits:["monorepo","web-frontend","backend-api"],flagship:!1,sky:[15909498,11033146],ground:{fill:14200945,fillLight:15849120,edge:9067066,edgeDark:6701098,sand:15981742},water:{ripple:16773577,rippleAlpha:.16},pathColor:16773577,labelColor:4860432,palettes:[{top:16640463,left:15386528,right:12885875,roof:14240570,roofD:11024940,win:5913120},{top:16640463,left:15386528,right:12885875,roof:3116938,roofD:2321255,win:5913120},{top:16640463,left:15386528,right:12885875,roof:4153231,roofD:3032683,win:5913120},{top:16640463,left:15386528,right:12885875,roof:14916398,roofD:12220959,win:5913120}],prop:"lamp",propColors:[16765566,16773577,6701098],vignette:2757640},Pb={...Rg,id:"monastery",name:"Monastery",tagline:"Mist on the mountain, a bell somewhere.",fits:["docs-content","library","systems"],flagship:!1,sky:[12110276,5204842],ground:{fill:8363898,fillLight:11585958,edge:6975334,edgeDark:4869703,sand:13093309},water:{ripple:16777215,rippleAlpha:.2},pathColor:14275520,labelColor:2042408,palettes:[{top:15855075,left:13880767,right:11248791,roof:5917242,roofD:4076072,win:16765566},{top:15855075,left:13880767,right:11248791,roof:9058858,roofD:6695454,win:16765566}],prop:"tree",propColors:[4157258,6986346,4863268],vignette:1055256},Ab={...Rs,id:"moonbase",name:"Moonbase",tagline:"Grey dust, black sky, one blue marble.",fits:["systems","infra-devops","data-ml"],flagship:!1,sky:[329228,724248],terrain:"platform",ground:{fill:9276821,fillLight:12105920,edge:6184550,edgeDark:3816e3,sand:11053232},water:{ripple:16777215,rippleAlpha:.28},pathColor:14474468,labelColor:15790326,palettes:[{top:16185082,left:14474468,right:11842750,roof:8188927,roofD:3848406,win:16765566},{top:16185082,left:14474468,right:11842750,roof:16758087,roofD:14257186,win:8188927}],prop:"antenna",propColors:[12105920,8188927,3816e3],vignette:0},Rb={...pi,id:"lanterns",name:"Lanterns",tagline:"A night festival, paper light everywhere.",fits:["web-frontend","game","unknown"],flagship:!1,sky:[1706542,3805232],terrain:"block",ground:{fill:3811908,fillLight:5915750,edge:2365998,edgeDark:1314332,sand:6969976},water:{ripple:16751194,rippleAlpha:.14},pathColor:16767392,labelColor:16771527,palettes:[{top:16771535,left:15910816,right:13211758,roof:14240570,roofD:11024940,win:16765566},{top:16180223,left:14268402,right:11177161,roof:16740261,roofD:14241919,win:16765566},{top:16774870,left:16769952,right:14268778,roof:14916398,roofD:12220959,win:16751194}],prop:"lamp",propColors:[16751194,16769952,2365998],vignette:656404},Tt=[Ee,Rs,pi,_b,yb,xb,Ag,bb,Rg,vb,wb,Tb,Sb,Cb,Mb,Eb,kb,Pb,Ab,Rb],ei=r=>Tt.find(e=>e.id===r)??Ee;function Io(r,e=0){const t=r?.kinds?.length?r.kinds:["unknown"],s=l=>t.reduce((h,c,u)=>h+(l.fits.includes(c)?(t.length-u)*2:0),0)+(l.flagship?1:0),i=Tt.filter(l=>s(l)>1),n=i.length>=3?i:Tt;let o=e>>>0||1;const a=()=>(o^=o<<13,o^=o>>>17,o^=o<<5,(o>>>0)%1e3/1e3);return[...n].map(l=>({s:l,k:s(l)+a()*.5})).sort((l,h)=>h.k-l.k).map(({s:l})=>l)}class ah{constructor(e){this.payload=e}mode="replay";onReady(e){queueMicrotask(()=>e(this.payload))}onBeats(){}}class Bb{constructor(e=""){this.base=e,this.connect()}mode="live";readyCb=null;beatsCb=null;signalCb=null;pending=null;async connect(){const e=await(await fetch(`${this.base}/api/scene`)).json(),t={world:e.world,events:e.events,beats:e.beats,repoId:e.repoId};this.readyCb?this.readyCb(t):this.pending=t,e.signal&&this.signalCb?.(e.signal);const s=()=>{const i=new WebSocket(`${location.origin.replace(/^http/,"ws")}${this.base}/live`);i.onmessage=n=>{const o=JSON.parse(String(n.data));o.type==="beats"&&o.beats&&this.beatsCb?.(o.beats,o.events??[]),o.type==="signal"&&o.state&&this.signalCb?.(o.state)},i.onclose=()=>{this.signalCb?.("lost"),setTimeout(s,2e3)}};s()}onReady(e){if(this.readyCb=e,this.pending){const t=this.pending;this.pending=null,e(t)}}onBeats(e){this.beatsCb=e}onSignal(e){this.signalCb=e}}async function Ib(r,e=""){const t=await fetch(`${e}/api/replay/${encodeURIComponent(r)}`);if(!t.ok)throw new Error(`session not found: ${r}`);const s=await t.json();return new ah({world:s.world,events:s.events,beats:s.beats,repoId:s.title?`${s.repoId} — ${s.title}`:s.repoId})}function Gb(r,e,t){const s=n=>e.places.find(o=>o.id===n)?.label??n.replace(/^p:/,""),i=r.actor==="pip"?"Pip":t?`A helper (${t})`:"A helper";switch(r.kind){case"curtain_up":return`${r.repoId}. Every building on this stage is a file in the repo.`;case"curtain_down":return r.verified?"Curtain. Every claim in this session was backed by a passing test.":"Curtain. Something was called done without a passing test to show for it.";case"walk_to":return`${i} heads to ${s(r.target)}.`;case"read":return`${i} reads ${s(r.target)}.`;case"build":return`${i} is working on ${s(r.target)}${r.intensity>.6?" — a big change":""}.`;case"raise":return`A new file rises: ${s(r.target)}.`;case"forge":return`${i} runs a command at the forge.`;case"search":return r.scope==="web"?`${i} looks something up on the web.`:`${i} searches the repo.`;case"run_tests":return`Running the tests at ${s(r.target)}…`;case"test_outcome":return r.outcome==="pass"?`${r.passed} tests pass.`:r.outcome==="fail"?`${r.failed} test${r.failed===1?"":"s"} fail${r.failed===1?"s":""}.`:"Tests ran — the runner didn't say how many.";case"spawn_gremlin":return`A bug gremlin pops out of ${s(r.target)}.`;case"chase":return`${i} chases the gremlin around ${s(r.target)}.`;case"banish":return"Caught. The gremlin is gone.";case"summon_helper":return`A helper arrives at the dock${r.label?` to ${r.label.toLowerCase()}`:""}.`;case"dismiss_helper":return r.ok?"The helper reports back and leaves.":"The helper leaves without finishing.";case"blocked_on_you":return r.reason==="permission"?"Pip needs your permission to continue.":"Pip has a question for you.";case"your_turn":return"Pip is done for now. Your turn.";case"stumble":return r.retrying?"Something went wrong. Pip tries again.":"Something went wrong.";case"celebrate":return"All green. Pip celebrates.";case"idle":return"";case"unverified_claim":return"Pip says it's done — but no test has passed since the last change. Something's hiding."}}function Db(r){if(!r.length)return[{label:"Scene",fromMs:0,toMs:0}];const e=Math.max(...r.map(l=>l.atMs+l.durationMs));let t=0,s=!1;const i=[];for(const l of r){let h=null;switch(l.kind){case"curtain_up":h="Arrive";break;case"curtain_down":h="Curtain";break;case"read":case"search":h=t?"Fix":s?"Explore":"Arrive",s=!0;break;case"build":case"raise":case"forge":h=t?"Fix":"Build";break;case"run_tests":h=t?"Fix":"Build";break;case"test_outcome":{h=l.outcome==="fail"?"Trouble":"Finale";const c=i.at(-1);c&&c.kind==="run_tests"&&(c.phase=h);break}case"spawn_gremlin":t++,h="Trouble";break;case"chase":h="Fix";break;case"banish":t=Math.max(0,t-1),h="Finale";break;case"celebrate":h="Finale";break;case"summon_helper":case"dismiss_helper":h="Help";break;case"blocked_on_you":h="Waiting";break;case"unverified_claim":h="Hmm";break;case"stumble":h="Trouble";break;case"your_turn":case"walk_to":case"idle":h=null;break}h&&i.push({phase:h,at:l.atMs,end:l.atMs+l.durationMs,kind:l.kind})}const n=[];for(const l of i){const h=n.at(-1);h&&h.phase===l.phase?h.to=Math.max(h.to,l.end):n.push({phase:l.phase,from:h?h.to:0,to:l.end})}n.length&&(n[0].from=0,n.at(-1).to=e);const o=2200;for(let l=n.length-1;l>=0&&n.length>1;l--){const h=n[l];h.to-h.from>=o||(l>0?(n[l-1].to=h.to,n.splice(l,1)):(n[1].from=h.from,n.splice(0,1)))}const a=n.at(-1);return a&&a.phase==="Curtain"&&n.length>1&&(n[n.length-2].to=a.to,n.pop()),n.map(l=>({label:l.phase==="Curtain"?"Finale":l.phase,fromMs:l.from,toMs:l.to}))}const In=r=>{const e=Math.floor(r/1e3);return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`},Gn=r=>`#${r.toString(16).padStart(6,"0")}`,j=(r,e,t)=>{const s=document.createElement(r);return e&&(s.className=e),t!==void 0&&(s.innerHTML=t),s},Fb='<svg viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 2.8v10.4a.6.6 0 0 0 .9.5l8.3-5.2a.6.6 0 0 0 0-1L5.4 2.3a.6.6 0 0 0-.9.5z"/></svg>',cu='<svg viewBox="0 0 16 16" fill="currentColor"><rect x="3.5" y="3" width="3" height="10" rx="1"/><rect x="9.5" y="3" width="3" height="10" rx="1"/></svg>',Lb='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5l3.2 3L13 4.5"/></svg>';class Ob{constructor(e,t){this.h=t,this.root=j("div","wrap");const s=j("header"),i=j("div","brand",'<div class="eyebrow">Agent Theatre</div><h1 id="title">Loading…</h1>'),n=j("div","toolbar");this.setBtn=j("button","btn ghost","Set"),this.setBtn.type="button",this.setBtn.onclick=()=>this.showPicker(!0),this.muteBtn=j("button","btn ghost","Effects on"),this.muteBtn.type="button",this.muteBtn.title="Sound effects",this.muteBtn.onclick=()=>t.onMute(),this.ambBtn=j("button","btn ghost","Ambience on"),this.ambBtn.type="button",this.ambBtn.title="Background sound",this.ambBtn.onclick=()=>t.onAmbience(),n.append(this.setBtn,this.muteBtn,this.ambBtn),s.append(i,n);const o=j("div","grid"),a=j("div","stage-col");this.stageEl=j("div","stage"),this.overlay=j("div","overlay"),this.bubbleEl=j("div","bubble"),this.bubbleEl.hidden=!0,this.overlay.append(this.bubbleEl),this.signal=j("div","signal","<i></i><span>live</span>"),this.signal.hidden=!0,this.chip=j("div","chip ok"),this.chip.hidden=!0,this.caption=j("div","caption","<span></span>"),this.title=j("div","card",'<div class="small">Agent Theatre</div><div class="big" id="titleBig">…</div>'),this.end=j("div","card",'<div class="big">Every agent run has a story.</div><div class="small">Agent Theatre</div>'),this.end.style.opacity="0",this.picker=j("div","picker"),this.picker.hidden=!0,this.stageEl.append(j("div","vignette"),this.overlay,this.signal,this.chip,this.caption,this.title,this.end,this.picker);const l=j("div","controls");this.playBtn=j("button","btn",`${cu}<span>Pause</span>`),this.playBtn.type="button",this.playBtn.onclick=()=>t.onPlayPause();const h=j("div","track");this.actsEl=j("div","acts"),this.labelsEl=j("div","actlabels"),this.head=j("div","head"),h.append(this.actsEl,this.labelsEl,this.head),h.addEventListener("pointerdown",f=>{const p=this.actsEl.getBoundingClientRect(),m=(f.clientX-p.left)/p.width;t.onSeek(m*this.durationMs)}),this.time=j("div","time","0:00 / 0:00"),this.rateBtn=j("button","btn ghost","1×"),this.rateBtn.type="button",this.rateBtn.onclick=()=>t.onRate(),l.append(this.playBtn,h,this.time,this.rateBtn),a.append(this.stageEl,l);const c=j("aside"),u=j("section","panel",'<h2>Event log</h2><p class="sub">Every scene is driven by one of these agent events. Tap one to jump there.</p>');this.logEl=j("ul","log"),u.append(this.logEl);const d=j("section","panel",`<h2>How to read the stage</h2><p class="sub">Buildings are files, districts are folders, beacons are test suites. Gremlins are failing tests. The lead character is the agent; its light shows its mood. Helpers are subagents. If the agent says it's done without a passing test, something hides behind it.</p>`);c.append(u,d),o.append(a,c),this.root.append(s,o,j("p","note","Everything you see is generated locally from agent events. No code, prompts or file contents are shown or sent anywhere.")),e.append(this.root)}root;stageEl;overlay;caption;chip;signal;title;end;picker;playBtn;rateBtn;muteBtn;ambBtn;setBtn;actsEl;labelsEl;head;time;logEl;acts=[];actBtns=[];actLabels=[];logBtns=[];lastCaption="";lastBeatId="";lastAct=-1;lastEv=-2;tagPool=[];bubbleEl;durationMs=0;repoId="";setTitle(e,t){this.root.querySelector("#title").textContent=e,this.root.querySelector("#titleBig").textContent=t??e}setMuted(e){this.muteBtn.textContent=e?"Effects off":"Effects on",this.muteBtn.setAttribute("aria-pressed",String(!e))}setAmbience(e){this.ambBtn.textContent=e?"Ambience on":"Ambience off",this.ambBtn.setAttribute("aria-pressed",String(e))}setRate(e){this.rateBtn.textContent=`${e}×`}loadTimeline(e,t,s){this.durationMs=e.length?Math.max(...e.map(n=>n.atMs+n.durationMs)):0,this.acts=Db(e),this.actsEl.innerHTML="",this.labelsEl.innerHTML="",this.actBtns=[],this.actLabels=[];for(const n of this.acts){const o=(n.toMs-n.fromMs)/Math.max(1,this.durationMs)*100,a=j("button");a.type="button",a.style.flex=`0 0 calc(${o}% - 3px)`,a.setAttribute("aria-label",`Jump to ${n.label}`),a.onclick=h=>{h.stopPropagation(),this.h.onSeek(n.fromMs+1)};const l=j("span","",n.label);l.style.flex=`0 0 calc(${o}% - 3px)`,this.actsEl.append(a),this.labelsEl.append(l),this.actBtns.push(a),this.actLabels.push(l)}this.logEl.innerHTML="",this.logBtns=[],t[0]?.ts;const i=n=>e.find(o=>o.sourceEventIds.includes(n));for(const n of t){if(n.kind==="session_start"||n.kind==="session_end")continue;const o=i(n.id);if(!o)continue;const a=j("li"),l=j("button");l.type="button";const[h,c]=Ub(n),u=n.kind==="test_result"&&!n.ok;l.innerHTML=`<time>${In(o.atMs)}</time><span class="dot k-${n.kind}${u?" fail":""}"></span><span class="ev"><b>${uu(h)}</b><code>${uu(c)}</code></span>`,l.onclick=()=>this.h.onSeek(o.atMs+1),a.append(l),this.logEl.append(a),this.logBtns.push({btn:l,ms:o.atMs})}}previews=new Map;get pickerOpen(){return!this.picker.hidden}profile;leadName="Pip";showAll=!1;showPicker(e,t){if(this.picker.hidden=!e,!e)return;this.picker.innerHTML="";const s=this.profile?.kinds?.[0],i=s&&s!=="unknown"?{"web-frontend":"a web app","backend-api":"a backend","cli-tool":"a CLI",library:"a library","data-ml":"data & ML work",mobile:"a mobile app",game:"a game","infra-devops":"infrastructure","docs-content":"documentation",monorepo:"a monorepo",systems:"systems code"}[s]:null,n=Io(this.profile,Nb(this.repoId)).slice(0,3),o=this.showAll?[...Tt]:n;this.picker.append(j("h3","",this.showAll?"All sets":"Choose your set"),j("p","",i&&!this.showAll?`This looks like ${i}${this.profile?.languages?.[0]?` in ${this.profile.languages[0]}`:""}. These stages suit it — or browse them all.`:"Same repo, same story — pick the stage. You can change it any time."));const a=j("div","setcards");for(const u of o){const d=j("button","setcard");d.type="button";const f=this.previews.get(u.id);d.innerHTML=`<div class="sw" style="--a:${Gn(u.sky[0])};--b:${Gn(u.palettes[0].left)}">${f?`<img src="${f}" alt="" />`:""}</div><div class="nm">${u.name}${u.id===t?" ✓":""}</div><div class="tg">${u.tagline}</div>`,d.onclick=()=>{this.h.onPickSet(u.id),this.showPicker(!1)},a.append(d)}const l=j("div","toolbar"),h=j("button","btn ghost","Surprise me");h.type="button",h.onclick=()=>this.h.onShuffle();const c=j("button","btn ghost",this.showAll?"Suggested":`All ${Tt.length} sets`);c.type="button",c.onclick=()=>{this.showAll=!this.showAll,this.showPicker(!0,t)},l.append(h,c),this.picker.append(a,l)}update(e,t,s,i){this.time.textContent=`${In(e.t)} / ${In(e.duration)}`,this.head.style.left=`${e.t/Math.max(1,e.duration)*100}%`,this.playBtn.innerHTML=e.playing?`${cu}<span>Pause</span>`:`${Fb}<span>${e.t>=e.duration-1?"Replay":"Play"}</span>`;const n=e.current;this.title.style.opacity=String(n&&n.kind==="curtain_up"?1-Math.min(1,Math.max(0,(e.t-n.atMs-600)/700)):e.t<600?1:0);const o=n&&n.kind==="curtain_down"?n:null;this.end.style.opacity=String(o?Math.min(1,Math.max(0,(e.t-o.atMs-400)/600)):0);const a=n?Gb(n,t,i).replace(/\bPip\b/g,this.leadName):"";n&&n.id!==this.lastBeatId&&(this.lastBeatId=n.id,a&&(this.lastCaption=a));const l=this.caption.firstElementChild;l.textContent=this.lastCaption,l.style.opacity=this.lastCaption&&!(n?.kind==="curtain_up"&&e.t-(n?.atMs??0)<900)?"1":"0",e.evidence?(this.chip.hidden=!1,this.chip.className="chip ok",this.chip.innerHTML=`${Lb}Evidence · ${e.evidence.passed} tests passed`):n?.kind==="unverified_claim"||n?.kind==="curtain_down"&&!n.verified?(this.chip.hidden=!1,this.chip.className="chip warn",this.chip.textContent="No test evidence"):this.chip.hidden=!0,this.signal.hidden=e.signal==="ok"||!this.liveMode,this.signal.className=`signal ${e.signal}`,this.signal.lastElementChild.textContent=e.signal==="lost"?"can't hear the agent":"live";let h=0;this.acts.forEach((p,m)=>{e.t>=p.fromMs&&(h=m)}),h!==this.lastAct&&(this.lastAct=h,this.actBtns.forEach((p,m)=>{p.classList.toggle("on",m<h),p.classList.toggle("now",m===h)}),this.actLabels.forEach((p,m)=>p.classList.toggle("now",m===h)));let c=-1;this.logBtns.forEach((p,m)=>{e.t>=p.ms&&(c=m)}),c!==this.lastEv&&(this.lastEv=c,this.logBtns.forEach((p,m)=>{p.btn.classList.toggle("done",m<c),p.btn.classList.toggle("now",m===c)}),this.logBtns[c]?.btn.scrollIntoView({block:"nearest",behavior:"smooth"}));const d=this.stageEl.getBoundingClientRect().width<600,f=e.labels.filter(p=>p.active||!d).sort((p,m)=>p.screen.y-m.screen.y||p.screen.x-m.screen.x);for(let p=0;p<f.length;p++)for(let m=0;m<p;m++){const g=f[m],_=f[p];Math.abs(g.screen.x-_.screen.x)<76&&Math.abs(g.screen.y-_.screen.y)<20&&(_.screen={x:_.screen.x,y:g.screen.y-20})}for(;this.tagPool.length<f.length;){const p=j("div","tag");this.overlay.append(p),this.tagPool.push(p)}this.tagPool.forEach((p,m)=>{const g=f[m];if(!g){p.hidden=!0;return}p.hidden=!1,p.textContent=g.text;const _=t.places.find(y=>y.label===g.text)?.id??"",x=s(_);p.className=`tag${g.active?" active":""}${x!=="idle"?` lamp-${x}`:""}`,p.style.left=`${g.screen.x}px`,p.style.top=`${g.screen.y}px`}),e.bubble?(this.bubbleEl.hidden=!1,this.bubbleEl.textContent=e.bubble.text,this.bubbleEl.style.color=Gn(e.bubble.color),this.bubbleEl.style.left=`${e.bubble.screen.x}px`,this.bubbleEl.style.top=`${e.bubble.screen.y}px`,this.bubbleEl.classList.toggle("pulse",n?.kind==="blocked_on_you")):this.bubbleEl.hidden=!0}liveMode=!1}function Ub(r,e){const t=s=>s.split("/").pop()??s;switch(r.kind){case"read_file":return["Read",r.path];case"edit_file":return["Edit",`${r.path} · +${r.added} −${r.removed}`];case"write_file":return[r.created?"Create":"Write",r.path];case"run_command":return[r.intent==="test"?"Run tests":r.intent==="git"?"Git":r.intent==="build"?"Build":r.intent==="install"?"Install":"Run",`${r.argv0}${r.touched.length?" · "+r.touched.map(t).join(", "):""}`];case"test_result":return[r.ok?`${r.passed} passed`:`${r.failed} failed`,r.framework?`${r.framework}`:""];case"search":return["Search",r.scope];case"subagent_start":return["Helper",r.label??r.childId];case"subagent_stop":return["Helper done",r.childId];case"waiting_for_user":return[r.reason==="permission"?"Needs permission":r.reason==="question"?"Has a question":"Waiting",""];case"error":return["Error",r.where];case"turn_end":return[r.claimedSuccess?"Says it's done":"Turn ends",""];default:return[r.kind,""]}}const Nb=r=>{let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0},uu=r=>r.replace(/[&<>"]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[e]);async function Hb(r,e,t,s=360,i=200){const n=new Sg(e,t);n.update(0);const o=new _e,a=e.places.flatMap(m=>[K(m.gx,m.gy),K(m.gx+m.footprint,m.gy+m.footprint)]),l=a.map(m=>m.x),h=a.map(m=>m.y),c=Math.max(...l)-Math.min(...l)+160,u=Math.max(...h)-Math.min(...h)+170,d=Math.min(s/c,i/u);o.scale.set(d),o.position.set(s/2-(Math.min(...l)+Math.max(...l))/2*d,i/2-((Math.min(...h)+Math.max(...h))/2-20)*d),o.addChild(n.container);const f=wr.create({width:s,height:i,resolution:1});r.renderer.render({container:o,target:f,clear:!0,clearColor:t.sky[1]});const p=await r.renderer.extract.base64(f);return f.destroy(!0),o.destroy({children:!0}),p}const le=new URLSearchParams(location.search),Vr=matchMedia("(prefers-reduced-motion: reduce)").matches,Bt={get:r=>{try{return localStorage.getItem(r)}catch{return null}},set:(r,e)=>{try{localStorage.setItem(r,e)}catch{}}};async function zb(r){try{const e=await(await fetch("/demo/demos.json")).json();return r==="any"?e[Math.floor(Math.random()*e.length)]??null:e.find(t=>t.id===r)??null}catch{return null}}async function Wb(r){const e=await zb(r);e&&(r=e.id,le.has("episode")||le.set("episode",`${e.title} · ${e.kind}`),!le.has("set")&&le.has("cinema")&&le.set("set",e.set));const t=await(await fetch(`/demo/${r}.jsonl`)).text(),{events:s}=Hx(t),i=Jx(s);let n=i.files,o=s[0]?.repoId??r;try{const h=await(await fetch(`/demo/${r}.files.json`)).json();if(Array.isArray(h.files)){const c=new Set(h.files.map(u=>u.path));n=[...h.files,...i.files.filter(u=>!c.has(u.path))],h.repoId&&(o=h.repoId)}}catch{}const a=Yx({repoId:o,files:n,touched:i.touched}),l=Jr(s,a);return new ah({world:a,events:s,beats:l,repoId:o})}async function $b(r,e){const t=new eb;let s=()=>{};const i=async()=>{await t.arm(),t.ready&&o?.audioReady()};for(const T of["pointerdown","keydown"])addEventListener(T,()=>{t.ready||i()},{passive:!0});let n=ei(le.get("set")),o=null,a=Number(le.get("rate"))||1,l=Bt.get("at:muted")==="1",h=Bt.get("at:ambience")!=="0";t.setMuted(l),t.setAmbienceEnabled(h);const c=new Ob(r,{onPlayPause:()=>{o&&(i(),o.playing?o.pause():(o.state.t>=o.state.duration-1&&o.seek(0),o.play()))},onSeek:T=>{o?.seek(T)},onRate:()=>{a=a>=4?1:a*2,o?.setRate(a),c.setRate(a)},onMute:()=>{if(!t.ready){i();return}l=!l,t.setMuted(l),Bt.set("at:muted",l?"1":"0"),c.setMuted(l)},onAmbience:()=>{if(!t.ready){i();return}h=!h,t.setAmbienceEnabled(h),Bt.set("at:ambience",h?"1":"0"),c.setAmbience(h)},onPickSet:T=>{n=ei(T),o&&(Bt.set(`at:set:${o.world.repoId}`,T),_())},onShuffle:()=>{const T=Io(f?.world.profile).filter(I=>I.id!==n.id),A=T.slice(0,Math.max(3,Math.min(5,T.length)));n=A[Math.floor(Math.random()*A.length)]??Tt[0],o&&(Bt.set(`at:set:${o.world.repoId}`,n.id),_()),c.showPicker(!1)}});c.setMuted(l),c.setAmbience(h),c.setRate(a),c.liveMode=e.mode==="live";const u=le.has("cinema");u&&(document.documentElement.classList.add("cinema"),l=!0,t.setMuted(!0));const d=new oa;await d.init({resizeTo:c.stageEl,antialias:!0,backgroundAlpha:1,background:n.sky[1],preference:"webgl",resolution:Math.min(2,devicePixelRatio||1),autoDensity:!0}),c.stageEl.prepend(d.canvas);let f=null;const p=(T,A)=>Kx(T,br[(T.seed+Tt.findIndex(I=>I.id===A.id)*7)%br.length]);let m=0,g=!1;function _(){if(!f)return;o&&(m=o.state.t,g=o.playing,o.destroy()),d.renderer.background.color=n.sky[1];const T=p(f.world,n),A=T===f.world?f.beats:Jr(f.events,T);o=new qs(d,T,n,t,Vr,le.get("cast")??Bt.get(`at:cast:${f.repoId}`)),globalThis.__agentTheatre={app:d,get player(){return o},panel:c},c.leadName=o.leadName,o.load(A),o.setRate(a),o.seek(m),g&&o.play(),c.loadTimeline(A,f.events,T)}e.onReady(T=>{f=T;const A=Bt.get(`at:set:${T.repoId}`),I=le.get("set")??A;c.profile=T.world.profile,c.repoId=T.repoId,I?n=ei(I):n=Io(T.world.profile,T.world.seed)[0]??Tt[0],c.setTitle(T.repoId,le.get("episode")??void 0),c.loadTimeline(T.beats,T.events,T.world),_();const F=Number(le.get("t"));F>0&&o&&o.seek(F*1e3);const X=(async()=>{if(!le.has("nopreview")){for(const R of Tt)try{c.previews.set(R.id,await Hb(d,p(T.world,R),R))}catch(M){console.warn("set preview failed",R.id,M)}c.pickerOpen&&c.showPicker(!0,n.id),s()}})();!I&&!le.has("t")&&X.then(()=>c.showPicker(!0,n.id)),le.get("paused")!=="1"&&!Vr&&o?.play(),u&&o&&!Vr&&o.play(),Vr&&!le.has("t")&&o?.seek(Math.min(o.state.duration,25400))}),e.onBeats((T,A)=>{if(!(!o||!f)){if(f.beats.push(...T),f.events.push(...A),o.world===f.world)o.append(T);else{const I=Jr(f.events,o.world);o.append(I.slice(o.beatCount))}c.loadTimeline(o.world===f.world?f.beats:Jr(f.events,o.world),f.events,o.world),o.playing||o.play(),s()}}),e.onSignal?.(T=>o?.setSignal(T));const x=Number(le.get("step"))||0;let y=performance.now(),b=0,w=!1,v=null;const S=T=>{w=!1;const A=x||Math.min(50,T-y);y=T,o&&!document.hidden&&((u||le.has("loop"))&&o.state.t>=o.state.duration-1&&o.state.duration>0&&(v||(v=setTimeout(()=>{v=null,o?.seek(0),o?.play()},600))),o.update(A),c.update(o.state,o.world,I=>o.worldLayer.lampOf(I)),o.playing?b=45:b--),(o?.playing||b>0)&&!document.hidden&&E()},E=()=>{w||(w=!0,requestAnimationFrame(S))};s=()=>{b=45,y=performance.now(),E()},s();for(const T of["pointerdown","keydown","resize"])addEventListener(T,s,{passive:!0});document.addEventListener("visibilitychange",()=>{document.hidden||s()});const k=qs.prototype.play;qs.prototype.play=function(){k.call(this),s()};const P=qs.prototype.seek;qs.prototype.seek=function(T){P.call(this,T),s()}}async function Vb(r){const{Application:e}=await wt(async()=>{const{Application:l}=await Promise.resolve().then(()=>bx);return{Application:l}},void 0),{Pip:t}=await wt(async()=>{const{Pip:l}=await Promise.resolve().then(()=>fb);return{Pip:l}},void 0),{castById:s,CAST:i}=await wt(async()=>{const{castById:l,CAST:h}=await Promise.resolve().then(()=>db);return{castById:l,CAST:h}},void 0),n=s(r)??i[0],o=ei(le.get("set")??"island");document.documentElement.style.background="transparent",document.body.style.background="transparent",document.body.style.margin="0";const a=new e;if(await a.init({width:320,height:320,backgroundAlpha:0,antialias:!0,resolution:2,autoDensity:!0,preference:"webgl"}),document.body.replaceChildren(a.canvas),r==="gremlin"){const{Gremlin:l}=await wt(async()=>{const{Gremlin:c}=await Promise.resolve().then(()=>cb);return{Gremlin:c}},void 0),h=new l("g",o,!1);h.scale=7,h.x=160,h.y=250,a.stage.addChild(h.container),a.ticker.add(c=>h.update(c.deltaMS))}else{const l=new t(o,!1,n);l.container.scale.set(6*n.size),l.pose.x=160,l.pose.y=272,a.stage.addChild(l.container),l.pose.mood=le.get("mood")??"curious",a.ticker.add(h=>l.update(h.deltaMS))}globalThis.__agentTheatre={app:a,player:!0}}const Dn=document.getElementById("app"),Xb=le.has("portrait")?Promise.resolve(new ah({world:null,events:[],beats:[],repoId:""})):le.has("live")?Promise.resolve(new Bb):le.get("session")?Ib(le.get("session")):Wb(le.get("demo")??"episode-1");le.has("portrait")?Vb(le.get("portrait")).catch(r=>{Dn.textContent=`Could not start: ${r}`}):Xb.then(r=>$b(Dn,r)).catch(r=>{Dn.textContent=`Could not start: ${r}`});export{T_ as A,_e as C,Lf as D,Uf as E,J0 as F,S_ as a,Xf as b,Hf as c,Vf as d,q as e};
956
- //# sourceMappingURL=index-BPj5KytA.js.map
955
+ `):""}function Gx(r){let e=0;for(const t of r.matchAll(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n\2(?=\n|$)/g))e+=Qr(t[3]);return e===0&&/(?:^|[\s)])\d?>{1,2}\s*[^\s|&;<>]+/.test(r)&&!/>\s*\/dev\/null/.test(r)&&(e=1),e}var Dx=new Set(["Grep","Glob","LS","ToolSearch"]),Fx=new Set(["WebSearch","WebFetch"]),Lx=new Set(["TodoWrite","TodoRead","Skill","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree","NotebookRead","ListAgents","SendMessage","TaskStop","Monitor","ScheduleWakeup","ReportFindings"]);function qc(r,e){const t=ze(r.input),s=r.response,i=!r.isError&&ze(s).interrupted!==!0,n=a=>vx(a,e),o=r.durationMs!==void 0?{durationMs:r.durationMs}:{};switch(r.name){case"Read":{const a=we(t.file_path)??we(t.path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:"Read without file_path"}};const l=we(ze(ze(s).file).content);return{bodies:[{kind:"read_file",path:n(a),...l!==void 0?{bytes:l.length}:{}}]}}case"Edit":case"MultiEdit":case"NotebookEdit":{const a=we(t.file_path)??we(t.notebook_path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:`${r.name} without file_path`}};const l=Bx(s)??{added:Qr(we(t.new_string)??we(t.new_source)),removed:Qr(we(t.old_string)),hunks:1};return{bodies:[{kind:"edit_file",path:n(a),...l}]}}case"Write":{const a=we(t.file_path);if(!a)return{bodies:[],warning:{code:"missing_field",detail:"Write without file_path"}};const l=ze(s),h=l.type==="create"||l.type===void 0&&l.originalFile===null;return{bodies:[{kind:"write_file",path:n(a),added:Qr(we(t.content)),created:h}]}}case"Bash":{const a=we(t.command)??"",l=Ax(a),h=[...new Set([...l.writes,...l.reads].map(n))],c=[{kind:"run_command",argv0:l.argv0,intent:l.intent,touched:h,ok:i,...o}],u=Gx(a);l.writes.forEach((d,f)=>c.push({kind:"write_file",path:n(d),added:f===0?u:0,created:!1}));for(const d of l.reads)c.push({kind:"read_file",path:n(d)});if(l.intent==="test"){const d=Rx(Ix(s));d?c.push({kind:"test_result",ok:d.failed===0&&i,passed:d.passed,failed:d.failed,...d.skipped!==void 0?{skipped:d.skipped}:{},framework:d.framework,...o}):c.push({kind:"test_result",ok:i,passed:0,failed:0,framework:"unknown",...o})}return{bodies:c}}case"Agent":case"Task":{const a=ze(s),l=we(a.agentId)??we(a.agent_id)??"",h=we(t.description)??we(t.subagent_type),c={kind:"subagent_start",childId:l,...h?{label:h}:{}};return a.status==="async_launched"||a.isAsync===!0?{bodies:[c],pendingSubagent:{childId:l}}:{bodies:[c,{kind:"subagent_stop",childId:l,ok:i}]}}case"AskUserQuestion":return{bodies:[{kind:"waiting_for_user",reason:"question"}]}}if(Dx.has(r.name)){const a=ze(s).numFiles??ze(s).numLines??ze(s).count;return{bodies:[{kind:"search",scope:"repo",...typeof a=="number"?{hits:a}:{}}]}}return Fx.has(r.name)?{bodies:[{kind:"search",scope:"web"}]}:Lx.has(r.name)?{bodies:[]}:{bodies:[{kind:"run_command",argv0:r.name.slice(0,40),intent:"other",touched:[],ok:i,...o}],warning:{code:"unknown_tool",detail:r.name.slice(0,80)}}}var Ox=[/\ball (?:\d+ )?tests? (?:are )?pass(?:ing|ed)?\b/i,/\btests? (?:are |is )?(?:now )?(?:passing|green)\b/i,/\b(?:is|are|it's|that's|everything(?:'s| is)) (?:now )?(?:fixed|working|done|complete|resolved)\b/i,/\bshould (?:now )?work\b/i,/\bworks now\b/i,/\b(?:done|complete|completed|fixed|resolved|shipped|implemented)[.!]/i,/✅/],Ux=[/\bnot (?:yet )?(?:done|fixed|working|tested|verified|complete)\b/i,/\bstill (?:fail|broken|not)/i,/\b(?:could ?n[’']?t|cannot|can ?not|unable to|wasn[’']?t able)\b/i,/\bfail(?:ed|ing|s)\b/i,/\bTODO\b/,/\bhaven[’']?t (?:run|tested|verified|checked)/i,/\buntested\b/i,/\bI did not (?:run|test|verify)/i],Yc=600;function Kc(r){if(!r)return!1;const e=r.length>Yc?r.slice(-Yc):r;return Ux.some(t=>t.test(e))?!1:Ox.some(t=>t.test(e))}var Nx=new Set(["user","assistant","system"]),Wr=r=>r&&typeof r=="object"?r:{},be=r=>typeof r=="string"?r:void 0;function Hx(r,e={}){const t=[],s=[],i=r.split(/\r?\n/);for(let o=0;o<i.length;o++){const a=i[o];if(a.trim())try{t.push(JSON.parse(a))}catch{s.push({code:"bad_json",detail:`line ${o+1}`,line:o+1})}}const n=zx(t,e);return{events:n.events,warnings:[...s,...n.warnings]}}function zx(r,e={}){const t=[],s=[],i=new Set,n=new Map,o=new Map;let a="",l="",h,c=Number.NaN,u=Number.NaN,d="",f=0,p=!1;const m=()=>({cwd:l,...e.home?{home:e.home}:{}}),g=(y,b,w,v={})=>{t.push({id:b,seq:f++,ts:y,sessionId:a,source:"transcript",...v,...w})},_=y=>{const b=be(y.timestamp),w=b?Date.parse(b):Number.NaN;return Number.isFinite(w)?w:Number.isFinite(u)?u:0},x=y=>be(y.agentId)??(y.isSidechain===!0?e.sidechainAgentId??"sidechain":void 0);for(const y of r){const b=Wr(y),w=be(b.type)??"";if(!Nx.has(w)){w&&i.add(w);continue}!a&&be(b.sessionId)&&(a=be(b.sessionId)),!l&&be(b.cwd)&&(l=be(b.cwd)),!h&&be(b.gitBranch)&&(h=be(b.gitBranch));const v=_(b);Number.isFinite(c)||(c=v,g(v,`${a||"session"}:start`,{kind:"session_start",repoId:wx(l)||"repo",...h?{branch:h}:{}})),u=v;const T=x(b),k=Wr(b.message),P=k.content;if(w==="system"){if(b.subtype==="api_error"){const C=typeof b.retryAttempt=="number"?b.retryAttempt:0,E=typeof b.maxRetries=="number"?b.maxRetries:0;g(v,be(b.uuid)??`sys:${f}`,{kind:"error",where:"api",retrying:C<E},T?{agentId:T}:{})}continue}if(w==="assistant"){const C=Array.isArray(P)?P:[];for(const E of C){const B=Wr(E);if(B.type==="tool_use"&&be(B.id)&&be(B.name))n.set(be(B.id),{name:be(B.name),input:B.input,ts:v,...T?{agentId:T}:{}});else if(B.type==="text"&&!T){const G=be(B.text);G&&(d=G)}}typeof P=="string"&&!T&&(d=P),k.stop_reason==="end_turn"&&!T&&g(v,`${be(b.uuid)??f}:turn`,{kind:"turn_end",claimedSuccess:Kc(d)});continue}b.toolDenialKind!==void 0&&g(v,`${be(b.uuid)??f}:deny`,{kind:"waiting_for_user",reason:"permission"});const A=Array.isArray(P)?P:[];for(const C of A){const E=Wr(C);if(E.type!=="tool_result")continue;const B=be(E.tool_use_id);if(!B)continue;const G=n.get(B);if(!G){s.push({code:"unpaired_result",detail:B});continue}n.delete(B);const V=b.toolUseResult??E.content,I=qc({name:G.name,input:G.input,response:V,isError:E.is_error===!0,durationMs:Math.max(0,v-G.ts)},m());I.warning&&s.push(I.warning);const M=G.agentId??T,D=M?o.get(M):void 0,R={...M?{agentId:M}:{},...D?{parentId:D}:{}};I.bodies.forEach((U,W)=>g(G.ts,W===0?B:`${B}:${W}`,U,R)),I.pendingSubagent&&o.set(I.pendingSubagent.childId,B)}A.length===0&&typeof P=="string"&&/\[Request interrupted by user/i.test(P)&&g(v,`${be(b.uuid)??f}:interrupt`,{kind:"waiting_for_user",reason:"idle"})}for(const[y,b]of n){s.push({code:"unpaired_result",detail:`tool_use ${y} (${b.name}) has no result`});const w=qc({name:b.name,input:b.input,isError:!0},m());w.warning&&s.push(w.warning),w.bodies.forEach((v,T)=>g(b.ts,T===0?y:`${y}:${T}`,v,b.agentId?{agentId:b.agentId}:{}))}for(const[y,b]of o)g(u,`${b}:stop`,{kind:"subagent_stop",childId:y,ok:!0},{parentId:b});for(const y of i)s.push({code:"unknown_row_type",detail:y});return Number.isFinite(c)&&!p&&(p=!0,g(u,`${a||"session"}:end`,{kind:"session_end",reason:"stop",claimedSuccess:Kc(d)})),{events:t,warnings:s}}function ko(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function ar(r){let e=r>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}var Wx=/(^|\/)(schema\.(sql|prisma|graphql|gql)|.*\.(sql|prisma|db|sqlite)|migrations?\/|drizzle\/|models?\/.*\.(ts|js|py|rb)$)/i,$x=/(^|\/)(node_modules|\.git|dist|build|out|coverage|_site|\.next|\.turbo|target|vendor|__pycache__|\.venv|venv)(\/|$)|(^|\/)\.[^/]+$|\.(lock|map|min\.js|png|jpg|jpeg|gif|webp|svg|ico|woff2?|ttf|mp4|mp3|pdf|zip)$/i;function Vx(r){return $x.test(r)}function mg(r){return fg(r)?"beacon":Wx.test(r)?"archive":"building"}function Zc(r){return typeof r.loc=="number"?r.loc:typeof r.size=="number"?Math.max(1,Math.round(r.size/40)):1}function Xx(r,e){const t=r.filter(n=>!Vx(n.path)),s=Math.max(1,...t.map(Zc)),i=Math.max(1,...t.map(n=>n.churn??0));return t.map(n=>{const o=Zc(n),a=e.has(n.path),l=.5*Math.sqrt(o/s)+.3*((n.churn??0)/i)+(a?.2:0);return{file:n,loc:o,score:l,kind:mg(n.path),touched:a}})}function Qc(r,e){const t=Math.sqrt(r/Math.max(1,e));return Math.max(1,Math.min(5,Math.ceil(t*5)))}function Jc(r){return r>=5?3:r>=3?2:1}var jx={ts:"TypeScript",tsx:"TypeScript",js:"JavaScript",jsx:"JavaScript",mjs:"JavaScript",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",swift:"Swift",rb:"Ruby",php:"PHP",cs:"C#",cpp:"C++",cc:"C++",c:"C",h:"C",m:"Objective-C",scala:"Scala",ex:"Elixir",exs:"Elixir",dart:"Dart",lua:"Lua",zig:"Zig",sh:"Shell",sql:"SQL",md:"Markdown",mdx:"Markdown",html:"HTML",css:"CSS",scss:"CSS",vue:"Vue",svelte:"Svelte",tf:"Terraform",yaml:"YAML",yml:"YAML",ipynb:"Notebook"};function qx(r,e={}){const t=r.map(p=>p.path.toLowerCase()),s=p=>t.some(m=>p.test(m)),i=p=>t.filter(m=>p.test(m)).length,n=new Map;for(const p of t){const m=p.slice(p.lastIndexOf(".")+1),g=jx[m];g&&!/^(markdown|yaml|html|css|shell|sql)$/i.test(g)&&n.set(g,(n.get(g)??0)+1)}const o=[...n.entries()].sort((p,m)=>m[1]-p[1]).map(([p])=>p).slice(0,4),a=(e["package.json"]??"").toLowerCase(),l=((e["pyproject.toml"]??"")+(e["requirements.txt"]??"")).toLowerCase(),h=p=>p.test(a)||p.test(l),c=new Map,u=(p,m)=>c.set(p,(c.get(p)??0)+m);h(/"(react|react-dom|next|vue|nuxt|svelte|@sveltejs\/kit|@angular\/core|solid-js|astro|remix|vite)"/)&&u("web-frontend",3),i(/\.(tsx|jsx|vue|svelte)$/)>3&&u("web-frontend",2),(s(/(^|\/)(index|app)\.html$/)||i(/\.(css|scss)$/)>3)&&u("web-frontend",1),h(/"(express|fastify|hono|koa|@nestjs\/core|apollo-server|prisma|drizzle-orm|django|flask|fastapi|sqlalchemy|gin|fiber|actix|axum|rails|spring)"/)&&u("backend-api",3),(s(/(^|\/)(routes?|controllers?|api|handlers?|migrations?)\//)||s(/\.(sql|prisma)$/))&&u("backend-api",2),(a.includes('"bin"')||s(/(^|\/)(cli|cmd|bin)\//)||h(/"(commander|yargs|clap|cobra|click|typer)"/))&&u("cli-tool",3),(h(/"(torch|tensorflow|jax|pandas|numpy|scikit-learn|sklearn|transformers|xgboost|lightgbm|polars)"/)||i(/\.ipynb$/)>0||s(/(^|\/)(notebooks?|models?|datasets?|training)\//))&&u("data-ml",3),(s(/\.(swift|kt)$/)||s(/(^|\/)(ios|android)\//)||s(/package\.swift$/)||s(/build\.gradle(\.kts)?$/)||h(/"(react-native|expo|flutter)"/)||s(/\.dart$/))&&u("mobile",3),(s(/\.(unity|unitypackage|godot|tscn|gd)$/)||s(/(^|\/)assets\/.*\.(prefab|fbx)$/)||h(/"(phaser|pixi\.js|three|babylonjs|@react-three\/fiber|excalibur|kaplay|bevy|godot)"/))&&u("game",3),(s(/\.tf$/)||s(/(^|\/)(dockerfile|docker-compose\.ya?ml|helm|k8s|kubernetes|\.github\/workflows|ansible|pulumi)/))&&u("infra-devops",s(/\.tf$/)||s(/(^|\/)(helm|k8s|kubernetes|ansible|pulumi)\//)?3:1);const d=i(/\.(md|mdx|rst)$/)/Math.max(1,t.length);(d>.4||s(/(^|\/)(mkdocs|docusaurus)\.config|(^|\/)docs\/.*\.mdx?$/)&&d>.25)&&u("docs-content",3),(s(/(^|\/)pnpm-workspace\.ya?ml$/)||s(/(^|\/)packages\/[^/]+\/package\.json$/)||s(/(^|\/)(lerna|nx|turbo)\.json$/)||s(/(^|\/)cargo\.toml$/)&&i(/(^|\/)crates\/[^/]+\//)>0)&&u("monorepo",2),i(/\.(rs|go|c|cpp|cc|h|zig)$/)>5&&!c.has("web-frontend")&&u("systems",2),a.includes('"main"')&&!a.includes('"bin"')&&!c.has("web-frontend")&&!c.has("backend-api")&&u("library",2),s(/(^|\/)(lib|src\/lib)\//)&&!c.has("web-frontend")&&u("library",1);const f=[...c.entries()].filter(([,p])=>p>=2).sort((p,m)=>m[1]-p[1]).map(([p])=>p);return{kinds:f.length?f:["unknown"],languages:o,files:r.length}}function Yx(r){const e=r.cap??60,t=r.beaconCap??8,s=r.touchedCap??48,i=new Set((r.touched??[]).map(eu).slice(0,s)),n=ko(r.repoId),o=ar(n),a=r.files.map(M=>({...M,path:eu(M.path)})),l=Xx(a,i),h=Math.max(1,...l.map(M=>M.loc)),c=[...l].sort((M,D)=>D.score-M.score||M.file.path.localeCompare(D.file.path)),u=ru(c.filter(M=>M.kind==="beacon"),t),d=ru(c.filter(M=>M.kind!=="beacon"),e),f=[...d,...u],p=f.length<l.length,m=new Map;for(const M of d){const D=Pn(M.file.path);(m.get(D)??m.set(D,[]).get(D)).push(M)}const g=[...m.keys()].sort(),_=new Set,x=[],y=[],b={id:"forge",kind:"forge",path:"",label:"forge",district:"",gx:-1,gy:-1,footprint:2,height:2,score:0,touched:!1};x.push(b);const w=r.layout??br[n%br.length],v=o()*Math.PI*2,T=g.map(M=>{const D=m.get(M).sort((W,se)=>se.score-W.score||W.file.path.localeCompare(se.file.path)),R=D.reduce((W,se)=>W+Jc(Qc(se.loc,h))**2,0),U=Math.max(3,Math.ceil(Math.sqrt(R*1.45)));return{name:M,items:D,side:U}}),k=[],P={x:-2,y:-2,w:4,h:4},A=bg(w,T.map(M=>M.side),P,v,o);k.push(P,...A);const C=vg(w,A);b.gx=C[0],b.gy=C[1],_.clear(),vt(_,b),T.forEach((M,D)=>{const R=A[D],U={id:`d:${M.name}`,label:M.name===""?"/":`${M.name}/`,bounds:R,cx:R.x+Math.floor(R.w/2),cy:R.y+Math.floor(R.h/2),placeIds:[]};for(const W of M.items){const se=Qc(W.loc,h),te=Jc(se),ie=Po(_,U.cx,U.cy,te,R),$={id:`p:${W.file.path}`,kind:W.kind,path:W.file.path,label:tu(W.file.path),district:U.id,gx:ie[0],gy:ie[1],footprint:te,height:se,score:su(W.score),touched:W.touched};vt(_,$),x.push($),U.placeIds.push($.id)}y.push(U)}),Math.ceil(yg(k));for(const M of k)for(let D=M.x-1;D<M.x+M.w+1;D++)for(let R=M.y-1;R<M.y+M.h+1;R++)_.add(`${D},${R}`);for(const M of u){const D=y.find(W=>W.id===`d:${Pn(M.file.path)}`),R=D?Tg(_,D,b,1):vr(_,b.gx+1,b.gy+1,o()*Math.PI*2,4,1),U={id:`p:${M.file.path}`,kind:"beacon",path:M.file.path,label:tu(M.file.path),district:D?.id??"",gx:R[0],gy:R[1],footprint:1,height:4,score:su(M.score),touched:M.touched};vt(_,U),x.push(U),D?.placeIds.push(U.id)}const E=vr(_,b.gx+1,b.gy+1,v+Math.PI,5,2),B={id:"dock",kind:"dock",path:"",label:"dock",district:"",gx:E[0],gy:E[1],footprint:2,height:1,score:0,touched:!1};vt(_,B),x.push(B);const G=wg(w,y,b,B);if(p)for(const M of y){const D=M.id.slice(2),R=l.filter(se=>se.kind!=="beacon"&&Pn(se.file.path)===D).length;if(R<=M.placeIds.length)continue;const U=Po(_,M.cx,M.cy,1,M.bounds),W={id:`p:${D?D+"/":""}…`,kind:"overflow",path:`${D?D+"/":""}…`,label:`+${R-M.placeIds.length} more`,district:M.id,gx:U[0],gy:U[1],footprint:1,height:2,score:0,touched:!1};vt(_,W),x.push(W),M.placeIds.push(W.id)}const V=xg(x,2),I=qx(a,r.manifests??{});return{repoId:r.repoId,seed:n,layout:w,profile:I,districts:y,places:x,paths:G,bounds:V,stats:{files:l.length,placed:f.length,capped:p}}}var eu=r=>r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,""),tu=r=>r.slice(r.lastIndexOf("/")+1),Pn=r=>r.includes("/")?r.slice(0,r.indexOf("/")):"",su=r=>Math.round(r*1e3)/1e3;function ru(r,e){const t=r.filter(i=>i.touched),s=r.filter(i=>!i.touched);return[...t,...s.slice(0,Math.max(0,e-t.length))]}function iu(r,e,t){return r.x<e.x+e.w+t&&e.x<r.x+r.w+t&&r.y<e.y+e.h+t&&e.y<r.y+r.h+t}function gg(r,e,t){const s=[];for(let i=0;i<t;i++)for(let n=0;n<t;n++)s.push(`${r+i},${e+n}`);return s}function _g(r,e,t,s){return gg(e,t,s).every(i=>!r.has(i))}function vt(r,e){for(const t of gg(e.gx,e.gy,e.footprint))r.add(t)}function Po(r,e,t,s,i){let n=0,o=0,a=0,l=-1,h=null;for(let c=0;c<4096;c++){const u=e+n-Math.floor(s/2),d=t+o-Math.floor(s/2);if(_g(r,u,d,s)){if(u>=i.x-1&&d>=i.y-1&&u+s<=i.x+i.w+1&&d+s<=i.y+i.h+1)return[u,d];if(h??=[u,d],c>600)return h}(n===o||n<0&&n===-o||n>0&&n===1-o)&&([a,l]=[-l,a]),n+=a,o+=l}return h??[e,t]}function yg(r){return Math.max(...r.map(e=>Math.max(Math.abs(e.x),Math.abs(e.x+e.w),Math.abs(e.y),Math.abs(e.y+e.h))))}function xg(r,e){const t=r.flatMap(o=>[o.gx,o.gx+o.footprint]),s=r.flatMap(o=>[o.gy,o.gy+o.footprint]),i=Math.min(...t)-e,n=Math.min(...s)-e;return{x:i,y:n,w:Math.max(...t)+e-i,h:Math.max(...s)+e-n}}var br=["ring","grid","strip","scatter","terrace","spine"];function bg(r,e,t,s,i){const n=e.length,o=[],a=Math.max(3,...e),l=c=>!iu(t,c,1)&&!o.some(u=>iu(u,c,1)),h=(c,u,d)=>{const f={x:c,y:u,w:d,h:d};return o.push(f),f};switch(r){case"grid":{const c=Math.max(2,Math.ceil(Math.sqrt(n+1))),u=[];let d=0,f=0;for(;f<n;){const g=e.slice(f,f+c),_=Math.max(...g)+2;let x=0;for(const y of g)u.push({x,y:d}),x+=y+2;d+=_,f+=c}const p=Math.max(...u.map((g,_)=>g.x+e[_])),m=d;for(let g=0;g<n;g++){let _={x:u[g].x-Math.round(p/2),y:u[g].y-Math.round(m/2),w:e[g],h:e[g]};for(;!l(_);)_={..._,x:_.x+1};o.push(_)}return o}case"strip":{const c=e.reduce((d,f)=>d+f+2,0);let u=Math.round(-c/2)+6;for(let d=0;d<n;d++){const f=Math.round((i()-.5)*3);h(u,f-Math.floor(e[d]/2),e[d]),u+=e[d]+2}return o}case"terrace":{let c=-Math.round(n*(a+1)/2),u=-Math.round(n*(a+1)*.3);for(let d=0;d<n;d++)h(c,u,e[d]),c+=e[d]+1,u+=Math.round(e[d]*.6)+1;return o}case"spine":{let c=-Math.round(n*(a+2)/4);for(let u=0;u<n;u++){const d=u%2===0;h(d?-e[u]-3:3,c,e[u]),d||(c+=a+2)}return o}case"scatter":{for(let c=0;c<n;c++){let u=5+a,d=!1;for(let f=0;f<400&&!d;f++){const p=s+i()*Math.PI*2,m=u*(.5+i()*.7),g={x:Math.round(Math.cos(p)*m),y:Math.round(Math.sin(p)*m*.8),w:e[c],h:e[c]};l(g)&&(o.push(g),d=!0),f%40===39&&(u+=2)}d||h(u+c*2,0,e[c])}return o}default:{let c=3;for(let u=0;u<n;u++){const d=e[u],f=s+u/Math.max(1,n)*Math.PI*2;let p=c+d/2,m;for(;;){const g=Math.round(Math.cos(f)*p),_=Math.round(Math.sin(f)*p*.8);if(m={x:g-Math.floor(d/2),y:_-Math.floor(d/2),w:d,h:d},l(m))break;p+=1}o.push(m),c=Math.max(c,p-d/2)}return o}}}function vg(r,e){if(!e.length)return[-1,-1];const t=Math.min(...e.map(i=>i.x)),s=Math.min(...e.map(i=>i.y));switch(r){case"strip":return[t-5,-1];case"terrace":return[t-5,s-1];case"spine":return[-1,s-5];default:return[-1,-1]}}function wg(r,e,t,s){const i=[t.gx+1,t.gy+1],n=[];if(r==="strip"||r==="terrace"){const o=[...e].sort((h,c)=>h.cx-c.cx||h.cy-c.cy);let a=i,l="forge";for(const h of o)n.push({from:l,to:h.id,points:[a,[h.cx,h.cy]]}),a=[h.cx,h.cy],l=h.id}else if(r==="grid"||r==="spine")for(const o of e)n.push({from:o.id,to:"forge",points:[[o.cx,o.cy],[o.cx,i[1]],i]});else for(const o of e)n.push({from:o.id,to:"forge",points:[[o.cx,o.cy],[Math.round((o.cx+i[0])/2),Math.round((o.cy+i[1])/2)],i]});return n.push({from:"dock",to:"forge",points:[[s.gx,s.gy],i]}),n}function Kx(r,e){if(r.layout===e)return r;const t=r.seed,s=ar(t^1374496523^br.indexOf(e)),i=new Set,n=[],o={...r.places.find(x=>x.kind==="forge"),gx:-1,gy:-1};n.push(o);const a=s()*Math.PI*2,h=r.districts.map(x=>({d:x,items:r.places.filter(y=>y.district===x.id&&(y.kind==="building"||y.kind==="archive"||y.kind==="overflow")).sort((y,b)=>b.score-y.score||y.path.localeCompare(b.path))})).map(x=>{const y=x.items.reduce((b,w)=>b+w.footprint**2,0);return{...x,side:Math.max(3,Math.ceil(Math.sqrt(y*1.45)))}}),c={x:-2,y:-2,w:4,h:4},u=bg(e,h.map(x=>x.side),c,a,s),d=[c,...u],f=vg(e,u);o.gx=f[0],o.gy=f[1],vt(i,o);const p=h.map((x,y)=>{const b=u[y],w={...x.d,bounds:b,cx:b.x+Math.floor(b.w/2),cy:b.y+Math.floor(b.h/2),placeIds:[]};for(const v of x.items){const T=Po(i,w.cx,w.cy,v.footprint,b),k={...v,gx:T[0],gy:T[1]};vt(i,k),n.push(k),w.placeIds.push(k.id)}return w});Math.ceil(yg(d));for(const x of d)for(let y=x.x-1;y<x.x+x.w+1;y++)for(let b=x.y-1;b<x.y+x.h+1;b++)i.add(`${y},${b}`);for(const x of r.places.filter(y=>y.kind==="beacon")){const y=p.find(v=>v.id===x.district),b=y?Tg(i,y,o,1):vr(i,o.gx+1,o.gy+1,s()*Math.PI*2,4,1),w={...x,gx:b[0],gy:b[1]};vt(i,w),n.push(w),y?.placeIds.push(w.id)}const m=vr(i,o.gx+1,o.gy+1,a+Math.PI,5,2),g={...r.places.find(x=>x.kind==="dock"),gx:m[0],gy:m[1]};vt(i,g),n.push(g);const _=wg(e,p,o,g);return{...r,layout:e,districts:p,places:n,paths:_,bounds:xg(n,2)}}function vr(r,e,t,s,i,n){for(let o=i;o<i+40;o++)for(let a=0;a<64;a++){const l=s+(a%2?1:-1)*Math.ceil(a/2)*(Math.PI/32),h=Math.round(e+Math.cos(l)*o),c=Math.round(t+Math.sin(l)*o*.85);if(_g(r,h,c,n))return[h,c]}return[e+i,t]}function Tg(r,e,t,s){const i=Math.atan2(e.cy-t.gy,e.cx-t.gx),n=Math.ceil(Math.max(e.bounds.w,e.bounds.h)/2)+2;return vr(r,e.cx,e.cy,i,n,s)}var Zx=class{constructor(r){this.windowMs=r}windowMs;mood="curious";trouble=[];recordTrouble(r){return this.trouble=this.trouble.filter(e=>r-e<=this.windowMs),this.trouble.push(r),this.trouble.length>=2}onRead(){return this.mood=this.mood==="lost"?"lost":"curious"}onBuild(){return this.mood=this.mood==="lost"?"lost":"focused"}onFail(r){return this.mood=this.recordTrouble(r)?"lost":"uneasy"}onError(r){return this.mood=this.recordTrouble(r)?"lost":"uneasy"}onPass(){return this.trouble=[],this.mood="happy"}onClaimUnverified(){return this.mood="uneasy"}},Qx=class{constructor(r,e={}){this.world=r;for(const t of r.places)this.places.set(t.id,t),t.path&&this.byPath.set(t.path,t);this.beacons=r.places.filter(t=>t.kind==="beacon"),this.forge=r.places.find(t=>t.kind==="forge")??r.places[0],this.dock=r.places.find(t=>t.kind==="dock")??this.forge,this.maxGap=e.maxGapMs??2500,this.msPerCell=e.walkMsPerCell??90,this.mood=new Zx(e.lostWindowMs??9e4),this.actorAt.set("pip",this.forge.id)}world;places=new Map;byPath=new Map;beacons;forge;dock;maxGap;msPerCell;mood;beats=[];sceneMs=0;lastRealTs=null;seq=0;actorAt=new Map;helpers=new Map;gremlins=new Map;lastEdited=null;pendingBeacon=null;editedSinceTurn=!1;verifiedSinceEdit=!1;everVerified=!1;claimGremlin=null;get timeline(){return this.beats}feed(r){const e=this.beats.length;this.advanceClock(r.ts,r.id);const t=r.agentId&&this.helpers.has(r.agentId)?r.agentId:"pip";switch(r.kind){case"session_start":this.emit(r,t,{kind:"curtain_up",repoId:r.repoId},1200);break;case"read_file":{const s=this.placeFor(r.path,r,t);this.walk(r,t,s),this.emit(r,t,{kind:"read",target:s.id},_s(700+(r.bytes??400)/4,900,1800),this.mood.onRead());break}case"edit_file":case"write_file":{const s=this.placeFor(r.path,r,t);this.walk(r,t,s);const i=r.kind==="edit_file"?r.added+r.removed:r.added,n=_s(Math.sqrt(i/50),.15,1),o=[...this.gremlins].find(([,a])=>a===s.id);o&&this.emit(r,t,{kind:"chase",gremlinId:o[0],target:s.id},900,this.mood.mood),r.kind==="write_file"&&r.created&&this.emit(r,t,{kind:"raise",target:s.id},900,this.mood.onBuild()),this.emit(r,t,{kind:"build",target:s.id,intensity:n},_s(600+n*1900,800,2500),this.mood.onBuild()),this.lastEdited=s,this.editedSinceTurn=!0,this.verifiedSinceEdit=!1;break}case"run_command":{if(r.intent==="test"){const s=this.beaconFor(r.touched);this.walk(r,t,s),this.pendingBeacon=s,this.emit(r,t,{kind:"run_tests",target:s.id},_s(r.durationMs??1200,900,3e3),this.mood.mood)}else if(r.intent==="search")this.emit(r,t,{kind:"search",scope:"repo"},700,this.mood.onRead());else if(r.touched.length===0||r.intent==="git"||r.intent==="install"||r.intent==="build"){this.walk(r,t,this.forge);const s=r.intent==="build"||r.intent==="install"?.8:r.intent==="git"?.4:.5;this.emit(r,t,{kind:"forge",intensity:s},_s(r.durationMs??800,700,2e3),this.mood.mood)}!r.ok&&r.intent!=="test"&&this.emit(r,t,{kind:"stumble",retrying:!1},600,this.mood.onError(r.ts));break}case"test_result":{const s=this.pendingBeacon??this.beaconFor([]);this.pendingBeacon=null;const i=(r.framework==="unknown"&&r.passed===0&&r.failed===0,r.ok?"pass":"fail");if(i==="pass"){this.emit(r,t,{kind:"test_outcome",target:s.id,outcome:i,passed:r.passed,failed:r.failed},800,this.mood.onPass()),(r.passed>0||r.framework==="unknown")&&(this.verifiedSinceEdit=!0,this.everVerified=!0);for(const[n]of this.gremlins)this.emit(r,t,{kind:"banish",gremlinId:n},700,"happy");this.gremlins.clear(),this.claimGremlin&&(this.emit(r,t,{kind:"banish",gremlinId:this.claimGremlin},700,"happy"),this.claimGremlin=null),this.emit(r,t,{kind:"celebrate",target:s.id},1600,"happy")}else{this.emit(r,t,{kind:"test_outcome",target:s.id,outcome:i,passed:r.passed,failed:r.failed},800,this.mood.onFail(r.ts));const n=this.lastEdited??s,o=`g:${r.id}`;this.gremlins.set(o,n.id),this.emit(r,t,{kind:"spawn_gremlin",gremlinId:o,target:n.id},900,this.mood.mood)}break}case"search":this.emit(r,t,{kind:"search",scope:r.scope},700,this.mood.onRead());break;case"subagent_start":this.helpers.set(r.childId,r.label?{label:r.label}:{}),this.actorAt.set(r.childId,this.dock.id),this.emit(r,"pip",{kind:"summon_helper",helperId:r.childId,...r.label?{label:r.label}:{}},1400,this.mood.mood);break;case"subagent_stop":this.helpers.has(r.childId)&&(this.emit(r,r.childId,{kind:"dismiss_helper",helperId:r.childId,ok:r.ok},1e3,this.mood.mood),this.helpers.delete(r.childId),this.actorAt.delete(r.childId));break;case"waiting_for_user":r.reason==="idle"?this.emit(r,t,{kind:"your_turn"},1e3,this.mood.mood):this.emit(r,t,{kind:"blocked_on_you",reason:r.reason},1200,this.mood.mood);break;case"error":this.emit(r,t,{kind:"stumble",retrying:r.retrying},700,this.mood.onError(r.ts));break;case"turn_end":{if(r.claimedSuccess&&this.editedSinceTurn&&!this.verifiedSinceEdit){const s=`claim:${r.id}`;this.claimGremlin=s,this.emit(r,t,{kind:"unverified_claim",gremlinId:s},1400,this.mood.onClaimUnverified())}this.editedSinceTurn=!1,this.emit(r,t,{kind:"your_turn"},1e3,this.mood.mood);break}case"session_end":this.emit(r,t,{kind:"curtain_down",verified:this.everVerified&&!this.claimGremlin},1500,this.mood.mood);break}return this.beats.slice(e)}advanceClock(r,e){if(this.lastRealTs!==null){const t=this.beats.length?Math.max(...this.beats.slice(-3).map(n=>n.atMs+n.durationMs)):this.sceneMs,s=Math.min(Math.max(0,r-this.lastRealTs),this.maxGap),i=Math.max(t,this.sceneMs)+s;if(i-t>=1e3){const n={id:`b${this.seq++}`,atMs:t,durationMs:i-t,realTs:this.lastRealTs,mood:this.mood.mood,actor:"pip",sourceEventIds:[e],kind:"idle"};this.beats.push(n)}this.sceneMs=Math.max(this.sceneMs,i)}this.lastRealTs=r}emit(r,e,t,s,i=this.mood.mood){s=Math.round(s),"intensity"in t&&(t={...t,intensity:Math.round(t.intensity*1e3)/1e3});const n={id:`b${this.seq++}`,atMs:Math.round(this.sceneMs),durationMs:s,realTs:r.ts,mood:i,actor:e,sourceEventIds:[r.id],...t};return this.beats.push(n),this.sceneMs+=s,n}walk(r,e,t){const s=this.actorAt.get(e)??this.forge.id;if(s===t.id)return;const i=this.places.get(s)??this.forge,n=Math.hypot(t.gx-i.gx,t.gy-i.gy);this.emit(r,e,{kind:"walk_to",target:t.id},_s(Math.round(n*this.msPerCell),300,2500)),this.actorAt.set(e,t.id)}raised=0;placeFor(r,e,t){const s=this.byPath.get(r);if(s)return s;const i=r.includes("/")?r.slice(0,r.indexOf("/")):"",n=this.byPath.get(`${i?i+"/":""}…`);if(n&&(this.raised>=24||this.world.stats.capped))return n;if(this.raised>=24)return n??this.forge;this.raised++;const o=this.world.districts.find(h=>h.id===`d:${i}`)??this.world.districts[0],a=o?{gx:o.cx,gy:o.cy}:{gx:this.forge.gx+3,gy:this.forge.gy},l={id:`p:${r}`,kind:mg(r),path:r,label:r.slice(r.lastIndexOf("/")+1),district:o?.id??"",gx:a.gx,gy:a.gy,footprint:1,height:1,score:0,touched:!0};return this.places.set(l.id,l),this.byPath.set(r,l),l.kind==="beacon"&&this.beacons.push(l),this.emit(e,t,{kind:"raise",target:l.id,newPlace:{path:r,label:l.label,kind:l.kind,district:l.district}},900),l}beaconFor(r){const e=r.find(t=>fg(t));if(e){const t=this.byPath.get(e);if(t)return t}if(this.lastEdited){const t=this.beacons.find(s=>s.district===this.lastEdited.district);if(t)return t}return this.beacons[0]??this.forge}};function Jr(r,e,t){const s=new Qx(e,t);for(const i of r)s.feed(i);return[...s.timeline]}var _s=(r,e,t)=>Math.min(t,Math.max(e,r));function Jx(r){const e=new Map,t=(i,n)=>e.set(i,(e.get(i)??0)+n);for(const i of r)if(i.kind==="read_file")t(i.path,Math.max(5,Math.round((i.bytes??400)/40)));else if(i.kind==="edit_file")t(i.path,Math.max(5,(i.added+i.removed)*3));else if(i.kind==="write_file")t(i.path,Math.max(5,i.added*2));else if(i.kind==="run_command")for(const n of i.touched)t(n,5);const s=[...e.keys()].sort((i,n)=>e.get(n)-e.get(i));return{files:s.map(i=>({path:i,loc:e.get(i)})),touched:s}}class eb{ctx=null;master=null;sfxBus=null;ambBus=null;duck=0;_muted=!1;_volume=.6;_ambience=!0;get ambienceEnabled(){return this._ambience}setAmbienceEnabled(e){this._ambience=e,this.ambBus&&this.ctx&&this.ambBus.gain.setTargetAtTime(e?.35:0,this.ctx.currentTime,.1)}noiseBuf=null;get ready(){return!!this.ctx&&this.ctx.state==="running"}get muted(){return this._muted}get volume(){return this._volume}async arm(){if(!this.ctx){const e=globalThis.AudioContext??globalThis.webkitAudioContext;if(!e)return;this.ctx=new e,this.master=this.ctx.createGain(),this.sfxBus=this.ctx.createGain(),this.ambBus=this.ctx.createGain(),this.sfxBus.connect(this.master),this.ambBus.connect(this.master),this.master.connect(this.ctx.destination),this.ambBus.gain.value=this._ambience?.35:0,this.applyGain();const t=this.ctx.sampleRate*2;this.noiseBuf=this.ctx.createBuffer(1,t,this.ctx.sampleRate);const s=this.noiseBuf.getChannelData(0);for(let i=0;i<t;i++)s[i]=Math.random()*2-1}this.ctx.state==="suspended"&&await this.ctx.resume()}setMuted(e){this._muted=e,this.applyGain()}setVolume(e){this._volume=Math.max(0,Math.min(1,e)),this.applyGain()}applyGain(){this.master&&this.master.gain.setTargetAtTime(this._muted?0:this._volume,this.ctx.currentTime,.02)}duckAmbience(e=.5,t=350){if(!this.ambBus||!this.ctx)return;const s=this.ctx.currentTime;this.ambBus.gain.cancelScheduledValues(s),this._ambience&&(this.ambBus.gain.setTargetAtTime(.35*(1-e),s,.01),this.ambBus.gain.setTargetAtTime(.35,s+t/1e3,.12),this.duck++)}tone(e,t,s={}){if(!this.ready||!this.ctx||!this.sfxBus)return;const i=this.ctx,n=i.currentTime,o=i.createOscillator();o.type=s.type??"sine",o.frequency.setValueAtTime(e,n),s.detune&&(o.detune.value=s.detune),s.slideTo&&o.frequency.exponentialRampToValueAtTime(Math.max(20,s.slideTo),n+t);const a=i.createGain(),l=s.attack??.005,h=s.decay??t;a.gain.setValueAtTime(1e-4,n),a.gain.exponentialRampToValueAtTime(s.gain??.25,n+l),a.gain.exponentialRampToValueAtTime(1e-4,n+l+h);let c=o;if(s.lowpass){const d=i.createBiquadFilter();d.type="lowpass",d.frequency.value=s.lowpass,o.connect(d),c=d}const u=i.createStereoPanner();u.pan.value=s.pan??0,c.connect(a),a.connect(u),u.connect(this.sfxBus),o.start(n),o.stop(n+l+h+.05),this.duckAmbience(.35,(l+h)*1e3)}noise(e,t={}){if(!this.ready||!this.ctx||!this.sfxBus||!this.noiseBuf)return;const s=this.ctx,i=s.currentTime,n=s.createBufferSource();n.buffer=this.noiseBuf,n.loop=!0;const o=s.createBiquadFilter();o.type=t.filter??"bandpass",o.frequency.setValueAtTime(t.freq??1200,i),o.Q.value=t.q??.8,t.sweepTo&&o.frequency.exponentialRampToValueAtTime(Math.max(40,t.sweepTo),i+e);const a=s.createGain(),l=t.attack??.004;a.gain.setValueAtTime(1e-4,i),a.gain.exponentialRampToValueAtTime(t.gain??.12,i+l),a.gain.exponentialRampToValueAtTime(1e-4,i+e);const h=s.createStereoPanner();h.pan.value=t.pan??0,n.connect(o),o.connect(a),a.connect(h),h.connect(this.sfxBus),n.start(i),n.stop(i+e+.05)}pad(e,t,s="sine"){if(!this.ready||!this.ctx||!this.ambBus)return()=>{};const i=this.ctx,n=i.currentTime,o=[],a=i.createGain();a.gain.setValueAtTime(1e-4,n),a.gain.exponentialRampToValueAtTime(t,n+1.5),a.connect(this.ambBus);for(const l of e){const h=i.createOscillator();h.type=s,h.frequency.value=l,h.detune.value=(Math.random()-.5)*6,h.connect(a),h.start(n),o.push(h)}return()=>{const l=i.currentTime;a.gain.cancelScheduledValues(l),a.gain.setTargetAtTime(1e-4,l,.4);for(const h of o)h.stop(l+2)}}wash(e,t,s,i=.12,n=.5){if(!this.ready||!this.ctx||!this.ambBus||!this.noiseBuf)return()=>{};const o=this.ctx,a=o.currentTime,l=o.createBufferSource();l.buffer=this.noiseBuf,l.loop=!0;const h=o.createBiquadFilter();h.type="lowpass",h.frequency.value=e,h.Q.value=t;const c=o.createGain();c.gain.setValueAtTime(1e-4,a),c.gain.exponentialRampToValueAtTime(s,a+2);const u=o.createOscillator();u.frequency.value=i;const d=o.createGain();return d.gain.value=s*n,u.connect(d),d.connect(c.gain),l.connect(h),h.connect(c),c.connect(this.ambBus),l.start(a),u.start(a),()=>{const f=o.currentTime;c.gain.setTargetAtTime(1e-4,f,.5),l.stop(f+2.5),u.stop(f+2.5)}}now(){return this.ctx?.currentTime??0}extra(e,t=(Math.random()-.5)*1.2){if(!this.ready||!this.ctx||!this.ambBus)return;const s=this.ctx,i=s.currentTime,n=(a,l,h,c,u,d=.01)=>{const f=s.createOscillator();f.type=a,f.frequency.setValueAtTime(l,i),f.frequency.exponentialRampToValueAtTime(Math.max(20,h),i+c);const p=s.createGain();p.gain.setValueAtTime(1e-4,i),p.gain.exponentialRampToValueAtTime(u,i+d),p.gain.exponentialRampToValueAtTime(1e-4,i+c);const m=s.createStereoPanner();m.pan.value=t,f.connect(p),p.connect(m),m.connect(this.ambBus),f.start(i),f.stop(i+c+.05)},o=(a,l,h,c,u,d="bandpass")=>{if(!this.noiseBuf)return;const f=s.createBufferSource();f.buffer=this.noiseBuf,f.loop=!0;const p=s.createBiquadFilter();p.type=d,p.frequency.setValueAtTime(a,i),u&&p.frequency.exponentialRampToValueAtTime(u,i+h),p.Q.value=l;const m=s.createGain();m.gain.setValueAtTime(1e-4,i),m.gain.exponentialRampToValueAtTime(c,i+.05),m.gain.exponentialRampToValueAtTime(1e-4,i+h);const g=s.createStereoPanner();g.pan.value=t,f.connect(p),p.connect(m),m.connect(g),g.connect(this.ambBus),f.start(i),f.stop(i+h+.05)};switch(e){case"gull":n("sine",1800,1100,.35,.05,.03),setTimeout(()=>n("sine",1700,1250,.3,.04,.03),260);return;case"cricket":for(let a=0;a<6;a++)setTimeout(()=>n("sine",4200,4100,.04,.02),a*70);return;case"bell":n("sine",880,870,2.2,.06,.005),n("sine",1760,1740,1.4,.03,.005),n("sine",2640,2600,.8,.015,.005);return;case"bubble":n("sine",300+Math.random()*300,900+Math.random()*600,.18,.04,.01);return;case"wind":o(500+Math.random()*400,.5,2.5+Math.random()*2,.05,300+Math.random()*300);return;case"horn":n("sawtooth",180,176,.8,.03,.08);return;case"hum":n("sine",60,60,2.5,.03,.4);return;case"chime":n("sine",1318.5,1316,1.2,.035,.005);return;case"owl":n("sine",420,380,.5,.04,.05),setTimeout(()=>n("sine",400,360,.6,.035,.05),420);return;case"rumble":o(90,1.2,2.5,.09,60,"lowpass");return;case"drip":n("sine",1200,600,.12,.04,.003);return;case"market":for(let a=0;a<4;a++)setTimeout(()=>o(600+Math.random()*1200,2,.12,.02),a*120);return}}}const tb=r=>1-Math.pow(1-r,3),An=r=>sb(.4,0,.2,1,r),nu=r=>1+(1.70158+1)*Math.pow(r-1,3)+1.70158*Math.pow(r-1,2),tt=r=>Math.sin(Math.PI*Math.min(1,Math.max(0,r)));function sb(r,e,t,s,i){const n=3*r,o=3*(t-r)-n,a=1-n-o,l=3*e,h=3*(s-e)-l,c=1-l-h,u=m=>((a*m+o)*m+n)*m,d=m=>((c*m+h)*m+l)*m,f=m=>(3*a*m+2*o)*m+n;let p=i;for(let m=0;m<6;m++){const g=f(p);if(Math.abs(g)<1e-6)break;p-=(u(p)-i)/g}return d(Math.min(1,Math.max(0,p)))}const rb=64,Ao=32,K=(r,e)=>({x:(r-e)*rb/2,y:(r+e)*Ao/2}),F=(r,e)=>({x:r.x,y:r.y-e}),Jt=(r,e,t)=>r+(e-r)*t,Be=(r,e,t)=>({x:Jt(r.x,e.x,t),y:Jt(r.y,e.y,t)}),ib=(r,e,t)=>r<e?e:r>t?t:r,Ue=(r,e,t)=>ib((r-e)/(t-e),0,1),ou=(r,e,t=1)=>r+e+t;function De(r,e,t,s=0){return[K(r,e),K(r+t,e),K(r+t,e+t),K(r,e+t)].map(i=>F(i,s))}const X=r=>r.flatMap(e=>[e.x,e.y]);class nb{constructor(e,t){this.stage=e,this.reducedMotion=t}cx=0;cy=0;zoom=1;tx=0;ty=0;tz=1;punch=0;shakeT=0;drift=0;t=0;fit(e,t,s,i,n=1.08){this.tz=Math.min(s/(e*n),i/(t*n))}follow(e,t,s=1){this.tx=Jt(this.tx,e,s),this.ty=Jt(this.ty,t,s)}setZoomFactor(e){this.tz=e}pushIn(e=.08){this.reducedMotion||(this.punch=Math.max(this.punch,e))}shake(e=220){this.reducedMotion||(this.shakeT=e/1e3)}setDrift(e){this.drift=this.reducedMotion?0:e?1:0}snap(){this.cx=this.tx,this.cy=this.ty,this.zoom=this.tz}update(e,t,s){const i=Number.isFinite(e)?Math.max(0,Math.min(.05,e/1e3)):0;this.t+=i;const n=1-Math.pow(.012,i),o=1-Math.pow(.05,i);this.cx+=(this.tx-this.cx)*n,this.cy+=(this.ty-this.cy)*n,this.punch=Math.max(0,this.punch-i*.12),this.zoom+=(this.tz*(1+tb(this.punch/.08)*this.punch)-this.zoom)*o;let a=0,l=0;if(this.shakeT>0){this.shakeT-=i;const h=this.shakeT*18;a=Math.sin(this.t*60)*h,l=Math.cos(this.t*47)*h}this.drift&&(a+=Math.sin(this.t*.7)*2.2,l+=Math.cos(this.t*.5)*1.6),this.stage.scale.set(this.zoom),this.stage.position.set(t/2-(this.cx+a)*this.zoom,s/2-(this.cy+l)*this.zoom)}toScreen(e,t){return{x:this.stage.position.x+e*this.zoom,y:this.stage.position.y+t*this.zoom}}get scale(){return this.zoom}}const ob={roof:"pitched",eave:.14,furniture:"chimney",stripes:!1},ab={roof:"flat",eave:.05,furniture:"vent",stripes:!1},lb={roof:"capsule",eave:0,furniture:"dish",stripes:!1},Rn={island:ob,orbit:lb,metropolis:ab,harbour:{roof:"gable",eave:.16,furniture:"chimney",stripes:!1},observatory:{roof:"dome",eave:.04,furniture:"dish",stripes:!1},greenhouse:{roof:"gable",eave:.1,furniture:"vent",stripes:!1},workshop:{roof:"gable",eave:.12,furniture:"chimney",stripes:!1},arcade:{roof:"flat",eave:.08,furniture:"mast",stripes:!0},kingdom:{roof:"pitched",eave:.1,furniture:"finial",stripes:!1},outpost:{roof:"flat",eave:.12,furniture:"vent",stripes:!1},snowfield:{roof:"pitched",eave:.2,furniture:"chimney",stripes:!1},canopy:{roof:"pitched",eave:.22,furniture:"none",stripes:!1},lagoon:{roof:"tent",eave:.18,furniture:"none",stripes:!0},volcano:{roof:"flat",eave:.06,furniture:"vent",stripes:!1},cloudtop:{roof:"dome",eave:.06,furniture:"finial",stripes:!1},reef:{roof:"dome",eave:.02,furniture:"none",stripes:!1},bazaar:{roof:"tent",eave:.2,furniture:"none",stripes:!0},monastery:{roof:"onion",eave:.08,furniture:"finial",stripes:!1},moonbase:{roof:"capsule",eave:0,furniture:"dish",stripes:!1},lanterns:{roof:"tiered",eave:.26,furniture:"lantern",stripes:!1}};class Sg{constructor(e,t){this.world=e,this.theme=t,this.container.addChild(this.ripples,this.terrain,this.paths,this.labels,this.shadows,this.clouds,this.objects),this.objects.sortableChildren=!0,this.shadows.alpha=.9,this.drawTerrain(),this.drawPaths(),this.drawLabels();for(const s of e.places)this.addPlace(s);this.placeProps()}container=new _e;terrain=new Pe;ripples=new Pe;paths=new Pe;labels=new _e;shadows=new Pe;clouds=new Pe;objects=new _e;drawn=new Map;props=[];time=0;positionOf(e){const t=this.drawn.get(e);if(!t)return null;const s=t.place,i=s.gx+s.footprint/2,n=s.gy+s.footprint/2,o=K(i,n);return{ground:o,top:F(o,this.heightPx(t)+10),place:s}}standingSpot(e){const t=this.drawn.get(e);if(!t)return K(0,0);const s=t.place;return K(s.gx+s.footprint/2,s.gy+s.footprint+.55)}setGlow(e,t){const s=this.drawn.get(e);s&&s.glow!==t&&(s.glow=t,s.dirty=!0)}setGrowth(e,t){const s=this.drawn.get(e);s&&s.extraH!==t&&(s.extraH=t,s.dirty=!0)}setScaffold(e,t){const s=this.drawn.get(e);s&&s.scaffold!==t&&(s.scaffold=t,s.dirty=!0)}setLamp(e,t){const s=this.drawn.get(e);s&&s.lamp!==t&&(s.lamp=t,s.dirty=!0)}lampOf(e){return this.drawn.get(e)?.lamp??"idle"}has(e){return this.drawn.has(e)}addPlace(e){if(this.drawn.has(e.id))return;const t=new Pe;t.zIndex=ou(e.gx,e.gy,e.footprint);const s=Math.max(0,this.world.districts.findIndex(u=>u.id===e.district)),i=e.kind==="beacon"?this.theme.beacon:e.kind==="archive"?this.theme.archive:e.kind==="forge"?this.theme.forge:this.theme.palettes[s%this.theme.palettes.length],n=e.kind==="building"?ko(e.path):0,o=e.kind==="building"?(n%5-2)*.05:0,a=e.kind==="building"&&n%3===0?this.theme.palettes[(s+1+n%2)%this.theme.palettes.length]:i,l=u=>o>=0?Q(u,16777215,o):Q(u,0,-o),h={top:l(i.top),left:l(i.left),right:l(i.right),roof:a.roof,roofD:a.roofD,win:i.win},c={place:e,g:t,palette:h,extraH:0,glow:0,lamp:"idle",scaffold:0,dirty:!0};this.drawn.set(e.id,c),this.objects.addChild(t),this.redraw(c)}update(e){this.time+=e/1e3,this.drawRipples(),this.drawCloudShadows();for(const t of this.props)t.canopy&&(t.canopy.x=Math.sin(this.time*1.4+t.phase)*1.2);for(const t of this.drawn.values())(t.glow>0||t.lamp==="scan"||t.lamp==="fail"||t.lamp==="pass"||t.place.kind==="dock"||t.place.kind==="forge")&&(t.dirty=!0),t.dirty&&this.redraw(t)}heightPx(e){const t=e.place;return(t.kind==="beacon"?70:t.kind==="forge"?34:t.kind==="dock"?4:t.kind==="archive"?30:18+t.height*8)+e.extraH}redraw(e){const{g:t,place:s,palette:i}=e;t.clear(),e.dirty=!1;const n=this.heightPx(e),o=s.footprint,a=De(s.gx+.12,s.gy+.12,o);if(t.poly(X(a)).fill({color:this.shadowInk,alpha:.22}),s.kind!=="dock"&&this.castShadow(t,s,n),s.kind==="dock")return this.drawDock(t,s);if(s.kind==="beacon")return this.drawBeacon(e,n);const l=this.box(t,s.gx,s.gy,o,n,s.kind==="forge"?i.roof:i.top,i.left,i.right),h=e.glow>0?.6+.4*Math.sin(this.time*10):0,c=e.glow>0?Q(i.win,16771496,.5+.5*h):i.win;if(s.kind!=="archive"&&s.kind!=="forge"){const u=Math.max(1,Math.round(n/28)),d=o>=3?3:2;this.windows(t,l[3],l[2],n,u,d,c,e.glow>0?1:.9),this.windows(t,l[2],l[1],n,u,d,c,e.glow>0?1:.8);const f=Be(l[3],l[2],.3);t.poly([f.x-3,f.y-1,f.x+3,f.y+1,f.x+3,f.y-9,f.x-3,f.y-11]).fill({color:i.roofD,alpha:.9})}if(s.kind==="building"&&o<=2&&this.roof(t,s,n,i),s.kind==="building"&&o>=3&&Rn[this.theme.id].roof!=="capsule"&&Rn[this.theme.id].roof!=="dome"){const u=l.map(p=>F(p,n));t.poly(X([u[3],u[2],F(u[2],4),F(u[3],4)])).fill(i.roofD),t.poly(X([u[2],u[1],F(u[1],4),F(u[2],4)])).fill(Q(i.roofD,0,.2)),t.poly(X(u.map(p=>F(p,4)))).fill(i.roof);const d=De(s.gx+.8,s.gy+.8,o-1.6,n+4);t.poly(X([d[3],d[2],F(d[2],10),F(d[3],10)])).fill(i.left),t.poly(X([d[2],d[1],F(d[1],10),F(d[2],10)])).fill(i.right),t.poly(X(d.map(p=>F(p,10)))).fill(i.top);const f=F(K(s.gx+o/2,s.gy+o/2),n+14);t.moveTo(f.x,f.y).lineTo(f.x,f.y-12).stroke({width:1.6,color:i.roofD}),t.circle(f.x,f.y-13-14,2.2).fill(e.glow>0?16766571:i.roof)}if(s.kind==="archive"){for(let u=1;u<6;u++){const d=Be(l[3],l[2],u/6);t.moveTo(d.x,d.y-3).lineTo(d.x,d.y-n+5).stroke({width:1.3,color:16777215,alpha:.6})}for(let u=1;u<5;u++){const d=Be(l[2],l[1],u/5);t.moveTo(d.x,d.y-3).lineTo(d.x,d.y-n+5).stroke({width:1.3,color:16777215,alpha:.45})}this.pyramid(t,l.map(u=>F(u,n)),F(K(s.gx+o/2,s.gy+o/2),n+10),i.roof,i.roofD)}if(s.kind==="forge"){const u=this.theme.forge.ember,d=Be(l[3],l[2],.5);t.poly([d.x-7,d.y-2,d.x+7,d.y+2,d.x+7,d.y-18,d.x-7,d.y-22]).fill({color:u,alpha:.85}),this.windows(t,l[2],l[1],n,2,2,u,.9),this.pyramid(t,l.map(m=>F(m,n)),F(K(s.gx+o/2,s.gy+o/2),n+16),i.roof,i.roofD);const f=F(K(s.gx+o*.75,s.gy+o*.3),n+6);t.rect(f.x-4,f.y-16,8,16).fill(i.roofD);for(let m=0;m<3;m++){const g=(this.time*.35+m/3)%1;t.circle(f.x+Math.sin(g*6+m)*4,f.y-18-g*26,3+g*6).fill({color:16777215,alpha:.22*(1-g)})}const p=.5+.5*Math.sin(this.time*3);t.circle(d.x,d.y-8,12+p*4).fill({color:u,alpha:.12+.08*p})}e.glow>0&&this.outline(t,l,n,16762970,.4+.4*h),e.scaffold>0&&this.scaffold(t,s,n,e.scaffold)}roof(e,t,s,i){const n=Rn[this.theme.id],o=t.footprint,a=n.eave,l=ko(t.path),h=De(t.gx-a,t.gy-a,o+a*2,s),c=K(t.gx+o/2,t.gy+o/2),u=Q(i.roofD,this.shadowInk,.35);switch(a>0&&(e.poly(X([h[3],h[2],F(h[2],-3),F(h[3],-3)])).fill({color:u,alpha:.9}),e.poly(X([h[2],h[1],F(h[1],-3),F(h[2],-3)])).fill({color:Q(u,0,.2),alpha:.9})),n.roof){case"pitched":{this.pyramid(e,h,F(c,s+12+o*9),i.roof,i.roofD);break}case"gable":{const f=11+o*7,p=F(Be(h[0],h[3],.5),s+f),m=F(Be(h[1],h[2],.5),s+f);e.poly(X([h[3],h[2],m,p])).fill(Rt(Q(i.roof,16777215,.1),i.roof,p.y,h[3].y)),e.poly(X([h[0],h[1],m,p])).fill(Q(i.roofD,this.shadowInk,.2)),e.poly(X([h[2],h[1],m])).fill(Q(i.right,this.shadowInk,.1)),e.poly(X([h[3],h[0],p])).fill(i.left),e.moveTo(p.x,p.y).lineTo(m.x,m.y).stroke({width:1.4,color:16777215,alpha:.4,cap:"round"});break}case"flat":{const f=h.map(m=>F(m,3));e.poly(X([h[3],h[2],f[2],f[3]])).fill(i.roofD),e.poly(X([h[2],h[1],f[1],f[2]])).fill(Q(i.roofD,0,.2)),e.poly(X(f)).fill(au(Q(i.roof,16777215,.08),i.roof,f[3].x,f[1].x));const p=De(t.gx+.25+l%3*.1,t.gy+.3,.4,s+3);e.poly(X([p[3],p[2],F(p[2],6),F(p[3],6)])).fill(i.left),e.poly(X([p[2],p[1],F(p[1],6),F(p[2],6)])).fill(i.right),e.poly(X(p.map(m=>F(m,6)))).fill(i.top);break}case"dome":{const f=o*32*.78,p=c.y-s+2;e.ellipse(c.x,p,f,f*.62).fill(Rt(Q(i.roof,16777215,.22),Q(i.roofD,this.shadowInk,.15),p-f*.62,p+f*.3)),e.rect(c.x-f,p,f*2,f*.62).fill({color:0,alpha:0}),e.ellipse(c.x-f*.3,p-f*.28,f*.28,f*.14).fill({color:16777215,alpha:.32});break}case"onion":{const f=o*16,p=c.y-s;e.moveTo(c.x-f,p).quadraticCurveTo(c.x-f*1.15,p-f*1.1,c.x,p-f*2.2).quadraticCurveTo(c.x+f*1.15,p-f*1.1,c.x+f,p).fill(Rt(Q(i.roof,16777215,.2),i.roofD,p-f*2.2,p)),e.moveTo(c.x-f*.4,p-f*.3).quadraticCurveTo(c.x-f*.5,p-f*1.2,c.x-f*.05,p-f*1.9).stroke({width:1.6,color:16777215,alpha:.35,cap:"round"});break}case"tiered":{for(let f=0;f<2;f++){const p=s+f*14,m=a*(1-f*.45),g=De(t.gx-m,t.gy-m,o+m*2,p);e.poly(X([g[3],g[2],F(g[2],-2),F(g[3],-2)])).fill(u);const _=F(c,p+9+o*3);e.poly(X([F(g[3],3),F(g[2],3),_])).fill(i.roof),e.poly(X([F(g[2],3),F(g[1],3),_])).fill(i.roofD),e.poly(X([F(g[3],3),F(g[0],3),_])).fill(Q(i.roof,16777215,.1));for(const x of[g[1],g[2],g[3]])e.moveTo(x.x,x.y+1).quadraticCurveTo(x.x+(x.x<c.x?-4:4),x.y-1,x.x+(x.x<c.x?-5:5),x.y-6).stroke({width:2,color:i.roofD,cap:"round"})}break}case"tent":{const f=F(c,s+16+o*8);this.pyramid(e,h,f,i.roof,i.roofD);for(let p=0;p<o*3;p++){const m=Be(h[3],h[2],p/(o*3)),g=Be(h[3],h[2],(p+1)/(o*3));e.moveTo(m.x,m.y).quadraticCurveTo((m.x+g.x)/2,(m.y+g.y)/2+4,g.x,g.y).fill(i.roofD)}e.moveTo(f.x,f.y).lineTo(f.x,f.y-8).stroke({width:1.5,color:i.roofD}),e.poly([f.x,f.y-8,f.x+7,f.y-6,f.x,f.y-4]).fill(i.win);break}case"capsule":{const f=o*32*.7,p=c.y-s+1;e.ellipse(c.x,p,f*1.02,f*.5).fill(Rt(Q(i.top,16777215,.25),i.top,p-f*.5,p+f*.1)),e.ellipse(c.x-f*.3,p-f*.22,f*.3,f*.1).fill({color:16777215,alpha:.4}),e.ellipse(c.x,p,f*1.02,f*.5).stroke({width:1.2,color:Q(i.roofD,16777215,.1),alpha:.6});break}}const d=F(K(t.gx+o*.72,t.gy+o*.3),s+(n.roof==="flat"?3:n.roof==="pitched"||n.roof==="gable"?8:0));switch(n.furniture){case"chimney":l%2===0&&(e.rect(d.x-3,d.y-12,6,12).fill(i.roofD),e.rect(d.x-4,d.y-13,8,3).fill(Q(i.roofD,0,.2)));break;case"vent":e.rect(d.x-4,d.y-5,8,5).fill(Q(i.left,this.shadowInk,.2)),e.ellipse(d.x,d.y-5,4,1.6).fill(i.top);break;case"mast":e.moveTo(d.x,d.y).lineTo(d.x,d.y-16).stroke({width:1.4,color:i.roofD}),e.circle(d.x,d.y-17,2).fill(i.win);break;case"finial":{const f=F(c,s+12+o*9+(n.roof==="onion"?o*16*2.2-12-o*9:0));e.moveTo(f.x,f.y).lineTo(f.x,f.y-7).stroke({width:1.4,color:16766571}),e.circle(f.x,f.y-8,2).fill(16766571);break}case"lantern":{const f=Be(h[3],h[2],.5);e.moveTo(f.x,f.y).lineTo(f.x,f.y+5).stroke({width:1,color:i.roofD}),e.roundRect(f.x-3,f.y+5,6,8,2).fill(hb(i.win));break}case"dish":e.ellipse(d.x,d.y-2,6,3).stroke({width:1.4,color:16777215,alpha:.7}),e.moveTo(d.x,d.y-2).lineTo(d.x+2,d.y-7).stroke({width:1,color:16777215,alpha:.7});break}if(n.stripes){const f=De(t.gx,t.gy,o);for(let p=0;p<o*4;p+=2){const m=Be(f[3],f[2],p/(o*4)),g=Be(f[3],f[2],(p+1)/(o*4));e.poly([m.x,m.y,g.x,g.y,g.x,g.y-s*.35,m.x,m.y-s*.35]).fill({color:16777215,alpha:.22})}}}box(e,t,s,i,n,o,a,l){const[h,c,u,d]=De(t,s,i),f=this.hazeOf(s+t),p=m=>Q(m,this.theme.sky[0],f);return e.poly(X([d,u,F(u,n),F(d,n)])).fill(Rt(p(Q(a,16777215,.08)),p(Q(a,this.shadowInk,.28)),d.y-n,d.y)),e.poly(X([u,c,F(c,n),F(u,n)])).fill(Rt(p(Q(l,this.coolInk,.06)),p(Q(l,this.shadowInk,.38)),u.y-n,u.y)),e.poly(X([F(h,n),F(c,n),F(u,n),F(d,n)])).fill(au(p(Q(o,16777215,.16)),p(o),d.x,c.x)),e.moveTo(d.x,d.y-n).lineTo(h.x,h.y-n).lineTo(c.x,c.y-n).stroke({width:1.3,color:16777215,alpha:.42,cap:"round"}),e.moveTo(d.x,d.y-n).lineTo(d.x,d.y).stroke({width:1.1,color:16777215,alpha:.22}),[h,c,u,d]}hazeOf(e){const t=this.world.bounds,s=t.x+t.y,i=t.x+t.w+t.y+t.h;return .16*(1-Math.max(0,Math.min(1,(e-s)/Math.max(1,i-s))))}get shadowInk(){return Q(this.theme.vignette,0,.3)}get coolInk(){return Q(this.theme.sky[0],2768746,.5)}castShadow(e,t,s){const i=t.footprint,n=s/36,o=De(t.gx,t.gy,i),a=.55*n,l=.95*n,h=[K(t.gx+a,t.gy+l),K(t.gx+i+a,t.gy+l),K(t.gx+i+a,t.gy+i+l),K(t.gx+a,t.gy+i+l)],c=[o[1],h[1],h[2],h[3],o[3],o[2]];e.poly(X(c)).fill({color:this.shadowInk,alpha:.16});const u=[K(t.gx+a*.6,t.gy+l*.6),K(t.gx+i+a*.6,t.gy+l*.6),K(t.gx+i+a*.6,t.gy+i+l*.6)];e.poly(X([o[1],u[1],u[2],o[3],o[2]])).fill({color:this.shadowInk,alpha:.12})}drawCloudShadows(){const e=this.clouds;if(e.clear(),this.theme.terrain!=="island"&&this.theme.terrain!=="block")return;const t=this.world.bounds,s=K(t.x+t.w/2,t.y+t.h/2),i=(t.w+t.h)*24;for(let n=0;n<3;n++){const o=(this.time*.012+n*.37)%1,a=s.x-i/2+o*i*1.3-i*.15,l=s.y-90+Math.sin(n*2.1)*120;e.ellipse(a,l,150+n*30,56+n*8).fill({color:this.shadowInk,alpha:.075}),e.ellipse(a+90,l+18,110,40).fill({color:this.shadowInk,alpha:.06})}}pyramid(e,t,s,i,n){e.poly(X([t[0],t[1],s])).fill(Q(n,this.shadowInk,.25)),e.poly(X([t[3],t[0],s])).fill(Q(i,16777215,.12)),e.poly(X([t[3],t[2],s])).fill(Rt(Q(i,16777215,.06),i,s.y,t[2].y)),e.poly(X([t[2],t[1],s])).fill(Rt(n,Q(n,this.shadowInk,.3),s.y,t[1].y)),e.moveTo(t[3].x,t[3].y).lineTo(s.x,s.y).stroke({width:1.2,color:16777215,alpha:.35,cap:"round"})}windows(e,t,s,i,n,o,a,l){const h=(s.x-t.x)/o*.3,c=(s.y-t.y)/o*.3;for(let u=0;u<n;u++)for(let d=0;d<o;d++){const f=Be(t,s,(d+.5)/o),p=f.y-i*(u+.75)/(n+.5),m=f.x;e.poly([m-h,p-c,m+h,p+c,m+h,p+c-6,m-h,p-c-6]).fill({color:a,alpha:l}),e.poly([m-h,p-c-4.5,m+h,p+c-4.5,m+h,p+c-6,m-h,p-c-6]).fill({color:16777215,alpha:l*.45})}}outline(e,t,s,i,n){const o=t.map(a=>F(a,s));e.moveTo(t[3].x,t[3].y).lineTo(t[2].x,t[2].y).lineTo(t[1].x,t[1].y).lineTo(o[1].x,o[1].y).lineTo(o[0].x,o[0].y).lineTo(o[3].x,o[3].y).closePath().stroke({width:2,color:i,alpha:n,join:"round"}),e.moveTo(t[2].x,t[2].y).lineTo(o[2].x,o[2].y).stroke({width:2,color:i,alpha:n})}scaffold(e,t,s,i){const n=De(t.gx-.12,t.gy-.12,t.footprint+.24);for(const o of[n[1],n[2],n[3]])e.moveTo(o.x,o.y).lineTo(o.x,o.y-s-8).stroke({width:1.1,color:16768150,alpha:i});for(let o=10;o<s+8;o+=11)e.moveTo(n[3].x,n[3].y-o).lineTo(n[2].x,n[2].y-o).lineTo(n[1].x,n[1].y-o).stroke({width:1.1,color:16768150,alpha:i})}drawBeacon(e,t){const{g:s,place:i}=e,n=this.theme.beacon,o=n.lamp[e.lamp],a=this.box(s,i.gx+.2,i.gy+.2,.6,t,n.top,n.left,n.right);for(const[u,d]of[[.2,.33],[.52,.65]])s.poly(X([F(a[3],t*u),F(a[2],t*u),F(a[2],t*d),F(a[3],t*d)])).fill(n.roof),s.poly(X([F(a[2],t*u),F(a[1],t*u),F(a[1],t*d),F(a[2],t*d)])).fill(n.roofD);const l=F(K(i.gx+.5,i.gy+.5),t+6),h=e.lamp==="fail"?.55+.45*Math.sin(this.time*9):e.lamp==="scan"?.8+.2*Math.sin(this.time*20):1,c=e.lamp==="idle"?16:26;if(s.circle(l.x,l.y,c).fill({color:o,alpha:.22*h}),s.circle(l.x,l.y,c*.55).fill({color:o,alpha:.3*h}),e.lamp==="scan"||e.lamp==="pass"){const u=e.lamp==="scan"?this.time*5:this.time*1.1,d=e.lamp==="scan"?190:120,f=.2;s.moveTo(l.x,l.y).arc(l.x,l.y,d,u-f,u+f).closePath().fill({color:o,alpha:.18})}this.box(s,i.gx+.28,i.gy+.28,.44,11,2899538,o,Q(o,0,.25)),this.pyramid(s,De(i.gx+.2,i.gy+.2,.6,t+11),F(K(i.gx+.5,i.gy+.5),t+22),n.roof,n.roofD)}drawDock(e,t){const s=De(t.gx,t.gy,t.footprint);e.poly(X([s[3],s[2],F(s[2],-5),F(s[3],-5)])).fill(this.theme.dock.post),e.poly(X([s[2],s[1],F(s[1],-5),F(s[2],-5)])).fill(Q(this.theme.dock.post,0,.2)),e.poly(X(s)).fill(this.theme.dock.deck);for(let o=1;o<5;o++){const a=Be(s[0],s[3],o/5),l=Be(s[1],s[2],o/5);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:0,alpha:.12})}for(const o of[s[0],s[1],s[2],s[3]])e.rect(o.x-2,o.y-12,4,12).fill(this.theme.dock.post);const i=Be(s[1],s[2],.5),n=Math.sin(this.time*1.6)*1.5;e.ellipse(i.x+22,i.y+6+n,16,6).fill(this.theme.dock.vessel),e.ellipse(i.x+22,i.y+3+n,13,4).fill(Q(this.theme.dock.vessel,0,.12)),e.rect(i.x+20,i.y-12+n,3,15).fill(this.theme.dock.post),e.poly([i.x+23,i.y-12+n,i.x+34,i.y-6+n,i.x+23,i.y-2+n]).fill({color:16777215,alpha:.9})}blobPath(e,t,s){const i=this.world.bounds,n=i.x+i.w/2,o=i.y+i.h/2,a=i.w/2+1.2,l=i.h/2+1.2,h=[],c=ar(this.world.seed^1540483477)()*6.28;for(let u=0;u<80;u++){const d=u/80*Math.PI*2,f=1+.07*Math.sin(3*d+c)+.04*Math.sin(5*d+2.1+c)+.025*Math.sin(8*d+1.3),p=K(n+Math.cos(d)*a*f*t,o+Math.sin(d)*l*f*t);h.push(p.x,p.y+s)}return e.poly(h)}drawTerrain(){const e=this.terrain,t=this.theme.ground;if(this.theme.terrain==="island"){this.blobPath(e,1,18).fill(t.edgeDark),this.blobPath(e,1,10).fill(t.edge),this.blobPath(e,1,0).fill(t.sand),this.blobPath(e,.88,-1).fill(t.fill),this.blobPath(e,.6,-2).fill({color:t.fillLight,alpha:.55});const s=this.world.bounds,i=K(s.x+s.w/2,s.y+s.h/2),n=(s.w+s.h)*14;e.circle(i.x-n*.45,i.y-n*.35,n*.9).fill({color:16777215,alpha:.07}),e.circle(i.x+n*.5,i.y+n*.4,n*1.1).fill({color:this.shadowInk,alpha:.08})}else if(this.theme.terrain==="platform"){const s=this.world.bounds,i=De(s.x,s.y,Math.max(s.w,s.h));e.poly(X([i[3],i[2],F(i[2],-14),F(i[3],-14)])).fill(t.edgeDark),e.poly(X([i[2],i[1],F(i[1],-14),F(i[2],-14)])).fill(t.edge),e.poly(X(i)).fill(t.fill),e.poly(X(De(s.x+1,s.y+1,Math.max(s.w,s.h)-2))).fill({color:t.fillLight,alpha:.25}),e.poly(X(i)).stroke({width:2,color:t.sand,alpha:.6})}else{const s=this.world.bounds,i=Math.max(s.w,s.h),n=De(s.x,s.y,i);e.poly(X([n[3],n[2],F(n[2],-10),F(n[3],-10)])).fill(t.edgeDark),e.poly(X([n[2],n[1],F(n[1],-10),F(n[2],-10)])).fill(t.edge),e.poly(X(n)).fill(t.fill);for(let o=1;o<i;o+=2){const a=K(s.x+o,s.y),l=K(s.x+o,s.y+i);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:t.sand,alpha:.12})}for(let o=1;o<i;o+=2){const a=K(s.x,s.y+o),l=K(s.x+i,s.y+o);e.moveTo(a.x,a.y).lineTo(l.x,l.y).stroke({width:1,color:t.sand,alpha:.12})}}}drawRipples(){const e=this.ripples;if(e.clear(),this.theme.terrain!=="island"){const t=ar(this.world.seed);for(let s=0;s<70;s++){const i=(t()-.5)*2600,n=(t()-.5)*1600,o=.5+.5*Math.sin(this.time*(.6+t())+s);e.circle(i,n,.8+t()*1.2).fill({color:this.theme.water.ripple,alpha:this.theme.water.rippleAlpha*o})}return}for(let t=0;t<3;t++){const s=(this.time*.06+t/3)%1;this.blobPath(e,1.04+s*.45,8).stroke({width:1.4,color:this.theme.water.ripple,alpha:this.theme.water.rippleAlpha*.7*(1-s)})}}drawPaths(){const e=this.paths;for(const t of this.world.paths){const s=t.points.map(([i,n])=>K(i+.5,n+.5));e.moveTo(s[0].x,s[0].y);for(const i of s.slice(1))e.lineTo(i.x,i.y);e.stroke({width:7,color:this.theme.pathColor,alpha:.9,cap:"round",join:"round"})}}drawLabels(){const e=new Ps({fontFamily:"Fredoka, Trebuchet MS, sans-serif",fontSize:22,fontWeight:"700",fill:16777215,letterSpacing:2,stroke:{color:this.theme.vignette,width:4,join:"round"}});for(const t of this.world.districts){const s=new bp({text:t.label,style:e});s.anchor.set(.5,.5);const i=K(t.bounds.x+t.bounds.w/2+.5,t.bounds.y+t.bounds.h+.55);s.position.set(i.x,i.y),s.alpha=.55,s.skew.set(-.35,.17),this.labels.addChild(s)}}placeProps(){const e=ar(this.world.seed^2654435769),t=new Set;for(const a of this.world.places)for(let l=0;l<a.footprint;l++)for(let h=0;h<a.footprint;h++)t.add(`${a.gx+l},${a.gy+h}`);const s=this.world.bounds;let i=0,n=0;const o=Math.min(18,5+Math.floor(this.world.places.length/5));for(;n<o&&i++<700;){const a=Math.floor(s.x+1+e()*(s.w-2)),l=Math.floor(s.y+1+e()*(s.h-2));if(t.has(`${a},${l}`)||this.world.districts.some(_=>a>=_.bounds.x&&a<_.bounds.x+_.bounds.w&&l>=_.bounds.y&&l<_.bounds.y+_.bounds.h))continue;t.add(`${a},${l}`);const h=new _e;h.zIndex=ou(a,l);const c=new Pe;h.addChild(c);const u=K(a+.5,l+.5),d=(.85+e()*.4)*1.25,[f,p,m]=this.theme.propColors;let g;this.theme.prop==="tree"?(c.ellipse(u.x+3,u.y+1,9*d,4*d).fill({color:666138,alpha:.18}),c.rect(u.x-1.5,u.y-10*d,3,10*d).fill(m),g=new Pe,g.ellipse(u.x+1*d,u.y-13*d,9.5*d,7.5*d).fill(Q(f,this.shadowInk,.25)),g.ellipse(u.x,u.y-16*d,9*d,8.5*d).fill(f),g.ellipse(u.x-4*d,u.y-19*d,6.5*d,6*d).fill(p),g.ellipse(u.x+4.5*d,u.y-20*d,5.5*d,5*d).fill(p),g.ellipse(u.x-3.5*d,u.y-22*d,3.2*d,2.4*d).fill({color:16777215,alpha:.32}),h.addChild(g)):this.theme.prop==="antenna"?(c.rect(u.x-1,u.y-18*d,2,18*d).fill(f),c.circle(u.x,u.y-20*d,2.5).fill(p),c.ellipse(u.x,u.y,5*d,2.5*d).fill(m)):(c.rect(u.x-1,u.y-16*d,2,16*d).fill(m),c.circle(u.x,u.y-17*d,3).fill(f),c.circle(u.x,u.y-17*d,7).fill({color:p,alpha:.18})),this.objects.addChild(h),this.props.push({g:c,gx:a,gy:l,phase:e()*6.28,...g?{canopy:g}:{}}),n++}}}const hb=r=>Q(r,16777215,.25),js=new Map;function Cg(r,e){let t=js.get(r);if(!t){if(js.size>1500){for(const s of js.values())s.destroy();js.clear()}t=e(),js.set(r,t)}return t}const fi=r=>Math.round(r/2)*2;function Rt(r,e,t,s){const i=fi(t),n=fi(s);return Cg(`v${r}|${e}|${i}|${n}`,()=>new Xe({start:{x:0,y:i},end:{x:0,y:n},colorStops:[{offset:0,color:r},{offset:1,color:e}],textureSpace:"global"}))}function au(r,e,t,s){const i=fi(t),n=fi(s);return Cg(`h${r}|${e}|${i}|${n}`,()=>new Xe({start:{x:i,y:0},end:{x:n,y:0},colorStops:[{offset:0,color:r},{offset:1,color:e}],textureSpace:"global"}))}function Q(r,e,t){const s=r>>16&255,i=r>>8&255,n=r&255,o=e>>16&255,a=e>>8&255,l=e&255,h=Math.round(s+(o-s)*t),c=Math.round(i+(a-i)*t),u=Math.round(n+(l-n)*t);return h<<16|c<<8|u}class Ro{constructor(e,t,s){this.id=e,this.theme=t,this.reducedMotion=s,this.container.addChild(this.g)}container=new _e;g=new Pe;t=Math.random()*10;x=0;y=0;scale=1;alpha=1;lift=0;panic=0;peek=0;update(e){this.t+=e/1e3;const t=this.t,s=this.g,i=this.theme.gremlin,n=this.reducedMotion?0:Math.abs(Math.sin(t*(7+this.panic*5)))*(6+this.panic*3);this.container.position.set(this.x,this.y),this.container.alpha=this.alpha,s.clear(),s.ellipse(0,0,7*this.scale,3*this.scale).fill({color:994600,alpha:.25}),s.position.set(0,0);const o=this.scale,a=9,l=[];for(let u=0;u<=a*2;u++){const d=u/(a*2)*Math.PI*2,f=(u%2?7.2:9.6+Math.sin(t*20+u)*.7)*o;l.push(Math.cos(d)*f,-9*o-n-this.lift+Math.sin(d)*f*.9)}s.poly(l).fill(i.body);const h=-10*o-n-this.lift;s.ellipse(-3*o,h,2.4*o,2.6*o).fill(16777215),s.ellipse(3*o,h,2.4*o,2.6*o).fill(16777215);const c=this.panic?Math.sin(t*9)*.8:.4;s.ellipse(-2.6*o+c,h+.4,1.2*o,1.3*o).fill(i.eye),s.ellipse(3.4*o+c,h+.4,1.2*o,1.3*o).fill(i.eye),s.moveTo(-5.5*o,h-4*o).lineTo(-1.2*o,h-2.4*o).moveTo(5.5*o,h-4*o).lineTo(1.2*o,h-2.4*o).stroke({width:1.3*o,color:i.eye,cap:"round"}),s.moveTo(-2.6*o,h+4.4*o).lineTo(-1.2*o,h+3.4*o).lineTo(.2*o,h+4.4*o).lineTo(1.6*o,h+3.4*o).lineTo(2.9*o,h+4.4*o).stroke({width:1.3*o,color:i.eye,cap:"round"})}}const cb=Object.freeze(Object.defineProperty({__proto__:null,Gremlin:Ro},Symbol.toStringTag,{value:"Module"}));class ub{constructor(e){this.reducedMotion=e}g=new Pe;parts=[];burst(e,t,s,i,n,o=0){this.reducedMotion&&(s=Math.ceil(s/4));for(let a=0;a<s;a++){const l=Math.random()*Math.PI*2,h=n*(.4+Math.random()*.8);this.parts.push({x:e,y:t,vx:Math.cos(l)*h,vy:Math.sin(l)*h*.6-o*(.5+Math.random()),life:0,max:.7+Math.random()*.8,c:i[a%i.length],r:1.4+Math.random()*2.4})}}clear(){this.parts=[],this.g.clear()}get count(){return this.parts.length}update(e){const t=e/1e3;this.parts=this.parts.filter(s=>(s.life+=t)<s.max),this.g.clear();for(const s of this.parts)s.vy+=140*t,s.x+=s.vx*t,s.y+=s.vy*t,this.g.rect(s.x-s.r/2,s.y-s.r/2,s.r,s.r*1.3).fill({color:s.c,alpha:1-s.life/s.max})}}const bt=[{id:"pip",name:"Pip",bio:"Curious, quick, a little clumsy. The original.",shape:"round",topper:"antenna",eyes:"wide",body:16751164,bodyLight:16765566,belly:16774620,ear:14712620,cheek:16739930,ink:2759959,size:1},{id:"mo",name:"Mo",bio:"Tall, calm, measures twice.",shape:"tall",topper:"tuft",eyes:"sleepy",body:6269183,bodyLight:11129599,belly:15398143,ear:4161488,cheek:16748448,ink:1385274,size:1.1},{id:"juno",name:"Juno",bio:"Bright, chatty, finds the bug by talking to it.",shape:"bean",topper:"ears",eyes:"wide",body:8380554,bodyLight:13172672,belly:15990768,ear:5223526,cheek:16756896,ink:1456671,size:.95},{id:"rook",name:"Rook",bio:"Boxy, deliberate, never guesses.",shape:"boxy",topper:"crest",eyes:"visor",body:10134712,bodyLight:14015462,belly:15659510,ear:7239820,cheek:8188927,ink:1778224,size:1.05},{id:"fen",name:"Fen",bio:"Quiet and sharp. Reads everything first.",shape:"teardrop",topper:"leaf",eyes:"dot",body:11967743,bodyLight:14734079,belly:16183551,ear:9401062,cheek:16754392,ink:2759498,size:.9},{id:"sol",name:"Sol",bio:"Warm, loud, celebrates everything.",shape:"round",topper:"halo",eyes:"wide",body:16765503,bodyLight:16773288,belly:16776166,ear:14723072,cheek:16747610,ink:3811845,size:1.08},{id:"ivy",name:"Ivy",bio:"Patient gardener of code. Hates loose ends.",shape:"bean",topper:"leaf",eyes:"sleepy",body:4177818,bodyLight:10481880,belly:15400952,ear:2788464,cheek:16756896,ink:997934,size:1},{id:"bolt",name:"Bolt",bio:"Fast. Sometimes too fast.",shape:"teardrop",topper:"crest",eyes:"dot",body:16734878,bodyLight:16756944,belly:16773366,ear:13645178,cheek:16765566,ink:3804962,size:.92},{id:"ash",name:"Ash",bio:"Dry wit, steady hands.",shape:"tall",topper:"ears",eyes:"sleepy",body:8024976,bodyLight:12104396,belly:15657973,ear:5656684,cheek:16758087,ink:1709872,size:1.06},{id:"nimbus",name:"Nimbus",bio:"Soft, cloud-headed, surprisingly precise.",shape:"round",topper:"halo",eyes:"wide",body:15660287,bodyLight:16777215,belly:16777215,ear:13228272,cheek:16756936,ink:2767442,size:1.02},{id:"ember",name:"Ember",bio:"Runs hot. Loves a red lighthouse.",shape:"boxy",topper:"antenna",eyes:"visor",body:16739133,bodyLight:16756874,belly:16773606,ear:12862506,cheek:16769899,ink:3805704,size:1},{id:"tove",name:"Tove",bio:"Small, brave, follows the map.",shape:"bean",topper:"tuft",eyes:"dot",body:13214827,bodyLight:15653293,belly:16775142,ear:10254916,cheek:16747610,ink:3811856,size:.85}],Mg=r=>bt.find(e=>e.id===r),lu=r=>(.2126*(r>>16&255)+.7152*(r>>8&255)+.0722*(r&255))/255,Eg=(r,e)=>Math.abs(lu(r.body)-lu(e))>.22;function kg(r,e,t){const s=a=>t===void 0||Eg(a,t);let i=Mg(e)??bt[r%bt.length];s(i)||(i=bt.find((a,l)=>l>=r%bt.length&&s(a))??bt.find(s)??i);const n=bt.filter(a=>a.id!==i.id&&s(a)),o=n.length?(r>>>3)%n.length:0;return{lead:i,helpers:[...n.slice(o),...n.slice(0,o)]}}const db=Object.freeze(Object.defineProperty({__proto__:null,CAST:bt,castById:Mg,pickCompany:kg,readableOn:Eg},Symbol.toStringTag,{value:"Module"}));class Bo{constructor(e,t,s=bt[0]){this.theme=e,this.reducedMotion=t,this.spec=s,this.container.addChild(this.shadow,this.body),this.container.scale.set(1.75*s.size)}container=new _e;shadow=new Pe;body=new Pe;t=0;pose={x:0,y:0,lift:0,sx:1,sy:1,lean:0,face:1,moving:!1,look:"fwd",mood:"curious",hiding:0};shown={x:0,y:0,lift:0,sx:1,sy:1,lean:0,face:1,faceK:1};snapNext=!0;snap(){this.snapNext=!0}get drawn(){return{x:this.shown.x,y:this.shown.y}}setTheme(e){this.theme=e}update(e){this.t+=e/1e3;const t=this.pose,s=this.spec,i=this.t,n=this.shown,o=Math.min(.05,e/1e3);this.snapNext&&(Object.assign(n,{x:t.x,y:t.y,lift:t.lift,sx:t.sx,sy:t.sy,lean:t.lean,face:t.face,faceK:1}),this.snapNext=!1);const a=1-Math.pow(5e-4,o),l=1-Math.pow(.002,o);n.x+=(t.x-n.x)*l,n.y+=(t.y-n.y)*l,n.lift+=(t.lift-n.lift)*a,n.sx+=(t.sx-n.sx)*a,n.sy+=(t.sy-n.sy)*a,n.lean+=(t.lean-n.lean)*a,n.face!==t.face?(n.faceK-=o*9,n.faceK<=0&&(n.face=t.face,n.faceK=.01)):n.faceK=Math.min(1,n.faceK+o*9);const h={...t,x:n.x,y:n.y,lift:n.lift,sx:n.sx*Math.max(.15,n.faceK),sy:n.sy,lean:n.lean,face:n.face};this.container.position.set(h.x,h.y),this.container.zIndex=1e6;const c=1-Math.min(.6,h.lift/90);this.shadow.clear().ellipse(0,0,11*c,5*c).fill({color:0,alpha:.28}),this.shadow.ellipse(0,0,14*c,7*c).fill({color:0,alpha:.1});const u=this.body;u.clear(),u.position.set(0,-h.lift),u.rotation=h.lean,u.scale.set(h.sx,h.sy);const d=h.moving||this.reducedMotion?0:Math.sin(i*2.2)*.012;u.scale.set(h.sx*(1-d),h.sy*(1+d));const f=h.moving?Math.sin(i*11)*3:0;switch(u.ellipse(-5+f,-1.5,4.2,2.6).fill(s.ear),u.ellipse(5-f,-1.5,4.2,2.6).fill(s.ear),s.shape){case"tall":u.ellipse(0,-16,9.5,16.5).fill(s.body),u.ellipse(-1.5,-21,7.5,9).fill({color:s.bodyLight,alpha:.55});break;case"boxy":u.roundRect(-11,-26,22,26,6).fill(s.body),u.roundRect(-9,-24,12,10,4).fill({color:s.bodyLight,alpha:.5});break;case"teardrop":u.moveTo(0,-30).quadraticCurveTo(13,-16,11,-6).quadraticCurveTo(0,2,-11,-6).quadraticCurveTo(-13,-16,0,-30).fill(s.body),u.ellipse(-2,-16,6,7).fill({color:s.bodyLight,alpha:.5});break;case"bean":u.ellipse(0,-12,12.5,11.5).fill(s.body),u.ellipse(-2,-18,8,6).fill({color:s.bodyLight,alpha:.55});break;default:u.ellipse(0,-13.5,11.5,13.5).fill(s.body),u.ellipse(-1.5,-17,9.5,9).fill({color:s.bodyLight,alpha:.55})}const p=s.shape==="tall"?9.5:s.shape==="boxy"?11:s.shape==="bean"?12.5:11.5,m=s.shape==="tall"?-16:s.shape==="boxy"?-13:s.shape==="bean"?-12:-13.5;u.moveTo(-p*.9,m-p*.2).quadraticCurveTo(-p*.75,m-p*.95,p*.1,m-p*1.02).stroke({width:2.2,color:16777215,alpha:.5,cap:"round"}),u.moveTo(p*.95,m+p*.1).quadraticCurveTo(p*.8,m+p*.8,p*.1,m+p*.98).stroke({width:2.4,color:this.theme.sky[0],alpha:.28,cap:"round"}),u.ellipse(h.face*1.2,-7.5,6.5,5.5).fill({color:s.belly,alpha:.92}),u.ellipse(-8+h.face*1.5,-11,2.4,1.5).fill({color:s.cheek,alpha:.45}),u.ellipse(8+h.face*1.5,-11,2.4,1.5).fill({color:s.cheek,alpha:.45});const g=h.moving?Math.sin(i*14)*.25:0,_=s.shape==="tall"?-33:s.shape==="teardrop"?-30:-27;switch(s.topper){case"ears":u.ellipse(-9,_+4+g*6,3.2,5).fill(s.ear),u.ellipse(9,_+4-g*6,3.2,5).fill(s.ear);break;case"tuft":u.moveTo(-3,_+1).quadraticCurveTo(-6,_-9,1,_-12).moveTo(0,_).quadraticCurveTo(4,_-10,8,_-8).stroke({width:2.2,color:s.ear,cap:"round"});break;case"leaf":u.moveTo(0,_).quadraticCurveTo(2+g*10,_-8,8,_-12).quadraticCurveTo(4,_-4,0,_).fill(s.ear),u.moveTo(0,_).lineTo(5,_-7).stroke({width:1,color:s.belly,alpha:.7});break;case"crest":for(const T of[-6,-2,2,6])u.moveTo(T,_+1).lineTo(T*1.4,_-7-Math.abs(T)*.3).stroke({width:2.4,color:s.ear,cap:"round"});break;case"halo":u.ellipse(0,_-7,9,2.6).stroke({width:1.8,color:this.theme.mood[h.mood],alpha:.9});break;case"antenna":u.ellipse(-9,_+4+g*6,3.2,5).fill(s.ear),u.ellipse(9,_+4-g*6,3.2,5).fill(s.ear);break}const x=h.face*1.8,y=-16,b=!this.reducedMotion&&i%3.3<.13&&h.mood!=="happy";for(const T of[-1,1]){const k=x+T*4.6;if(h.mood==="happy"){u.beginPath(),u.arc(k,y+1.5,2.8,Math.PI*1.1,Math.PI*1.9).stroke({width:1.6,color:s.ink,cap:"round"});continue}if(b){u.moveTo(k-2.6,y).lineTo(k+2.6,y).stroke({width:1.6,color:s.ink,cap:"round"});continue}if(s.eyes==="visor"){T<0&&(u.roundRect(x-8.5,y-3,17,6,3).fill(16777215),u.roundRect(x-7+(h.look==="up"?0:1),y-1.5,5,3,1.5).fill(s.ink),u.roundRect(x+2+(h.look==="up"?0:1),y-1.5,5,3,1.5).fill(s.ink));continue}const P=s.eyes==="dot"?2.6:s.eyes==="sleepy"?2.4:h.mood==="focused"?3:4.3;u.ellipse(k,y,s.eyes==="dot"?2.6:3.4,P).fill(16777215),s.eyes==="sleepy"&&u.moveTo(k-3.4,y-2.2).lineTo(k+3.4,y-2.2).stroke({width:2,color:s.body});const A=!h.moving&&!this.reducedMotion&&i%4.1>3.3?Math.sin((i%4.1-3.3)/.8*Math.PI):0;let C=h.face*1.1+A*1.6,E=(h.look==="up"?-1.6:h.look==="down"?1.4:.3)-A*.8;h.mood==="lost"&&(C=Math.sin(i*3)*1.4,E=-1.2),u.ellipse(k+C,y+E,1.9,h.mood==="focused"?1.8:2.2).fill(s.ink),u.ellipse(k+C+.7,y+E-.8,.6,.6).fill(16777215),h.mood==="lost"&&u.moveTo(k-3,y-5.6-(T>0?0:1.3)).lineTo(k+3,y-5.6-(T>0?1.3:0)).stroke({width:1.6,color:s.ink,cap:"round"}),h.mood==="focused"&&u.moveTo(k-3.2,y-3.7-(T>0?1:0)).lineTo(k+3.2,y-3.7-(T>0?0:1)).stroke({width:1.6,color:s.ink,cap:"round"}),h.mood==="uneasy"&&u.moveTo(k-3,y-5).lineTo(k+3,y-6+(T>0?1.5:-1.5)).stroke({width:1.4,color:s.ink,cap:"round"})}u.beginPath(),h.mood==="happy"?u.arc(x,-10.5,3.2,0,Math.PI).fill(8007202):h.mood==="lost"||h.mood==="uneasy"?u.arc(x,-8.4,2.2,Math.PI*1.15,Math.PI*1.85).stroke({width:1.6,color:s.ink,cap:"round"}):u.arc(x,-11.2,1.9,Math.PI*.15,Math.PI*.85).stroke({width:1.6,color:s.ink,cap:"round"});const w=(this.reducedMotion?0:Math.sin(i*5)*2)-h.lean*10,v=this.theme.mood[h.mood];if(s.topper==="antenna"?(u.moveTo(0,_+.5).quadraticCurveTo(w*.5,_-5,w+1.5,_-9).stroke({width:1.4,color:s.ear}),u.circle(w+1.5,_-10,9).fill({color:v,alpha:.28}),u.circle(w+1.5,_-10,5.5).fill({color:v,alpha:.35}),u.circle(w+1.5,_-10,2.8).fill(v)):s.topper!=="halo"&&(u.circle(0,_-2,7).fill({color:v,alpha:.22}),u.circle(0,_-2,2.2).fill({color:v,alpha:.9})),h.hiding>0){const T=tt(i*.5%1)*h.hiding;u.rotation=h.lean+T*.06}}}const fb=Object.freeze(Object.defineProperty({__proto__:null,Pip:Bo},Symbol.toStringTag,{value:"Module"})),je={wave:"triangle",pitch:1,decay:1,tone:3200,surface:"grass"},Bn={wave:"square",pitch:1.18,decay:.8,tone:2600,surface:"metal"},hu={wave:"sawtooth",pitch:.95,decay:1.1,tone:2200,surface:"stone"},Pg={island:{voice:je,ambience:{washes:[{hz:520,q:.6,gain:.09,lfoHz:.11,depth:.6},{hz:240,q:.9,gain:.05,lfoHz:.07,depth:.8}],extras:["gull","cricket"],every:9}},orbit:{voice:Bn,ambience:{washes:[{hz:900,q:2,gain:.015,lfoHz:.05,depth:.9}],pad:{chord:[55,110,164.8],gain:.05,wave:"sine"},extras:["hum","chime"],every:11}},metropolis:{voice:hu,ambience:{washes:[{hz:380,q:.5,gain:.07,lfoHz:.2,depth:.5}],pad:{chord:[65.4,98],gain:.03,wave:"triangle"},extras:["horn","hum"],every:10}},harbour:{voice:{...je,surface:"wood",decay:1.3},ambience:{washes:[{hz:420,q:.6,gain:.1,lfoHz:.09,depth:.7}],extras:["gull","bell","horn"],every:8}},observatory:{voice:{...Bn,wave:"sine",pitch:1.3,decay:1.6,tone:4e3,surface:"stone"},ambience:{washes:[{hz:300,q:.8,gain:.04,lfoHz:.04,depth:.9}],pad:{chord:[49,98,146.8],gain:.04,wave:"sine"},extras:["wind","chime"],every:12}},greenhouse:{voice:{...je,pitch:1.1,decay:1.2},ambience:{washes:[{hz:600,q:.6,gain:.05,lfoHz:.1,depth:.5}],extras:["cricket","drip","bell"],every:7}},workshop:{voice:{...je,wave:"triangle",pitch:.9,decay:.8,tone:2800,surface:"wood"},ambience:{washes:[{hz:500,q:.6,gain:.05,lfoHz:.12,depth:.5}],extras:["cricket","bell"],every:9}},arcade:{voice:{wave:"square",pitch:1.35,decay:.6,tone:3600,surface:"neon"},ambience:{washes:[{hz:300,q:.5,gain:.05,lfoHz:.25,depth:.4}],pad:{chord:[65.4,82.4,98],gain:.03,wave:"square"},extras:["chime","horn"],every:6}},kingdom:{voice:{...je,wave:"triangle",pitch:.85,decay:1.5,tone:2400,surface:"stone"},ambience:{washes:[{hz:450,q:.6,gain:.07,lfoHz:.1,depth:.6}],extras:["bell","wind","owl"],every:10}},outpost:{voice:{...je,pitch:.92,decay:1.4,tone:2600,surface:"sand"},ambience:{washes:[{hz:700,q:.4,gain:.08,lfoHz:.06,depth:.9}],extras:["wind","hum"],every:9}},snowfield:{voice:{...je,wave:"sine",pitch:1.15,decay:1.7,tone:3400,surface:"snow"},ambience:{washes:[{hz:800,q:.4,gain:.05,lfoHz:.05,depth:.9}],extras:["wind","chime","owl"],every:11}},canopy:{voice:{...je,pitch:1.05,decay:1.2,tone:3e3,surface:"wood"},ambience:{washes:[{hz:650,q:.7,gain:.07,lfoHz:.09,depth:.5}],extras:["cricket","owl","drip"],every:6}},lagoon:{voice:{...je,wave:"sine",pitch:1.2,decay:1.3,tone:3600,surface:"sand"},ambience:{washes:[{hz:480,q:.6,gain:.1,lfoHz:.1,depth:.7}],extras:["gull","bubble"],every:8}},volcano:{voice:{wave:"sawtooth",pitch:.75,decay:1.6,tone:1600,surface:"stone"},ambience:{washes:[{hz:160,q:1,gain:.1,lfoHz:.08,depth:.8}],pad:{chord:[41.2,61.7],gain:.04,wave:"sawtooth"},extras:["rumble","wind"],every:8}},cloudtop:{voice:{...je,wave:"sine",pitch:1.25,decay:1.8,tone:4200,surface:"grass"},ambience:{washes:[{hz:900,q:.4,gain:.05,lfoHz:.04,depth:.9}],pad:{chord:[130.8,196,261.6],gain:.025,wave:"sine"},extras:["wind","chime"],every:12}},reef:{voice:{wave:"sine",pitch:.9,decay:1.9,tone:1400,surface:"water"},ambience:{washes:[{hz:220,q:1.2,gain:.09,lfoHz:.09,depth:.7}],extras:["bubble","drip"],every:5}},bazaar:{voice:{...je,pitch:1.05,decay:.9,tone:3e3,surface:"sand"},ambience:{washes:[{hz:500,q:.5,gain:.06,lfoHz:.3,depth:.4}],extras:["market","bell","chime"],every:6}},monastery:{voice:{...je,wave:"sine",pitch:.95,decay:2,tone:2600,surface:"stone"},ambience:{washes:[{hz:420,q:.5,gain:.05,lfoHz:.05,depth:.8}],extras:["bell","wind","owl"],every:12}},moonbase:{voice:{...Bn,pitch:1.05,decay:1.2,tone:2200},ambience:{washes:[{hz:240,q:1.5,gain:.03,lfoHz:.03,depth:.9}],pad:{chord:[55,82.4],gain:.04,wave:"sine"},extras:["hum","chime"],every:13}},lanterns:{voice:{...hu,wave:"triangle",pitch:1.1,decay:1.2,tone:3e3,surface:"stone"},ambience:{washes:[{hz:400,q:.5,gain:.05,lfoHz:.2,depth:.5}],extras:["market","chime","bell"],every:6}}},pb=new Set(["curtain_up","curtain_down","test_outcome","celebrate","blocked_on_you","unverified_claim","spawn_gremlin","banish"]),mb=[523.25,659.25,783.99,1046.5],Ie=(r,e)=>r+Math.random()*(e-r);class $r{constructor(e){this.a=e}footstep(e,t){const s=this.a;switch(e){case"stone":s.noise(.04,{filter:"bandpass",freq:Ie(1400,1900),q:2,gain:.05,pan:t}),s.tone(Ie(160,200),.03,{type:"triangle",gain:.03,pan:t});return;case"metal":s.tone(Ie(700,900),.05,{type:"square",gain:.03,lowpass:2e3,pan:t}),s.noise(.03,{filter:"highpass",freq:3e3,gain:.03,pan:t});return;case"sand":s.noise(.09,{filter:"lowpass",freq:Ie(700,1e3),q:.5,gain:.05,pan:t});return;case"snow":s.noise(.08,{filter:"bandpass",freq:Ie(2500,3500),q:.8,gain:.04,pan:t});return;case"wood":s.tone(Ie(220,300),.05,{type:"triangle",gain:.05,slideTo:120,pan:t});return;case"water":s.noise(.08,{filter:"bandpass",freq:Ie(400,700),q:1,gain:.05,sweepTo:1200,pan:t});return;case"neon":s.tone(Ie(900,1200),.035,{type:"square",gain:.025,lowpass:3e3,pan:t});return;default:s.noise(.05,{filter:"bandpass",freq:Ie(900,1300),q:1.2,gain:.05,pan:t});return}}static plays(e,t){return t<=1.01||pb.has(e)}play(e,t){const s=this.a,i=t.pan??0,n=t.intensity??.5,o=Pg[t.theme.id].voice,a={tone:(l,h,c={})=>s.tone(l*o.pitch,h*o.decay,{...c,type:c.type??o.wave,lowpass:Math.min(c.lowpass??o.tone,o.tone),...c.slideTo?{slideTo:c.slideTo*o.pitch}:{}}),noise:s.noise.bind(s)};if(e==="footstep")return this.footstep(o.surface,i);switch(e){case"curtain_up":a.tone(392,1.2,{attack:.3,gain:.14}),a.tone(587.3,1.3,{attack:.5,gain:.1}),a.tone(784,1.4,{attack:.7,gain:.08});return;case"curtain_down":a.tone(523.25,1.6,{attack:.2,gain:.12}),a.tone(392,1.8,{attack:.4,gain:.1});return;case"walk_to":return;case"read":a.noise(.14,{filter:"highpass",freq:2500,sweepTo:6e3,gain:.07,pan:i}),a.tone(2200,.05,{gain:.04,pan:i});return;case"hammer":a.tone(Ie(180,240)*(1+n*.4),.06,{type:"triangle",gain:.12+n*.1,slideTo:90,pan:i}),a.noise(.03,{filter:"bandpass",freq:3e3,q:2,gain:.05,pan:i});return;case"build":return;case"raise":a.tone(220,.7,{type:"sawtooth",slideTo:660,gain:.08,lowpass:1800,pan:i}),a.tone(440,.3,{gain:.06,pan:i,attack:.3});return;case"forge":a.tone(620,.25,{type:"square",gain:.06,slideTo:580,lowpass:2400,pan:i}),a.tone(1240,.18,{type:"triangle",gain:.05,detune:30,pan:i}),a.noise(.08,{filter:"highpass",freq:4e3,gain:.04,pan:i});return;case"spark":a.tone(Ie(2500,4200),.04,{gain:.03,pan:i});return;case"search":a.noise(.35,{filter:"bandpass",freq:700,sweepTo:2600,q:1.5,gain:.08,pan:i}),a.tone(1568,.12,{gain:.05,pan:i,attack:.02});return;case"run_tests":a.tone(330,.9,{attack:.15,gain:.06,type:"triangle",lowpass:1200,pan:i}),a.tone(495,.9,{attack:.25,gain:.04,type:"triangle",lowpass:1200,pan:i});return;case"test_outcome":t.outcome==="pass"?mb.forEach((l,h)=>setTimeout(()=>a.tone(l,.5,{gain:.12,attack:.01,pan:i}),h*70)):(a.tone(311,.35,{type:"sawtooth",gain:.09,lowpass:900,slideTo:262,pan:i}),setTimeout(()=>a.tone(233,.5,{type:"sawtooth",gain:.09,lowpass:700,slideTo:196,pan:i}),170));return;case"spawn_gremlin":for(let l=0;l<4;l++)setTimeout(()=>a.tone(Ie(900,1300)+l*80,.07,{type:"square",gain:.05,lowpass:2600,slideTo:Ie(700,1100),pan:i}),l*60);return;case"chase":for(let l=0;l<3;l++)setTimeout(()=>a.tone(600+l*120,.08,{type:"triangle",gain:.06,pan:i}),l*90);return;case"banish":a.noise(.06,{filter:"lowpass",freq:1500,gain:.14,pan:i}),setTimeout(()=>a.tone(2093,.25,{gain:.07,pan:i}),40),setTimeout(()=>a.tone(2637,.3,{gain:.05,pan:i}),90);return;case"celebrate":[523.25,659.25,783.99,1046.5,1318.5].forEach((l,h)=>setTimeout(()=>a.tone(l,.45,{gain:.11,attack:.01,pan:i}),h*60));for(let l=0;l<10;l++)setTimeout(()=>a.tone(Ie(1800,4e3),.05,{gain:.03,pan:Ie(-.8,.8)}),200+l*55);return;case"summon_helper":t.theme.id==="orbit"?a.noise(.7,{filter:"bandpass",freq:300,sweepTo:1800,q:1.2,gain:.1,pan:i}):t.theme.id==="metropolis"?(a.tone(880,.12,{type:"square",gain:.06,lowpass:2500,pan:i}),setTimeout(()=>a.tone(880,.12,{type:"square",gain:.06,lowpass:2500,pan:i}),180)):(a.tone(146.8,.8,{type:"triangle",attack:.08,gain:.12,lowpass:800,pan:i}),a.tone(147.5,.8,{type:"triangle",attack:.08,gain:.08,lowpass:800,pan:i}));return;case"dismiss_helper":a.noise(.5,{filter:"bandpass",freq:1800,sweepTo:300,q:1.2,gain:.07,pan:i});return;case"blocked_on_you":a.tone(880,.35,{gain:.16,attack:.01}),setTimeout(()=>a.tone(659.25,.6,{gain:.16,attack:.01}),220);return;case"your_turn":a.tone(1046.5,.5,{gain:.07,attack:.02});return;case"stumble":a.noise(.12,{filter:"lowpass",freq:400,gain:.14,pan:i}),a.tone(120,.25,{type:"triangle",gain:.1,slideTo:70,pan:i});return;case"unverified_claim":a.tone(196,.14,{type:"triangle",gain:.07,lowpass:900,pan:i}),setTimeout(()=>a.tone(185,.14,{type:"triangle",gain:.07,lowpass:900,pan:i}),240),setTimeout(()=>a.tone(174.6,.24,{type:"triangle",gain:.06,lowpass:900,pan:i}),480);return;case"idle":return}}}class gb{constructor(e){this.a=e}stops=[];current=null;padStop=null;padMood=null;extraTimer=null;start(e){if(!this.a.ready||this.current===e.id)return;this.stop(),this.current=e.id;const t=Pg[e.id].ambience;for(const i of t.washes)this.stops.push(this.a.wash(i.hz,i.q,i.gain,i.lfoHz,i.depth));t.pad&&this.stops.push(this.a.pad(t.pad.chord,t.pad.gain,t.pad.wave));const s=()=>{if(this.current!==e.id)return;const i=t.extras[Math.floor(Math.random()*t.extras.length)];i&&this.a.extra(i),this.extraTimer=setTimeout(s,t.every*1e3*(.5+Math.random()))};this.extraTimer=setTimeout(s,2e3+Math.random()*3e3)}setMood(e){if(!this.a.ready||e===this.padMood)return;this.padMood=e,this.padStop?.();const t=e==="happy"?[261.6,329.6,392]:e==="lost"?[261.6,311.1,370]:e==="uneasy"?[261.6,311.1,392]:e==="focused"?[261.6,392]:[261.6,329.6];this.padStop=this.a.pad(t.map(s=>s/2),.022,"sine")}stop(){this.extraTimer&&clearTimeout(this.extraTimer),this.extraTimer=null;for(const e of this.stops)e();this.stops=[],this.padStop?.(),this.padStop=null,this.padMood=null,this.current=null}}class qs{constructor(e,t,s,i,n,o){this.app=e,this.world=t,this.theme=s,this.audio=i,this.reducedMotion=n,this.worldLayer=new Sg(t,s),this.particles=new ub(n),this.company=kg(t.seed,o,s.ground.fill),this.pip=new Bo(s,n,this.company.lead),this.camera=new nb(this.stage,n),this.sfx=new $r(i),this.amb=new gb(i),this.stage.sortableChildren=!0,this.stage.addChild(this.worldLayer.container),this.worldLayer.container.sortableChildren=!0,this.worldLayer.container.addChild(this.pip.container,this.particles.g),this.particles.g.zIndex=1e7,e.stage.addChild(this.stage),this.actorAt.set("pip","forge"),this.fitCamera(),this.camera.snap()}stage=new _e;worldLayer;camera;pip;helpers=new Map;gremlins=new Map;particles;sfx;amb;beats=[];t=0;prevT=-1;_playing=!1;rate=1;duration=0;mood="curious";actorAt=new Map;walkFrom=new Map;growth=new Map;lastPass=0;signal="ok";footT=0;hammerT=0;claimGremlinId=null;evidenceCount=null;company;helperIndex=0;load(e){this.beats=e,this.duration=e.length?Math.max(...e.map(t=>t.atMs+t.durationMs)):0,this.seek(0)}get beatCount(){return this.beats.length}append(e){this.beats.push(...e),this.duration=Math.max(this.duration,...e.map(t=>t.atMs+t.durationMs))}get playing(){return this._playing}play(){this._playing=!0,this.amb.start(this.theme)}audioReady(){this.amb.stop(),this._playing&&this.amb.start(this.theme)}pause(){this._playing=!1}setRate(e){this.rate=e}setSignal(e){this.signal=e}seek(e){this.t=Math.max(0,Math.min(this.duration,e)),this.rebuild(this.t),this.prevT=this.t,this.particles.clear()}get leadName(){return this.company.lead.name}get state(){const e=this.currentBeat();return{t:this.t,duration:this.duration,playing:this._playing,rate:this.rate,current:e,mood:this.mood,bubble:this.bubble(e),labels:this.labels(e),evidence:this.evidenceCount!==null?{passed:this.evidenceCount}:null,signal:this.signal}}update(e){this._playing&&(this.t=Math.min(this.duration,this.t+e*this.rate),this.t>=this.duration&&this.duration>0&&(this._playing=!1),this.triggerBetween(this.prevT,this.t),this.prevT=this.t);const t=this.currentBeat();this.pose(t,e),this.worldState(t),this.worldLayer.update(e),this.pip.update(e);for(const s of this.helpers.values())s.update(e);for(const s of this.gremlins.values())s.update(e);this.particles.update(e),this.cameraStep(t,e),this.amb.setMood(this.mood)}currentBeat(){let e=null;for(const t of this.beats)if(t.atMs<=this.t)(!e||t.atMs>=e.atMs)&&(t.kind==="idle"&&e&&e.kind!=="idle"&&e.atMs+e.durationMs>this.t||(e=t));else break;return e}completed(){return this.beats.filter(e=>e.atMs+e.durationMs<=this.t)}rebuild(e){this.actorAt.clear(),this.actorAt.set("pip","forge"),this.growth.clear(),this.lastPass=0,this.evidenceCount=null,this.mood="curious",this.claimGremlinId=null,this.helperIndex=0;for(const s of this.gremlins.values())s.container.destroy();this.gremlins.clear();for(const s of this.helpers.values())s.container.destroy();this.helpers.clear();for(const s of this.world.places)this.worldLayer.setLamp(s.id,"idle"),this.worldLayer.setGrowth(s.id,0),this.worldLayer.setGlow(s.id,0),this.worldLayer.setScaffold(s.id,0);for(const s of this.beats){if(s.atMs>e)break;this.onStart(s,!0),s.atMs+s.durationMs<=e&&this.onEnd(s,!0)}this.pip.pose.mood=this.mood;const t=this.worldLayer.standingSpot(this.actorAt.get("pip")??"forge");this.pip.pose.x=t.x,this.pip.pose.y=t.y,this.pip.snap(),this.camTarget=null,this.fitCamera(),this.cameraStep(this.currentBeat(),0),this.camera.snap()}triggerBetween(e,t){for(const s of this.beats){s.atMs>e&&s.atMs<=t&&this.onStart(s,!1);const i=s.atMs+s.durationMs;i>e&&i<=t&&this.onEnd(s,!1)}}onStart(e,t){this.mood=e.mood;const s=this.theme,i=o=>{const a=this.worldLayer.positionOf(o);return a?Math.max(-.8,Math.min(.8,a.ground.x/600)):0},n=(o,a={})=>{!t&&$r.plays(o,this.rate)&&this.sfx.play(o,{theme:s,...a})};switch(e.kind){case"curtain_up":n("curtain_up"),t||this.camera.pushIn(.12);break;case"walk_to":{const o=this.worldLayer.standingSpot(this.actorAt.get(e.actor)??"forge");this.walkFrom.set(e.actor,o);break}case"read":n("read",{pan:i(e.target)});break;case"raise":{if(e.newPlace&&!this.worldLayer.has(e.target)){const o=this.world.districts.find(l=>l.id===e.newPlace.district)??this.world.districts[0],a={id:e.target,kind:e.newPlace.kind,path:e.newPlace.path,label:e.newPlace.label,district:e.newPlace.district,gx:(o?.cx??2)+1,gy:(o?.cy??2)+1,footprint:1,height:1,score:0,touched:!0};this.world.places.push(a),this.worldLayer.addPlace(a)}n("raise",{pan:i(e.target)});break}case"build":n("build");break;case"forge":n("forge");break;case"search":n("search",{pan:i("forge")});break;case"run_tests":this.worldLayer.setLamp(e.target,"scan"),n("run_tests",{pan:i(e.target)});break;case"test_outcome":{const o=e.outcome==="pass"?"pass":e.outcome==="fail"?"fail":"idle";if(this.worldLayer.setLamp(e.target,o),e.outcome==="pass"&&(this.lastPass=e.atMs,this.evidenceCount=e.passed),n("test_outcome",{outcome:e.outcome,pan:i(e.target)}),!t&&e.outcome==="fail"&&this.camera.shake(200),!t&&e.outcome==="pass"){const a=this.worldLayer.positionOf(e.target);a&&this.particles.burst(a.top.x,a.top.y,16,[s.beacon.lamp.pass,14090217],70,40)}break}case"spawn_gremlin":{const o=new Ro(e.gremlinId,s,this.reducedMotion),a=this.worldLayer.positionOf(e.target),l=a?a.ground:K(0,0);o.x=l.x+18,o.y=l.y+8,o.scale=t?1:.01,this.worldLayer.container.addChild(o.container),this.gremlins.set(e.gremlinId,o),n("spawn_gremlin",{pan:i(e.target)}),t||(this.camera.pushIn(.06),this.particles.burst(o.x,o.y-10,18,[s.gremlin.body,11967743],60,30));break}case"chase":{const o=this.gremlins.get(e.gremlinId);o&&(o.panic=1),n("chase",{pan:i(e.target)});break}case"banish":{const o=this.gremlins.get(e.gremlinId);o&&(t||this.particles.burst(o.x,o.y-10,30,[16777215,s.gremlin.body],80,35),o.container.destroy(),this.gremlins.delete(e.gremlinId)),this.claimGremlinId===e.gremlinId&&(this.claimGremlinId=null,this.pip.pose.hiding=0),n("banish");break}case"celebrate":{if(n("celebrate"),!t){this.camera.pushIn(.1);const o=this.worldLayer.standingSpot(this.actorAt.get("pip")??"forge");this.particles.burst(o.x,o.y-30,56,[16758087,6287526,8177919,16743273,11967743,16777215],130,90)}break}case"summon_helper":{const o=this.company.helpers[this.helperIndex++%this.company.helpers.length],a=new Bo(s,this.reducedMotion,o);a.container.scale.set(.82*o.size);const l=this.worldLayer.standingSpot("dock");a.pose.x=l.x,a.pose.y=l.y,this.worldLayer.container.addChild(a.container),this.helpers.set(e.helperId,a),this.actorAt.set(e.helperId,"dock"),n("summon_helper",{pan:i("dock")});break}case"dismiss_helper":n("dismiss_helper",{pan:i("dock")});break;case"blocked_on_you":n("blocked_on_you");break;case"your_turn":n("your_turn");break;case"stumble":n("stumble"),t||this.camera.shake(160);break;case"unverified_claim":{const o=new Ro(e.gremlinId,s,this.reducedMotion);o.scale=.8,o.alpha=.95,this.worldLayer.container.addChild(o.container),this.gremlins.set(e.gremlinId,o),this.claimGremlinId=e.gremlinId,this.pip.pose.hiding=1,n("unverified_claim");break}case"curtain_down":n("curtain_down");break}}onEnd(e,t){switch(e.kind){case"walk_to":this.actorAt.set(e.actor,e.target),this.walkFrom.delete(e.actor);break;case"build":this.growth.set(e.target,Math.min(18,(this.growth.get(e.target)??0)+3+Math.round(e.intensity*6))),this.worldLayer.setGrowth(e.target,this.growth.get(e.target)),this.worldLayer.setScaffold(e.target,0);break;case"dismiss_helper":{const s=this.helpers.get(e.helperId);s&&(s.container.destroy(),this.helpers.delete(e.helperId),this.actorAt.delete(e.helperId));break}}}pose(e,t){const s=t/1e3;for(const[i,n]of[["pip",this.pip],...this.helpers.entries()]){const o=n.pose;o.moving=!1,o.lift=0,o.sx=1,o.sy=1,o.lean=0,o.look="fwd",o.mood=this.mood;const a=e&&e.actor===i?e:null,l=this.worldLayer.standingSpot(this.actorAt.get(i)??(i==="pip"?"forge":"dock"));if(o.x=l.x,o.y=l.y,!a){i!=="pip"&&(o.sy=.96);continue}const h=Ue(this.t,a.atMs,a.atMs+a.durationMs),c="target"in a?this.worldLayer.standingSpot(a.target):l;switch(a.kind){case"curtain_up":{o.lift=(1-Math.min(1,h/.5))**2*150,o.sy=h<.5?1.1:1-.25*tt(Ue(h,.5,.75)),o.sx=1/o.sy;break}case"walk_to":{const u=this.walkFrom.get(i)??l,d=Math.min(.22,140/a.durationMs),f=h<d?0:An((h-d)/(1-d));if(o.x=Jt(u.x,c.x,f),o.y=Jt(u.y,c.y,f),o.moving=h>=d&&h<.98,o.face=c.x>=u.x?1:-1,h<d){const p=tt(h/d);o.sy=1-.1*p,o.sx=1+.08*p,o.lean=-o.face*.12*p}else{const p=this.t/1e3*(this.mood==="lost"?16:11);o.lift=Math.abs(Math.sin(p))*3.5;const m=Math.cos(p*2);if(o.sy=1+.05*m,o.sx=1-.05*m,o.lean=o.face*.07,h>.86){const g=tt((h-.86)/.14);o.lean=o.face*.16*g,o.sy=1-.06*g,o.sx=1+.05*g}}i==="pip"&&this._playing&&(this.footT+=s,this.footT>.19&&$r.plays("footstep",this.rate)&&(this.footT=0,this.sfx.play("footstep",{theme:this.theme,pan:Math.max(-.8,Math.min(.8,o.x/600))})));break}case"read":{const u=tt(this.t/1e3%1.4/.25);o.lean=-.17+Math.sin(this.t/1e3*3)*.03-u*.05,o.sy=1-u*.03,o.face=this.facing(o,a.target);break}case"build":case"forge":{const u=a.kind==="build"?.28-a.intensity*.1:.34,d=this.t/1e3%u/u,f=d<.7?d/.7:1-(d-.7)/.3;if(o.lift=f*4,o.lean=d<.7?-.06*f:.12*(1-f),o.sy=d<.7?1+.04*f:1-.08*(1-f),o.sx=1/o.sy,"target"in a&&(o.face=this.facing(o,a.target)),i==="pip"&&this._playing&&!this.reducedMotion){this.hammerT+=s;const p=a.kind==="build"?.28-a.intensity*.1:.34;if(this.hammerT>p){this.hammerT=0,$r.plays("hammer",this.rate)&&this.sfx.play(a.kind==="build"?"hammer":"spark",{theme:this.theme,intensity:a.kind==="build"?a.intensity:.5});const m="target"in a?this.worldLayer.positionOf(a.target):this.worldLayer.positionOf("forge");m&&Math.random()<.7&&this.particles.burst(m.top.x+(Math.random()*24-12),m.top.y+10,2,[16766571,16774084],50,60)}}break}case"raise":o.look="up",o.sy=1+.05*tt(h);break;case"search":o.look="up",o.lean=Math.sin(this.t/1e3*1.5)*.12;break;case"run_tests":o.look="up",o.lean=Math.sin(this.t/1e3*2)*.04;break;case"test_outcome":if(a.outcome==="fail"){const u=tt(Ue(h,0,.5));o.lean=-.25*u,o.sy=1-.1*u,o.sx=1+.08*u}else o.lift=tt(h)*14;break;case"spawn_gremlin":{const u=tt(Ue(h,0,.5));o.lift=Math.sin(Math.PI*Ue(h,.05,.45))*12,o.lean=-.22*u,o.sx=1+.1*u,o.sy=1-.1*u,o.look="down",o.x=l.x-o.face*10*u;break}case"chase":{const u=this.gremlins.get(a.gremlinId),d=c,f=h*Math.PI*2*1.5,p=26,m=d.x+Math.cos(f)*p,g=d.y+Math.sin(f)*p*.5;u&&(u.x=m,u.y=g,u.panic=1);const _=f-1.1;o.x=d.x+Math.cos(_)*p,o.y=d.y+Math.sin(_)*p*.5,o.moving=!0,o.face=Math.cos(f)>Math.cos(_)?1:-1;const x=this.t/1e3*16;o.lift=Math.abs(Math.sin(x))*4,o.lean=o.face*.12;break}case"banish":{o.sy=1-.2*tt(Ue(h,0,.4)),o.sx=1/o.sy;break}case"celebrate":{const u=(this.t-a.atMs)%1300/1300;if(u<.22){const d=Math.sin(Math.PI*u/.22);o.sy=1-.24*d,o.sx=1+.2*d}else if(u<.8){const d=(u-.22)/.58;o.lift=Math.sin(Math.PI*d)*32,o.sy=d<.5?1+.14*(1-d*2):1,o.sx=1/o.sy}else{const d=Math.sin(Math.PI*(u-.8)/.2);o.sy=1-.2*d,o.sx=1+.16*d}break}case"blocked_on_you":o.face=1,o.look="fwd",o.sy=1+.03*Math.sin(this.t/1e3*6),o.sx=1/o.sy;break;case"your_turn":o.sy=.86,o.sx=1.08;break;case"stumble":{const u=tt(Ue(h,0,.7));o.lean=Math.sin(this.t/1e3*40)*.12*u,o.sy=1-.08*u,o.sx=1+.06*u;break}case"unverified_claim":{o.face=1,o.hiding=1;const u=this.claimGremlinId?this.gremlins.get(this.claimGremlinId):null;u&&(u.x=o.x-o.face*14,u.y=o.y-2,u.peek=1);break}case"curtain_down":o.lean=Math.sin(this.t/1e3*6)*.15,o.face=1;break}if(this.claimGremlinId&&a.kind!=="unverified_claim"){const u=this.gremlins.get(this.claimGremlinId);u&&(u.x=o.x-o.face*14,u.y=o.y-2)}n.container.zIndex=o.y/(Ao/2)+.6,i!=="pip"&&(o.mood="focused")}for(const i of this.gremlins.values())i.container.zIndex=i.y/(Ao/2)+.7}facing(e,t){const s=this.worldLayer.positionOf(t);return s&&s.ground.x<e.x?-1:1}worldState(e){for(const t of this.world.places)this.worldLayer.setGlow(t.id,0);if(e){if((e.kind==="read"||e.kind==="build"||e.kind==="chase"||e.kind==="raise")&&this.worldLayer.setGlow(e.target,e.kind==="read"?.5:1),e.kind==="build"){const t=Ue(this.t,e.atMs,e.atMs+e.durationMs);this.worldLayer.setScaffold(e.target,.85*Math.min(Ue(t,0,.12),1-Ue(t,.85,1))),this.worldLayer.setGrowth(e.target,(this.growth.get(e.target)??0)+Math.round((3+e.intensity*6)*An(t)))}if(e.kind==="raise"){const t=Ue(this.t,e.atMs,e.atMs+e.durationMs);this.worldLayer.positionOf(e.target)&&this.worldLayer.setGrowth(e.target,Math.round(-30*(1-nu(t))))}if(e.kind==="spawn_gremlin"){const t=this.gremlins.get(e.gremlinId);t&&(t.scale=Math.max(.01,nu(Ue(this.t,e.atMs,e.atMs+400))))}for(const t of this.world.places)t.kind==="beacon"&&this.worldLayer.lampOf(t.id)==="pass"&&this.t-this.lastPass>12e3&&this.worldLayer.setLamp(t.id,"idle")}}fitCamera(){this.camera.setZoomFactor(this.fitZoom()),this.baseZoom=this.fitZoom()}baseZoom=1;camTarget=null;cameraStep(e,t){const s={w:this.app.renderer.screen.width,h:this.app.renderer.screen.height},i=s.w<640,n=!e||e.kind==="curtain_up"||e.kind==="curtain_down"||e.kind==="celebrate",o=this.world.places.map(v=>K(v.gx+v.footprint/2,v.gy+v.footprint/2)),a=Math.min(...o.map(v=>v.x))-70,l=Math.max(...o.map(v=>v.x))+70,h=Math.min(...o.map(v=>v.y))-110,c=Math.max(...o.map(v=>v.y))+50,u={x:(a+l)/2,y:(h+c)/2},d=Math.max(.05,this.camera.scale),f=s.w/d/2,p=s.h/d/2,m=(v,T,k)=>T+f>k-f?(T+k)/2:Math.max(T+f,Math.min(k-f,v)),g=(v,T,k)=>T+p>k-p?(T+k)/2:Math.max(T+p,Math.min(k-p,v)),_=this.pip.drawn,x=this.pip.pose.moving?this.pip.pose.face*f*.18:0,y={x:_.x+x,y:_.y-24};if(n||i)this.camTarget=n?{x:u.x,y:u.y}:y;else{this.camTarget||(this.camTarget=y);const v=f*.28,T=p*.26,k=y.x-this.camTarget.x,P=y.y-this.camTarget.y;Math.abs(k)>v&&(this.camTarget.x+=k-Math.sign(k)*v),Math.abs(P)>T&&(this.camTarget.y+=P-Math.sign(P)*T)}const b=m(this.camTarget.x,a,l),w=g(this.camTarget.y,h,c);this.camera.follow(b,w,1),this.camera.setDrift(this.mood==="lost"),this.camera.setZoomFactor(this.zoomFor(e,s.h)),this.camera.update(t,s.w,s.h)}zoomFor(e,t){const s=this.fitZoom();if(!e)return s;const i=Math.max(s,Math.min(1.7,Math.max(.95,t/430)));switch(e.kind){case"curtain_up":return s*Jt(1.08,1,An(Ue(this.t,e.atMs,e.atMs+e.durationMs)));case"curtain_down":return s*1.05;case"celebrate":return s*1.15;default:return i}}fitZoom(){const e=this.world.places.flatMap(l=>[K(l.gx,l.gy),K(l.gx+l.footprint,l.gy+l.footprint)]),t=e.map(l=>l.x),s=e.map(l=>l.y),i=Math.max(60,Math.max(...t)-Math.min(...t)+140),n=Math.max(60,Math.max(...s)-Math.min(...s)+150),o=this.app.renderer.screen.width,a=this.app.renderer.screen.height;return Math.min(o/(i*1.05),a/(n*1.05),2.2)}bubble(e){if(!e)return null;const t=this.pip.pose,s=this.camera.toScreen(t.x+16,t.y-t.lift-52);return e.kind==="read"||e.kind==="search"?{text:"…",color:4219274,screen:s}:e.kind==="spawn_gremlin"||this.mood==="lost"&&e.kind!=="celebrate"?{text:"?",color:14833484,screen:s}:e.kind==="celebrate"?{text:"!",color:2071139,screen:s}:e.kind==="blocked_on_you"?{text:"!",color:16758087,screen:s}:e.kind==="unverified_claim"?{text:"…",color:8215807,screen:s}:null}labels(e){const t=[],s=e&&"target"in e?e.target:null;for(const i of this.world.places){if(i.kind==="forge"||i.kind==="dock")continue;const n=i.id===s,o=i.kind==="beacon"?this.worldLayer.lampOf(i.id):"idle";if(!n&&o==="idle")continue;const a=this.worldLayer.positionOf(i.id);a&&t.push({text:i.label,screen:this.camera.toScreen(a.top.x,a.top.y-2),active:n})}return t}destroy(){this.amb.stop(),this.stage.destroy({children:!0})}}const Ee={id:"island",name:"Island",tagline:"A warm little island at golden hour.",fits:["cli-tool","library","unknown"],flagship:!0,sky:[2191498,1195610],terrain:"island",ground:{fill:6073960,fillLight:10740879,edge:9070154,edgeDark:6966328,sand:15915942},water:{ripple:16777215,rippleAlpha:.24},pathColor:16245940,labelColor:1592880,palettes:[{top:16310456,left:15382917,right:13605734,roof:15495007,roofD:12735050,win:9067068},{top:14478328,left:11455462,right:9153999,roof:5934020,roofD:4616351,win:4219274},{top:13625820,left:9226664,right:6464387,roof:3122570,roofD:2393199,win:3106389},{top:16507860,left:15908774,right:14261124,roof:14248828,roofD:11554657,win:8014418},{top:16774086,left:16112010,right:14268778,roof:14916398,roofD:12220959,win:8018476}],beacon:{top:16514040,left:15855592,right:14276043,roof:14833484,roofD:12141627,win:3820122,lamp:{idle:16766571,scan:16777215,fail:16734798,pass:6287526}},archive:{top:15327743,left:12891376,right:10916824,roof:9073359,roofD:7231664,win:5062278},forge:{top:7041664,left:4937059,right:3621201,roof:10265519,roofD:7041664,win:16758087,ember:16751164},dock:{deck:11569754,post:8018490,vessel:15855592},prop:"tree",propColors:[4168284,6472819,9067066],gremlin:{body:8215807,eye:1773616},pip:{body:16751164,bodyLight:16765566,belly:16774620,ear:14712620,cheek:16739930,ink:2759959},mood:{curious:16769899,focused:8177919,lost:16743273,happy:6287526,uneasy:16754250},vignette:332832},Rs={...Ee,id:"orbit",name:"Orbit",tagline:"A quiet station turning above a blue planet.",fits:["backend-api","infra-devops","systems"],flagship:!0,sky:[725030,1780309],terrain:"platform",ground:{fill:3885675,fillLight:7045032,edge:2568522,edgeDark:1712695,sand:9082808},water:{ripple:10473727,rippleAlpha:.18},pathColor:13624319,labelColor:14411775,palettes:[{top:15266303,left:12571890,right:9678036,roof:6280191,roofD:3844566,win:8188927},{top:16054011,left:14015464,right:11187143,roof:11967743,roofD:9401062,win:13481983},{top:15138806,left:12185820,right:9423800,roof:6287526,roofD:4177795,win:11075542}],beacon:{top:16777215,left:15133685,right:12174038,roof:6280191,roofD:3844566,win:8188927,lamp:{idle:10473727,scan:16777215,fail:16734798,pass:6287526}},forge:{top:10134712,left:7239820,right:5133930,roof:12634328,roofD:9081768,win:8188927,ember:8188927},dock:{deck:7239820,post:5133930,vessel:16777215},prop:"antenna",propColors:[12174038,8188927,5133930],gremlin:{body:16734878,eye:1773616},vignette:198162},pi={...Ee,id:"metropolis",name:"Metropolis",tagline:"A warm night city, lights just coming on.",fits:["web-frontend","monorepo"],flagship:!0,sky:[1708080,3874127],terrain:"block",ground:{fill:3814736,fillLight:5919864,edge:2762304,edgeDark:1709872,sand:6972296},water:{ripple:16758087,rippleAlpha:.1},pathColor:16767392,labelColor:16771527,palettes:[{top:16769730,left:15907216,right:13208422,roof:16743273,roofD:13916746,win:16766571},{top:14933247,left:12036592,right:9075664,roof:11967743,roofD:9401062,win:16771496},{top:14087423,left:10147568,right:7318220,roof:6280191,roofD:3844566,win:16774084},{top:16770799,left:16234188,right:13929126,roof:16740261,roofD:14241919,win:16766571}],beacon:{top:16119285,left:14277081,right:11579568,roof:16740261,roofD:14241919,win:3355443,lamp:{idle:16758087,scan:16777215,fail:16734798,pass:6287526}},forge:{top:8024976,left:5656684,right:3946572,roof:10656699,roofD:7301256,win:16758087,ember:16758087},dock:{deck:5656684,post:3946572,vessel:16766571},prop:"lamp",propColors:[16766571,16774084,3946572],gremlin:{body:6287526,eye:993820},vignette:525332},_b={...Ee,id:"harbour",name:"Harbour",tagline:"Fog lifting off a working port.",fits:["backend-api","infra-devops"],flagship:!1,sky:[2841971,995135],ground:{fill:8032106,fillLight:11124115,edge:6052434,edgeDark:4012853,sand:13222829},water:{ripple:14283263,rippleAlpha:.3},pathColor:14275261,labelColor:2046506,palettes:[{top:16051424,left:14273459,right:11772806,roof:4090762,roofD:2969446,win:5917242},{top:16247268,left:14925746,right:12556423,roof:13195850,roofD:10503482,win:7027248},{top:15331298,left:12898743,right:10201996,roof:5209950,roofD:3825990,win:3099192}],dock:{deck:9203532,post:5916210,vessel:15223612},prop:"lamp",propColors:[16767392,16773590,4868682],vignette:398879},yb={...Rs,id:"observatory",name:"Observatory",tagline:"A mountaintop under a hard, clear sky.",fits:["data-ml","systems"],flagship:!1,sky:[659504,2367562],terrain:"block",ground:{fill:4867942,fillLight:7236495,edge:3091781,edgeDark:1907502,sand:9275818},water:{ripple:16777215,rippleAlpha:.22},pathColor:14276336,labelColor:15394815,palettes:[{top:15855615,left:13617646,right:10722761,roof:11967743,roofD:9401062,win:16773544},{top:15135743,left:12375795,right:9415113,roof:6280191,roofD:3844566,win:16773544}],beacon:{...Rs.beacon,roof:11967743,roofD:9401062},prop:"antenna",propColors:[13617646,16773544,3091781],vignette:329756},xb={...Ee,id:"greenhouse",name:"Greenhouse",tagline:"Glass, leaves and warm afternoon light.",fits:["data-ml","library"],flagship:!1,sky:[9423280,4098938],ground:{fill:8175466,fillLight:11985823,edge:8020552,edgeDark:5916212,sand:15129779},water:{ripple:16777215,rippleAlpha:.18},pathColor:15985874,labelColor:1985843,palettes:[{top:15794166,left:13496029,right:10735033,roof:8115107,roofD:5220732,win:14286832},{top:16775654,left:15918008,right:13483407,roof:15774556,roofD:13077307,win:8018476},{top:16183551,left:14470131,right:11903953,roof:11832575,roofD:9070294,win:5062278}],prop:"tree",propColors:[5223530,9429132,8018490],vignette:731676},Ag={...Ee,id:"workshop",name:"Workshop",tagline:"A village of makers, sawdust in the air.",fits:["cli-tool","library","systems"],flagship:!1,sky:[14264428,9064238],ground:{fill:10404970,fillLight:13624221,edge:9067066,edgeDark:6701098,sand:15323811},water:{ripple:16771527,rippleAlpha:.2},pathColor:15916982,labelColor:4860432,palettes:[{top:16245699,left:14727562,right:12160867,roof:10902330,roofD:8340265,win:16765566},{top:15919320,left:14206894,right:11574144,roof:6057866,roofD:4543594,win:16765566},{top:16508889,left:15712936,right:13343362,roof:13190970,roofD:10499372,win:16765566}],forge:{...Ee.forge,ember:16758087},prop:"tree",propColors:[5940060,8832366,8014378],vignette:2757640},bb={...pi,id:"arcade",name:"Arcade",tagline:"Neon rain on a late-night strip.",fits:["game","web-frontend"],flagship:!1,sky:[1181734,2756426],ground:{fill:2366012,fillLight:3811932,edge:1445930,edgeDark:788506,sand:5913228},water:{ripple:16732120,rippleAlpha:.12},pathColor:8188927,labelColor:16773375,palettes:[{top:16766710,left:16748512,right:13916856,roof:8188927,roofD:3848406,win:8188927},{top:14284543,left:9430271,right:5944532,roof:16732120,roofD:12987048,win:16773227},{top:16774604,left:16769899,right:14071882,roof:11967743,roofD:9401062,win:16732120}],beacon:{...pi.beacon,roof:16732120,roofD:12987048,lamp:{idle:8188927,scan:16777215,fail:16734798,pass:6287526}},gremlin:{body:16773227,eye:2759173},prop:"lamp",propColors:[16732120,16766710,1445930],vignette:328206},Rg={...Ee,id:"kingdom",name:"Kingdom",tagline:"Stone walls, banners, a river below.",fits:["monorepo","backend-api","unknown"],flagship:!1,sky:[8369113,3894937],ground:{fill:7319134,fillLight:10933647,edge:8354410,edgeDark:6117709,sand:14209725},water:{ripple:16777215,rippleAlpha:.22},pathColor:13616813,labelColor:2828834,palettes:[{top:15855075,left:13880767,right:11248791,roof:4153231,roofD:3032683,win:5917242},{top:15855075,left:13880767,right:11248791,roof:11024954,roofD:8465452,win:5917242},{top:15855075,left:13880767,right:11248791,roof:4882258,roofD:3563581,win:5917242}],beacon:{...Ee.beacon,top:15328470,left:13617334,right:10722701,roof:4153231,roofD:3032683},prop:"tree",propColors:[4165458,7323498,5916212],vignette:858662},vb={...Ee,id:"outpost",name:"Outpost",tagline:"A desert station at dusk, dust in the light.",fits:["infra-devops","cli-tool","systems"],flagship:!1,sky:[15770458,7024458],ground:{fill:14267502,fillLight:15848346,edge:10842175,edgeDark:8016429,sand:15980451},water:{ripple:16769200,rippleAlpha:.14},pathColor:16509124,labelColor:4860432,palettes:[{top:16509392,left:15255450,right:12885875,roof:14246463,roofD:11094061,win:5913120},{top:16182752,left:14667960,right:12101261,roof:3116938,roofD:2321255,win:5913120}],prop:"antenna",propColors:[12885875,16769200,8016429],vignette:2756372},wb={...Ee,id:"snowfield",name:"Snowfield",tagline:"Blue hour, fresh snow, chimney smoke.",fits:["library","docs-content","unknown"],flagship:!1,sky:[10470374,4153231],ground:{fill:15397370,fillLight:16777215,edge:9346485,edgeDark:6714764,sand:14082802},water:{ripple:16777215,rippleAlpha:.3},pathColor:12833768,labelColor:2767442,palettes:[{top:16183526,left:14470070,right:11969164,roof:12077626,roofD:9188648,win:16765566},{top:15791352,left:13358560,right:10661564,roof:4090762,roofD:2969446,win:16765566},{top:15661040,left:13032912,right:10467498,roof:4882258,roofD:3563581,win:16765566}],prop:"tree",propColors:[3107658,5216874,5916212],vignette:858666},Tb={...Ee,id:"canopy",name:"Canopy",tagline:"Treehouses strung through an old forest.",fits:["docs-content","data-ml","library"],flagship:!1,sky:[6266731,2050611],ground:{fill:5214031,fillLight:8372074,edge:5916212,edgeDark:4075556,sand:11050866},water:{ripple:14218704,rippleAlpha:.18},pathColor:14076314,labelColor:15398879,palettes:[{top:15918793,left:14271643,right:11770482,roof:6983487,roofD:5139245,win:16765566},{top:16181976,left:14927782,right:12558206,roof:12085818,roofD:9195306,win:16765566}],prop:"tree",propColors:[3111487,6075226,4863268],vignette:398860},Sb={...Ee,id:"lagoon",name:"Lagoon",tagline:"Turquoise shallows and white sand at noon.",fits:["web-frontend","library","docs-content"],flagship:!1,sky:[8378351,2068408],ground:{fill:10147978,fillLight:13890493,edge:13218430,edgeDark:10719327,sand:16774102},water:{ripple:16777215,rippleAlpha:.36},pathColor:16774620,labelColor:1002074,palettes:[{top:16777215,left:15790056,right:13618628,roof:3126217,roofD:2133923,win:3107450},{top:16774886,left:16769464,right:14728332,roof:16747610,roofD:14051902,win:8014380},{top:15925240,left:13235165,right:10473913,roof:4177818,roofD:2788464,win:2054730}],prop:"tree",propColors:[4169564,9166970,10254916],vignette:536640},Cb={...Ee,id:"volcano",name:"Volcano",tagline:"Black rock, red sky, light from below.",fits:["systems","infra-devops","game"],flagship:!1,sky:[5904922,1705992],ground:{fill:3813167,fillLight:5917256,edge:2365978,edgeDark:1182218,sand:6969942},water:{ripple:16743226,rippleAlpha:.22},pathColor:16751194,labelColor:16769479,palettes:[{top:4866114,left:3813940,right:2761766,roof:16739133,roofD:12864036,win:16758087},{top:5917266,left:4602432,right:3353135,roof:16758087,roofD:14257186,win:16739133}],beacon:{...Ee.beacon,top:3813940,left:2761766,right:2038300,roof:16739133,roofD:12864036,lamp:{idle:16758087,scan:16777215,fail:16734798,pass:6287526}},forge:{...Ee.forge,ember:16739133},dock:{deck:4602432,post:2761766,vessel:16758087},prop:"antenna",propColors:[5917256,16739133,2365978],gremlin:{body:8188927,eye:666160},vignette:655874},Mb={...Rs,id:"cloudtop",name:"Cloudtop",tagline:"A floating town above a sea of cloud.",fits:["web-frontend","mobile","docs-content"],flagship:!1,sky:[13625087,8368358],terrain:"platform",ground:{fill:15988475,fillLight:16777215,edge:14147822,edgeDark:12043480,sand:16777215},water:{ripple:16777215,rippleAlpha:.5},pathColor:16771496,labelColor:2767442,palettes:[{top:16777215,left:15791354,right:13621478,roof:16748448,roofD:14051964,win:16765566},{top:16777215,left:15791354,right:13621478,roof:8177919,roofD:5216982,win:16765566},{top:16777215,left:15791354,right:13621478,roof:11967743,roofD:9401062,win:16765566}],beacon:{...Rs.beacon,roof:16748448,roofD:14051964,lamp:{idle:16765566,scan:16777215,fail:16734798,pass:6287526}},dock:{deck:15791354,post:12043480,vessel:16748448},prop:"tree",propColors:[9426848,13168832,12043480],vignette:4876954},Eb={...Ee,id:"reef",name:"Reef",tagline:"Underwater, where the light comes in ribbons.",fits:["data-ml","game","library"],flagship:!1,sky:[1802144,404032],terrain:"island",ground:{fill:13220234,fillLight:15326384,edge:9075290,edgeDark:5918266,sand:14930854},water:{ripple:10479871,rippleAlpha:.3},pathColor:15984579,labelColor:15137791,palettes:[{top:16767462,left:16752320,right:14052498,roof:16740261,roofD:14241919,win:8006218},{top:16773577,left:16765566,right:14265690,roof:16747610,roofD:14051902,win:8014380},{top:14286838,left:10481880,right:7129520,roof:4177818,roofD:2788464,win:2054730}],prop:"antenna",propColors:[16752320,10481880,9075290],gremlin:{body:1773616,eye:10479871},vignette:136224},kb={...Ag,id:"bazaar",name:"Bazaar",tagline:"Ochre walls, striped awnings, late light.",fits:["monorepo","web-frontend","backend-api"],flagship:!1,sky:[15909498,11033146],ground:{fill:14200945,fillLight:15849120,edge:9067066,edgeDark:6701098,sand:15981742},water:{ripple:16773577,rippleAlpha:.16},pathColor:16773577,labelColor:4860432,palettes:[{top:16640463,left:15386528,right:12885875,roof:14240570,roofD:11024940,win:5913120},{top:16640463,left:15386528,right:12885875,roof:3116938,roofD:2321255,win:5913120},{top:16640463,left:15386528,right:12885875,roof:4153231,roofD:3032683,win:5913120},{top:16640463,left:15386528,right:12885875,roof:14916398,roofD:12220959,win:5913120}],prop:"lamp",propColors:[16765566,16773577,6701098],vignette:2757640},Pb={...Rg,id:"monastery",name:"Monastery",tagline:"Mist on the mountain, a bell somewhere.",fits:["docs-content","library","systems"],flagship:!1,sky:[12110276,5204842],ground:{fill:8363898,fillLight:11585958,edge:6975334,edgeDark:4869703,sand:13093309},water:{ripple:16777215,rippleAlpha:.2},pathColor:14275520,labelColor:2042408,palettes:[{top:15855075,left:13880767,right:11248791,roof:5917242,roofD:4076072,win:16765566},{top:15855075,left:13880767,right:11248791,roof:9058858,roofD:6695454,win:16765566}],prop:"tree",propColors:[4157258,6986346,4863268],vignette:1055256},Ab={...Rs,id:"moonbase",name:"Moonbase",tagline:"Grey dust, black sky, one blue marble.",fits:["systems","infra-devops","data-ml"],flagship:!1,sky:[329228,724248],terrain:"platform",ground:{fill:9276821,fillLight:12105920,edge:6184550,edgeDark:3816e3,sand:11053232},water:{ripple:16777215,rippleAlpha:.28},pathColor:14474468,labelColor:15790326,palettes:[{top:16185082,left:14474468,right:11842750,roof:8188927,roofD:3848406,win:16765566},{top:16185082,left:14474468,right:11842750,roof:16758087,roofD:14257186,win:8188927}],prop:"antenna",propColors:[12105920,8188927,3816e3],vignette:0},Rb={...pi,id:"lanterns",name:"Lanterns",tagline:"A night festival, paper light everywhere.",fits:["web-frontend","game","unknown"],flagship:!1,sky:[1706542,3805232],terrain:"block",ground:{fill:3811908,fillLight:5915750,edge:2365998,edgeDark:1314332,sand:6969976},water:{ripple:16751194,rippleAlpha:.14},pathColor:16767392,labelColor:16771527,palettes:[{top:16771535,left:15910816,right:13211758,roof:14240570,roofD:11024940,win:16765566},{top:16180223,left:14268402,right:11177161,roof:16740261,roofD:14241919,win:16765566},{top:16774870,left:16769952,right:14268778,roof:14916398,roofD:12220959,win:16751194}],prop:"lamp",propColors:[16751194,16769952,2365998],vignette:656404},Tt=[Ee,Rs,pi,_b,yb,xb,Ag,bb,Rg,vb,wb,Tb,Sb,Cb,Mb,Eb,kb,Pb,Ab,Rb],ei=r=>Tt.find(e=>e.id===r)??Ee;function Io(r,e=0){const t=r?.kinds?.length?r.kinds:["unknown"],s=l=>t.reduce((h,c,u)=>h+(l.fits.includes(c)?(t.length-u)*2:0),0)+(l.flagship?1:0),i=Tt.filter(l=>s(l)>1),n=i.length>=3?i:Tt;let o=e>>>0||1;const a=()=>(o^=o<<13,o^=o>>>17,o^=o<<5,(o>>>0)%1e3/1e3);return[...n].map(l=>({s:l,k:s(l)+a()*.5})).sort((l,h)=>h.k-l.k).map(({s:l})=>l)}class ah{constructor(e){this.payload=e}mode="replay";onReady(e){queueMicrotask(()=>e(this.payload))}onBeats(){}}class Bb{constructor(e=""){this.base=e,this.connect()}mode="live";readyCb=null;beatsCb=null;signalCb=null;pending=null;async connect(){const e=await(await fetch(`${this.base}/api/scene`)).json(),t={world:e.world,events:e.events,beats:e.beats,repoId:e.repoId};this.readyCb?this.readyCb(t):this.pending=t,e.signal&&this.signalCb?.(e.signal);const s=()=>{const i=new WebSocket(`${location.origin.replace(/^http/,"ws")}${this.base}/live`);i.onmessage=n=>{const o=JSON.parse(String(n.data));o.type==="beats"&&o.beats&&this.beatsCb?.(o.beats,o.events??[]),o.type==="signal"&&o.state&&this.signalCb?.(o.state)},i.onclose=()=>{this.signalCb?.("lost"),setTimeout(s,2e3)}};s()}onReady(e){if(this.readyCb=e,this.pending){const t=this.pending;this.pending=null,e(t)}}onBeats(e){this.beatsCb=e}onSignal(e){this.signalCb=e}}async function Ib(r,e=""){const t=await fetch(`${e}/api/replay/${encodeURIComponent(r)}`);if(!t.ok)throw new Error(`session not found: ${r}`);const s=await t.json();return new ah({world:s.world,events:s.events,beats:s.beats,repoId:s.title?`${s.repoId} — ${s.title}`:s.repoId})}function Gb(r,e,t){const s=n=>e.places.find(o=>o.id===n)?.label??n.replace(/^p:/,""),i=r.actor==="pip"?"Pip":t?`A helper (${t})`:"A helper";switch(r.kind){case"curtain_up":return`${r.repoId}. Every building on this stage is a file in the repo.`;case"curtain_down":return r.verified?"Curtain. Every claim in this session was backed by a passing test.":"Curtain. Something was called done without a passing test to show for it.";case"walk_to":return`${i} heads to ${s(r.target)}.`;case"read":return`${i} reads ${s(r.target)}.`;case"build":return`${i} is working on ${s(r.target)}${r.intensity>.6?" — a big change":""}.`;case"raise":return`A new file rises: ${s(r.target)}.`;case"forge":return`${i} runs a command at the forge.`;case"search":return r.scope==="web"?`${i} looks something up on the web.`:`${i} searches the repo.`;case"run_tests":return`Running the tests at ${s(r.target)}…`;case"test_outcome":return r.outcome==="pass"?`${r.passed} tests pass.`:r.outcome==="fail"?`${r.failed} test${r.failed===1?"":"s"} fail${r.failed===1?"s":""}.`:"Tests ran — the runner didn't say how many.";case"spawn_gremlin":return`A bug gremlin pops out of ${s(r.target)}.`;case"chase":return`${i} chases the gremlin around ${s(r.target)}.`;case"banish":return"Caught. The gremlin is gone.";case"summon_helper":return`A helper arrives at the dock${r.label?` to ${r.label.toLowerCase()}`:""}.`;case"dismiss_helper":return r.ok?"The helper reports back and leaves.":"The helper leaves without finishing.";case"blocked_on_you":return r.reason==="permission"?"Pip needs your permission to continue.":"Pip has a question for you.";case"your_turn":return"Pip is done for now. Your turn.";case"stumble":return r.retrying?"Something went wrong. Pip tries again.":"Something went wrong.";case"celebrate":return"All green. Pip celebrates.";case"idle":return"";case"unverified_claim":return"Pip says it's done — but no test has passed since the last change. Something's hiding."}}function Db(r){if(!r.length)return[{label:"Scene",fromMs:0,toMs:0}];const e=Math.max(...r.map(l=>l.atMs+l.durationMs));let t=0,s=!1;const i=[];for(const l of r){let h=null;switch(l.kind){case"curtain_up":h="Arrive";break;case"curtain_down":h="Curtain";break;case"read":case"search":h=t?"Fix":s?"Explore":"Arrive",s=!0;break;case"build":case"raise":case"forge":h=t?"Fix":"Build";break;case"run_tests":h=t?"Fix":"Build";break;case"test_outcome":{h=l.outcome==="fail"?"Trouble":"Finale";const c=i.at(-1);c&&c.kind==="run_tests"&&(c.phase=h);break}case"spawn_gremlin":t++,h="Trouble";break;case"chase":h="Fix";break;case"banish":t=Math.max(0,t-1),h="Finale";break;case"celebrate":h="Finale";break;case"summon_helper":case"dismiss_helper":h="Help";break;case"blocked_on_you":h="Waiting";break;case"unverified_claim":h="Hmm";break;case"stumble":h="Trouble";break;case"your_turn":case"walk_to":case"idle":h=null;break}h&&i.push({phase:h,at:l.atMs,end:l.atMs+l.durationMs,kind:l.kind})}const n=[];for(const l of i){const h=n.at(-1);h&&h.phase===l.phase?h.to=Math.max(h.to,l.end):n.push({phase:l.phase,from:h?h.to:0,to:l.end})}n.length&&(n[0].from=0,n.at(-1).to=e);const o=2200;for(let l=n.length-1;l>=0&&n.length>1;l--){const h=n[l];h.to-h.from>=o||(l>0?(n[l-1].to=h.to,n.splice(l,1)):(n[1].from=h.from,n.splice(0,1)))}const a=n.at(-1);return a&&a.phase==="Curtain"&&n.length>1&&(n[n.length-2].to=a.to,n.pop()),n.map(l=>({label:l.phase==="Curtain"?"Finale":l.phase,fromMs:l.from,toMs:l.to}))}const In=r=>{const e=Math.floor(r/1e3);return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`},Gn=r=>`#${r.toString(16).padStart(6,"0")}`,j=(r,e,t)=>{const s=document.createElement(r);return e&&(s.className=e),t!==void 0&&(s.innerHTML=t),s},Fb='<svg viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 2.8v10.4a.6.6 0 0 0 .9.5l8.3-5.2a.6.6 0 0 0 0-1L5.4 2.3a.6.6 0 0 0-.9.5z"/></svg>',cu='<svg viewBox="0 0 16 16" fill="currentColor"><rect x="3.5" y="3" width="3" height="10" rx="1"/><rect x="9.5" y="3" width="3" height="10" rx="1"/></svg>',Lb='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5l3.2 3L13 4.5"/></svg>';class Ob{constructor(e,t){this.h=t,this.root=j("div","wrap");const s=j("header"),i=j("div","brand",'<a class="eyebrow" href="https://agenttheatre.dev/" title="Back to agenttheatre.dev">← Agent Theatre</a><h1 id="title">Loading…</h1>'),n=j("div","toolbar");this.setBtn=j("button","btn ghost","Set"),this.setBtn.type="button",this.setBtn.onclick=()=>this.showPicker(!0),this.muteBtn=j("button","btn ghost","Effects on"),this.muteBtn.type="button",this.muteBtn.title="Sound effects",this.muteBtn.onclick=()=>t.onMute(),this.ambBtn=j("button","btn ghost","Ambience on"),this.ambBtn.type="button",this.ambBtn.title="Background sound",this.ambBtn.onclick=()=>t.onAmbience(),n.append(this.setBtn,this.muteBtn,this.ambBtn),s.append(i,n);const o=j("div","grid"),a=j("div","stage-col");this.stageEl=j("div","stage"),this.overlay=j("div","overlay"),this.bubbleEl=j("div","bubble"),this.bubbleEl.hidden=!0,this.overlay.append(this.bubbleEl),this.signal=j("div","signal","<i></i><span>live</span>"),this.signal.hidden=!0,this.chip=j("div","chip ok"),this.chip.hidden=!0,this.caption=j("div","caption","<span></span>"),this.title=j("div","card",'<div class="small">Agent Theatre</div><div class="big" id="titleBig">…</div>'),this.end=j("div","card",'<div class="big">Every agent run has a story.</div><div class="small">Agent Theatre</div>'),this.end.style.opacity="0",this.picker=j("div","picker"),this.picker.hidden=!0,this.stageEl.append(j("div","vignette"),this.overlay,this.signal,this.chip,this.caption,this.title,this.end,this.picker);const l=j("div","controls");this.playBtn=j("button","btn",`${cu}<span>Pause</span>`),this.playBtn.type="button",this.playBtn.onclick=()=>t.onPlayPause();const h=j("div","track");this.actsEl=j("div","acts"),this.labelsEl=j("div","actlabels"),this.head=j("div","head"),h.append(this.actsEl,this.labelsEl,this.head),h.addEventListener("pointerdown",f=>{const p=this.actsEl.getBoundingClientRect(),m=(f.clientX-p.left)/p.width;t.onSeek(m*this.durationMs)}),this.time=j("div","time","0:00 / 0:00"),this.rateBtn=j("button","btn ghost","1×"),this.rateBtn.type="button",this.rateBtn.onclick=()=>t.onRate(),l.append(this.playBtn,h,this.time,this.rateBtn),a.append(this.stageEl,l);const c=j("aside"),u=j("section","panel",'<h2>Event log</h2><p class="sub">Every scene is driven by one of these agent events. Tap one to jump there.</p>');this.logEl=j("ul","log"),u.append(this.logEl);const d=j("section","panel",`<h2>How to read the stage</h2><p class="sub">Buildings are files, districts are folders, beacons are test suites. Gremlins are failing tests. The lead character is the agent; its light shows its mood. Helpers are subagents. If the agent says it's done without a passing test, something hides behind it.</p>`);c.append(u,d),o.append(a,c),this.root.append(s,o,j("p","note","Everything you see is generated locally from agent events. No code, prompts or file contents are shown or sent anywhere.")),e.append(this.root)}root;stageEl;overlay;caption;chip;signal;title;end;picker;playBtn;rateBtn;muteBtn;ambBtn;setBtn;actsEl;labelsEl;head;time;logEl;acts=[];actBtns=[];actLabels=[];logBtns=[];lastCaption="";lastBeatId="";lastAct=-1;lastEv=-2;tagPool=[];bubbleEl;durationMs=0;repoId="";setTitle(e,t){this.root.querySelector("#title").textContent=e,this.root.querySelector("#titleBig").textContent=t??e}setMuted(e){this.muteBtn.textContent=e?"Effects off":"Effects on",this.muteBtn.setAttribute("aria-pressed",String(!e))}setAmbience(e){this.ambBtn.textContent=e?"Ambience on":"Ambience off",this.ambBtn.setAttribute("aria-pressed",String(e))}setRate(e){this.rateBtn.textContent=`${e}×`}loadTimeline(e,t,s){this.durationMs=e.length?Math.max(...e.map(n=>n.atMs+n.durationMs)):0,this.acts=Db(e),this.actsEl.innerHTML="",this.labelsEl.innerHTML="",this.actBtns=[],this.actLabels=[];for(const n of this.acts){const o=(n.toMs-n.fromMs)/Math.max(1,this.durationMs)*100,a=j("button");a.type="button",a.style.flex=`0 0 calc(${o}% - 3px)`,a.setAttribute("aria-label",`Jump to ${n.label}`),a.onclick=h=>{h.stopPropagation(),this.h.onSeek(n.fromMs+1)};const l=j("span","",n.label);l.style.flex=`0 0 calc(${o}% - 3px)`,this.actsEl.append(a),this.labelsEl.append(l),this.actBtns.push(a),this.actLabels.push(l)}this.logEl.innerHTML="",this.logBtns=[],t[0]?.ts;const i=n=>e.find(o=>o.sourceEventIds.includes(n));for(const n of t){if(n.kind==="session_start"||n.kind==="session_end")continue;const o=i(n.id);if(!o)continue;const a=j("li"),l=j("button");l.type="button";const[h,c]=Ub(n),u=n.kind==="test_result"&&!n.ok;l.innerHTML=`<time>${In(o.atMs)}</time><span class="dot k-${n.kind}${u?" fail":""}"></span><span class="ev"><b>${uu(h)}</b><code>${uu(c)}</code></span>`,l.onclick=()=>this.h.onSeek(o.atMs+1),a.append(l),this.logEl.append(a),this.logBtns.push({btn:l,ms:o.atMs})}}previews=new Map;get pickerOpen(){return!this.picker.hidden}profile;leadName="Pip";showAll=!1;showPicker(e,t){if(this.picker.hidden=!e,!e)return;this.picker.innerHTML="";const s=this.profile?.kinds?.[0],i=s&&s!=="unknown"?{"web-frontend":"a web app","backend-api":"a backend","cli-tool":"a CLI",library:"a library","data-ml":"data & ML work",mobile:"a mobile app",game:"a game","infra-devops":"infrastructure","docs-content":"documentation",monorepo:"a monorepo",systems:"systems code"}[s]:null,n=Io(this.profile,Nb(this.repoId)).slice(0,3),o=this.showAll?[...Tt]:n;this.picker.append(j("h3","",this.showAll?"All sets":"Choose your set"),j("p","",i&&!this.showAll?`This looks like ${i}${this.profile?.languages?.[0]?` in ${this.profile.languages[0]}`:""}. These stages suit it — or browse them all.`:"Same repo, same story — pick the stage. You can change it any time."));const a=j("div","setcards");for(const u of o){const d=j("button","setcard");d.type="button";const f=this.previews.get(u.id);d.innerHTML=`<div class="sw" style="--a:${Gn(u.sky[0])};--b:${Gn(u.palettes[0].left)}">${f?`<img src="${f}" alt="" />`:""}</div><div class="nm">${u.name}${u.id===t?" ✓":""}</div><div class="tg">${u.tagline}</div>`,d.onclick=()=>{this.h.onPickSet(u.id),this.showPicker(!1)},a.append(d)}const l=j("div","toolbar"),h=j("button","btn ghost","Surprise me");h.type="button",h.onclick=()=>this.h.onShuffle();const c=j("button","btn ghost",this.showAll?"Suggested":`All ${Tt.length} sets`);c.type="button",c.onclick=()=>{this.showAll=!this.showAll,this.showPicker(!0,t)},l.append(h,c),this.picker.append(a,l)}update(e,t,s,i){this.time.textContent=`${In(e.t)} / ${In(e.duration)}`,this.head.style.left=`${e.t/Math.max(1,e.duration)*100}%`,this.playBtn.innerHTML=e.playing?`${cu}<span>Pause</span>`:`${Fb}<span>${e.t>=e.duration-1?"Replay":"Play"}</span>`;const n=e.current;this.title.style.opacity=String(n&&n.kind==="curtain_up"?1-Math.min(1,Math.max(0,(e.t-n.atMs-600)/700)):e.t<600?1:0);const o=n&&n.kind==="curtain_down"?n:null;this.end.style.opacity=String(o?Math.min(1,Math.max(0,(e.t-o.atMs-400)/600)):0);const a=n?Gb(n,t,i).replace(/\bPip\b/g,this.leadName):"";n&&n.id!==this.lastBeatId&&(this.lastBeatId=n.id,a&&(this.lastCaption=a));const l=this.caption.firstElementChild;l.textContent=this.lastCaption,l.style.opacity=this.lastCaption&&!(n?.kind==="curtain_up"&&e.t-(n?.atMs??0)<900)?"1":"0",e.evidence?(this.chip.hidden=!1,this.chip.className="chip ok",this.chip.innerHTML=`${Lb}Evidence · ${e.evidence.passed} tests passed`):n?.kind==="unverified_claim"||n?.kind==="curtain_down"&&!n.verified?(this.chip.hidden=!1,this.chip.className="chip warn",this.chip.textContent="No test evidence"):this.chip.hidden=!0,this.signal.hidden=e.signal==="ok"||!this.liveMode,this.signal.className=`signal ${e.signal}`,this.signal.lastElementChild.textContent=e.signal==="lost"?"can't hear the agent":"live";let h=0;this.acts.forEach((p,m)=>{e.t>=p.fromMs&&(h=m)}),h!==this.lastAct&&(this.lastAct=h,this.actBtns.forEach((p,m)=>{p.classList.toggle("on",m<h),p.classList.toggle("now",m===h)}),this.actLabels.forEach((p,m)=>p.classList.toggle("now",m===h)));let c=-1;this.logBtns.forEach((p,m)=>{e.t>=p.ms&&(c=m)}),c!==this.lastEv&&(this.lastEv=c,this.logBtns.forEach((p,m)=>{p.btn.classList.toggle("done",m<c),p.btn.classList.toggle("now",m===c)}),this.logBtns[c]?.btn.scrollIntoView({block:"nearest",behavior:"smooth"}));const d=this.stageEl.getBoundingClientRect().width<600,f=e.labels.filter(p=>p.active||!d).sort((p,m)=>p.screen.y-m.screen.y||p.screen.x-m.screen.x);for(let p=0;p<f.length;p++)for(let m=0;m<p;m++){const g=f[m],_=f[p];Math.abs(g.screen.x-_.screen.x)<76&&Math.abs(g.screen.y-_.screen.y)<20&&(_.screen={x:_.screen.x,y:g.screen.y-20})}for(;this.tagPool.length<f.length;){const p=j("div","tag");this.overlay.append(p),this.tagPool.push(p)}this.tagPool.forEach((p,m)=>{const g=f[m];if(!g){p.hidden=!0;return}p.hidden=!1,p.textContent=g.text;const _=t.places.find(y=>y.label===g.text)?.id??"",x=s(_);p.className=`tag${g.active?" active":""}${x!=="idle"?` lamp-${x}`:""}`,p.style.left=`${g.screen.x}px`,p.style.top=`${g.screen.y}px`}),e.bubble?(this.bubbleEl.hidden=!1,this.bubbleEl.textContent=e.bubble.text,this.bubbleEl.style.color=Gn(e.bubble.color),this.bubbleEl.style.left=`${e.bubble.screen.x}px`,this.bubbleEl.style.top=`${e.bubble.screen.y}px`,this.bubbleEl.classList.toggle("pulse",n?.kind==="blocked_on_you")):this.bubbleEl.hidden=!0}liveMode=!1}function Ub(r,e){const t=s=>s.split("/").pop()??s;switch(r.kind){case"read_file":return["Read",r.path];case"edit_file":return["Edit",`${r.path} · +${r.added} −${r.removed}`];case"write_file":return[r.created?"Create":"Write",r.path];case"run_command":return[r.intent==="test"?"Run tests":r.intent==="git"?"Git":r.intent==="build"?"Build":r.intent==="install"?"Install":"Run",`${r.argv0}${r.touched.length?" · "+r.touched.map(t).join(", "):""}`];case"test_result":return[r.ok?`${r.passed} passed`:`${r.failed} failed`,r.framework?`${r.framework}`:""];case"search":return["Search",r.scope];case"subagent_start":return["Helper",r.label??r.childId];case"subagent_stop":return["Helper done",r.childId];case"waiting_for_user":return[r.reason==="permission"?"Needs permission":r.reason==="question"?"Has a question":"Waiting",""];case"error":return["Error",r.where];case"turn_end":return[r.claimedSuccess?"Says it's done":"Turn ends",""];default:return[r.kind,""]}}const Nb=r=>{let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0},uu=r=>r.replace(/[&<>"]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[e]);async function Hb(r,e,t,s=360,i=200){const n=new Sg(e,t);n.update(0);const o=new _e,a=e.places.flatMap(m=>[K(m.gx,m.gy),K(m.gx+m.footprint,m.gy+m.footprint)]),l=a.map(m=>m.x),h=a.map(m=>m.y),c=Math.max(...l)-Math.min(...l)+160,u=Math.max(...h)-Math.min(...h)+170,d=Math.min(s/c,i/u);o.scale.set(d),o.position.set(s/2-(Math.min(...l)+Math.max(...l))/2*d,i/2-((Math.min(...h)+Math.max(...h))/2-20)*d),o.addChild(n.container);const f=wr.create({width:s,height:i,resolution:1});r.renderer.render({container:o,target:f,clear:!0,clearColor:t.sky[1]});const p=await r.renderer.extract.base64(f);return f.destroy(!0),o.destroy({children:!0}),p}const le=new URLSearchParams(location.search),Vr=matchMedia("(prefers-reduced-motion: reduce)").matches,Bt={get:r=>{try{return localStorage.getItem(r)}catch{return null}},set:(r,e)=>{try{localStorage.setItem(r,e)}catch{}}};async function zb(r){try{const e=await(await fetch("/demo/demos.json")).json();return r==="any"?e[Math.floor(Math.random()*e.length)]??null:e.find(t=>t.id===r)??null}catch{return null}}async function Wb(r){const e=await zb(r);e&&(r=e.id,le.has("episode")||le.set("episode",`${e.title} · ${e.kind}`),!le.has("set")&&le.has("cinema")&&le.set("set",e.set));const t=await(await fetch(`/demo/${r}.jsonl`)).text(),{events:s}=Hx(t),i=Jx(s);let n=i.files,o=s[0]?.repoId??r;try{const h=await(await fetch(`/demo/${r}.files.json`)).json();if(Array.isArray(h.files)){const c=new Set(h.files.map(u=>u.path));n=[...h.files,...i.files.filter(u=>!c.has(u.path))],h.repoId&&(o=h.repoId)}}catch{}const a=Yx({repoId:o,files:n,touched:i.touched}),l=Jr(s,a);return new ah({world:a,events:s,beats:l,repoId:o})}async function $b(r,e){const t=new eb;let s=()=>{};const i=async()=>{await t.arm(),t.ready&&o?.audioReady()};for(const E of["pointerdown","keydown"])addEventListener(E,()=>{t.ready||i()},{passive:!0});let n=ei(le.get("set")),o=null,a=Number(le.get("rate"))||1,l=Bt.get("at:muted")==="1",h=Bt.get("at:ambience")!=="0";t.setMuted(l),t.setAmbienceEnabled(h);const c=new Ob(r,{onPlayPause:()=>{o&&(i(),o.playing?o.pause():(o.state.t>=o.state.duration-1&&o.seek(0),o.play()))},onSeek:E=>{o?.seek(E)},onRate:()=>{a=a>=4?1:a*2,o?.setRate(a),c.setRate(a)},onMute:()=>{if(!t.ready){i();return}l=!l,t.setMuted(l),Bt.set("at:muted",l?"1":"0"),c.setMuted(l)},onAmbience:()=>{if(!t.ready){i();return}h=!h,t.setAmbienceEnabled(h),Bt.set("at:ambience",h?"1":"0"),c.setAmbience(h)},onPickSet:E=>{n=ei(E),o&&(Bt.set(`at:set:${o.world.repoId}`,E),x())},onShuffle:()=>{const E=Io(f?.world.profile).filter(G=>G.id!==n.id),B=E.slice(0,Math.max(3,Math.min(5,E.length)));n=B[Math.floor(Math.random()*B.length)]??Tt[0],o&&(Bt.set(`at:set:${o.world.repoId}`,n.id),x()),c.showPicker(!1)}});c.setMuted(l),c.setAmbience(h),c.setRate(a),c.liveMode=e.mode==="live";const u=le.has("cinema");u&&(document.documentElement.classList.add("cinema"),l=!0,t.setMuted(!0));const d=new oa;await d.init({resizeTo:c.stageEl,antialias:!0,backgroundAlpha:1,background:n.sky[1],preference:"webgl",resolution:Math.min(2,devicePixelRatio||1),autoDensity:!0}),c.stageEl.prepend(d.canvas);let f=null;const p=(E,B)=>Kx(E,br[(E.seed+Tt.findIndex(G=>G.id===B.id)*7)%br.length]);let m=0,g=!1,_="";function x(){if(!f)return;o&&(m=o.state.t,g=o.playing,o.destroy()),d.renderer.background.color=n.sky[1];const E=p(f.world,n),B=E===f.world?f.beats:Jr(f.events,E);o=new qs(d,E,n,t,Vr,le.get("cast")??Bt.get(`at:cast:${f.repoId}`)),globalThis.__agentTheatre={app:d,get player(){return o},panel:c},c.leadName=o.leadName,o.load(B),o.setRate(a),o.theme.id!==_?(o.seek(0),o.play()):(o.seek(m),g&&o.play()),_=o.theme.id,c.loadTimeline(B,f.events,E)}e.onReady(E=>{f=E;const B=Bt.get(`at:set:${E.repoId}`),G=le.get("set")??B;c.profile=E.world.profile,c.repoId=E.repoId,G?n=ei(G):n=Io(E.world.profile,E.world.seed)[0]??Tt[0],c.setTitle(E.repoId,le.get("episode")??void 0),c.loadTimeline(E.beats,E.events,E.world),x();const V=Number(le.get("t"));V>0&&o&&o.seek(V*1e3);const I=(async()=>{if(!le.has("nopreview")){for(const M of Tt)try{c.previews.set(M.id,await Hb(d,p(E.world,M),M))}catch(D){console.warn("set preview failed",M.id,D)}c.pickerOpen&&c.showPicker(!0,n.id),s()}})();!G&&!le.has("t")&&I.then(()=>c.showPicker(!0,n.id)),le.get("paused")!=="1"&&!Vr&&o?.play(),u&&o&&!Vr&&o.play(),Vr&&!le.has("t")&&o?.seek(Math.min(o.state.duration,25400))}),e.onBeats((E,B)=>{if(!(!o||!f)){if(f.beats.push(...E),f.events.push(...B),o.world===f.world)o.append(E);else{const G=Jr(f.events,o.world);o.append(G.slice(o.beatCount))}c.loadTimeline(o.world===f.world?f.beats:Jr(f.events,o.world),f.events,o.world),o.playing||o.play(),s()}}),e.onSignal?.(E=>o?.setSignal(E));const y=Number(le.get("step"))||0;let b=performance.now(),w=0,v=!1,T=null;const k=E=>{v=!1;const B=y||Math.min(50,E-b);b=E,o&&!document.hidden&&((u||le.has("loop"))&&o.state.t>=o.state.duration-1&&o.state.duration>0&&(T||(T=setTimeout(()=>{T=null,o?.seek(0),o?.play()},600))),o.update(B),c.update(o.state,o.world,G=>o.worldLayer.lampOf(G)),o.playing?w=45:w--),(o?.playing||w>0)&&!document.hidden&&P()},P=()=>{v||(v=!0,requestAnimationFrame(k))};s=()=>{w=45,b=performance.now(),P()},s();for(const E of["pointerdown","keydown","resize"])addEventListener(E,s,{passive:!0});document.addEventListener("visibilitychange",()=>{document.hidden||s()});const A=qs.prototype.play;qs.prototype.play=function(){A.call(this),s()};const C=qs.prototype.seek;qs.prototype.seek=function(E){C.call(this,E),s()}}async function Vb(r){const{Application:e}=await wt(async()=>{const{Application:l}=await Promise.resolve().then(()=>bx);return{Application:l}},void 0),{Pip:t}=await wt(async()=>{const{Pip:l}=await Promise.resolve().then(()=>fb);return{Pip:l}},void 0),{castById:s,CAST:i}=await wt(async()=>{const{castById:l,CAST:h}=await Promise.resolve().then(()=>db);return{castById:l,CAST:h}},void 0),n=s(r)??i[0],o=ei(le.get("set")??"island");document.documentElement.style.background="transparent",document.body.style.background="transparent",document.body.style.margin="0";const a=new e;if(await a.init({width:320,height:320,backgroundAlpha:0,antialias:!0,resolution:2,autoDensity:!0,preference:"webgl"}),document.body.replaceChildren(a.canvas),r==="gremlin"){const{Gremlin:l}=await wt(async()=>{const{Gremlin:c}=await Promise.resolve().then(()=>cb);return{Gremlin:c}},void 0),h=new l("g",o,!1);h.scale=7,h.x=160,h.y=250,a.stage.addChild(h.container),a.ticker.add(c=>h.update(c.deltaMS))}else{const l=new t(o,!1,n);l.container.scale.set(6*n.size),l.pose.x=160,l.pose.y=272,a.stage.addChild(l.container),l.pose.mood=le.get("mood")??"curious",a.ticker.add(h=>l.update(h.deltaMS))}globalThis.__agentTheatre={app:a,player:!0}}const Dn=document.getElementById("app"),Xb=le.has("portrait")?Promise.resolve(new ah({world:null,events:[],beats:[],repoId:""})):le.has("live")?Promise.resolve(new Bb):le.get("session")?Ib(le.get("session")):Wb(le.get("demo")??"episode-1");le.has("portrait")?Vb(le.get("portrait")).catch(r=>{Dn.textContent=`Could not start: ${r}`}):Xb.then(r=>$b(Dn,r)).catch(r=>{Dn.textContent=`Could not start: ${r}`});export{T_ as A,_e as C,Lf as D,Uf as E,J0 as F,S_ as a,Xf as b,Hf as c,Vf as d,q as e};
956
+ //# sourceMappingURL=index-BW3_w3GY.js.map